1use crate::{raw_wallet::RawWalletOpts, utils, wallet_signer::WalletSigner};
2use alloy_primitives::Address;
3use clap::Parser;
4use eyre::Result;
5use serde::Serialize;
6
7#[derive(Clone, Debug, Default, Serialize, Parser)]
15#[command(next_help_heading = "Wallet options", about = None, long_about = None)]
16pub struct WalletOpts {
17 #[arg(
19 long,
20 short,
21 value_name = "ADDRESS",
22 help_heading = "Wallet options - raw",
23 env = "ETH_FROM"
24 )]
25 pub from: Option<Address>,
26
27 #[command(flatten)]
28 pub raw: RawWalletOpts,
29
30 #[arg(
32 long = "keystore",
33 help_heading = "Wallet options - keystore",
34 value_name = "PATH",
35 env = "ETH_KEYSTORE"
36 )]
37 pub keystore_path: Option<String>,
38
39 #[arg(
41 long = "account",
42 help_heading = "Wallet options - keystore",
43 value_name = "ACCOUNT_NAME",
44 env = "ETH_KEYSTORE_ACCOUNT",
45 conflicts_with = "keystore_path"
46 )]
47 pub keystore_account_name: Option<String>,
48
49 #[arg(
53 long = "password",
54 help_heading = "Wallet options - keystore",
55 requires = "keystore_path",
56 value_name = "PASSWORD"
57 )]
58 pub keystore_password: Option<String>,
59
60 #[arg(
64 long = "password-file",
65 help_heading = "Wallet options - keystore",
66 requires = "keystore_path",
67 value_name = "PASSWORD_FILE",
68 env = "ETH_PASSWORD"
69 )]
70 pub keystore_password_file: Option<String>,
71
72 #[arg(long, short, help_heading = "Wallet options - hardware wallet")]
74 pub ledger: bool,
75
76 #[arg(long, short, help_heading = "Wallet options - hardware wallet")]
78 pub trezor: bool,
79
80 #[arg(long, help_heading = "Wallet options - remote", hide = !cfg!(feature = "aws-kms"))]
82 pub aws: bool,
83
84 #[arg(long, help_heading = "Wallet options - remote", hide = !cfg!(feature = "gcp-kms"))]
86 pub gcp: bool,
87}
88
89impl WalletOpts {
90 pub async fn signer(&self) -> Result<WalletSigner> {
91 trace!("start finding signer");
92
93 let get_env = |key: &str| {
94 std::env::var(key)
95 .map_err(|_| eyre::eyre!("{key} environment variable is required for signer"))
96 };
97
98 let signer = if self.ledger {
99 utils::create_ledger_signer(self.raw.hd_path.as_deref(), self.raw.mnemonic_index)
100 .await?
101 } else if self.trezor {
102 utils::create_trezor_signer(self.raw.hd_path.as_deref(), self.raw.mnemonic_index)
103 .await?
104 } else if self.aws {
105 let key_id = get_env("AWS_KMS_KEY_ID")?;
106 WalletSigner::from_aws(key_id).await?
107 } else if self.gcp {
108 let project_id = get_env("GCP_PROJECT_ID")?;
109 let location = get_env("GCP_LOCATION")?;
110 let keyring = get_env("GCP_KEYRING")?;
111 let key_name = get_env("GCP_NAME")?;
112 let key_version = get_env("GCP_KEY_VERSION")?
113 .parse()
114 .map_err(|_| eyre::eyre!("GCP_KEY_VERSION could not be parsed into u64"))?;
115 WalletSigner::from_gcp(project_id, location, keyring, key_name, key_version).await?
116 } else if let Some(raw_wallet) = self.raw.signer()? {
117 raw_wallet
118 } else if let Some(path) = utils::maybe_get_keystore_path(
119 self.keystore_path.as_deref(),
120 self.keystore_account_name.as_deref(),
121 )? {
122 let (maybe_signer, maybe_pending) = utils::create_keystore_signer(
123 &path,
124 self.keystore_password.as_deref(),
125 self.keystore_password_file.as_deref(),
126 )?;
127 if let Some(pending) = maybe_pending {
128 pending.unlock()?
129 } else if let Some(signer) = maybe_signer {
130 signer
131 } else {
132 unreachable!()
133 }
134 } else {
135 eyre::bail!(
136 "\
137Error accessing local wallet. Did you pass a keystore, hardware wallet, private key or mnemonic?
138
139Run the command with --help flag for more information or use the corresponding CLI
140flag to set your key via:
141
142--keystore
143--interactive
144--private-key
145--mnemonic-path
146--aws
147--gcp
148--trezor
149--ledger
150
151Alternatively, when using the `cast send` or `cast mktx` commands with a local node
152or RPC that has unlocked accounts, the --unlocked or --ethsign flags can be used,
153respectively. The sender address can be specified by setting the `ETH_FROM` environment
154variable to the desired unlocked account address, or by providing the address directly
155using the --from flag."
156 )
157 };
158
159 Ok(signer)
160 }
161}
162
163impl From<RawWalletOpts> for WalletOpts {
164 fn from(options: RawWalletOpts) -> Self {
165 Self { raw: options, ..Default::default() }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use alloy_signer::Signer;
173 use std::{path::Path, str::FromStr};
174
175 #[tokio::test]
176 async fn find_keystore() {
177 let keystore =
178 Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../cast/tests/fixtures/keystore"));
179 let keystore_file = keystore
180 .join("UTC--2022-12-20T10-30-43.591916000Z--ec554aeafe75601aaab43bd4621a22284db566c2");
181 let password_file = keystore.join("password-ec554");
182 let wallet: WalletOpts = WalletOpts::parse_from([
183 "foundry-cli",
184 "--from",
185 "560d246fcddc9ea98a8b032c9a2f474efb493c28",
186 "--keystore",
187 keystore_file.to_str().unwrap(),
188 "--password-file",
189 password_file.to_str().unwrap(),
190 ]);
191 let signer = wallet.signer().await.unwrap();
192 assert_eq!(
193 signer.address(),
194 Address::from_str("ec554aeafe75601aaab43bd4621a22284db566c2").unwrap()
195 );
196 }
197
198 #[tokio::test]
199 async fn illformed_private_key_generates_user_friendly_error() {
200 let wallet = WalletOpts {
201 raw: RawWalletOpts {
202 interactive: false,
203 private_key: Some("123".to_string()),
204 mnemonic: None,
205 mnemonic_passphrase: None,
206 hd_path: None,
207 mnemonic_index: 0,
208 },
209 from: None,
210 keystore_path: None,
211 keystore_account_name: None,
212 keystore_password: None,
213 keystore_password_file: None,
214 ledger: false,
215 trezor: false,
216 aws: false,
217 gcp: false,
218 };
219 match wallet.signer().await {
220 Ok(_) => {
221 panic!("illformed private key shouldn't decode")
222 }
223 Err(x) => {
224 assert!(
225 x.to_string().contains("Failed to decode private key"),
226 "Error message is not user-friendly"
227 );
228 }
229 }
230 }
231}