首页 > 解决方案 > 以太坊交易给出错误“无效发件人”

问题描述

我的合同是这样的——

pragma solidity >=0.4.25 <0.8.0;


contract Calculator {
    uint public result;

    event Added(address caller, uint a, uint b, uint res);

    constructor() public {
        result = 777;
    }

    function add(uint a, uint b) public returns (uint, address) {
        result = a + b;
        emit Added(msg.sender, a, b, result);
        return (result, msg.sender);
    }
}

上述合约部署在 Ropsten 测试网上。我正在尝试add(...)使用事务调用该函数。我的代码看起来像这样 -

const accountAddress = rtUtil.getAccountAddress();
const accountPk = Buffer.from(rtUtil.getAccountAddressPk(), "hex");
const contract = await rtUtil.getCalculatorContract();
const data = contract.methods.add(3, 74).encodeABI();

const web3 = rtUtil.getWeb3();
const taxCount = await web3.eth.getTransactionCount(accountAddress);

const txObject = {
   nonce: web3.utils.toHex(taxCount),
   to: rtUtil.getCalculatorContractAddress(),
   value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
   gasLimit: web3.utils.toHex(2100000),
   gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
   data: data
};

const commmon = new Common({chain: "ropsten", hardfork: "petersburg"});
const tx = Transaction.fromTxData(txObject, {commmon});
tx.sign(accountPk);

const serializedTx = tx.serialize();
const raw = web3.utils.toHex(serializedTx);
const transaction = await web3.eth.sendSignedTransaction(raw);

当我运行代码时,我得到错误 -

Uncaught Error: Returned error: invalid sender
Process exited with code 1

我的 Nodejs 版本是v15.1.0

我的package.json依赖是 -

"dependencies": {
  "@ethereumjs/common": "^2.0.0",
  "@ethereumjs/tx": "^3.0.0",
  "@truffle/contract": "^4.2.30",
  "@truffle/hdwallet-provider": "^1.2.0",
  "web3": "^1.3.0"
}

谁能告诉我我做错了什么?

提前致谢。

标签: ethereumsolidityweb3js

解决方案


在您的 txObject 中,您需要指定链 id。

将 Ropsten 的链 id,3 添加到 txObject 中。

const txObject = {
   nonce: web3.utils.toHex(taxCount),
   to: rtUtil.getCalculatorContractAddress(),
   value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
   gasLimit: web3.utils.toHex(2100000),
   gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
   data: data,
   chainId: web3.utils.toHex(3)
};

推荐阅读