1use {
2 crate::keypair::{
3 keypair_from_seed_phrase, pubkey_from_path, resolve_signer_from_path, signer_from_path,
4 ASK_KEYWORD, SKIP_SEED_PHRASE_VALIDATION_ARG,
5 },
6 chrono::DateTime,
7 clap::ArgMatches,
8 solana_clock::UnixTimestamp,
9 solana_cluster_type::ClusterType,
10 solana_commitment_config::CommitmentConfig,
11 solana_keypair::{read_keypair_file, Keypair},
12 solana_native_token::sol_to_lamports,
13 solana_pubkey::Pubkey,
14 solana_remote_wallet::remote_wallet::RemoteWalletManager,
15 solana_signature::Signature,
16 solana_signer::Signer,
17 std::{rc::Rc, str::FromStr},
18};
19
20pub const STDOUT_OUTFILE_TOKEN: &str = "-";
22
23pub fn values_of<T>(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<T>>
25where
26 T: std::str::FromStr,
27 <T as std::str::FromStr>::Err: std::fmt::Debug,
28{
29 matches
30 .values_of(name)
31 .map(|xs| xs.map(|x| x.parse::<T>().unwrap()).collect())
32}
33
34pub fn value_of<T>(matches: &ArgMatches<'_>, name: &str) -> Option<T>
36where
37 T: std::str::FromStr,
38 <T as std::str::FromStr>::Err: std::fmt::Debug,
39{
40 if let Some(value) = matches.value_of(name) {
41 value.parse::<T>().ok()
42 } else {
43 None
44 }
45}
46
47pub fn unix_timestamp_from_rfc3339_datetime(
48 matches: &ArgMatches<'_>,
49 name: &str,
50) -> Option<UnixTimestamp> {
51 matches.value_of(name).and_then(|value| {
52 DateTime::parse_from_rfc3339(value)
53 .ok()
54 .map(|date_time| date_time.timestamp())
55 })
56}
57
58pub fn keypair_of(matches: &ArgMatches<'_>, name: &str) -> Option<Keypair> {
60 if let Some(value) = matches.value_of(name) {
61 if value == ASK_KEYWORD {
62 let skip_validation = matches.is_present(SKIP_SEED_PHRASE_VALIDATION_ARG.name);
63 keypair_from_seed_phrase(name, skip_validation, true, None, true).ok()
64 } else {
65 read_keypair_file(value).ok()
66 }
67 } else {
68 None
69 }
70}
71
72pub fn keypairs_of(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<Keypair>> {
73 matches.values_of(name).map(|values| {
74 values
75 .filter_map(|value| {
76 if value == ASK_KEYWORD {
77 let skip_validation = matches.is_present(SKIP_SEED_PHRASE_VALIDATION_ARG.name);
78 keypair_from_seed_phrase(name, skip_validation, true, None, true).ok()
79 } else {
80 read_keypair_file(value).ok()
81 }
82 })
83 .collect()
84 })
85}
86
87pub fn pubkey_of(matches: &ArgMatches<'_>, name: &str) -> Option<Pubkey> {
90 value_of(matches, name).or_else(|| keypair_of(matches, name).map(|keypair| keypair.pubkey()))
91}
92
93pub fn pubkeys_of(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<Pubkey>> {
94 matches.values_of(name).map(|values| {
95 values
96 .map(|value| {
97 value.parse::<Pubkey>().unwrap_or_else(|_| {
98 read_keypair_file(value)
99 .expect("read_keypair_file failed")
100 .pubkey()
101 })
102 })
103 .collect()
104 })
105}
106
107pub fn pubkeys_sigs_of(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<(Pubkey, Signature)>> {
109 matches.values_of(name).map(|values| {
110 values
111 .map(|pubkey_signer_string| {
112 let mut signer = pubkey_signer_string.split('=');
113 let key = Pubkey::from_str(signer.next().unwrap()).unwrap();
114 let sig = Signature::from_str(signer.next().unwrap()).unwrap();
115 (key, sig)
116 })
117 .collect()
118 })
119}
120
121#[allow(clippy::type_complexity)]
123pub fn signer_of(
124 matches: &ArgMatches<'_>,
125 name: &str,
126 wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
127) -> Result<(Option<Box<dyn Signer>>, Option<Pubkey>), Box<dyn std::error::Error>> {
128 if let Some(location) = matches.value_of(name) {
129 let signer = signer_from_path(matches, location, name, wallet_manager)?;
130 let signer_pubkey = signer.pubkey();
131 Ok((Some(signer), Some(signer_pubkey)))
132 } else {
133 Ok((None, None))
134 }
135}
136
137pub fn pubkey_of_signer(
138 matches: &ArgMatches<'_>,
139 name: &str,
140 wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
141) -> Result<Option<Pubkey>, Box<dyn std::error::Error>> {
142 if let Some(location) = matches.value_of(name) {
143 Ok(Some(pubkey_from_path(
144 matches,
145 location,
146 name,
147 wallet_manager,
148 )?))
149 } else {
150 Ok(None)
151 }
152}
153
154pub fn pubkeys_of_multiple_signers(
155 matches: &ArgMatches<'_>,
156 name: &str,
157 wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
158) -> Result<Option<Vec<Pubkey>>, Box<dyn std::error::Error>> {
159 if let Some(pubkey_matches) = matches.values_of(name) {
160 let mut pubkeys: Vec<Pubkey> = vec![];
161 for signer in pubkey_matches {
162 pubkeys.push(pubkey_from_path(matches, signer, name, wallet_manager)?);
163 }
164 Ok(Some(pubkeys))
165 } else {
166 Ok(None)
167 }
168}
169
170pub fn resolve_signer(
171 matches: &ArgMatches<'_>,
172 name: &str,
173 wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
174) -> Result<Option<String>, Box<dyn std::error::Error>> {
175 resolve_signer_from_path(
176 matches,
177 matches.value_of(name).unwrap(),
178 name,
179 wallet_manager,
180 )
181}
182
183pub fn lamports_of_sol(matches: &ArgMatches<'_>, name: &str) -> Option<u64> {
184 value_of(matches, name).map(sol_to_lamports)
185}
186
187pub fn cluster_type_of(matches: &ArgMatches<'_>, name: &str) -> Option<ClusterType> {
188 value_of(matches, name)
189}
190
191pub fn commitment_of(matches: &ArgMatches<'_>, name: &str) -> Option<CommitmentConfig> {
192 matches
193 .value_of(name)
194 .map(|value| CommitmentConfig::from_str(value).unwrap_or_default())
195}
196
197#[cfg(test)]
198mod tests {
199 use {
200 super::*,
201 clap::{App, Arg},
202 solana_keypair::write_keypair_file,
203 std::fs,
204 };
205
206 fn app<'ab, 'v>() -> App<'ab, 'v> {
207 App::new("test")
208 .arg(
209 Arg::with_name("multiple")
210 .long("multiple")
211 .takes_value(true)
212 .multiple(true),
213 )
214 .arg(Arg::with_name("single").takes_value(true).long("single"))
215 .arg(Arg::with_name("unit").takes_value(true).long("unit"))
216 }
217
218 fn tmp_file_path(name: &str, pubkey: &Pubkey) -> String {
219 use std::env;
220 let out_dir = env::var("FARF_DIR").unwrap_or_else(|_| "farf".to_string());
221
222 format!("{out_dir}/tmp/{name}-{pubkey}")
223 }
224
225 #[test]
226 fn test_values_of() {
227 let matches = app().get_matches_from(vec!["test", "--multiple", "50", "--multiple", "39"]);
228 assert_eq!(values_of(&matches, "multiple"), Some(vec![50, 39]));
229 assert_eq!(values_of::<u64>(&matches, "single"), None);
230
231 let pubkey0 = solana_pubkey::new_rand();
232 let pubkey1 = solana_pubkey::new_rand();
233 let matches = app().get_matches_from(vec![
234 "test",
235 "--multiple",
236 &pubkey0.to_string(),
237 "--multiple",
238 &pubkey1.to_string(),
239 ]);
240 assert_eq!(
241 values_of(&matches, "multiple"),
242 Some(vec![pubkey0, pubkey1])
243 );
244 }
245
246 #[test]
247 fn test_value_of() {
248 let matches = app().get_matches_from(vec!["test", "--single", "50"]);
249 assert_eq!(value_of(&matches, "single"), Some(50));
250 assert_eq!(value_of::<u64>(&matches, "multiple"), None);
251
252 let pubkey = solana_pubkey::new_rand();
253 let matches = app().get_matches_from(vec!["test", "--single", &pubkey.to_string()]);
254 assert_eq!(value_of(&matches, "single"), Some(pubkey));
255 }
256
257 #[test]
258 fn test_keypair_of() {
259 let keypair = Keypair::new();
260 let outfile = tmp_file_path("test_keypair_of.json", &keypair.pubkey());
261 let _ = write_keypair_file(&keypair, &outfile).unwrap();
262
263 let matches = app().get_matches_from(vec!["test", "--single", &outfile]);
264 assert_eq!(
265 keypair_of(&matches, "single").unwrap().pubkey(),
266 keypair.pubkey()
267 );
268 assert!(keypair_of(&matches, "multiple").is_none());
269
270 let matches = app().get_matches_from(vec!["test", "--single", "random_keypair_file.json"]);
271 assert!(keypair_of(&matches, "single").is_none());
272
273 fs::remove_file(&outfile).unwrap();
274 }
275
276 #[test]
277 fn test_pubkey_of() {
278 let keypair = Keypair::new();
279 let outfile = tmp_file_path("test_pubkey_of.json", &keypair.pubkey());
280 let _ = write_keypair_file(&keypair, &outfile).unwrap();
281
282 let matches = app().get_matches_from(vec!["test", "--single", &outfile]);
283 assert_eq!(pubkey_of(&matches, "single"), Some(keypair.pubkey()));
284 assert_eq!(pubkey_of(&matches, "multiple"), None);
285
286 let matches =
287 app().get_matches_from(vec!["test", "--single", &keypair.pubkey().to_string()]);
288 assert_eq!(pubkey_of(&matches, "single"), Some(keypair.pubkey()));
289
290 let matches = app().get_matches_from(vec!["test", "--single", "random_keypair_file.json"]);
291 assert_eq!(pubkey_of(&matches, "single"), None);
292
293 fs::remove_file(&outfile).unwrap();
294 }
295
296 #[test]
297 fn test_pubkeys_of() {
298 let keypair = Keypair::new();
299 let outfile = tmp_file_path("test_pubkeys_of.json", &keypair.pubkey());
300 let _ = write_keypair_file(&keypair, &outfile).unwrap();
301
302 let matches = app().get_matches_from(vec![
303 "test",
304 "--multiple",
305 &keypair.pubkey().to_string(),
306 "--multiple",
307 &outfile,
308 ]);
309 assert_eq!(
310 pubkeys_of(&matches, "multiple"),
311 Some(vec![keypair.pubkey(), keypair.pubkey()])
312 );
313 fs::remove_file(&outfile).unwrap();
314 }
315
316 #[test]
317 fn test_pubkeys_sigs_of() {
318 let key1 = solana_pubkey::new_rand();
319 let key2 = solana_pubkey::new_rand();
320 let sig1 = Keypair::new().sign_message(&[0u8]);
321 let sig2 = Keypair::new().sign_message(&[1u8]);
322 let signer1 = format!("{key1}={sig1}");
323 let signer2 = format!("{key2}={sig2}");
324 let matches =
325 app().get_matches_from(vec!["test", "--multiple", &signer1, "--multiple", &signer2]);
326 assert_eq!(
327 pubkeys_sigs_of(&matches, "multiple"),
328 Some(vec![(key1, sig1), (key2, sig2)])
329 );
330 }
331
332 #[test]
333 fn test_lamports_of_sol() {
334 let matches = app().get_matches_from(vec!["test", "--single", "50"]);
335 assert_eq!(lamports_of_sol(&matches, "single"), Some(50_000_000_000));
336 assert_eq!(lamports_of_sol(&matches, "multiple"), None);
337 let matches = app().get_matches_from(vec!["test", "--single", "1.5"]);
338 assert_eq!(lamports_of_sol(&matches, "single"), Some(1_500_000_000));
339 assert_eq!(lamports_of_sol(&matches, "multiple"), None);
340 let matches = app().get_matches_from(vec!["test", "--single", "0.03"]);
341 assert_eq!(lamports_of_sol(&matches, "single"), Some(30_000_000));
342 }
343}