处理智能合约交易快递nodejs

时间:2018-05-20 14:50:48

标签: node.js express ethereum solidity

我一直在编写我的小项目,但我遇到了问题。 这是我的代码:

app.get('/thu', (req, res) => {
  thu(function(err, output){
    if(err){
      res.json({"err": ""+err, "output": output});
      return;
    }
    res.send("ket qua: ", output);
  });
});
var thu = function(callback){
  web3.eth.getTransactionCount(senderAddress).then((txnCount) => {
    console.log("goi thu");
    var method = contract.methods.thu();
    var encodedABI = method.encodeABI();
    var thuTx = {
      from: senderAddress,
      to: contractAddress,
      nonce: web3.utils.toHex(txnCount),
      gasLimit: web3.utils.toHex(GAS_LIMIT),
      gasPrice: web3.utils.toHex(GAS_PRICE),
      data: encodedABI,
    };
    sendTxn(thuTx, callback);
  }).catch((err) => {
    console.log("web3 err", err);
    callback(err, null);
  });
};

function sendTxn(rawTx, callback) {
  var privateKeyBuffer = new Buffer(privateKey, 'hex');
  var transaction = new tx(rawTx);
  transaction.sign(privateKeyBuffer);
  var serializedTx = transaction.serialize().toString('hex');
  web3.eth.sendSignedTransaction(
  '0x' + serializedTx, function(err, txnHash) {
    if(err) {
      console.log("txn err", err);
      callback(err, null);
    } else {
      console.log("txn result", txnHash);
    }
  }).catch((err) => {
    callback(err, null);
  });
}

我确定我的智能合约运行正常。当我点击提交代码时,向Rinkeby发送一个交易即可。但我无法收到任何回复。 请帮助我解决我的问题。谢谢。

2 个答案:

答案 0 :(得分:0)

sendSignedTransaction返回Promise组合事件发射器。

  

以太坊作为区块链有不同程度的终结性   因此需要返回一个动作的多个“阶段”。应付   要求我们为像这样的函数返回一个“promiEvent”   web3.eth.sendTransaction或合同方法。这个“promiEvent”是一个   承诺结合事件发射器,允许在不同的行动   区块链的行动阶段,就像交易一样。

您可以在每个活动上放置一个console.log,以查看正在发生的事情,或者您是否收到错误。

web3.eth.sendSignedTransaction('0x' + serializedTx)
    .once('transactionHash', hash => console.log(`Hash: ${hash}`)
    .once('receipt', receipt => console.log(`Receipt: ${receipt}`)
    .on('confirmation', (confNumber, receipt) => console.log(confNumber))
    .on('error', error => console.error(error))
    .then(receipt => {
        // will be fired once the receipt its mined
    });

答案 1 :(得分:0)

问题解决了。问题是我忘了将回调(...)放在else {...}中。

相关问题