Uncaught TypeError: Cannot read properties of undefined (reading 'utils')

2.4k Views Asked by At

I am trying to generate random cryptographic keys, but when I try to run my app, it results to this error in my browser console Uncaught TypeError: Cannot read properties of undefined (reading 'utils').

Here is my code:

import secp from "ethereum-cryptography/secp256k1";
import { keccak256 } from "ethereum-cryptography/keccak";
import { toHex } from "ethereum-cryptography/utils";

const privateKey = secp.utils.randomPrivateKey();
console.log('Private key:', toHex(privateKey));

const publicKey = secp.getPublicKey(privateKey);
console.log('Public key:', toHex(publicKey));

const address = (keccak256(publicKey.slice(1)).slice(-20));
console.log('Ethereum public key:', toHex(address));

function GenerateKey() {
    return (
        <div>
            <p>Private key: {privateKey}</p>
            <p>Public key: {publicKey}</p>
            <p>Address: {address}</p>
        </div>
    )
}

export default GenerateKey;

Please how can I fix this?

3

There are 3 best solutions below

2
Pavel Sturov On

Try to use imports like this:

import {
  getPublicKey,
  utils,
} from 'ethereum-cryptography/secp256k1'

And then generate your keys:

const privateKey = utils.randomPrivateKey()

const publicKey = getPublicKey(privateKey) 

You get an error because ethereum-cryptography/secp256k1 path doesn't have a default export.

Another approach is to use * as construction:

import * as secp from 'ethereum-cryptography/secp256k1'

const privateKey = secp.utils.randomPrivateKey()

const publicKey = secp.getPublicKey(privateKey)
0
Edna On

Try importing the secp as secp256k1 as shown below:

Change line 1 to:

import { secp256k1 } from 'ethereum-cryptography/secp256k1';

Change line 5 to:

const privateKey = secp256k1.utils.randomPrivateKey();

Change line 8 to:

const publicKey = secp256k1.getPublicKey(privateKey);

This is because of the updates that were made on the secp256k1 module. Before, it was using the noble-secp256k1 1.7 and now it is using the safer noble-curve. Please refer to the upgrading section from curves README.

I hope this was helpful.

1
user22392433 On

Try replacing import secp from "ethereum-cryptography/secp256k1";

by const { secp256k1 } = require("ethereum-cryptography/secp256k1.js");

and instead of secp.utils ... use secp256k1.utils