Ethers.js – How to Change Default Wallet Address in Ethers.js

ethers.js

I am trying to change the default address used by the wallet to send transactions.

let wallet = Wallet.fromMnemonic('hurdle cloud ...').connect(provider);

wallet.address // 0xfB98c...

How do I change the wallet's address to another address from the same private key? I feel like this should be obvious but digging through the documentation it doesn't appear possible.

Edit

Given that a single private key only has a single public key (and public address), the question needs adjusting. How would it be possible to generate new private keys (and therefore public addresses) from this mnemonic using ethers.js?

Best Answer

You can use an HDNode which is defined as:

A Hierarchical Deterministic Wallet represents a large tree of private keys which can reliably be reproduced from an initial seed. Each node in the tree is represented by an HDNode which can be descended into.

When you use this HDNode, you can change the path variable you give it in order to get different private/public key pairs that are derived from this HDNode.

You can learn more about the path variable here. For Ethereum wallets, the default address / private key used is at path: m/44'/60'/0'/0/0. To follow the outlined protocol, for ethereum addresses, you can change the account and/or index fields: m/44'/60'/1'/0/0 m/44'/60'/0'/0/1

let HDNode = require('ethers').utils.HDNode;

let mnemonic = "radar blur cabbage chef fix engine embark joy scheme fiction master release";

let masterNode = HDNode.fromMnemonic(mnemonic);

let standardEthereum = masterNode.derivePath("m/44'/60'/0'/0/0");

console.log(standardEthereum.publicKey);
console.log(standardEthereum.privateKey);

//account 0 index 1
let accountZeroIndexOne = masterNode.derivePath("m/44'/60'/0'/0/1");
console.log(accountZeroIndexOne.publicKey);
console.log(accountZeroIndexOne.privateKey);
Related Topic