前言
求其区块链团队出品
旗下网站
- Web3js 教程:web3js.cn
- Hardhat 中文网: hardhat.cn
执行交易
交易步骤:
- 构建交易对象
- 交易签名
- 交易广播
1. 构建交易对象
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. 签署交易
// 使用私钥签名
const privateKey = '0xabc...';
const signedTransaction = web3.eth.accounts.signTransaction(transactionObject, privateKey)
.then((signedTx) => {
console.log(signedTx.rawTransaction);
})
.catch((error) => {
console.log(error);
});
3. 广播交易
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): 交易被确认并包含在区块中后获取该交易的收据信息