foundry_wallets/
wallet.rs

1use crate::{raw_wallet::RawWalletOpts, utils, wallet_signer::WalletSigner};
2use alloy_primitives::Address;
3use clap::Parser;
4use eyre::Result;
5use serde::Serialize;
6
7/// The wallet options can either be:
8/// 1. Raw (via private key / mnemonic file, see `RawWallet`)
9/// 2. Ledger
10/// 3. Trezor
11/// 4. Keystore (via file path)
12/// 5. AWS KMS
13/// 6. Google Cloud KMS
14#[derive(Clone, Debug, Default, Serialize, Parser)]
15#[command(next_help_heading = "Wallet options", about = None, long_about = None)]
16pub struct WalletOpts {
17    /// The sender account.
18    #[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    /// Use the keystore in the given folder or file.
31    #[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    /// Use a keystore from the default keystores folder (~/.foundry/keystores) by its filename
40    #[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    /// The keystore password.
50    ///
51    /// Used with --keystore.
52    #[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    /// The keystore password file path.
61    ///
62    /// Used with --keystore.
63    #[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    /// Use a Ledger hardware wallet.
73    #[arg(long, short, help_heading = "Wallet options - hardware wallet")]
74    pub ledger: bool,
75
76    /// Use a Trezor hardware wallet.
77    #[arg(long, short, help_heading = "Wallet options - hardware wallet")]
78    pub trezor: bool,
79
80    /// Use AWS Key Management Service.
81    #[arg(long, help_heading = "Wallet options - remote", hide = !cfg!(feature = "aws-kms"))]
82    pub aws: bool,
83
84    /// Use Google Cloud Key Management Service.
85    #[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 signer = if self.ledger {
94            utils::create_ledger_signer(self.raw.hd_path.as_deref(), self.raw.mnemonic_index)
95                .await?
96        } else if self.trezor {
97            utils::create_trezor_signer(self.raw.hd_path.as_deref(), self.raw.mnemonic_index)
98                .await?
99        } else if self.aws {
100            let key_id = std::env::var("AWS_KMS_KEY_ID")?;
101            WalletSigner::from_aws(key_id).await?
102        } else if self.gcp {
103            let project_id = std::env::var("GCP_PROJECT_ID")?;
104            let location = std::env::var("GCP_LOCATION")?;
105            let keyring = std::env::var("GCP_KEYRING")?;
106            let key_name = std::env::var("GCP_KEY_NAME")?;
107            let key_version = std::env::var("GCP_KEY_VERSION")?.parse()?;
108            WalletSigner::from_gcp(project_id, location, keyring, key_name, key_version).await?
109        } else if let Some(raw_wallet) = self.raw.signer()? {
110            raw_wallet
111        } else if let Some(path) = utils::maybe_get_keystore_path(
112            self.keystore_path.as_deref(),
113            self.keystore_account_name.as_deref(),
114        )? {
115            let (maybe_signer, maybe_pending) = utils::create_keystore_signer(
116                &path,
117                self.keystore_password.as_deref(),
118                self.keystore_password_file.as_deref(),
119            )?;
120            if let Some(pending) = maybe_pending {
121                pending.unlock()?
122            } else if let Some(signer) = maybe_signer {
123                signer
124            } else {
125                unreachable!()
126            }
127        } else {
128            eyre::bail!(
129                "\
130Error accessing local wallet. Did you set a private key, mnemonic or keystore?
131Run the command with --help flag for more information or use the corresponding CLI
132flag to set your key via:
133--private-key, --mnemonic-path, --aws, --gcp, --interactive, --trezor or --ledger.
134Alternatively, when using the `cast send` or `cast mktx` commands with a local node
135or RPC that has unlocked accounts, the --unlocked or --ethsign flags can be used,
136respectively. The sender address can be specified by setting the `ETH_FROM` environment
137variable to the desired unlocked account address, or by providing the address directly
138using the --from flag."
139            )
140        };
141
142        Ok(signer)
143    }
144}
145
146impl From<RawWalletOpts> for WalletOpts {
147    fn from(options: RawWalletOpts) -> Self {
148        Self { raw: options, ..Default::default() }
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use alloy_signer::Signer;
156    use std::{path::Path, str::FromStr};
157
158    #[tokio::test]
159    async fn find_keystore() {
160        let keystore =
161            Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../cast/tests/fixtures/keystore"));
162        let keystore_file = keystore
163            .join("UTC--2022-12-20T10-30-43.591916000Z--ec554aeafe75601aaab43bd4621a22284db566c2");
164        let password_file = keystore.join("password-ec554");
165        let wallet: WalletOpts = WalletOpts::parse_from([
166            "foundry-cli",
167            "--from",
168            "560d246fcddc9ea98a8b032c9a2f474efb493c28",
169            "--keystore",
170            keystore_file.to_str().unwrap(),
171            "--password-file",
172            password_file.to_str().unwrap(),
173        ]);
174        let signer = wallet.signer().await.unwrap();
175        assert_eq!(
176            signer.address(),
177            Address::from_str("ec554aeafe75601aaab43bd4621a22284db566c2").unwrap()
178        );
179    }
180
181    #[tokio::test]
182    async fn illformed_private_key_generates_user_friendly_error() {
183        let wallet = WalletOpts {
184            raw: RawWalletOpts {
185                interactive: false,
186                private_key: Some("123".to_string()),
187                mnemonic: None,
188                mnemonic_passphrase: None,
189                hd_path: None,
190                mnemonic_index: 0,
191            },
192            from: None,
193            keystore_path: None,
194            keystore_account_name: None,
195            keystore_password: None,
196            keystore_password_file: None,
197            ledger: false,
198            trezor: false,
199            aws: false,
200            gcp: false,
201        };
202        match wallet.signer().await {
203            Ok(_) => {
204                panic!("illformed private key shouldn't decode")
205            }
206            Err(x) => {
207                assert!(
208                    x.to_string().contains("Failed to decode private key"),
209                    "Error message is not user-friendly"
210                );
211            }
212        }
213    }
214}