odra-cli 2.6.0

Odra CLI - Command Line Interface for Odra smart contracts.
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
use std::any::Any;

use crate::cmd::args::CommandArg;
use crate::cmd::SCENARIOS_SUBCOMMAND;
use crate::custom_types::CustomTypeSet;
use crate::{container::ContractError, types, DeployedContractsContainer};
use anyhow::Result;
use clap::{ArgMatches, Command};
use odra::casper_types::{CLTyped, CLValue};
use odra::schema::NamedCLTyped;
use odra::{casper_types::bytesrepr::FromBytes, host::HostEnv, prelude::OdraError};
use thiserror::Error;

use super::OdraCommand;

/// Scenario is a trait that represents a custom scenario.
///
/// A scenario is a user-defined set of actions that can be run in the Odra CLI.
/// If you want to run a custom scenario that calls multiple entry points,
/// you need to implement this trait.
pub trait Scenario: Any {
    fn args(&self) -> Vec<CommandArg> {
        vec![]
    }
    fn run(
        &self,
        env: &HostEnv,
        container: &DeployedContractsContainer,
        args: ScenarioArgs
    ) -> core::result::Result<(), ScenarioError>;
}

#[derive(Default)]
pub(crate) struct ScenariosCmd {
    scenarios: Vec<ScenarioCmd>
}

impl ScenariosCmd {
    pub fn add_scenario<S: ScenarioMetadata + Scenario>(&mut self, scenario: S) {
        self.scenarios.push(ScenarioCmd::new(scenario));
    }
}

impl OdraCommand for ScenariosCmd {
    fn run(
        &self,
        env: &HostEnv,
        args: &ArgMatches,
        types: &CustomTypeSet,
        container: &DeployedContractsContainer
    ) -> Result<()> {
        args.subcommand()
            .map(|(scenario_name, scenario_args)| {
                self.scenarios
                    .iter()
                    .find(|cmd| cmd.name == scenario_name)
                    .map(|scenario| scenario.run(env, scenario_args, types, container))
                    .unwrap_or(Err(anyhow::anyhow!("No scenario found")))
            })
            .unwrap_or(Err(anyhow::anyhow!("No scenario found")))
    }
}

impl From<&ScenariosCmd> for Command {
    fn from(value: &ScenariosCmd) -> Self {
        Command::new(SCENARIOS_SUBCOMMAND)
            .about("Commands for interacting with scenarios")
            .subcommand_required(true)
            .arg_required_else_help(true)
            .subcommands(&value.scenarios)
    }
}

/// ScenarioCmd is a struct that represents a scenario command in the Odra CLI.
///
/// The scenario command runs a [Scenario]. A scenario is a user-defined set of
/// actions that can be run in the Odra CLI.
struct ScenarioCmd {
    name: String,
    description: String,
    scenario: Box<dyn Scenario>
}

impl ScenarioCmd {
    pub fn new<S: ScenarioMetadata + Scenario>(scenario: S) -> Self {
        ScenarioCmd {
            name: S::NAME.to_string(),
            description: S::DESCRIPTION.to_string(),
            scenario: Box::new(scenario)
        }
    }
}

impl OdraCommand for ScenarioCmd {
    fn run(
        &self,
        env: &HostEnv,
        args: &ArgMatches,
        _types: &CustomTypeSet,
        container: &DeployedContractsContainer
    ) -> Result<()> {
        let args = ScenarioArgs::new(args);
        env.set_captures_events(false);
        self.scenario.run(env, container, args)?;
        Ok(())
    }
}

impl From<&ScenarioCmd> for Command {
    fn from(value: &ScenarioCmd) -> Self {
        Command::new(&value.name)
            .about(&value.description)
            .args(value.scenario.args())
    }
}

