前端写web3.js调用钱包发送交易的例子
时间: 2023-03-22 17:01:25 浏览: 130
以下是使用Web3.js调用钱包发送交易的一个简单例子:
```
const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'));
// 设置账户私钥和地址
const account = {
address: 'YOUR-ADDRESS',
privateKey: Buffer.from('YOUR-PRIVATE-KEY', 'hex')
};
// 设置转账信息
const toAddress = 'RECIPIENT-ADDRESS';
const value = web3.utils.toWei('1', 'ether');
// 获取账户的交易数
web3.eth.getTransactionCount(account.address, (err, txCount) => {
if (err) {
console.error(err);
return;
}
// 构造交易对象
const txObject = {
nonce: web3.utils.toHex(txCount),
to: toAddress,
value: web3.utils.toHex(value),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
};
// 签名交易
const tx = new Tx(txObject, { 'chain': 'mainnet' });
tx.sign(account.privateKey);
// 序列化交易对象
const serializedTx = tx.serialize();
const rawTx = '0x' + serializedTx.toString('hex');
// 发送交易
web3.eth.sendSignedTransaction(rawTx, (err, txHash) => {
if (err) {
console.error(err);
return;
}
console.log(`Transaction hash: ${txHash}`);
});
});
```
在这个例子中,我们使用Web3.js连接到以太坊主网的Infura节点,设置了发送交易的账户地址和私钥,以及转账信息,构造交易对象,签名交易并序列化交易对象,最后发送交易。请注意,在实际使用中,您需要替换上面的变量和值为您自己的信息。