Skip to main content

cast/cmd/wallet/
list.rs

1use clap::Parser;
2use eyre::Result;
3use foundry_cli::json::print_json_success;
4use foundry_common::{
5    fs,
6    fs::canonicalize_path,
7    sh_println, shell,
8    tempo::configurable_account::{
9        LINKED_ACCOUNT_SUFFIX, LinkedAccountFileState, linked_account_file_state,
10    },
11};
12use foundry_config::Config;
13use foundry_wallets::wallet_multi::MultiWalletOptsBuilder;
14use serde::Serialize;
15use std::{borrow::Cow, env};
16
17/// CLI arguments for `cast wallet list`.
18#[derive(Clone, Debug, Parser)]
19pub struct ListArgs {
20    /// List all the accounts in the keystore directory.
21    /// Default keystore directory is used if no path provided.
22    #[arg(long, default_missing_value = "", num_args(0..=1))]
23    dir: Option<String>,
24
25    /// List accounts from a Ledger hardware wallet.
26    #[arg(long, short, group = "hw-wallets")]
27    ledger: bool,
28
29    /// List accounts from a Trezor hardware wallet.
30    #[arg(long, short, group = "hw-wallets")]
31    trezor: bool,
32
33    /// List accounts from AWS KMS.
34    ///
35    /// Ensure either one of AWS_KMS_KEY_IDS (comma-separated) or AWS_KMS_KEY_ID environment
36    /// variables are set.
37    #[arg(long, hide = !cfg!(feature = "aws-kms"))]
38    aws: bool,
39
40    /// List accounts from Google Cloud KMS.
41    ///
42    /// Ensure the following environment variables are set: GCP_PROJECT_ID, GCP_LOCATION,
43    /// GCP_KEY_RING, GCP_KEY_NAME, GCP_KEY_VERSION.
44    ///
45    /// See: <https://cloud.google.com/kms/docs>
46    #[arg(long, hide = !cfg!(feature = "gcp-kms"))]
47    gcp: bool,
48
49    /// List accounts from Turnkey.
50    #[arg(long, hide = !cfg!(feature = "turnkey"))]
51    turnkey: bool,
52
53    /// List all configured accounts.
54    #[arg(long, group = "hw-wallets")]
55    all: bool,
56
57    /// Max number of addresses to display from hardware wallets.
58    #[arg(long, short, default_value = "3", requires = "hw-wallets")]
59    max_senders: usize,
60}
61
62impl ListArgs {
63    pub async fn run(self) -> Result<()> {
64        let format_json = shell::is_json();
65        let mut accounts: Vec<WalletAccount> = Vec::new();
66
67        // list local accounts as files in keystore dir, no need to unlock / provide password
68        if self.dir.is_some()
69            || self.all
70            || (!self.ledger && !self.trezor && !self.aws && !self.gcp && !self.turnkey)
71        {
72            match self.list_local_senders() {
73                Ok(local) => accounts.extend(local),
74                Err(e) if !self.all => return Err(e),
75                _ => {}
76            }
77        }
78
79        // Create options for multi wallet - ledger, trezor and AWS
80        let list_opts = MultiWalletOptsBuilder::default()
81            .ledger(self.ledger || self.all)
82            .mnemonic_indexes(Some(vec![0]))
83            .trezor(self.trezor || self.all)
84            .aws(self.aws || self.all)
85            .gcp(self.gcp || (self.all && gcp_env_vars_set()))
86            .turnkey(self.turnkey || self.all)
87            .interactives(0)
88            .interactive(false)
89            .browser(Default::default())
90            .build()
91            .expect("build multi wallet");
92
93        // macro to collect or print senders for a list of signers
94        macro_rules! list_senders {
95            ($signers:expr, $label:literal) => {
96                match $signers.await {
97                    Ok(signers) => {
98                        for signer in signers.unwrap_or_default().iter() {
99                            for sender in signer.available_senders(self.max_senders).await? {
100                                if format_json {
101                                    accounts.push(WalletAccount {
102                                        address: sender.to_string(),
103                                        source: $label,
104                                    });
105                                } else {
106                                    let _ = sh_println!("{} ({})", sender, $label);
107                                }
108                            }
109                        }
110                    }
111                    Err(e) if !self.all => return Err(e),
112                    _ => {}
113                }
114            };
115        }
116
117        list_senders!(list_opts.ledgers(), "Ledger");
118        list_senders!(list_opts.trezors(), "Trezor");
119        list_senders!(list_opts.aws_signers(), "AWS");
120        list_senders!(list_opts.gcp_signers(), "GCP");
121        list_senders!(async { list_opts.turnkey_signers() }, "Turnkey");
122
123        if format_json {
124            print_json_success(accounts)?;
125        }
126
127        Ok(())
128    }
129
130    fn list_local_senders(&self) -> Result<Vec<WalletAccount>> {
131        let keystore_path = self.dir.as_deref().unwrap_or_default();
132        let keystore_dir = if keystore_path.is_empty() {
133            // Create the keystore default directory if it doesn't exist
134            let default_dir = Config::foundry_keystores_dir().unwrap();
135            fs::create_dir_all(&default_dir)?;
136            default_dir
137        } else {
138            canonicalize_path(keystore_path)?
139        };
140
141        let mut accounts = Vec::new();
142
143        // List all files within the keystore directory.
144        let mut paths = std::fs::read_dir(keystore_dir)?
145            .map(|entry| entry.map(|entry| entry.path()))
146            .collect::<Result<Vec<_>, _>>()?;
147        paths.sort();
148        for path in paths {
149            if path.is_file()
150                && let Some(file_name) = path.file_name()
151                && let Some(name) = file_name.to_str()
152                // Skip recognized Touch ID and linked account sidecars while retaining ambiguous
153                // files, such as a keystore an earlier version created with that suffix.
154                && !matches!(super::is_touch_id_sidecar(&path), Ok(true))
155                && !(name.ends_with(LINKED_ACCOUNT_SUFFIX)
156                    && matches!(
157                        linked_account_file_state(&path),
158                        Ok(LinkedAccountFileState::Linked { .. })
159                    ))
160            {
161                let account = local_account_name(name);
162                if shell::is_json() {
163                    accounts.push(WalletAccount { address: account.into_owned(), source: "Local" });
164                } else {
165                    sh_println!("{} (Local)", account)?;
166                }
167            }
168        }
169
170        Ok(accounts)
171    }
172}
173
174/// Extracts the address from a Geth-style keystore filename, preserving custom names.
175fn local_account_name(name: &str) -> Cow<'_, str> {
176    if let Some((timestamp, address)) =
177        name.strip_prefix("UTC--").and_then(|suffix| suffix.rsplit_once("--"))
178        && !timestamp.is_empty()
179        && address.len() == 40
180        && address.bytes().all(|byte| byte.is_ascii_hexdigit())
181    {
182        Cow::Owned(format!("0x{address}"))
183    } else {
184        Cow::Borrowed(name)
185    }
186}
187
188#[derive(Serialize)]
189struct WalletAccount {
190    address: String,
191    source: &'static str,
192}
193
194fn gcp_env_vars_set() -> bool {
195    let required_vars =
196        ["GCP_PROJECT_ID", "GCP_LOCATION", "GCP_KEY_RING", "GCP_KEY_NAME", "GCP_KEY_VERSION"];
197
198    required_vars.iter().all(|&var| env::var(var).is_ok())
199}