/// ScenarioError is an enum representing the different errors that can occur when running a scenario.
#[derive(Debug, Error)]
pub enum ScenarioError {
    #[error("Odra error: {message}")]
    OdraError { message: String },
    #[error("Contract read error: {0}")]
    ContractReadError(#[from] ContractError),
    #[error("Arg error")]
    ArgError(#[from] ArgError),
    #[error("Types error")]
    TypesError(#[from] types::Error),
    #[error("Missing scenario argument: {0}")]
    MissingScenarioArg(String)
}

impl From<OdraError> for ScenarioError {
    fn from(err: OdraError) -> Self {
        ScenarioError::OdraError {
            message: format!("{:?}", err)
        }
    }
}

/// ScenarioArgs is a struct that represents the arguments passed to a scenario.
pub struct ScenarioArgs<'a>(&'a ArgMatches);

impl<'a> ScenarioArgs<'a> {
    pub(crate) fn new(matches: &'a ArgMatches) -> Self {
        Self(matches)
    }

    pub fn get_single<T: NamedCLTyped + FromBytes + CLTyped>(
        &self,
        name: &str
    ) -> Result<T, ScenarioError> {
        let arg = self
            .0
            .try_get_one::<CLValue>(name)
            .map_err(|_| ScenarioError::ArgError(ArgError::UnexpectedArg(name.to_string())))?
            .ok_or(ArgError::MissingArg(name.to_string()))?;

        arg.clone()
            .into_t::<T>()
            .map_err(|_| ScenarioError::ArgError(ArgError::Deserialization))
    }

    pub fn get_many<T: NamedCLTyped + FromBytes + CLTyped>(
        &self,
        name: &str
    ) -> Result<Vec<T>, ScenarioError> {
        self.0
            .try_get_many::<CLValue>(name)
            .map_err(|_| ScenarioError::ArgError(ArgError::UnexpectedArg(name.to_string())))?
            .unwrap_or_default()
            .collect::<Vec<_>>()
            .into_iter()
            .map(|value| value.clone().into_t::<T>())
            .collect::<Result<Vec<T>, _>>()
            .map_err(|_| ScenarioError::ArgError(ArgError::Deserialization))
    }
}

/// ArgError is an enum representing the different errors that can occur when parsing scenario arguments.
#[derive(Debug, Error, PartialEq)]
pub enum ArgError {
    #[error("Arg deserialization failed")]
    Deserialization,
    #[error("Multiple values expected")]
    ManyExpected,
    #[error("Single value expected")]
    SingleExpected,
    #[error("Missing arg: {0}")]
    MissingArg(String),
    #[error("Unexpected arg: {0}")]
    UnexpectedArg(String)
}

/// ScenarioMetadata is a trait that represents the metadata of a scenario.
pub trait ScenarioMetadata {
    const NAME: &'static str;
    const DESCRIPTION: &'static str;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils;
    use odra::schema::casper_contract_schema::NamedCLType;

    struct TestScenario;

    impl Scenario for TestScenario {
        fn args(&self) -> Vec<CommandArg> {
            vec![
                CommandArg::new("arg1", "First argument", NamedCLType::U32).required(),
                CommandArg::new("arg2", "Second argument", NamedCLType::String),
                CommandArg::new("arg3", "Optional argument", NamedCLType::String).list(),
            ]
        }

        fn run(
            &self,
            _env: &HostEnv,
            _container: &DeployedContractsContainer,
            args: ScenarioArgs
        ) -> core::result::Result<(), ScenarioError> {
            _ = args.get_single::<u32>("arg1")?;
            _ = args.get_single::<String>("arg2")?;
            _ = args.get_many::<String>("arg3")?;
            Ok(())
        }
    }

    impl ScenarioMetadata for TestScenario {
        const NAME: &'static str = "test_scenario";
        const DESCRIPTION: &'static str = "A test scenario for unit testing";
    }

    #[test]
    fn test_scenarios_command() {
        let mut scenarios = ScenariosCmd::default();
        scenarios.add_scenario(TestScenario);

        let cmd: Command = (&scenarios).into();

        assert_eq!(cmd.get_name(), SCENARIOS_SUBCOMMAND);
        assert!(cmd
            .get_subcommands()
            .any(|c| c.get_name() == "test_scenario"));
    }

    #[test]
    fn test_match_required_args() {
        let cmd = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&cmd).into();

        let matches = cmd.try_get_matches_from(vec!["odra-cli", "--arg1", "1"]);
        assert!(matches.is_ok());
        assert_eq!(
            matches.unwrap().get_one::<CLValue>("arg1"),
            Some(&CLValue::from_t(1u32).unwrap())
        );
    }

    #[test]
    fn test_match_required_arg_missing() {
        let cmd = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&cmd).into();

        let matches = cmd.try_get_matches_from(vec!["odra-cli"]);
        assert!(matches.is_err());
        assert_eq!(
            matches.unwrap_err().kind(),
            clap::error::ErrorKind::MissingRequiredArgument
        );
    }

    #[test]
    fn test_match_required_arg_with_wrong_type() {
        let cmd = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&cmd).into();

