const bip39 = require ( "bip39" ) ; const bip32 = require ( "bip32" ) ; import { Buffer } from "buffer/" ; export type RNG = < T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null > ( array : T ) => Promise < T > ; export class Mnemonic { static async generateWallet ( rng , path = `m/44'/118'/0'/0/0` , password = "" , strength = 256 ) { const mnemonic = await Mnemonic . generateSeed ( rng , strength ) ; const privKey = Mnemonic . generateWalletFromMnemonic ( mnemonic , path , password ) ; return { privKey , mnemonic , } ; } static validateMnemonic ( mnemonic ) { bip39 . validateMnemonic ( mnemonic ) ; } static async generateSeed ( rng , strength = 128 ) { if ( strength % 32 !== 0 ) { throw new TypeError ( "invalid entropy" ) ; } let bytes = new Uint8Array ( strength / 8 ) ; bytes = await rng ( bytes ) ; return bip39 . entropyToMnemonic ( Buffer . from ( bytes ) . toString ( "hex" ) ) ; } static generateWalletFromMnemonic ( mnemonic , path = `m/44'/118'/0'/0/0` , password = "" ) { const seed = bip39 . mnemonicToSeedSync ( mnemonic , password ) ; const masterKey = bip32 . fromSeed ( seed ) ; const hd = masterKey . derivePath ( path ) ; const privateKey = hd . privateKey ; if ( ! privateKey ) { throw new Error ( "null hd key" ) ; } return privateKey ; } }