Java中如何转账发送ETH
Web3j是一个很好用的工具,但是使用起来有点复杂,因此我写了一些使用示例,希望可以帮到各位。
完整示例代码仓库地址:web3j-eth-sample
本章内容是如何使用Web3j在Java是进行以太坊余额查询和转账,发送ETH。
依赖
Maven依赖
<!--web3j-->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>5.0.0</version>
</dependency>
示例
查询余额
/**
* Retrieves the Ether balance of the given Ethereum address.
*
* @param address The Ethereum address whose balance is to be retrieved.
* @return The balance in Ether as a BigDecimal.
* @throws IOException If there is an issue communicating with the Ethereum node.
*/
public static BigDecimal getETHBalance(String address) throws IOException {
// Retrieve balance in Wei
BigInteger balanceInWei = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send().getBalance();
// Convert Wei to Ether
return Convert.fromWei(new BigDecimal(balanceInWei), Convert.Unit.ETHER);
}
转账,发送ETH
/**
* Transfers Ether from a sender's account to a recipient's account.
*
* @param senderPrivateKey The private key of the sender's Ethereum account (keep this secure).
* @param recipientAddress The recipient's Ethereum address.
* @param amountInEther The amount to transfer in Ether.
* @return The transaction hash if the transfer is successful; otherwise, returns null.
* @throws IOException If there is an issue communicating with the Ethereum node.
*/
public static String transfer(String senderPrivateKey, String recipientAddress, BigDecimal amountInEther) throws IOException {
// Retrieve the chain ID of the connected network
EthChainId chainIdResponse = web3j.ethChainId().send();
long chainId = chainIdResponse.getChainId().longValue();
/* Sender Account Configuration */
// Create credentials from the sender's private key
Credentials credentials = Credentials.create(senderPrivateKey);
String senderAddress = credentials.getAddress();
// Get the current nonce for the sender's account
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
senderAddress, DefaultBlockParameterName.LATEST).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
/* Transaction Amount and Fee Configuration */
// Convert the amount from Ether to Wei (1 ETH = 10^18 Wei)
BigInteger value = Convert.toWei(am