Search code examples
blockchainsolidityweb3jshardhat

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


Following the guide from https://ethereum.org/vi/developers/tutorials/hello-world-smart-contract/

I am getting this error when trying to run my deploy script. I am absolutely lost as to why this is not working as I have copied every piece of code directly from the guide.

My 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}`]
      }
   },
}

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

my .env

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

It compiles fine but gives me the error when I use the command

npx hardhat run scripts/deploy.js --network ropsten

Solution

  • You don't need the 0x in the private key, just put the exact key you got from metamask :)