为什么在尝试从节点脚本部署以太坊智能合约时 "invalid sender" (-32000)?

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

正在尝试将我的智能合约部署到 rinkeby 网络,但我收到此错误消息 { code: -32000, message: 'invalid sender' }.

我尝试通过 Remix 部署我的合同并且它工作正常但我有点迷失为什么我会收到这个错误。

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

开始使用了。问题是,交易必须在发送前签名。这是更新后的部署函数。

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