Search code examples
javascriptdotenv

When using dotenv to encrypt a private key in javaScript, I met an error: TypeError: Cannot read properties of undefined (reading 'toHexString')


This is encrypt.js

const ethers = require("ethers");
const fs = require("fs-extra");
require("dotenv").config();

async function main() {
  const wallet = new ethers.Wallet(process.env.RRIVATE_KEY);
  const encryptedJsonKey = await wallet.encrypt(
    process.env.PRIVATE_KEY_PASSWORD,
    process.env.PRIVATE_KEY
  );
  console.log(encryptedJsonKey);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

This is .env

PRIVATE_KEY=0x3ed74d4599fbc880e1f2dd094bf1dde078e808779f4f888d4b59a6d07bee99cb
RPC_URL=http://127.0.0.1:7545
PRIVATE_KEY_PASSWORD=password

This is error:TypeError: Cannot read properties of undefined (reading 'toHexString')

I tried to find how to fix the problem online. And Someone told that I should put all in one directory. However,I had done it. directory And if I put mouse on "PRIVATE_KEY_PASSWORD" or "PRIVATE_PASSWORD", it will show "string | undefined". Where is the issue?


I found the issue just now. There is a spelling mistake: const wallet = new ethers.Wallet(process.env.RRIVATE_KEY); Just change RRIVATE to PRIVATE. Sorry, my bad.


Solution

  • you are using a Hexadecimal number syntax here

    PRIVATE_KEY=0x3ed74d4599fbc880e1f2dd094bf1dde078e808779f4f888d4b59a6d07bee99cb
    

    so change this to a string like this

    PRIVATE_KEY=`0x3ed74d4599fbc880e1f2dd094bf1dde078e808779f4f888d4b59a6d07bee99cb`