Web3js原始事务被发送两次

时间:2018-12-12 02:07:07

标签: express web3 web3js

我正在使用节点中的Ropsten模块将原始交易发送到web3测试网络。 web3代码位于express后端。这是代码:

var express = require(“ express”); var router = express.Router();

var Tx = require("ethereumjs-tx");
const Web3 = require("web3");
const web3 = new Web3(
  "https://ropsten.infura.io/v3/d55489f8ea264a1484c293b05ed7eb85"
);

const abi = [...];
const contractAddress = "0x15E1ff7d97CB0D7C054D19bCF579e3147FC9009b";
const myAccount = "0x59f568176e21EF86017EfED3660625F4397A2ecE";
const privateKey1 = new Buffer(
  "...",
  "hex"
);

hashValue = "newly updated value";

router.post("/", function(req, res, next) {
  const hashValue = req.body.hash,
    fileName = req.body.fileName,
    value = req.body.value;

  const contract = new web3.eth.Contract(abi, contractAddress, {
    from: myAccount
  });

  web3.eth.getTransactionCount(myAccount, (err, txCount) => {
    //Smart contract data
    const data = contract.methods
      .setHashValue(value + fileName + hashValue)
      .encodeABI();

    // Build the transaction
    const txObject = {
      nonce: web3.utils.toHex(txCount),
      gasLimit: web3.utils.toHex(1000000),
      gasPrice: 20000000000,
      data: data,
      from: myAccount,
      to: contractAddress
    };

    // Sign the transaction
    const tx = new Tx(txObject);
    tx.sign(privateKey1);

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

    // Broadcast the transaction
    web3.eth
      .sendSignedTransaction("0x" + serializedTx.toString("hex"))
      .on("receipt", console.log, receipt => {
        callback(receipt);
      })
      .then(() => {
        res.json({ transactionHash });
      })
      .catch(() => {
        // fail
      });
  });
});

module.exports = router;

.post看起来像这样

axios.post(
        "http://compute.amazonaws.com:3000/users",
        {
          value: "value",
          fileName: "fileName",
          hash: "hash"
        }
      );

交易成功,并返回带有所有相关块数据的json。大约2-3分钟后,同一交易在Ropsten上发送并进行了挖掘。大约在第二笔交易被开采时,我的控制台(请求是通过浏览器的http发送的)显示以下错误:

POST http://ec2-54-67-28-69.us-west-1.compute.amazonaws.com:3000/users net::ERR_EMPTY_RESPONSE

createError.js:17 Uncaught (in promise) Error: Network Error
    at createError (createError.js:17)
    at XMLHttpRequest.handleError (xhr.js:87)

直到我添加

,这种情况才发生
const hashValue = req.body.hash,
fileName = req.body.fileName,
value = req.body.value;

输入代码。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这不能回答为什么发生双重事务,但是一种解决方法是将next()放在代码的末尾。嗯......