咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

12、Android通过web3j交易以太坊币

为了防止交易重复进行,以太坊要求每笔交易必须有一个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
/**
* 以太坊交易
* @throws ExecutionException
* @throws InterruptedException
*/
public void testTransferEther() throws ExecutionException, InterruptedException {

EthCoinbase coinbase = web3j.ethCoinbase().sendAsync().get();

//拨款地址,这里用coinbase账号的地址
final String formAddress = coinbase.getAddress();
//拨款账号的Key,Key是账号的身份验证,很重要
final String formKey = "58e7f34b59a828d1dc37a97a921b55de0cb8cedea91b1e09b490f39264b151ce";
//收款地址
final String toAddress = "0x9958eC47C8286DC89F5CbCbD842458bD43540a7D";

EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
formAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();

//转0.5个以太坊币
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》