Appearance
执行交易
交易步骤:
- 构建交易对象
- 交易签名
- 交易广播
1. 构建交易对象
js
let Web3 = require("web3")
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:8545"))
// 发送者地址
const fromAddress = '0x123...';
// 接收者地址
const toAddress = '0x456...';
// 发送的金额
const etherAmount = web3.utils.toWei('1', 'ether');
// gas 配置
const gasPrice = web3.utils.toWei('10', 'gwei');
const gasLimit = 21000;
const transactionObject = {
from: fromAddress,
to: toAddress,
value: etherAmount,
gasPrice: gasPrice,
gas: gasLimit
};
2. 签署交易
js
// 使用私钥签名
const privateKey = '0xabc...';
const signedTransaction = web3.eth.accounts.signTransaction(transactionObject, privateKey)
.then((signedTx) => {
console.log(signedTx.rawTransaction);
})
.catch((error) => {
console.log(error);
});
3. 广播交易
js
web3.eth.sendSignedTransaction(signedTransaction.rawTransaction)
.on('transactionHash', (txHash) => {
console.log(`Transaction Hash: ${txHash}`);
})
.on('receipt', (receipt) => {
console.log(`Transaction Receipt: ${receipt}`);
})
.on('error', console.error);
on('transactionHash', callback)
: 在交易发送后获取交易哈希on('receipt', callback)
: 交易被确认并包含在区块中后获取该交易的收据信息