Error: Expected private key to be an Uint8Array with length 32

Error: Expected private key to be an Uint8Array with length 32

遵循 https://ethereum.org/vi/developers/tutorials/hello-world-smart-contract/

中的指南

我在尝试 运行 我的部署脚本时遇到此错误。我完全不知道为什么这不起作用,因为我直接从指南中复制了每一段代码。

我的hardhat.config.js

require('dotenv').config();

require("@nomiclabs/hardhat-ethers");
const { API_URL, PRIVATE_KEY } = process.env;

/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
   solidity: "0.7.3",
   defaultNetwork: "ropsten",
   networks: {
      hardhat: {},
      ropsten: {
         url: API_URL,
         accounts: [`0x${PRIVATE_KEY}`]
      }
   },
}

我的deploy.js

async function main() {
    const HelloWorld = await ethers.getContractFactory("HelloWorld");
 
    // Start deployment, returning a promise that resolves to a contract object
    const hello_world = await HelloWorld.deploy("Hello World!");
    console.log("Contract deployed to address:", hello_world.address);}
 
 main()
   .then(() => process.exit(0))
   .catch(error => {
     console.error(error);
     process.exit(1);
   });
 

我的.env

API_URL = "https://eth-ropsten.alchemyapi.io/v2/[REDACTED]"
PRIVATE_KEY = "[REDACTED]".  // my private key goes here, not including the 0x

它编译得很好但是当我使用命令时给我错误

npx 安全帽 运行 scripts/deploy.js --network ropsten

你不需要私钥中的 0x,只需输入你从 metamask 获得的确切密钥 :)

https://github.com/ethereumjs/ethereumjs-tx

根据使用示例,我们需要在创建交易时添加链名称。

const tx = new Tx(txObject , { chain: 'rinkeby' })