5 java使用org.web3j 版本5.0.0;通过web3.ethGetTransactionCount()获取nonce;通过RawTransaction.createTransaction()构建交易;通过RawTransactionManager.signAndSend()发送交易;上链失败,返回错误{ code:-32000, message:"replacement transaction underpriced" }

关键代码如下:

     Credentials credentials = Credentials.create(privateKey);
                BigInteger nonce = web3.ethGetTransactionCount(ChainInfoConfig.getBaseAddress(), DefaultBlockParameterName.LATEST).sendAsync().get().getTransactionCount();
                BigInteger gasPrice = web3.ethGasPrice().send().getGasPrice();
                BigInteger chainId = web3.ethChainId().send().getChainId();
                String methodName = "transferFrom";
                List<Type> inputParameters = new ArrayList<>();
                inputParameters.add(new Address(transferUsdtParam.getFrom()));
                inputParameters.add(new Address(transferUsdtParam.getTo()));
                inputParameters.add(new Uint256(transferUsdtParam.getAmount()));
                List<TypeReference<?>> outputParameters = new ArrayList<>();

                Function function = new Function(methodName, inputParameters, outputParameters);
                String encodedFunction = FunctionEncoder.encode(function);
                RawTransactionManager rawTransactionManager = new RawTransactionManager(web3, credentials, Long.valueOf(chainId + ""));

                RawTransaction rawTransaction = RawTransaction.createTransaction(
                        nonce,
                        gasPrice,
                        TRANSFER_GAS_LIMIT,
                        ChainInfoConfig.getUsdtContractAddress(),
                        encodedFunction);
                transactionResponse = rawTransactionManager.signAndSend(rawTransaction);

报错内容:

{
code:-32000,
message:"replacement transaction underpriced"
}

根据多笔交易分析: nonce出现相同情况; 问题分析:

通过
BigInteger nonce = web3.ethGetTransactionCount(ChainInfoConfig.getBaseAddress(), DefaultBlockParameterName.LATEST).sendAsync().get().getTransactionCount()
获取nonce方式是否有问题,如果有问题怎么调整?
===============================================================
RawTransaction rawTransaction = RawTransaction.createTransaction(
                        nonce,
                        gasPrice,
                        TRANSFER_GAS_LIMIT,
                        ChainInfoConfig.getUsdtContractAddress(),
                        encodedFunction)
 携带nonce构建新交易nonce是否需要手动nonce+1?出现失败原因感觉就是相同地址nonce的问题?求解。
请先 登录 后评论

最佳答案 2023-10-17 09:45

直接是用获取的 getTransactionCount 作为下一个交易的 nonce 即可: https://docs.web3j.io/4.10.0/transactions/transaction_nonce/

使用 pending 参数时,包含未打包的交易。

你的错误提示有 replacement , 说明你在覆盖上一个交易,并且给的gas 很低。

请先 登录 后评论

其它 0 个回答

  • 1 关注
  • 0 收藏,1829 浏览
  • 提出于 2023-10-11 15:13