【问题标题】:Web3js raw transaction is being sent twiceWeb3js 原始事务被发送两次
【发布时间】:2023-04-08 23:27:01
【问题描述】:

我正在向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;

到代码。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: express web3 web3js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2013-09-18
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多