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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use inquire::validator::{ErrorMessage, Validation};
use inquire::{required, Confirm, Text};
use rust_decimal::Decimal;
use solana_cli_config::Config;
use solana_cli_output::OutputFormat;
use solana_program::pubkey::Pubkey;
use solana_sdk::commitment_config::CommitmentConfig;
use solana_sdk::signature::{Signer, SignerError};
use std::fs::File;
use std::str::FromStr;
use std::time::Duration;

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

pub trait Parser {
    fn to_pubkey(self) -> Result<Pubkey, Box<dyn std::error::Error>>;
    fn to_u128(self) -> Result<u128, Box<dyn std::error::Error>>;
    fn to_u64(self) -> Result<u64, Box<dyn std::error::Error>>;
    fn to_u16(self) -> Result<u16, Box<dyn std::error::Error>>;
    fn to_f64(self) -> Result<f64, Box<dyn std::error::Error>>;
    fn to_file(self) -> Result<String, Box<dyn std::error::Error>>;
    fn to_string(self) -> Result<String, Box<dyn std::error::Error>>;
    fn to_decimal(self) -> Result<Decimal, Box<dyn std::error::Error>>;
    fn confirm() -> Result<(), Box<dyn std::error::Error>>;
}

impl Parser for Text<'_> {
    fn to_pubkey(self) -> Result<Pubkey, Box<dyn std::error::Error>> {
        let s = self
            .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())
    }

    fn to_u128(self) -> Result<u128, Box<dyn std::error::Error>> {
        let s = self
            .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())
    }

    fn to_u64(self) -> Result<u64, Box<dyn std::error::Error>> {
        let s = self
            .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())
    }

    fn to_u16(self) -> Result<u16, Box<dyn std::error::Error>> {
        let s = self
            .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())
    }

    fn to_f64(self) -> Result<f64, Box<dyn std::error::Error>> {
        let s = self
            .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())
    }

    fn to_file(self) -> Result<String, Box<dyn std::error::Error>> {
        let s = self
            .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)
    }

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

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

    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())),
        }
    }
}

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 new_with_default<'a>(title: &'a str, message: &'a str) -> Parse<'a> {
        Parse {
            text: Text::new(title).with_default(message),
        }
    }

    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,
    pub config: Config,
}

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))
}