namada_apps_lib 0.251.4

Namada CLI apps library code
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Command line interface utilities
use std::fmt::Debug;
use std::io::Write;
use std::marker::PhantomData;
use std::str::FromStr;
use std::sync::Arc;

use clap::{ArgAction, ArgMatches};
use color_eyre::eyre::Result;
use data_encoding::HEXLOWER_PERMISSIVE;
use namada_sdk::eth_bridge::ethers::core::k256::elliptic_curve::SecretKey as Secp256k1Sk;
use namada_sdk::eth_bridge::ethers::middleware::SignerMiddleware;
use namada_sdk::eth_bridge::ethers::providers::{Http, Middleware, Provider};
use namada_sdk::eth_bridge::ethers::signers::{Signer, Wallet};

use super::args;
use super::context::Context;
use crate::cli::api::CliIo;
use crate::cli::context::FromContext;

/// Environment variable where Ethereum relayer private
/// keys are stored.
// TODO(namada#2029): remove this in favor of getting eth keys from
// namadaw, ledger, or something more secure
#[cfg_attr(not(feature = "namada-eth-bridge"), allow(dead_code))]
const RELAYER_KEY_ENV_VAR: &str = "NAMADA_RELAYER_KEY";

// We only use static strings
pub type App = clap::Command;
pub type ClapArg = clap::Arg;

/// Mode of operation of [`ArgMulti`] where zero or
/// more arguments may be present (i.e. `<pattern>*`).
pub enum GlobStar {}

/// Mode of operation of [`ArgMulti`] where at least
/// one argument must be present (i.e. `<pattern>+`).
pub enum GlobPlus {}

pub trait Cmd: Sized {
    fn add_sub(app: App) -> App;
    fn parse(matches: &ArgMatches) -> Option<Self>;

    fn parse_or_print_help(app: App) -> Result<(Self, Context)> {
        let matches = app.clone().get_matches();
        match Self::parse(&matches) {
            Some(cmd) => {
                let global_args = args::Global::parse(&matches);
                let context = Context::new::<CliIo>(global_args)?;
                Ok((cmd, context))
            }
            None => {
                let mut app = app;
                app.print_help().unwrap();
                safe_exit(2);
            }
        }
    }
}

pub trait SubCmd: Sized {
    const CMD: &'static str;
    fn parse(matches: &ArgMatches) -> Option<Self>;
    fn def() -> App;
}

pub trait Args {
    fn parse(matches: &ArgMatches) -> Self;
    fn def(app: App) -> App;
}

pub struct Arg<T> {
    pub name: &'static str,
    pub r#type: PhantomData<T>,
}

pub struct ArgOpt<T> {
    pub name: &'static str,
    pub r#type: PhantomData<T>,
}

pub struct ArgDefault<T> {
    pub name: &'static str,
    pub default: DefaultFn<T>,
    pub r#type: PhantomData<T>,
}

pub struct ArgDefaultFromCtx<T> {
    pub name: &'static str,
    pub default: DefaultFn<String>,
    pub r#type: PhantomData<T>,
}

/// This wrapper type is a workaround for "function pointers in const fn are
/// unstable", which allows us to use this type in a const fn, because the
/// type-checker doesn't inspect the wrapped type.
/// Const function pointers: <https://github.com/rust-lang/rust/issues/63997>.
pub struct DefaultFn<T>(pub fn() -> T);

pub struct ArgFlag {
    pub name: &'static str,
}

#[allow(dead_code)]
pub struct ArgMulti<T, K> {
    pub name: &'static str,
    pub r#type: PhantomData<(T, K)>,
}

pub const fn arg<T>(name: &'static str) -> Arg<T> {
    Arg {
        name,
        r#type: PhantomData,
    }
}

pub const fn arg_opt<T>(name: &'static str) -> ArgOpt<T> {
    ArgOpt {
        name,
        r#type: PhantomData,
    }
}

pub const fn arg_default<T>(
    name: &'static str,
    default: DefaultFn<T>,
) -> ArgDefault<T> {
    ArgDefault {
        name,
        default,
        r#type: PhantomData,
    }
}

