Web3j使用示例(三)——Java中如何实现以太坊余额查询和转账(发送ETH)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值