Jahid Shohel
Jahid Shohel

Reputation: 1485

Ethereum transaction giving error 'invalid sender'

This is how my contract looks like -

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);
    }
}

Above contract is deployed on Ropsten test net. And I am trying to invoke the add(...) function with a transaction. And my code looks like this -

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);

And when I run the code I get error -

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

My Nodejs versions is v15.1.0

And my package.json dependencies are -

"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"
}

Can anyone tell me what I am doing wrong?

Thanks in advance.

Upvotes: 4

Views: 9406

Answers (2)

Ming
Ming

Reputation: 775

In your txObject, you need to specific the chain id.

Add Ropsten's chain id, 3 into 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)
};

Upvotes: 10

SimonR
SimonR

Reputation: 1824

You need to include from in your txObject:

const txObject = {
   from: accountAddress,
   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
};

Upvotes: 1

Related Questions