9

I am new using ethers.js

const { Wallet } = require('ethers');
const wallet = Wallet.fromMnemonic('one two three four ...');

I want to use that code to recover all the accounts from that Mnemonic. Maybe it is something that I do not understand quite well but it is just retrieving the first account for that Mnemonic.

How do I recover all the accounts?

3 Answers 3

18

The Wallet.fromMnemonic function has a second argument to specify the BIP-32 derivation path. By default it will use m/44'/60'/0'/0/0, but if you want to get the second account, you can use m/44'/60'/0'/0/1 for example:

const { Wallet } = require('ethers');
const wallet = Wallet.fromMnemonic('one two three four ...', `m/44'/60'/0'/0/1`);

Alternatively, you can use the HDNode class to quickly derive child keys from a mnemonic phrase. For example:

const { utils } = require('ethers');
const hdNode = utils.HDNode.fromMnemonic('one two three four ...');

const secondAccount = hdNode.derivePath(`m/44'/60'/0'/0/1`); // This returns a new HDNode
const thirdAccount = hdNode.derivePath(`m/44'/60'/0'/0/2`);

The HDNode can also be used to get an instance of Wallet. This is also what Wallet.fromMnemonic does.

const wallet = new Wallet(hdNode);
0
3

In the newer ethers version, this is slightly changed.

const { ethers }  = require('ethers');

const mnemonic = "one two three four .....";
const hdNode = ethers.HDNodeWallet.fromPhrase(mnemonic);

const secondAccount = hdNode.derivePath(`m/44'/60'/0'/0/1`);
const thirdAccount = hdNode.derivePath(`m/44'/60'/0'/0/2`);

console.log(secondAccount.address);
console.log(thirdAccount.address);
3

If you're struggling to recover all accounts created by Metamask, here is the solution (ethers.js v6):

const ethers = require("ethers");

const phrase = "YOUR_PHRASE";

const mnemonic = ethers.Mnemonic.fromPhrase(phrase);

for (let index = 0; index < 10; index++) {
    const wallet = ethers.HDNodeWallet.fromMnemonic(mnemonic, `m/44'/60'/0'/0/${index}`);
    console.log(wallet.address);
}

Your Answer

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

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