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
use crate::entry_point_callback::{Argument, EntryPointsCaller};
use crate::{prelude::*, OdraResult};
use crate::{CallDef, OdraError, VmError};
use casper_types::bytesrepr::Bytes;
use casper_types::RuntimeArgs;

/// A wrapper struct for a EntryPointsCaller that is a layer of abstraction between the host and the entry points caller.
///
/// The container validates a contract call definition before calling the entry point.
#[derive(Clone)]
pub struct ContractContainer {
    entry_points_caller: EntryPointsCaller
}

impl ContractContainer {
    /// Creates a new instance of `ContractContainer`.
    pub fn new(entry_points_caller: EntryPointsCaller) -> Self {
        Self {
            entry_points_caller
        }
    }

    /// Calls the entry point with the given call definition.
    pub fn call(&self, call_def: CallDef) -> OdraResult<Bytes> {
        // find the entry point
        let ep = self
            .entry_points_caller
            .entry_points()
            .iter()
            .find(|ep| ep.name == call_def.entry_point())
            .ok_or_else(|| {
                OdraError::VmError(VmError::NoSuchMethod(call_def.entry_point().to_string()))
            })?;
        // validate the args, return an error if the args are invalid
        self.validate_args(&ep.args, call_def.args())?;
        self.entry_points_caller.call(call_def)
    }

    fn validate_args(&self, args: &[Argument], input_args: &RuntimeArgs) -> OdraResult<()> {
        for arg in args {
            // check if the input args contain the arg
            if let Some(input) = input_args
                .named_args()
                .find(|input| input.name() == arg.name.as_str())
            {
                // check if the input arg has the expected type
                let input_ty = input.cl_value().cl_type();
                let expected_ty = &arg.ty;
                if input_ty != expected_ty {
                    return Err(OdraError::VmError(VmError::TypeMismatch {
                        expected: expected_ty.clone(),
                        found: input_ty.clone()
                    }));
                }
            } else {
                return Err(OdraError::VmError(VmError::MissingArg));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use casper_types::CLType;

    use super::ContractContainer;
    use crate::contract_context::MockContractContext;
    use crate::entry_point_callback::{Argument, EntryPoint, EntryPointsCaller};
    use crate::host::{HostEnv, MockHostContext};
    use crate::{
        casper_types::{runtime_args, RuntimeArgs},
        OdraError, VmError
    };
    use crate::{prelude::*, CallDef, ContractEnv};

    const TEST_ENTRYPOINT: &str = "ep";

    #[test]
    fn test_call_wrong_entrypoint() {
        // Given an instance with no entrypoints.
        let instance = ContractContainer::empty();

        // When call some entrypoint.
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, RuntimeArgs::new());
        let result = instance.call(call_def);

        // Then an error occurs.
        assert!(result.is_err());
    }

    #[test]
    fn test_call_valid_entrypoint() {
        // Given an instance with a single no-args entrypoint.
        let instance = ContractContainer::with_entrypoint(vec![]);

        // When call the registered entrypoint.
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, RuntimeArgs::new());
        let result = instance.call(call_def);

        // Then teh call succeeds.
        assert!(result.is_ok());
    }

    #[test]
    fn test_call_valid_entrypoint_with_wrong_arg_name() {
        // Given an instance with a single entrypoint with one arg named "first".
        let instance = ContractContainer::with_entrypoint(vec!["first"]);

        // When call the registered entrypoint with an arg named "second".
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, runtime_args! { "second" => 0u32 });
        let result = instance.call(call_def);

        // Then MissingArg error is returned.
        assert_eq!(result.unwrap_err(), OdraError::VmError(VmError::MissingArg));
    }

    #[test]
    fn test_call_valid_entrypoint_with_wrong_arg_type() {
        // Given an instance with a single entrypoint with one arg named "first".
        let instance = ContractContainer::with_entrypoint(vec!["first"]);

        // When call the registered entrypoint with an arg named "second".
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, runtime_args! { "first" => true });
        let result = instance.call(call_def);

        // Then MissingArg error is returned.
        assert_eq!(
            result.unwrap_err(),
            OdraError::VmError(VmError::TypeMismatch {
                expected: CLType::U32,
                found: CLType::Bool
            })
        );
    }

    #[test]
    fn test_call_valid_entrypoint_with_missing_arg() {
        // Given an instance with a single entrypoint with one arg named "first".
        let instance = ContractContainer::with_entrypoint(vec!["first"]);

        // When call a valid entrypoint without args.
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, RuntimeArgs::new());
        let result = instance.call(call_def);

        // Then MissingArg error is returned.
        assert_eq!(result.unwrap_err(), OdraError::VmError(VmError::MissingArg));
    }

    #[test]
    fn test_many_missing_args() {
        // Given an instance with a single entrypoint with "first", "second" and "third" args.
        let instance = ContractContainer::with_entrypoint(vec!["first", "second", "third"]);

        // When call a valid entrypoint with a single valid args,
        let call_def = CallDef::new(TEST_ENTRYPOINT, false, runtime_args! { "third" => 0u32 });
        let result = instance.call(call_def);

        // Then MissingArg error is returned.
        assert_eq!(result.unwrap_err(), OdraError::VmError(VmError::MissingArg));
    }

    impl ContractContainer {
        fn empty() -> Self {
            let ctx = Rc::new(RefCell::new(MockHostContext::new()));
            let env = HostEnv::new(ctx);
            let entry_points_caller = EntryPointsCaller::new(env, vec![], |_, call_def| {
                Err(OdraError::VmError(VmError::NoSuchMethod(
                    call_def.entry_point().to_string()
                )))
            });
            Self {
                entry_points_caller
            }
        }

        fn with_entrypoint(args: Vec<&str>) -> Self {
            let entry_points = vec![EntryPoint::new(
                String::from(TEST_ENTRYPOINT),
                args.iter()
                    .map(|name| Argument::new::<u32>(String::from(*name)))
                    .collect()
            )];
            let mut ctx = MockHostContext::new();
            ctx.expect_contract_env().returning(|| {
                ContractEnv::new(0, Rc::new(RefCell::new(MockContractContext::new())))
            });
            let env = HostEnv::new(Rc::new(RefCell::new(ctx)));

            let entry_points_caller = EntryPointsCaller::new(env, entry_points, |_, call_def| {
                if call_def.entry_point() == TEST_ENTRYPOINT {
                    Ok(vec![1, 2, 3].into())
                } else {
                    Err(OdraError::VmError(VmError::NoSuchMethod(
                        call_def.entry_point().to_string()
                    )))
                }
            });

            Self {
                entry_points_caller
            }
        }
    }
}