LoginSignup
0
0

More than 3 years have passed since last update.

Ethereum トランザクションの送信方法sendとsendAsyncの違い

Posted at

記事の内容

EthereumのJavaライブラリ「Web3j」を使って署名付きトランザクションを送信する方法でsendメソッドとsendAsyncメソッドがあります。
この記事でsendを使ったトランザクションの送信方法を記載しましたが、sendAsyncを使った方法も実装してみたので記録として残します。
Web3jを使って署名付きトランザクションを送信する

環境

  • geth:1.9.0-stable
  • web3j:4.5.0

実装

コードです。

SendTransaction.java
 public TransactionReceipt sendTransactionAsync(Credentials credentials, String password, String toAddress, long value) {

    CompletableFuture<TransactionReceipt> receipt = null;
      try {
        // トランザクションの生成
        // "personal_unlockAccount"のリクエストを送信し、レスポンスを受信する
        PersonalUnlockAccount unlockAccountResponse = web3j.personalUnlockAccount(
              credentials.getAddress(), // アドレス
              password  // パスワード
              ).send();

        // アンロックが成功していたら、Etherを送金する
        if (unlockAccountResponse.getResult()) {
          // Transactionを送信する。
          receipt = Transfer.sendFunds(web3j, credentials, toAddress, BigDecimal.valueOf(value), Unit.ETHER).sendAsync();
        }

          return receipt.get();
        }catch(IOException | TransactionException ex) {
          ex.printStackTrace();
        }catch(Exception ex) {
          ex.printStackTrace();
        }
      return null;
    }

違いとしては以下の部分になります。

SendTransaction.java
receipt = Transfer.sendFunds(web3j, credentials, toAddress, BigDecimal.valueOf(value), Unit.ETHER).send();
SendTransaction.java
receipt = Transfer.sendFunds(web3j, credentials, toAddress, BigDecimal.valueOf(value), Unit.ETHER).sendAsync();

sendの方はトランザクションがブロックに取り込まれるまで応答が返ってきません。
sendAsyncの方はトランザクションが送信された時点で応答が返ってくるため、ブロックに取り込まれるのを待つ必要がありません。

ただし、sendAsyncの実行結果として得られる「CompletableFuture」のgetメソッドを使用し、TransactionReceiptを取得する際はブロックに取り込まれるまで応答が返ってきません。

トランザクションがブロックに取り込まれるのを待つ必要がない場面ではsendAsyncを使うほうが良さそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0