Error: Only replay-protected (EIP-155) transactions allowed over RPC

Viewed 1227

When I try to send funds from a token address to another I encounter this error: only replay-protected (EIP-155) transactions allowed over RPC

My Code:

const contract = new web3.eth.Contract(ABI, token_contract_address);

const data = contract.methods.transfer(to, req.body.value).encodeABI();

const rawTransaction = {
    'from': from,
    'nonce': web3.utils.toHex(web3.eth.getTransactionCount(from)),
    'gasPrice': web3.utils.toHex(web3.eth.gasPrice),
    'gasLimit': web3.utils.toHex(21000),
    'to': token_contract_address,
    'value': 0,
    'data': data,
    'chainId': web3.utils.toHex(chainid)
};

const privateKey = new Buffer.from(req.body.PrivateKey, 'hex');
const tx = new Tx(rawTransaction);
tx.sign(privateKey);

const serializedTx = tx.serialize();
web3.eth.sendSignedTransaction(('0x' + serializedTx.toString('hex')), req.body.PrivateKey)
    .then(function (result) {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(result * decimals);
        console.log(result);
    })
    .catch((err) => next(err));

Notice I have already added ChainId

1 Answers

Here is an excellent example that looks like yours and should definitely work. What I think is happening here, is that there are already some pending transactions, so that your current nonce is causing this error message. Some small steps that might solve your issue and improve your code:

  • Change value from 0 to 0x00, this should also be hex encoded. Or you could leave it out, because you are also sending data.

  • Alternatively you could set value to something like web3.utils.toHex(web3.utils.toWei('123', 'wei')).

  • Create the nonce with web3.eth.getTransactionCount(account.address, 'pending');. This would also include pending transactions to the count so that they are not used twice.

  • And what is the reason why you are adding req.body.PrivateKey to sendSignedTransaction(..)? Just adding the serialized transaction that you signed before is enough: '0x' + serializedTx.toString('hex').

  • It is not clear what your current chainId is. Try running your code on another chain to see if that works.

    • Ropsten = 3
    • Rinkeby = 4
  • Finally, update all your dependencies / the tools you are using. Changes in packages may sometimes cause issues like this.

You'll find another excellent example here.

Related