web3j版本:
<groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>4.8.4</version>
操作:erc20转币操作
区块链网络:使用了币安BSC测试网
主代码如下: `
public static String transferErc20(String from, String to, String value, String privateKey, String contractAddress, int decimal) {
try {
//转账的凭证,需要传入私钥
Credentials credentials = Credentials.create(privateKey);
//获取交易笔数
BigInteger nonce;
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from,DefaultBlockParameterName.LATEST).sendAsync().get();
if (ethGetTransactionCount == null) {
return null;
}
nonce = ethGetTransactionCount.getTransactionCount();
//手续费
BigInteger gasPrice;
EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
if (ethGasPrice == null) {
return null;
}
gasPrice = ethGasPrice.getGasPrice();
//获取最后一个区块对应gaslimit做参考
EthBlock.Block block = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
Long chainId = web3j.ethChainId().send().getChainId().longValue();
BigInteger gasLimit = block.getGasLimit();
BigInteger val = new BigDecimal(value).multiply(new BigDecimal("10").pow(decimal)).toBigInteger();// 单位换算
Function function = new Function(
"transfer",
Arrays.asList(new Address(to), new Uint256(val)),
Collections.singletonList(new TypeReference<Type>() {
}));
//创建交易对象
String encodedFunction = FunctionEncoder.encode(function);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
contractAddress, encodedFunction);
//进行签名操作
byte[] signMessage = TransactionEncoder.signMessage(rawTransaction,chainId, credentials);
String hexValue = Numeric.toHexString(signMessage);
//发起交易,广播交易!
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
// hash 可以通过这个查询交易状态
String hash = ethSendTransaction.getTransactionHash();
if (hash != null) {
//执行业务
System.out.printf("执行成功:" + hash);
return hash;
}
} catch (Exception ex) {
//报错应进行错误处理
ex.printStackTrace();
}
return null;
}
` 报错如下:
这里尝试过手工设置了gaslimit 任意大小,仍提示exceeds block gas limit,请教如何解决,谢谢
获取gasLimit 是否有更好的方式