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

Bob5421
  • 1,457
  • 1
  • 12
  • 38
  • const wallet = Wallet.fromPrivateKey(privateKeyBuffer); generates "TypeError: Wallet.fromPrivateKey is not a function" – ekkis Sep 14 '22 at 00:56

2 Answers2

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);
Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82
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

Morten
  • 6,017
  • 2
  • 12
  • 26