准备好了账号,就可以执行转账交易了。
交易可分为3个步骤:
- 构建交易对象
- 签署交易
- 广播交易
构建交易对象
const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}
参数解释:
nonce
– 这是账号的前一个交易计数。这个值必须是十六进制,可以使用Web3.js的web3.utils.toHex()
转换。to
– 目标账户。value
– 要发送的以太币金额。这个值必须以十六进制表示,单位必须是wei。我们可以使用Web3.js工具web3.utils.toWei()
转换单位。gasLimit
– 交易能消耗Gas的上限。像这样的基本交易总是要花费21000单位的Gas。gasPrice
– Gas价格,这里是 10 Gwei。
注意,这个交易对象中没有from
字段。当使用account1
的私钥签署这个交易时,它将被推算出来。
现在为nonce
变量赋值,可以使用web3.eth.getTransactionCount()
函数获取交易nonce
。将构建交易对象的代码封装在一个回调函数中,如下所示:
web3.eth.getTransactionCount(account1, (err, txCount) => {
const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}
})
签署交易
接下来,需要签署交易:
const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTx = tx.serialize()
const raw = '0x' + serializedTx.toString('hex')
这里使用etheremjs-tx库来创建一个新的Tx对象,然后使用这个库与privateKey1
签署交易。接着,序列化交易并转换为十六进制字符串,以便将其传递给Web3。
广播交易
最后广播交易,可以使用web3.eth.sendSignedTransaction()
函数将这个已签名的序列化交易发送到测试网络,如下所示:
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
})
至此,我们完成了交易的执行。