【web3.js】如何在真实发送交易前取得交易hash

我为什么要提前获取交易hash?

我不想unlockAccount来解锁账号,所以需要用私钥来签名交易后发送,所以使用web3.eth.sendSignedTransaction

但是web3.eth.sendSignedTransaction 是在交易被打包之后才得到返回值,我无法在交易未打包之前获得交易hash. 注. 貌似马上会有返回hash的功能了: Add ‘txHash’ field to the result of ‘accounts.signTransaction’ #2694
【web3.js】如何在真实发送交易前取得交易hash_第1张图片
但是实际开发中不可能等每一步交易都被打包了之后,才进行使用,所以需要先获得交易hash

直接上方法:

web3.utils.sha3(serializedTx)

serializedTx如何获取:
官方文档

var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')

var rawTx = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  //data: 若是调用合约则为abi
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}

var tx = new Tx(rawTx);
tx.sign(privateKey);

var serializedTx = tx.serialize();

// console.log(serializedTx.toString('hex'));
// 0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f

 // 提前获取交易hash
  web3.utils.sha3(serializedTx).then(
         txHash =>{
             console.log("txHash: ",txHash)
         }
     );

//发送交易
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);

OK,完成~!

你可能感兴趣的:(以太坊)