Search code examples
javascriptethereumweb3jstruffle

Why "invalid sender" (-32000) when trying to deploy an Ethereum smart contract from node script?


Trying to deploy my smart contract to the rinkeby network but I am receiving this error message { code: -32000, message: 'invalid sender' }.

I tried deploying my contract via Remix and it worked fine but I am a bit lost on why I am receiving this error.

const HDWalletProvider = require("@truffle/hdwallet-provider"); // "^1.2.4"
const Web3 = require("web3"); // "^1.3.4"
const compiledFactory = require("./build/factory.json");
const abi = compiledFactory.abi;
const bytecode = compiledFactory.evm.bytecode.object;

const provider = new HDWalletProvider({
  mnemonic: {
    phrase:
      "twelve word mnemonic phrase twelve word mnemonic phrase twelve word mnemonic phrase",
  },
  providerOrUrl: "https://rinkeby.infura.io/v3/12345678",
});
const web3 = new Web3(provider);

const deploy = async () => {
  const accounts = await web3.eth.getAccounts();

  console.log("Attempting to deploy from account", accounts[0]);
  try {
    const result = await new web3.eth.Contract(abi)
      .deploy({ data: bytecode })
      .send({ from: accounts[0], gas: "1000000" });
    console.log("Contract deployed to", result.options.address);
  } catch (e) {
    console.error(e);
  }
};

deploy();

Solution

  • Got it to work. Problem is, the transaction has to be signed before sending it. Here is the updated deploy function.

    const deploy = async () => {
      const accounts = await web3.eth.getAccounts();
      const deploymentAccount = accounts[0];
      const privateKey = provider.wallets[
        deploymentAccount.toLowerCase()
      ].privateKey.toString("hex");
    
      console.log("Attempting to deploy from account", deploymentAccount);
    
      try {
        let contract = await new web3.eth.Contract(abi)
          .deploy({
            data: bytecode,
            arguments: [],
          })
          .encodeABI();
    
        let transactionObject = {
          gas: 4000000,
          data: contract,
          from: deploymentAccount,
          // chainId: 3,
        };
    
        let signedTransactionObject = await web3.eth.accounts.signTransaction(
          transactionObject,
          "0x" + privateKey
        );
    
        let result = await web3.eth.sendSignedTransaction(
          signedTransactionObject.rawTransaction
        );
        console.log("Contract deployed to", result.contractAddress);
      } catch (e) {
        console.error(e);
      }
    
      process.exit(1);
    };