[Ethereum] “Invalid Chain Id” on Kovan testnet

ethereumjs-txkovantransactionsweb3js

I'm attempting to initiate a transaction (transfer of ETH) from my main account to a test account on the Kovan Testnet, but I'm getting the error Returned error: Invalid chain id. from the following code:

const Web3 = require("web3");
const EthereumTx = require("ethereumjs-tx").Transaction;

const SK = process.env.PROD ? nice try ;)
const PK = process.env.PROD ? "0x5A8721b7DE69b3538a4cC61614628f7c1A6E59Fb"
  : "0x33Bcd8bf72D594B0974beFd830a29CeC55079976";
const url = process.env.PROD ? "https://kovan.infura.io/v3/2bd0c2e1f29f4ab9b47374c6b50023c5"
  : "http://127.0.0.1:8545";

const web3Provider = new Web3.providers.HttpProvider(url);
const web3 = new Web3(web3Provider);
const { toWei, numberToHex: toHex } = web3.utils;

const sendETH = async () => {
  const nonce = await web3.eth.getTransactionCount(PK);
  const tx = new EthereumTx({
    from: PK,
    to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
    value: toHex(toWei(".1")),
    gas: toHex("21000"),
    nonce,
  });
  tx.sign(Buffer.from(SK, "hex"));
  const serializedTx = tx.serialize();
  web3.eth.sendSignedTransaction("0x" + serializedTx.toString("hex"));
}
sendETH();

When I set PROD to false (testing on local network), it works fine. However I get that stubborn error every time I set the PROD to true (testing on Kovan).

Best Answer

Hey you need to do this for testing on kovan

const tx = new EthereumTx({
    from: PK,
    chainId: 42, // kovan chain id
    to: "0x8631c939359FBb8cb336532b191ED80b20287CD1",
    value: toHex(toWei(".1")),
    gas: toHex("21000"),
    nonce,
  });