There are send method and sendAsync method to send a signed transaction using Ethereum's Java library "Web3j". In this article, I described how to send a transaction using send, but I also implemented the method using sendAsync, so I will keep it as a record. Send signed transaction using Web3j
The code.
SendTransaction.java
public TransactionReceipt sendTransactionAsync(Credentials credentials, String password, String toAddress, long value) {
CompletableFuture<TransactionReceipt> receipt = null;
try {
//Transaction generation
// "personal_unlockAccount"Send a request and receive a response
PersonalUnlockAccount unlockAccountResponse = web3j.personalUnlockAccount(
credentials.getAddress(), //address
password //password
).send();
//If the unlock is successful, send Ether
if (unlockAccountResponse.getResult()) {
//Send a 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;
}
The differences are as follows.
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 does not return a response until the transaction is included in the block. sendAsync returns a response when a transaction is sent, so you don't have to wait for it to be captured in a block.
However, when using the get method of "CompletableFuture
It seems better to use sendAsync when you don't have to wait for a transaction to get into a block.
Recommended Posts