pub const fn arg_default_from_ctx<T>(
    name: &'static str,
    default: DefaultFn<String>,
) -> ArgDefaultFromCtx<T> {
    ArgDefaultFromCtx {
        name,
        default,
        r#type: PhantomData,
    }
}

pub const fn flag(name: &'static str) -> ArgFlag {
    ArgFlag { name }
}

pub const fn arg_multi<T, K>(name: &'static str) -> ArgMulti<T, K> {
    ArgMulti {
        name,
        r#type: PhantomData,
    }
}

#[macro_export]
macro_rules! wrap {
    ($text:literal) => {
        textwrap_macros::fill!($text, 80)
    };
}

impl<T> Arg<T> {
    pub const fn opt(self) -> ArgOpt<T> {
        ArgOpt {
            name: self.name,
            r#type: PhantomData,
        }
    }

    pub const fn default(self, default: DefaultFn<T>) -> ArgDefault<T> {
        ArgDefault {
            name: self.name,
            default,
            r#type: PhantomData,
        }
    }

    #[allow(dead_code)]
    pub const fn multi_glob_star(self) -> ArgMulti<T, GlobStar> {
        ArgMulti {
            name: self.name,
            r#type: PhantomData,
        }
    }

    #[allow(dead_code)]
    pub const fn multi_glob_plus(self) -> ArgMulti<T, GlobPlus> {
        ArgMulti {
            name: self.name,
            r#type: PhantomData,
        }
    }
}

impl<T> Arg<T> {
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name)
            .long(self.name)
            .num_args(1)
            .required(true)
    }
}

impl<T> Arg<T>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> T {
        parse_opt(matches, self.name).unwrap()
    }
}

impl<T> Arg<FromContext<T>> {
    pub fn parse(&self, matches: &ArgMatches) -> FromContext<T> {
        let raw = matches.get_one::<String>(self.name).unwrap();
        FromContext::new(raw.to_string())
    }
}

impl<T> ArgOpt<T> {
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name).long(self.name).num_args(1)
    }
}

impl<T> ArgOpt<T>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> Option<T> {
        parse_opt(matches, self.name)
    }
}

impl<T> ArgOpt<FromContext<T>> {
    pub fn parse(&self, matches: &ArgMatches) -> Option<FromContext<T>> {
        let raw = matches.get_one::<String>(self.name).map(|s| s.as_str())?;
        Some(FromContext::new(raw.to_string()))
    }
}

impl<T> ArgDefault<T>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name).long(self.name).num_args(1)
    }

    pub fn parse(&self, matches: &ArgMatches) -> T {
        parse_opt(matches, self.name).unwrap_or_else(|| {
            let DefaultFn(default) = self.default;
            default()
        })
    }
}

impl<T, K> ArgMulti<T, K> {
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name)
            .long(self.name)
            .num_args(1..)
            .value_delimiter(',')
    }
}

impl<T> ArgMulti<FromContext<T>, GlobStar>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> Vec<FromContext<T>> {
        matches
            .get_many(self.name)
            .unwrap_or_default()
            .map(|raw: &String| FromContext::new(raw.to_string()))
            .collect()
    }
}

impl<T> ArgMulti<FromContext<T>, GlobPlus>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> Vec<FromContext<T>> {
        matches
            .get_many(self.name)
            .unwrap_or_else(|| {
                eprintln!("Missing at least one argument to `--{}`", self.name);
                safe_exit(1)
            })
            .map(|raw: &String| FromContext::new(raw.to_string()))
            .collect()
    }
}

impl<T> ArgMulti<T, GlobStar>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> Vec<T> {
        matches
            .get_many(self.name)
            .unwrap_or_default()
            .map(|raw: &String| {
                raw.parse().unwrap_or_else(|e| {
                    eprintln!(
                        "Failed to parse the {} argument. Raw value: {}, \
                         error: {:?}",
                        self.name, raw, e
                    );
                    safe_exit(1)
                })
            })
            .collect()
    }
}

