美文网首页
以太币转账

以太币转账

作者: 徐亮亮2333 | 来源:发表于2018-08-31 13:21 被阅读0次

node js

https://www.npmjs.com/package/web3

npm install web3

https://www.npmjs.com/package/ethereumjs-tx

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)
      }
    });
  });
};

相关文章

网友评论

      本文标题:以太币转账

      本文链接:https://www.haomeiwen.com/subject/sruswftx.html