How to Restore a Keypair from a Mnemonic

Many wallet extensions use mnemonics to represent their secret keys. You can convert the mnemonic to Keypairs for local testing.

Restoring BIP39 format mnemonics

import { createKeyPairSignerFromPrivateKeyBytes } from "@solana/kit";
import * as bip39 from "bip39";
const mnemonic =
"pill tomorrow foster begin walnut borrow virtual kick shift mutual shoe scatter";
const seed = bip39.mnemonicToSeedSync(mnemonic, "");
// Extract the first 32 bytes for the private key
const privateKeyBytes = seed.subarray(0, 32);
const signer = await createKeyPairSignerFromPrivateKeyBytes(
new Uint8Array(privateKeyBytes)
);
console.log(signer.address);
Click to execute the code.

Restoring BIP44 format mnemonics

import { HDKey } from "micro-ed25519-hdkey";
import * as bip39 from "bip39";
import { createKeyPairSignerFromPrivateKeyBytes } from "@solana/kit";
const mnemonic =
"neither lonely flavor argue grass remind eye tag avocado spot unusual intact";
const seed = bip39.mnemonicToSeedSync(mnemonic);
const hd = HDKey.fromMasterSeed(seed.toString("hex"));
for (let i = 0; i < 10; i++) {
const path = `m/44'/501'/${i}'/0'`;
const child = hd.derive(path);
const signer = await createKeyPairSignerFromPrivateKeyBytes(
new Uint8Array(child.privateKey)
);
// The signer object has the address directly
console.log(`${path} => ${signer.address}`);
}
Click to execute the code.

Is this page helpful?