为了防止交易重复进行,以太坊要求每笔交易必须有一个nonce数值。nonce值从0开始递增,每发送一笔交易,nonce便加1。
交易处理从nonce值较小的开始,所以nonce的值太大的话,交易会被延迟处理。
如何合理的获取nonce的值:向以太坊节点获取。
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
public void testTransferEther() throws ExecutionException, InterruptedException {
EthCoinbase coinbase = web3j.ethCoinbase().sendAsync().get();
final String formAddress = coinbase.getAddress(); final String formKey = "58e7f34b59a828d1dc37a97a921b55de0cb8cedea91b1e09b490f39264b151ce"; final String toAddress = "0x9958eC47C8286DC89F5CbCbD842458bD43540a7D";
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount( formAddress, DefaultBlockParameterName.LATEST).sendAsync().get(); BigInteger nonce = ethGetTransactionCount.getTransactionCount();
BigInteger value = Convert.toWei("0.5", Convert.Unit.ETHER).toBigInteger(); Log.e(TAG, "transaction nonce: " + nonce );
RawTransaction rawTransaction = RawTransaction.createEtherTransaction( nonce, GAS_PRICE, GAS_LIMIT, toAddress, value); Credentials credentials = Credentials.create(formKey); byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); String hexValue = Numeric.toHexString(signedMessage); EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get(); Log.e(TAG, "transactionHash: " + ethSendTransaction.getTransactionHash()); }
|
参考: 以太坊实战之《如何正确处理nonce》