safecoin_clap_utils/
input_parsers.rs

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    safecoin_remote_wallet::remote_wallet::RemoteWalletManager,
9    solana_sdk::{
10        clock::UnixTimestamp,
11        commitment_config::CommitmentConfig,
12        genesis_config::ClusterType,
13        native_token::sol_to_lamports,
14        pubkey::Pubkey,
15        signature::{read_keypair_file, Keypair, Signature, Signer},
16    },
17    std::{str::FromStr, sync::Arc},
18};
19
20// Sentinel value used to indicate to write to screen instead of file
21pub const STDOUT_OUTFILE_TOKEN: &str = "-";
22
23// Return parsed values from matches at `name`
24pub 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
34// Return a parsed value from matches at `name`
35pub 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
58// Return the keypair for an argument with filename `name` or None if not present.
59pub 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
87// Return a pubkey for an argument that can itself be parsed into a pubkey,
88// or is a filename that can be read as a keypair
89pub 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
107// Return pubkey/signature pairs for a string of the form pubkey=signature
108pub 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// Return a signer from matches at `name`
122#[allow(clippy::type_complexity)]
123pub fn signer_of(
124    matches: &ArgMatches<'_>,
125    name: &str,
126    wallet_manager: &mut Option<Arc<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<Arc<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<Arc<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<Arc<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_sdk::signature::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!("{}/tmp/{}-{}", out_dir, name, pubkey)
223    }
224
225    #[test]
226    fn test_values_of() {
227        let matches =
228            app()
229                .clone()
230                .get_matches_from(vec!["test", "--multiple", "50", "--multiple", "39"]);
231        assert_eq!(values_of(&matches, "multiple"), Some(vec![50, 39]));
232        assert_eq!(values_of::<u64>(&matches, "single"), None);
233
234        let pubkey0 = solana_sdk::pubkey::new_rand();
235        let pubkey1 = solana_sdk::pubkey::new_rand();
236        let matches = app().clone().get_matches_from(vec![
237            "test",
238            "--multiple",
239            &pubkey0.to_string(),
240            "--multiple",
241            &pubkey1.to_string(),
242        ]);
243        assert_eq!(
244            values_of(&matches, "multiple"),
245            Some(vec![pubkey0, pubkey1])
246        );
247    }
248
249    #[test]
250    fn test_value_of() {
251        let matches = app()
252            .clone()
253            .get_matches_from(vec!["test", "--single", "50"]);
254        assert_eq!(value_of(&matches, "single"), Some(50));
255        assert_eq!(value_of::<u64>(&matches, "multiple"), None);
256
257        let pubkey = solana_sdk::pubkey::new_rand();
258        let matches = app()
259            .clone()
260            .get_matches_from(vec!["test", "--single", &pubkey.to_string()]);
261        assert_eq!(value_of(&matches, "single"), Some(pubkey));
262    }
263
264    #[test]
265    fn test_keypair_of() {
266        let keypair = Keypair::new();
267        let outfile = tmp_file_path("test_keypair_of.json", &keypair.pubkey());
268        let _ = write_keypair_file(&keypair, &outfile).unwrap();
269
270        let matches = app()
271            .clone()
272            .get_matches_from(vec!["test", "--single", &outfile]);
273        assert_eq!(
274            keypair_of(&matches, "single").unwrap().pubkey(),
275            keypair.pubkey()
276        );
277        assert!(keypair_of(&matches, "multiple").is_none());
278
279        let matches =
280            app()
281                .clone()
282                .get_matches_from(vec!["test", "--single", "random_keypair_file.json"]);
283        assert!(keypair_of(&matches, "single").is_none());
284
285        fs::remove_file(&outfile).unwrap();
286    }
287
288    #[test]
289    fn test_pubkey_of() {
290        let keypair = Keypair::new();
291        let outfile = tmp_file_path("test_pubkey_of.json", &keypair.pubkey());
292        let _ = write_keypair_file(&keypair, &outfile).unwrap();
293
294        let matches = app()
295            .clone()
296            .get_matches_from(vec!["test", "--single", &outfile]);
297        assert_eq!(pubkey_of(&matches, "single"), Some(keypair.pubkey()));
298        assert_eq!(pubkey_of(&matches, "multiple"), None);
299
300        let matches =
301            app()
302                .clone()
303                .get_matches_from(vec!["test", "--single", &keypair.pubkey().to_string()]);
304        assert_eq!(pubkey_of(&matches, "single"), Some(keypair.pubkey()));
305
306        let matches =
307            app()
308                .clone()
309                .get_matches_from(vec!["test", "--single", "random_keypair_file.json"]);
310        assert_eq!(pubkey_of(&matches, "single"), None);
311
312        fs::remove_file(&outfile).unwrap();
313    }
314
315    #[test]
316    fn test_pubkeys_of() {
317        let keypair = Keypair::new();
318        let outfile = tmp_file_path("test_pubkeys_of.json", &keypair.pubkey());
319        let _ = write_keypair_file(&keypair, &outfile).unwrap();
320
321        let matches = app().clone().get_matches_from(vec![
322            "test",
323            "--multiple",
324            &keypair.pubkey().to_string(),
325            "--multiple",
326            &outfile,
327        ]);
328        assert_eq!(
329            pubkeys_of(&matches, "multiple"),
330            Some(vec![keypair.pubkey(), keypair.pubkey()])
331        );
332        fs::remove_file(&outfile).unwrap();
333    }
334
335    #[test]
336    fn test_pubkeys_sigs_of() {
337        let key1 = solana_sdk::pubkey::new_rand();
338        let key2 = solana_sdk::pubkey::new_rand();
339        let sig1 = Keypair::new().sign_message(&[0u8]);
340        let sig2 = Keypair::new().sign_message(&[1u8]);
341        let signer1 = format!("{}={}", key1, sig1);
342        let signer2 = format!("{}={}", key2, sig2);
343        let matches = app().clone().get_matches_from(vec![
344            "test",
345            "--multiple",
346            &signer1,
347            "--multiple",
348            &signer2,
349        ]);
350        assert_eq!(
351            pubkeys_sigs_of(&matches, "multiple"),
352            Some(vec![(key1, sig1), (key2, sig2)])
353        );
354    }
355
356    #[test]
357    fn test_lamports_of_sol() {
358        let matches = app()
359            .clone()
360            .get_matches_from(vec!["test", "--single", "50"]);
361        assert_eq!(lamports_of_sol(&matches, "single"), Some(50_000_000_000));
362        assert_eq!(lamports_of_sol(&matches, "multiple"), None);
363        let matches = app()
364            .clone()
365            .get_matches_from(vec!["test", "--single", "1.5"]);
366        assert_eq!(lamports_of_sol(&matches, "single"), Some(1_33_370_166));
367        assert_eq!(lamports_of_sol(&matches, "multiple"), None);
368        let matches = app()
369            .clone()
370            .get_matches_from(vec!["test", "--single", "0.03"]);
371        assert_eq!(lamports_of_sol(&matches, "single"), Some(30_000_000));
372    }
373}