1- import { existsSync , readFileSync } from "node:fs" ;
2- import { HDKey } from "@scure/bip32" ;
3- import { mnemonicToSeedSync , validateMnemonic } from "@scure/bip39" ;
4- import { wordlist } from "@scure/bip39/wordlists/english.js" ;
51import type { Command } from "commander" ;
62import { Wallet } from "xrpl" ;
73import {
84 encryptKeypair ,
95 encryptSeed ,
106 saveKeystore ,
117} from "../../lib/keystore.js" ;
8+ import { walletFromMnemonic } from "../../lib/mnemonic.js" ;
129import { output } from "../../lib/output.js" ;
1310import { prompt } from "../../lib/prompt.js" ;
1411import type { GlobalOptions } from "../../lib/types.js" ;
@@ -26,39 +23,6 @@ interface ImportOpts {
2623 mnemonicIndex ?: number ;
2724}
2825
29- function walletFromMnemonic (
30- mnemonic : string ,
31- opts : ImportOpts ,
32- ) : { wallet : Wallet ; publicKey : string ; privateKey : string } {
33- if ( ! validateMnemonic ( mnemonic , wordlist ) ) {
34- throw new Error ( "Invalid BIP39 mnemonic phrase." ) ;
35- }
36-
37- const passphrase = opts . mnemonicPassphrase ?? "" ;
38- const seed = mnemonicToSeedSync ( mnemonic , passphrase ) ;
39- const masterNode = HDKey . fromMasterSeed ( seed ) ;
40-
41- let derivationPath = opts . mnemonicDerivationPath ?? DEFAULT_DERIVATION_PATH ;
42- if ( opts . mnemonicIndex != null ) {
43- const parts = derivationPath . split ( "/" ) ;
44- parts [ parts . length - 1 ] = String ( opts . mnemonicIndex ) ;
45- derivationPath = parts . join ( "/" ) ;
46- }
47-
48- const node = masterNode . derive ( derivationPath ) ;
49- if ( ! node . publicKey || ! node . privateKey ) {
50- throw new Error (
51- `Unable to derive keys from mnemonic at path ${ derivationPath } ` ,
52- ) ;
53- }
54-
55- const publicKey = Buffer . from ( node . publicKey ) . toString ( "hex" ) . toUpperCase ( ) ;
56- const privateKey = `00${ Buffer . from ( node . privateKey ) . toString ( "hex" ) . toUpperCase ( ) } ` ;
57- const wallet = new Wallet ( publicKey , privateKey ) ;
58-
59- return { wallet, publicKey, privateKey } ;
60- }
61-
6226async function importWallet (
6327 name : string ,
6428 opts : ImportOpts ,
@@ -81,13 +45,8 @@ async function importWallet(
8145 const password = await getPassword ( opts ) ;
8246
8347 if ( hasMnemonic ) {
84- const mnemonicInput = opts . mnemonic ! ;
85- const mnemonic = existsSync ( mnemonicInput )
86- ? readFileSync ( mnemonicInput , "utf-8" ) . trim ( )
87- : mnemonicInput ;
88-
8948 const { wallet, publicKey, privateKey } = walletFromMnemonic (
90- mnemonic ,
49+ opts . mnemonic ! ,
9150 opts ,
9251 ) ;
9352 keystore = encryptKeypair (
0 commit comments