以太坊私链 利用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 balanceOf = erc20.balanceOf("以太坊账户地址");
CompletableFuture sendAsync = balanceOf.sendAsync();
System.out.println(sendAsync.get());

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

调用合约转账方法

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

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

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

 

 

 

你可能感兴趣的:(区块链)