主页 > 华为imtoken无法安装 > 以太坊私有链使用Java调用智能合约

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

华为imtoken无法安装 2023-06-25 10:13:53

使用Java发布智能合约:

合约在使用前需要转成java代码:

如果您没有本地以太坊节点以太坊私链是什么,可以使用云客户端 infura:

连接到以太坊网络

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

创建凭据

sitesohu.com 以太坊公链私链_以太经典是以太坊的分叉币吗_以太坊私链是什么

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

获取当前 gasPrice

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

sitesohu.com 以太坊公链私链_以太经典是以太坊的分叉币吗_以太坊私链是什么

return gasPrice; }

初始化合约

String contractAddress = "合约地址";
BigInteger gasPrice = getPrice(Web3j web3j);

以太坊私链是什么_sitesohu.com 以太坊公链私链_以太经典是以太坊的分叉币吗

BigInteger gasLimit = BigInteger.valueOf(80_000); Contract erc20 = Contract.load(contractAddress, web3j, credentials, gasPrice, gasLimit );

注意:这里GasLimit设置为默认10KWei以太坊私链是什么,GasPrice获取当前链上的实时GasPrice

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

RemoteCall balanceOf = erc20.balanceOf("以太坊账户地址");

以太经典是以太坊的分叉币吗_以太坊私链是什么_sitesohu.com 以太坊公链私链

CompletableFuture sendAsync = balanceOf.sendAsync(); System.out.println(sendAsync.get());

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

调用合约转账方法

BigInteger price = BigInteger.valueOf(10_000_000);

以太经典是以太坊的分叉币吗_以太坊私链是什么_sitesohu.com 以太坊公链私链

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

注意:由于此处以太坊手续费不同,打包时间可能不同。 这里需要注意

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