以太坊私链 利用Java 调用智能合约

朴灿烈づ我的快乐病毒、 2022-05-11 08:36 761阅读 0赞

利用Java 发布智能合约:https://blog.csdn.net/Keith003/article/details/82744534

使用前需要将合约转换为java 代码 :https://blog.csdn.net/Keith003/article/details/81873154

如果没有搭建本地以太坊节点可以使用云客户端 infura :https://infura.io

连接以太坊网络

  1. Web3j web3j = Web3j.build(new HttpService("以太坊节点地址"));

创建凭证

  1. Credentials credentials = WalletUtils.loadCredentials("密码","Keystore文件地址");

获取当前gasPrice

  1. public BigInteger getPrice(Web3j web3j) throws Exception{
  2. EthGasPrice send = web3j.ethGasPrice().send();
  3. BigInteger gasPrice = send.getGasPrice();
  4. return gasPrice;
  5. }

初始化合约

  1. String contractAddress = "合约地址";
  2. BigInteger gasPrice = getPrice(Web3j web3j);
  3. BigInteger gasLimit = BigInteger.valueOf(80_000);
  4. Contract erc20 = Contract.load(contractAddress, web3j, credentials, gasPrice, gasLimit );

注:这里GasLimit 设置为默认10KWei ,GasPrice 获取当前链上实时的GasPrice

调用合约方法:获取账户代币数量

  1. RemoteCall<BigInteger> balanceOf = erc20.balanceOf("以太坊账户地址");
  2. CompletableFuture<BigInteger> sendAsync = balanceOf.sendAsync();
  3. System.out.println(sendAsync.get());

注:合约方法提供了send 同步方法和 sendAsync 异步方法 可根据具体需要选择

调用合约转账方法

  1. BigInteger price = BigInteger.valueOf(10_000_000);
  2. String to = "转到的账户地址";
  3. RemoteCall<TransactionReceipt> transfer = erc20.transfer(to , price);
  4. CompletableFuture<TransactionReceipt> sendAsync = transfer.sendAsync();
  5. TransactionReceipt transactionReceipt = sendAsync.get();//返回交易信息

注:这里以太坊由于手续费不同可能打包的时间会不同 这里需要注意

还有很多接口这里就不一一列举了

发表评论

表情:
评论列表 (有 0 条评论,761人围观)

还没有评论,来说两句吧...

相关阅读

    相关 智能合约 简介

    以太坊是一个分布式的计算平台。它会生成一个名为Ether的加密货币。程序员可以在以太坊区块链上写下“智能合约”,这些以太坊智能合约会根据代码自动执行。 以太坊是什么?

    相关 智能合约是什么?

    以太坊是最早提出做智能合约的平台。由于以太坊区块链被普遍接受,因此多数区块链的智能合约采取与以太坊相似的设计。本文将详细介绍以太坊的智能合约:它是什么?它有什么用? 以太...