构建交易对象
签署交易
广播交易
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。
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')
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
})