Search code examples
javascriptweb3jsethers.js

How to get a Wallet from a mnemonic phrase?


I need to migrate a project from ethers.js to web3js, but I can't find any clear documentation on how to use web3js with mnemonic phrases. For example:

const provider = new StaticJsonRpcProvider(process.env.RPC_URL);

const wallet = Wallet.fromMnemonic(mnemonic).connect(provider);
                       ^^^^^^^^^^ equivalent in web3.js???

Solution

  • web3js currently (v1.8) doesn't support generating private keys from mnemonic.

    As a workaround, you can use Truffle's hdwallet-provider that accepts a mnemonic and an RPC URL.

    const HDWalletProvider = require("@truffle/hdwallet-provider");
    const Web3 = require("web3");
    
    let provider = new HDWalletProvider({
        mnemonic: {
            phrase: "test test test test test test test test test test test junk"
        },
        providerOrUrl: "https://mainnet.infura.io/v3/<your_api_key>"
    });
    
    const web3 = new Web3(provider);