0

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?

0

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);
| improve this answer | |
  • Thank you. It worked like a charm! – Luis Lopez Jun 29 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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