node js
npm install web3
npm install ethereumjs-tx
let Web3 = require('web3');
let Tx = require('ethereumjs-tx');
// 账号
let currentAccount = (loc) => {
return loc;
};
export const EthTransfer = () => {
// 以太币转账
// 先获取当前账号交易的nonce
web3.eth.getTransactionCount(currentAccount("xxxxxxxxxxx"), web3.eth.defaultBlock.pending).then(function(nonce){
// 获取交易数据
let txData = {
// nonce每次++,以免覆盖之前pending中的交易
nonce: web3.utils.toHex(nonce++),
// 设置gasLimit和gasPrice
gasLimit: web3.utils.toHex(99000),
gasPrice: web3.utils.toHex(10e9),
// 要转账的哪个账号
to: 'xxxxxxxxxxx',
// 从哪个账号转
from: currentAccount("xxxxxxxxxx"),
// 0.001 以太币
value: web3.utils.toHex(web3.utils.toWei('0.001', 'ether')),
data: ''
}
let tx = new Tx(txData);
// 引入私钥,并转换为16进制
const privateKey = new Buffer('xxxxxxx', 'hex');
// 用私钥签署交易
tx.sign(privateKey);
// 序列化
let serializedTx = tx.serialize().toString('hex');
web3.eth.sendSignedTransaction(serializedTx.toString('hex'), function(err, hash) {
if (!err) {
alert(hash)
} else {
alert(err)
}
});
});
};
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。