Creating Wallet / ETH Address using Ether.js
To create new ETH Address, we can use some library like ethers.js . It enable us to interacting with the Ethereum Blockchain and its ecosystem.
Sample Code to Create New ETH Address (Node.JS)
const ethers = require('ethers');
const wallet = ethers.Wallet.createRandom();
console.log('address:', wallet.address);
console.log('mnemonic:', wallet.mnemonic.phrase);
console.log('privateKey:', wallet.privateKey);
Result :
address: 0xb985d345c4bb8121cE2d18583b2a28e98D56d04b
mnemonic: produce alley citizen bone enact settle hedgehog common plate dwarf lady someone
privateKey: 0x49723865a8ab41e5e8081839e33dff15ab6b0125ba3acc82c25df64e8a8668f5
We can also restore user’s wallet / address by using mnemonic:
const { Wallet } = require('ethers');
const wallet = Wallet.fromMnemonic('one two three four ...');
Or using mnemonic to create new Eth Address.
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 we want to get the second account, we 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, we 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`);
Later, we can use service like Alchemy or Infura as Provider to interact with Ethereum API
Thanks!!