Web3.js 发送ERC20转账交易

web3 1.0 版本以下的用法:

var Web3 = require("web3");
var Tx = require('ethereumjs-tx');

var web3 = new Web3();

// 连接测试网络
web3.setProvider(new web3.providers.HttpProvider("https://ropsten.infura.io/v3/18b6909fdc9b4ba0af..."));

web3.eth.defaultAccount = "0x2b54...";

var abi = ...;

var TokenContract = web3.eth.contract(abi);
var contractId = '0xa7f705022c15cc56a809bd399...';
var mytt = TokenContract.at(contractId);

// 转账
var addr_from = "0x2b547f3098408f0...";
var addr_to = "0xee57d615459bf95...";

var count = web3.eth.getTransactionCount(addr_from);
var data = mytt.transfer.getData(addr_to,
                1000000,
                {from: addr_from});

var gasPrice = web3.eth.gasPrice;
var gasLimit = 90000;

var rawTransaction = {
    "from": addr_from,
    "nonce": web3.toHex(count),
    "gasPrice": web3.toHex(gasPrice),
    "gasLimit": web3.toHex(gasLimit),
    "to": contractId,
    "value": "0x0",
    "data": data,
};

// 用私钥签名交易信息
var privateKey = new Buffer.from('512F597B114...', 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privateKey);
var tx_serialize = tx.serialize();

// 发送交易
web3.eth.sendRawTransaction('0x' + tx_serialize.toString('hex'), 
    function(err, data) {
        if (!err)
            console.log("tx hash: " + data);
        else
            console.log("error: " + err);
});

web3 1.0 的用法:

var addr_from = "0x2B547F3098408F06...";
var addr_to = "0x42d053BDe9ef2B40...";

// 读取私钥,这里不包含‘0x’两个字符
var privKey = new Buffer.from('512F597B11432...', 'hex');

web3.eth.getTransactionCount(addr_from, (err, txCount) => {

  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(800000), // Raise the gas limit to a much higher amount
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
    to: contractId,
    data: mytt.methods.transfer(addr_to, 1200000).encodeABI()
  }

  const tx = new Tx(txObject)
  tx.sign(privKey)

  const serializedTx = tx.serialize()
  const raw = '0x' + serializedTx.toString('hex')

  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    console.log('err:', err, 'txHash:', txHash)
    res.send("ok " + txHash);
  })
})

web3js API 文档:
http://web3.tryblockchain.org/Web3.js-api-refrence.html

你可能感兴趣的:(Web3.js 发送ERC20转账交易)