Search code examples
expressweb3js

Web3js raw transaction is being sent twice


I am sending a raw transaction to Ropsten test network with web3js module in node. The web3s code lives on an express back end. Here is the code:

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;

The .post looks like this

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

The transaction is successful and returns a json with all relevant block data. about 2-3 minutes later, the same transaction is sent and mined on Ropsten. About the time that the second transaction is mined, my console (the request is sent through an http from browser) shows the following errors:

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)

This didn't happen until I added

const hashValue = req.body.hash,
fileName = req.body.fileName,
value = req.body.value;

to the code.

Any ideas?


Solution

  • This doesn't answer why the double transaction was happening, but a work around is to put next() at the end of the code.