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

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

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

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

连接以太坊网络

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

创建凭证

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

获取当前gasPrice

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

初始化合约

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

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

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

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

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

调用合约转账方法

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

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

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

 

 

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值