impl<T> ArgMulti<T, GlobPlus>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn parse(&self, matches: &ArgMatches) -> Vec<T> {
        matches
            .get_many(self.name)
            .unwrap_or_else(|| {
                eprintln!("Missing at least one argument to `--{}`", self.name);
                safe_exit(1)
            })
            .map(|raw: &String| {
                raw.parse().unwrap_or_else(|e| {
                    eprintln!(
                        "Failed to parse the {} argument. Raw value: {}, \
                         error: {:?}",
                        self.name, raw, e
                    );
                    safe_exit(1)
                })
            })
            .collect()
    }
}

impl<T> ArgDefaultFromCtx<FromContext<T>>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name).long(self.name).num_args(1)
    }

    pub fn parse(&self, matches: &ArgMatches) -> FromContext<T> {
        let raw = parse_opt(matches, self.name).unwrap_or_else(|| {
            let DefaultFn(default) = self.default;
            default()
        });
        FromContext::new(raw)
    }
}

impl ArgFlag {
    pub fn def(&self) -> ClapArg {
        ClapArg::new(self.name)
            .long(self.name)
            .action(ArgAction::SetTrue)
    }

    pub fn parse(&self, matches: &ArgMatches) -> bool {
        matches.get_flag(self.name)
    }
}

/// Extensions for defining commands and arguments.
/// Every function here should have a matcher in [`ArgMatchesExt`].
pub trait AppExt {
    fn add_args<T: Args>(self) -> Self;
}

/// Extensions for finding matching commands and arguments.
/// The functions match commands and arguments defined in [`AppExt`].
pub trait ArgMatchesExt {
    #[allow(dead_code)]
    fn args_parse<T: Args>(&self) -> T;
}

impl AppExt for App {
    fn add_args<T: Args>(self) -> Self {
        T::def(self)
    }
}

impl ArgMatchesExt for ArgMatches {
    fn args_parse<T: Args>(&self) -> T {
        T::parse(self)
    }
}

pub fn parse_opt<T>(args: &ArgMatches, field: &str) -> Option<T>
where
    T: FromStr,
    T::Err: Debug,
{
    args.get_one::<String>(field).map(|s| {
        s.as_str().parse().unwrap_or_else(|e| {
            eprintln!(
                "Failed to parse the argument {}. Raw value: {}, error: {:?}",
                field, s, e
            );
            safe_exit(1)
        })
    })
}

#[cfg(not(feature = "testing"))]
/// A helper to exit after flushing output, borrowed from `clap::util` module.
pub fn safe_exit(code: i32) -> ! {
    let _ = std::io::stdout().lock().flush();
    let _ = std::io::stderr().lock().flush();

    std::process::exit(code)
}

#[cfg(feature = "testing")]
/// A helper to exit after flushing output, borrowed from `clap::util` module.
pub fn safe_exit(_: i32) -> ! {
    let _ = std::io::stdout().lock().flush();
    let _ = std::io::stderr().lock().flush();

    panic!("Test failed because the client exited unexpectedly.")
}

/// Load an Ethereum wallet from the environment.
#[cfg_attr(not(feature = "namada-eth-bridge"), allow(dead_code))]
fn get_eth_signer_from_env(chain_id: u64) -> Option<impl Signer> {
    let relayer_key = std::env::var(RELAYER_KEY_ENV_VAR).ok()?;
    let relayer_key = HEXLOWER_PERMISSIVE.decode(relayer_key.as_ref()).ok()?;
    let relayer_key = Secp256k1Sk::from_slice(&relayer_key).ok()?;

    let wallet: Wallet<_> = relayer_key.into();
    let wallet = wallet.with_chain_id(chain_id);

    Some(wallet)
}

/// Return an Ethereum RPC client.
#[cfg_attr(not(feature = "namada-eth-bridge"), allow(dead_code))]
pub async fn get_eth_rpc_client(url: &str) -> Arc<impl Middleware> {
    let client = Provider::<Http>::try_from(url)
        .expect("Failed to instantiate Ethereum RPC client");
    let chain_id = client
        .get_chainid()
        .await
        .expect("Failed to query chain id")
        .as_u64();
    let signer = get_eth_signer_from_env(chain_id).unwrap_or_else(|| {
        panic!("Failed to get Ethereum key from {RELAYER_KEY_ENV_VAR} env var")
    });
    Arc::new(SignerMiddleware::new(client, signer))
}