Skip to content

Commit

Permalink
feat: add deafult path when cast new wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
kien6034 committed Oct 26, 2024
1 parent 6913a3d commit 31537dc
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 62 deletions.
103 changes: 41 additions & 62 deletions crates/cast/bin/cmd/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub enum WalletSubcommands {
/// Password for the JSON keystore in cleartext.
///
/// This is UNSAFE to use and we recommend using the --password.
#[arg(long, requires = "path", env = "CAST_PASSWORD", value_name = "PASSWORD")]
#[arg(long, env = "CAST_PASSWORD", value_name = "PASSWORD")]
unsafe_password: Option<String>,

/// Number of wallets to generate.
Expand Down Expand Up @@ -221,77 +221,56 @@ impl WalletSubcommands {
match self {
Self::New { path, unsafe_password, number, json, .. } => {
let mut rng = thread_rng();

let mut json_values = if json { Some(vec![]) } else { None };
if let Some(path) = path {
let path = match dunce::canonicalize(path.clone()) {
Ok(path) => path,
// If the path doesn't exist, it will fail to be canonicalized,
// so we attach more context to the error message.

// Determine the path to use
let path = if let Some(path) = path {
match dunce::canonicalize(path.clone()) {
Ok(path) => {
if !path.is_dir() {
eyre::bail!("`{}` is not a directory", path.display());
}
path
}
Err(e) => {
eyre::bail!("If you specified a directory, please make sure it exists, or create it before running `cast wallet new <DIR>`.\n{path} is not a directory.\nError: {}", e);
}
};
if !path.is_dir() {
// we require path to be an existing directory
eyre::bail!("`{}` is not a directory", path.display());
}
} else {
// Use the default keystore directory if no path is provided
let default_path = Config::foundry_keystores_dir().ok_or_else(|| {
eyre::eyre!("Could not find the default keystore directory.")
})?;
fs::create_dir_all(&default_path)?;
default_path
};

let password = if let Some(password) = unsafe_password {
password
} else {
// if no --unsafe-password was provided read via stdin
rpassword::prompt_password("Enter secret: ")?
};

for _ in 0..number {
let (wallet, uuid) = PrivateKeySigner::new_keystore(
&path,
&mut rng,
password.clone(),
None,
)?;
let password = if let Some(password) = unsafe_password {
password
} else {
rpassword::prompt_password("Enter secret: ")?
};

if let Some(json) = json_values.as_mut() {
json.push(json!({
"address": wallet.address().to_checksum(None),
"path": format!("{}", path.join(uuid).display()),
}
));
} else {
sh_println!(
"Created new encrypted keystore file: {}",
path.join(uuid).display()
)?;
sh_println!("Address: {}", wallet.address().to_checksum(None))?;
}
}
for _ in 0..number {
let (wallet, uuid) =
PrivateKeySigner::new_keystore(&path, &mut rng, password.clone(), None)?;

if let Some(json) = json_values.as_ref() {
sh_println!("{}", serde_json::to_string_pretty(json)?)?;
}
} else {
for _ in 0..number {
let wallet = PrivateKeySigner::random_with(&mut rng);

if let Some(json) = json_values.as_mut() {
json.push(json!({
"address": wallet.address().to_checksum(None),
"private_key": format!("0x{}", hex::encode(wallet.credential().to_bytes())),
}))
} else {
sh_println!("Successfully created new keypair.")?;
sh_println!("Address: {}", wallet.address().to_checksum(None))?;
sh_println!(
"Private key: 0x{}",
hex::encode(wallet.credential().to_bytes())
)?;
}
if let Some(json) = json_values.as_mut() {
json.push(json!({
"address": wallet.address().to_checksum(None),
"path": format!("{}", path.join(uuid).display()),
}));
} else {
sh_println!(
"Created new encrypted keystore file: {}",
path.join(uuid).display()
)?;
sh_println!("Address: {}", wallet.address().to_checksum(None))?;
}
}

if let Some(json) = json_values.as_ref() {
sh_println!("{}", serde_json::to_string_pretty(json)?)?;
}
if let Some(json) = json_values.as_ref() {
sh_println!("{}", serde_json::to_string_pretty(json)?)?;
}
}
Self::NewMnemonic { words, accounts, entropy, json } => {
Expand Down
11 changes: 11 additions & 0 deletions crates/cast/tests/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,17 @@ Created new encrypted keystore file: [..]
]);
});

// tests that we can create a new wallet with keystore
casttest!(new_wallet_default_keystore_with_password, |_prj, cmd| {
cmd.args(["wallet", "new", "--unsafe-password", "test"]).assert_success().stdout_eq(str![[
r#"
Created new encrypted keystore file: [..]
[ADDRESS]
"#
]]);
});

// tests that we can get the address of a keystore file
casttest!(wallet_address_keystore_with_password_file, |_prj, cmd| {
let keystore_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/keystore");
Expand Down

0 comments on commit 31537dc

Please sign in to comment.