Cannot read properties of undefined (reading 'toHexString') in ether.js

Viewed 2372

Please don't judge, i've no idea what to do and how to do :)

My code: ether.js ( ^5.6.0)

import { ThirdwebSDK } from '@3rdweb/sdk'
import { ethers } from 'ethers'

const sdk = new ThirdwebSDK(
  new ethers.Wallet(
    process.env.METAMASK_PRIVATE_KEY,
    ethers.getDefaultProvider(
      'https://rinkeby.infura.io/v3/'
    )
  ) 
)

bug enter image description here

4 Answers

If you are using JavaScript and getting this error then You made a mistake while importing dotenv. you are using ".config" as property . Use it like a method like following

require("dotenv").config()

It will work.

Another problem you might have is where your .env is located. Make sure that your .env is in the same folder as your code.

You most likely messed up env variable. Check if METAMASK_PRIVATE_KEY is the correct name. Because otherwise it will throw undefined and one of the ethersjs library will try to run hexToString() method on undefined value, thus you get the error.

EDIT:

You might as well forget to include this in your code:

import {} from 'dotenv/config' 

// or if its not ESmodule 

require('dotenv').config()

Absence of this import will throw undefined as well when you access env variable.

I had this problem aswell. I used a constructor for my sol contract that looked as following:

constructor(
        address vrfCoordinatorV2,
        uint256 entranceFee,
        bytes32 gasLane,
        uint64 subscriptionId,
        uint32 callbackGasLimit,
        uint256 interval
    )

After alot of frustration i found out that my arguments for the deploy script wasn't lined up in the same order. This was causing the error:

"Cannot read properties of undefined (reading 'toHexString')"

In my case the arguments needed to be lined up as following:

const args = [
        vrfCoordinatorV2Address,
        networkConfig[chainId]["raffleEntranceFee"],
        networkConfig[chainId]["gasLane"],
        subscriptionId,
        networkConfig[chainId]["callbackGasLimit"],
        networkConfig[chainId]["keepersUpdateInterval"],
    ];
Related