UNPKG

1.3 kBJavaScriptView Raw
1import { hasBigInt } from '@polkadot/util';
2import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
3import { mnemonicToSeedSync } from './bip39.js';
4import { mnemonicValidate } from './validate.js';
5/**
6 * @name mnemonicToLegacySeed
7 * @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
8 * @example
9 * <BR>
10 *
11 * ```javascript
12 * import { mnemonicGenerate, mnemonicToLegacySeed, mnemonicValidate } from '@polkadot/util-crypto';
13 *
14 * const mnemonic = mnemonicGenerate(); // => string
15 * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
16 *
17 * if (isValidMnemonic) {
18 * console.log(`Seed generated from mnemonic: ${mnemonicToLegacySeed(mnemonic)}`); => u8a
19 * }
20 * ```
21 */
22export function mnemonicToLegacySeed(mnemonic, password = '', onlyJs, byteLength = 32) {
23 if (!mnemonicValidate(mnemonic)) {
24 throw new Error('Invalid bip39 mnemonic specified');
25 }
26 else if (![32, 64].includes(byteLength)) {
27 throw new Error(`Invalid seed length ${byteLength}, expected 32 or 64`);
28 }
29 return byteLength === 32
30 ? !hasBigInt || (!onlyJs && isReady())
31 ? bip39ToSeed(mnemonic, password)
32 : mnemonicToSeedSync(mnemonic, password).subarray(0, 32)
33 : mnemonicToSeedSync(mnemonic, password);
34}