5 使用web3j 进行erc20转币,gasLimit无论设置多大都提示:exceeds block gas limit

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&lt;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;
}

` 报错如下:

截屏2022-10-23 下午11.27.33.png

这里尝试过手工设置了gaslimit 任意大小,仍提示exceeds block gas limit,请教如何解决,谢谢

获取gasLimit 是否有更好的方式

请先 登录 后评论

最佳答案 2022-10-24 11:40

gas limit 使用错误. 你取的是这个块所有 tx 允许的 gas limit. 如何预估 gaslimit , 使用 EstimateGas 方法获取. 或者干脆固定写 50W .

请先 登录 后评论

其它 1 个回答

daydream
请先 登录 后评论
  • 2 关注
  • 0 收藏,7477 浏览
  • daydream 提出于 2022-10-23 23:39