In addition to @dapp-deep 's answer, I would like to add a bit renewed answer, as the Account
from @solana/web.js
is depreciated now and instead we can use KeyPair
.
- bip39.mnemonicToSeed(mnemonic): This line uses the bip39 library to convert the mnemonic phrase (a sequence of easy-to-remember words) into a seed buffer (a fixed-length binary value).
2.Buffer.from(seed).toString('hex'): The seed buffer is then converted to a hexadecimal string representation.
const path44Change = \m/44'/501'/0'/0'
;: This line defines a derivation path using the BIP44 standard. The path m/44'/501'/0'/0'` is specific to the Solana cryptocurrency and represents the following:
m
stands for the master key (root of the derivation path).
44'
is the purpose field, indicating that the derived keys will be used for a coin-type purpose.
501'
is the coin-type field, which specifies the cryptocurrency (501 is the assigned value for Solana).
0'
is the account field, typically used to represent different accounts derived from the same seed.
0'
is the change field, usually used to differentiate between external and internal/change addresses.
const derivedSeed = derivePath(path44Change, seedBuffer).key;
: This line uses an unspecified derivePath
function to derive a new seed from the provided derivation path and the seed buffer. The key property of the returned object is assigned to derivedSeed
.
const kp = Keypair.fromSeed(derivedSeed);
: Finally, the Keypair.fromSeed
method from the Solana library is used to create a new keypair object (kp
) from the derived seed.
return kp;
: The function returns the generated keypair object, which contains both the public and private keys.
The derivation path is necessary because it provides a standardized way to derive multiple keypairs from a single seed (the mnemonic phrase) in a deterministic and reproducible manner. This is particularly useful in cryptocurrency wallets, where multiple addresses can be generated from the same mnemonic, allowing for better organization and management of funds.
By following the BIP44 standard, the derivation path ensures that the derived keys are compatible with other wallets and tools that follow the same standard. It also provides a level of isolation between different types of coins or accounts, reducing the risk of accidental fund transfers or key reuse.
Below is the code needed:
import * as bip39 from "bip39";
import {
Keypair,
Connection,
} from "@solana/web3.js";
import { derivePath } from 'ed25519-hd-key';
async function getKeyCreatedBySolanaKeygenFromMnemonic(mnemonic: string) {
const seed = await bip39.mnemonicToSeed(mnemonic);
const seedBuffer = Buffer.from(seed).toString('hex');
const path44Change = `m/44'/501'/0'/0'`;
const derivedSeed = derivePath(path44Change, seedBuffer).key;
const kp = Keypair.fromSeed(derivedSeed);
return kp;
}