1use clap::Parser;
2use eyre::Result;
3use foundry_cli::json::print_json_success;
4use foundry_common::{fs, fs::canonicalize_path, sh_err, sh_println, shell};
5use foundry_config::Config;
6use foundry_wallets::wallet_multi::MultiWalletOptsBuilder;
7use serde::Serialize;
8use std::{borrow::Cow, env};
9
10#[derive(Clone, Debug, Parser)]
12pub struct ListArgs {
13 #[arg(long, default_missing_value = "", num_args(0..=1))]
16 dir: Option<String>,
17
18 #[arg(long, short, group = "hw-wallets")]
20 ledger: bool,
21
22 #[arg(long, short, group = "hw-wallets")]
24 trezor: bool,
25
26 #[arg(long, hide = !cfg!(feature = "aws-kms"))]
31 aws: bool,
32
33 #[arg(long, hide = !cfg!(feature = "gcp-kms"))]
40 gcp: bool,
41
42 #[arg(long, hide = !cfg!(feature = "turnkey"))]
44 turnkey: bool,
45
46 #[arg(long, group = "hw-wallets")]
48 all: bool,
49
50 #[arg(long, short, default_value = "3", requires = "hw-wallets")]
52 max_senders: usize,
53}
54
55impl ListArgs {
56 pub async fn run(self) -> Result<()> {
57 let format_json = shell::is_json();
58 let mut accounts: Vec<WalletAccount> = Vec::new();
59
60 if self.dir.is_some()
62 || self.all
63 || (!self.ledger && !self.trezor && !self.aws && !self.gcp && !self.turnkey)
64 {
65 match self.list_local_senders() {
66 Ok(local) => accounts.extend(local),
67 Err(e) if !self.all => {
68 sh_err!("{}", e)?;
69 }
70 _ => {}
71 }
72 }
73
74 let list_opts = MultiWalletOptsBuilder::default()
76 .ledger(self.ledger || self.all)
77 .mnemonic_indexes(Some(vec![0]))
78 .trezor(self.trezor || self.all)
79 .aws(self.aws || self.all)
80 .gcp(self.gcp || (self.all && gcp_env_vars_set()))
81 .turnkey(self.turnkey || self.all)
82 .interactives(0)
83 .interactive(false)
84 .browser(Default::default())
85 .build()
86 .expect("build multi wallet");
87
88 macro_rules! list_senders {
90 ($signers:expr, $label:literal) => {
91 match $signers.await {
92 Ok(signers) => {
93 for signer in signers.unwrap_or_default().iter() {
94 for sender in signer.available_senders(self.max_senders).await? {
95 if format_json {
96 accounts.push(WalletAccount {
97 address: sender.to_string(),
98 source: $label,
99 });
100 } else {
101 let _ = sh_println!("{} ({})", sender, $label);
102 }
103 }
104 }
105 }
106 Err(e) if !self.all => {
107 sh_err!("{}", e)?;
108 }
109 _ => {}
110 }
111 };
112 }
113
114 list_senders!(list_opts.ledgers(), "Ledger");
115 list_senders!(list_opts.trezors(), "Trezor");
116 list_senders!(list_opts.aws_signers(), "AWS");
117 list_senders!(list_opts.gcp_signers(), "GCP");
118 list_senders!(async { list_opts.turnkey_signers() }, "Turnkey");
119
120 if format_json {
121 print_json_success(accounts)?;
122 }
123
124 Ok(())
125 }
126
127 fn list_local_senders(&self) -> Result<Vec<WalletAccount>> {
128 let keystore_path = self.dir.as_deref().unwrap_or_default();
129 let keystore_dir = if keystore_path.is_empty() {
130 let default_dir = Config::foundry_keystores_dir().unwrap();
132 fs::create_dir_all(&default_dir)?;
133 default_dir
134 } else {
135 canonicalize_path(keystore_path)?
136 };
137
138 let mut accounts = Vec::new();
139
140 let mut paths = std::fs::read_dir(keystore_dir)?
142 .map(|entry| entry.map(|entry| entry.path()))
143 .collect::<Result<Vec<_>, _>>()?;
144 paths.sort();
145 for path in paths {
146 if path.is_file()
147 && let Some(file_name) = path.file_name()
148 && let Some(name) = file_name.to_str()
149 && !matches!(super::is_touch_id_sidecar(&path), Ok(true))
151 {
152 let account = local_account_name(name);
153 if shell::is_json() {
154 accounts.push(WalletAccount { address: account.into_owned(), source: "Local" });
155 } else {
156 sh_println!("{} (Local)", account)?;
157 }
158 }
159 }
160
161 Ok(accounts)
162 }
163}
164
165fn local_account_name(name: &str) -> Cow<'_, str> {
167 if let Some((timestamp, address)) =
168 name.strip_prefix("UTC--").and_then(|suffix| suffix.rsplit_once("--"))
169 && !timestamp.is_empty()
170 && address.len() == 40
171 && address.bytes().all(|byte| byte.is_ascii_hexdigit())
172 {
173 Cow::Owned(format!("0x{address}"))
174 } else {
175 Cow::Borrowed(name)
176 }
177}
178
179#[derive(Serialize)]
180struct WalletAccount {
181 address: String,
182 source: &'static str,
183}
184
185fn gcp_env_vars_set() -> bool {
186 let required_vars =
187 ["GCP_PROJECT_ID", "GCP_LOCATION", "GCP_KEY_RING", "GCP_KEY_NAME", "GCP_KEY_VERSION"];
188
189 required_vars.iter().all(|&var| env::var(var).is_ok())
190}