20 如何使用私钥离线签名发起一笔合约调用交易?

我在使用web3准备开发一个后台的程序定时自动调用一些合约, web3.js 的文档没明白, 能否写一段实例代码, 谢谢。

请先 登录 后评论

最佳答案 2020-01-22 10:14

// 构造出合约调用交易

var contract = new web3.eth.Contract(contractJson, contractAddress);
var transfer = contract.methods.transfer("0x...", 490);
var encodedABI = transfer.encodeABI();
var tx = {
    from: "0x...",
    to: contractAddress,
    gas: 2000000,
    data: encodedABI
  }; 

 // 对交易签名
web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
    var tran = web3.eth.sendSignedTransaction(signed.rawTransaction);
    tran.on('confirmation', (confirmationNumber, receipt) => {
      console.log('confirmation: ' + confirmationNumber);
    });
    tran.on('transactionHash', hash => {
      console.log('hash');
      console.log(hash);
    });
    tran.on('receipt', receipt => {
      console.log('reciept');
      console.log(receipt);
    });
    tran.on('error', console.error);
  });
请先 登录 后评论

其它 2 个回答

Allen - 区块链测试 工程师
请先 登录 后评论
Elliott
请先 登录 后评论