10

I want to convert a 24 words length seed phrase into a private key using web3.

viarnes
  • 268
  • 1
  • 2
  • 10

1 Answers1

25

Here are two options:

Using ethers.js - the example below uses a mnemonic ethers wallet documentation

const ethers = require('ethers');
let mnemonic = "YOUR MNEMONIC";
let mnemonicWallet = ethers.Wallet.fromMnemonic(mnemonic);
console.log(mnemonicWallet.privateKey);

This doesn't seem to be included in web3, but has been added to the list of enhancements for 2.0. There are some options described in this thread.

Update Mar 31, 2022

As of ethers@6.2.3, the api now uses fromPhrase instead of fromMnemonic:

const ethers = require("ethers");
const mnemonic = "YOUR MNEMONIC";
const mnemonicWallet = ethers.Wallet.fromPhrase(mnemonic);
console.log(mnemonicWallet.privateKey);
0xPingo
  • 135
  • 1
  • 7
Steven V
  • 1,461
  • 10
  • 15
  • Code works but I'm not getting the expected result. FYI I'm using a MyEtherWallet recovery phrase as mnemonic. – viarnes Jan 24 '20 at 21:56
  • 1
    Updated answer and tested. This seems to be working. I created a MyEthersWallet, used this code with the mnemonic from mew. Then I used the logged private key to add the account in metamask and I got the same address. Sorry for the initial answer. – Steven V Jan 24 '20 at 23:48
  • 1
    this is great! was able to convert SafePal mnemonic and old MEW keystore into private keys enabling mirroring of accounts in Metamask and SafePal! needed an extra lib called 'keythereum' and everything worked smooth! – 4UmNinja Mar 29 '21 at 08:30
  • You need to also look into derivation paths. The resulting private keys would differ according to the derivation paths configured. – Ahmed Ihsan Tawfeeq Aug 19 '21 at 06:28
  • 1
    As of ethers@6.2.3 the api is now Wallet.fromPhrase(mnemonic) – 0xPingo Mar 31 '23 at 04:03
  • 1
    How about with Foundry instead of Ethers? I there a way? – currenthandle Jun 17 '23 at 00:33
  • https://book.getfoundry.sh/reference/forge-std/derive-remember-key @currenthandle – Steven V Jul 13 '23 at 10:34