1use crate::{
2 DEFAULT_CACHE_ACCOUNTS,
3 account::derive_and_cache_addresses,
4 utils::{
5 ensure_no_wallet_exists, request_new_password, write_wallet_from_mnemonic_and_password,
6 },
7};
8use anyhow::{Result, bail};
9use clap::Args;
10use fuels::{accounts::signers::derivation::DEFAULT_DERIVATION_PATH, crypto::SecretKey};
11use std::io::stdin;
12
13#[derive(Debug, Args)]
14pub struct Import {
15 #[clap(short, long)]
17 pub force: bool,
18 #[clap(short, long)]
20 pub cache_accounts: Option<usize>,
21}
22
23fn check_mnemonic(mnemonic: &str) -> Result<()> {
25 if SecretKey::new_from_mnemonic_phrase_with_path(mnemonic, DEFAULT_DERIVATION_PATH).is_err() {
27 bail!("Cannot generate a wallet from provided mnemonics, please check your mnemonic phrase")
28 }
29 Ok(())
30}
31
32pub async fn import_wallet_cli(ctx: &crate::CliContext, import: Import) -> Result<()> {
33 ensure_no_wallet_exists(&ctx.wallet_path, import.force, stdin().lock())?;
34 let mnemonic = rpassword::prompt_password("Please enter your mnemonic phrase: ")?;
35 check_mnemonic(&mnemonic)?;
36 let password = request_new_password();
37 write_wallet_from_mnemonic_and_password(&ctx.wallet_path, &mnemonic, &password)?;
38 derive_and_cache_addresses(
39 ctx,
40 &mnemonic,
41 0..import.cache_accounts.unwrap_or(DEFAULT_CACHE_ACCOUNTS),
42 )
43 .await?;
44 Ok(())
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50 use crate::utils::test_utils::TEST_MNEMONIC;
51
52 #[test]
53 fn check_mnemonic_should_succeed() {
54 assert!(check_mnemonic(TEST_MNEMONIC).is_ok())
55 }
56
57 #[test]
58 fn check_mnemonic_should_fail() {
59 let invalid_mnemonic = "this is an invalid mnemonic";
60 assert!(check_mnemonic(invalid_mnemonic).is_err())
61 }
62}