        let matches = cmd.try_get_matches_from(vec!["odra-cli", "--arg1", "not_a_number"]);
        assert!(matches.is_err());
        assert_eq!(
            matches.unwrap_err().kind(),
            clap::error::ErrorKind::InvalidValue
        );
    }

    #[test]
    fn test_match_optional_args() {
        let cmd = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&cmd).into();

        let matches = cmd.try_get_matches_from(vec![
            "odra-cli", "--arg1", "1", "--arg2", "test", "--arg3", "value1", "--arg3", "value2",
        ]);
        assert!(matches.is_ok());
        let matches = matches.unwrap();
        assert_eq!(
            matches.get_one::<CLValue>("arg1"),
            Some(&CLValue::from_t(1u32).unwrap())
        );
        assert_eq!(
            matches.get_one::<CLValue>("arg2"),
            Some(&CLValue::from_t("test".to_string()).unwrap())
        );
        assert_eq!(
            matches
                .get_many::<CLValue>("arg3")
                .unwrap()
                .collect::<Vec<_>>(),
            vec![
                &CLValue::from_t("value1".to_string()).unwrap(),
                &CLValue::from_t("value2".to_string()).unwrap()
            ]
        );
    }

    #[test]
    fn test_matching_list_args() {
        let scenario = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&scenario).into();

        let matches = cmd.try_get_matches_from(vec![
            "odra-cli", "--arg1", "1", "--arg3", "value1", "--arg3", "value2",
        ]);
        assert!(matches.is_ok());
        let matches = matches.unwrap();
        assert_eq!(
            matches
                .get_many::<CLValue>("arg3")
                .unwrap()
                .collect::<Vec<_>>(),
            vec![
                &CLValue::from_t("value1".to_string()).unwrap(),
                &CLValue::from_t("value2".to_string()).unwrap()
            ]
        );

        // If we pass `arg2` multiple times, it should return an error
        let cmd: Command = (&scenario).into();
        let matches = cmd.try_get_matches_from(vec![
            "odra-cli", "--arg1", "1", "--arg2", "value1", "--arg2", "value2",
        ]);

        assert!(matches.is_err());
        assert_eq!(
            matches.unwrap_err().kind(),
            clap::error::ErrorKind::ArgumentConflict
        );
    }

    #[test]
    fn test_scenario_args_get_single() {
        let scenario = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&scenario).into();

        let matches = cmd
            .try_get_matches_from(vec!["odra-cli", "--arg1", "42", "--arg2", "test_value"])
            .unwrap();

        let args = ScenarioArgs::new(&matches);
        let arg1: u32 = args.get_single("arg1").unwrap();
        assert_eq!(arg1, 42);

        let arg2: String = args.get_single("arg2").unwrap();
        assert_eq!(arg2, "test_value");
    }

    #[test]
    fn test_scenario_args_get_many() {
        let scenario = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&scenario).into();

        let matches = cmd
            .try_get_matches_from(vec![
                "odra-cli", "--arg1", "42", "--arg3", "value1", "--arg3", "value2",
            ])
            .unwrap();

        let args = ScenarioArgs::new(&matches);
        let arg3: Vec<String> = args.get_many("arg3").unwrap();
        assert_eq!(arg3, vec!["value1".to_string(), "value2".to_string()]);
    }

    #[test]
    fn test_run_cmd() {
        let scenario = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&scenario).into();

        let matches = cmd
            .try_get_matches_from(vec![
                "odra-cli",
                "--arg1",
                "42",
                "--arg2",
                "test_value",
                "--arg3",
                "value1",
                "--arg3",
                "value2",
            ])
            .unwrap();

        let env = test_utils::mock_host_env();
        let container = test_utils::mock_contracts_container();
        let result = scenario.run(&env, &matches, &CustomTypeSet::default(), &container);
        assert!(result.is_ok());
    }

    #[test]
    fn test_scenario_args_missing_arg() {
        let scenario = ScenarioCmd::new(TestScenario);
        let cmd: Command = (&scenario).into();

        let matches = cmd.get_matches_from(vec!["odra-cli", "--arg1", "1", "--arg2", "value1"]);
        ScenarioArgs(&matches)
            .get_single::<u32>("arg3")
            .expect_err("Expected an error for missing arg3");

        assert_eq!(ScenarioArgs(&matches).get_single::<u32>("arg1").unwrap(), 1);
    }
}