1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::fs::File;
use std::str::FromStr;
use std::time::Duration;
use inquire::{Confirm, required, Text};
use inquire::validator::{ErrorMessage, Validation};
use solana_cli_output::OutputFormat;
use solana_program::pubkey::Pubkey;
use solana_sdk::commitment_config::CommitmentConfig;
use solana_sdk::signature::{Signer, SignerError};


pub struct Parse<'a> {
    pub text: Text<'a>
}


impl Parse<'_> {
    pub fn new(title: &str, require: bool) -> Parse {
        let mut t = Text::new(title);
        if require {
            t = t.with_validator(required!("This field is required"));
        }
        Parse {
            text: t
        }
    }

    pub fn to_pubkey(self) -> Result<Pubkey, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match Pubkey::from_str(s).is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong address".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(Pubkey::from_str(s.as_str()).unwrap())
    }

    pub fn to_u128(self) -> Result<u128, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match s.parse::<u128>().is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong number with u128".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(s.parse::<u128>().unwrap())
    }

    pub fn to_u64(self) -> Result<u64, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match s.parse::<u64>().is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong number with u64".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(s.parse::<u64>().unwrap())
    }

    pub fn to_u16(self) -> Result<u16, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match s.parse::<u16>().is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong number with u16".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(s.parse::<u16>().unwrap())
    }

    pub fn to_f64(self) -> Result<f64, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match s.parse::<f64>().is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong number with f64".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(s.parse::<f64>().unwrap())
    }

    pub fn to_file(self) -> Result<String, Box<dyn std::error::Error>> {
        let s = self.text.with_validator(|s: &str|
            match File::open(s).is_err() {
                true => Ok(Validation::Invalid(ErrorMessage::Custom("wrong file path".to_string()))),
                false => Ok(Validation::Valid)
            }
        ).prompt()?;
        Ok(s)
    }

    pub fn to_string(self) -> Result<String, Box<dyn std::error::Error>> {
        Ok(self.text.prompt()?)
    }


    pub fn confirm() -> Result<(), Box<dyn std::error::Error>> {
        let res = Confirm::new("Confirm this operation?")
            .with_default(false)
            .prompt();
        match res {
            Ok(true) => Ok(()),
            Ok(false) => Err(Box::<dyn std::error::Error>::from("Cancel the operation")),
            Err(_) => Err(Box::new(res.err().unwrap()))
        }
    }
}

pub struct CliConfig {
    pub signers: Vec<Box<dyn Signer>>,
    pub json_rpc_url: String,
    pub rpc_timeout: Duration,
    pub commitment: CommitmentConfig,
    pub confirm_transaction_initial_timeout: Duration,
    pub output_format: OutputFormat,
}

impl CliConfig {
    pub fn pubkey(&self) -> Result<Pubkey, SignerError> {
        if !self.signers.is_empty() {
            self.signers[0].try_pubkey()
        } else {
            Err(SignerError::Custom(
                "Default keypair must be set if pubkey arg not provided".to_string(),
            ))
        }
    }
}


pub type ProcessResult = Result<String, Box<dyn std::error::Error>>;

pub fn process_result_from_str(msg: &str) -> ProcessResult {
    Err(Box::<dyn std::error::Error>::from(msg))
}