利用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();//返回交易信息

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

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

 

 

 

Logo

为所有Web3兴趣爱好者提供学习成长、分享交流、生态实践、资源工具等服务,作为Anome Land原住民可不断优先享受各种福利,共同打造全球最大的Web3 UGC游戏平台。

更多推荐