4

I want to understand how Ethereum works and i want to calculate the public key and wallet address from private key.

I have read this tutorial: https://piyopiyo.medium.com/generating-an-ethereum-wallet-with-an-existing-private-key-5cda690a8eb8

Here is the code:

var Wallet = require('ethereumjs-wallet');
var EthUtil = require('ethereumjs-util');
const privateKeyString = '0x...MyPrivateKey...';
const privateKeyBuffer = EthUtil.toBuffer(privateKeyString);
const wallet = Wallet.fromPrivateKey(privateKeyBuffer);
const publicKey = wallet.getPublicKeyString();
console.log(publicKey);
const address = wallet.getAddressString();
console.log(address);

It sounds great but i have this runtime error:

TypeError: Wallet.fromPrivateKey is not a function

I think this is because ethereumjs-wallet has changed in the latest versions. But how can i load a private key with latest version ?

Thanks

1
  • const wallet = Wallet.fromPrivateKey(privateKeyBuffer); generates "TypeError: Wallet.fromPrivateKey is not a function"
    – ekkis
    Sep 14, 2022 at 0:56

2 Answers 2

2

const wallet = Wallet['default'].fromPrivateKey(privateKeyBuffer);

replace this in line5

var Wallet = require('ethereumjs-wallet');
var EthUtil = require('ethereumjs-util');
const privateKeyString = '0x...MyPrivateKey...';//your privateKey
const privateKeyBuffer = EthUtil.toBuffer(privateKeyString);
const wallet = Wallet['default'].fromPrivateKey(privateKeyBuffer);
const publicKey = wallet.getPublicKeyString();
console.log(publicKey);
const address = wallet.getAddressString();
console.log(address);
1

ethereumjs-wallet doesn´t have a default export. You can import Wallet like this in Node.js:

const { Wallet } = require('ethereumjs-wallet')

You can find the docs here: https://github.com/ethereumjs/ethereumjs-wallet#wallet-api

2
  • This time i get this error: "TypeError: Cannot read property 'fromPrivateKey' of undefined"
    – Bob5421
    Apr 5, 2021 at 17:25
  • it's wrong. there is no Wallet element exported. if you look at it, it's called "default"
    – ekkis
    Sep 14, 2022 at 1:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.