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
//! Home of RuntimeArgs for calling contracts

use alloc::{collections::BTreeMap, string::String, vec::Vec};

use crate::{
    bytesrepr::{self, Error, FromBytes, ToBytes},
    CLTyped, CLValue,
};

/// Named arguments to a contract
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct NamedArg(String, CLValue);

impl NamedArg {
    /// ctor
    pub fn new(name: String, value: CLValue) -> Self {
        NamedArg(name, value)
    }
    /// returns `name`
    pub fn name(&self) -> &str {
        &self.0
    }
    /// returns `value`
    pub fn cl_value(&self) -> &CLValue {
        &self.1
    }
}

impl From<(String, CLValue)> for NamedArg {
    fn from((name, value): (String, CLValue)) -> NamedArg {
        NamedArg(name, value)
    }
}

impl ToBytes for NamedArg {
    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        result.append(&mut self.0.to_bytes()?);
        result.append(&mut self.1.to_bytes()?);
        Ok(result)
    }

    fn serialized_length(&self) -> usize {
        self.0.serialized_length() + self.1.serialized_length()
    }
}

impl FromBytes for NamedArg {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
        let (name, remainder) = String::from_bytes(bytes)?;
        let (cl_value, remainder) = CLValue::from_bytes(remainder)?;
        Ok((NamedArg(name, cl_value), remainder))
    }
}

/// Represents a collection of arguments passed to a smart contract.
#[derive(PartialEq, Eq, Clone, Debug, Default)]
pub struct RuntimeArgs(Vec<NamedArg>);

impl RuntimeArgs {
    /// Create an empty [`RuntimeArgs`] instance.
    pub fn new() -> RuntimeArgs {
        RuntimeArgs::default()
    }

    /// Gets an argument by its name.
    pub fn get(&self, name: &str) -> Option<&CLValue> {
        self.0.iter().find_map(|NamedArg(named_name, named_value)| {
            if named_name == name {
                Some(named_value)
            } else {
                None
            }
        })
    }

    /// Get length of the collection.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Check if collection of arguments is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Insert new named argument into the collection.
    pub fn insert<K, V>(&mut self, key: K, value: V)
    where
        K: Into<String>,
        V: CLTyped + ToBytes,
    {
        let cl_value = CLValue::from_t(value).expect("should create CLValue");
        self.0.push(NamedArg(key.into(), cl_value));
    }

    /// Insert new named argument into the collection.
    pub fn insert_cl_value<K>(&mut self, key: K, cl_value: CLValue)
    where
        K: Into<String>,
    {
        self.0.push(NamedArg(key.into(), cl_value));
    }

    /// Returns values held regardless of the variant.
    pub fn to_values(&self) -> Vec<&CLValue> {
        self.0.iter().map(|NamedArg(_name, value)| value).collect()
    }
}

impl From<Vec<NamedArg>> for RuntimeArgs {
    fn from(values: Vec<NamedArg>) -> Self {
        RuntimeArgs(values)
    }
}

impl From<BTreeMap<String, CLValue>> for RuntimeArgs {
    fn from(cl_values: BTreeMap<String, CLValue>) -> RuntimeArgs {
        RuntimeArgs(cl_values.into_iter().map(NamedArg::from).collect())
    }
}

impl Into<BTreeMap<String, CLValue>> for RuntimeArgs {
    fn into(self) -> BTreeMap<String, CLValue> {
        let mut map = BTreeMap::new();
        for named in self.0 {
            map.insert(named.0, named.1);
        }
        map
    }
}

impl ToBytes for RuntimeArgs {
    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        self.0.to_bytes()
    }

    fn serialized_length(&self) -> usize {
        self.0.serialized_length()
    }
}

impl FromBytes for RuntimeArgs {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
        let (args, remainder) = Vec::<NamedArg>::from_bytes(bytes)?;
        Ok((RuntimeArgs(args), remainder))
    }
}

/// Macro that makes it easier to construct named arguments.
///
/// # Example usage
/// ```
/// use casperlabs_types::{RuntimeArgs, runtime_args};
/// let _named_args = runtime_args! {
///   "foo" => 42,
///   "bar" => "Hello, world!"
/// };
/// ```
#[macro_export]
macro_rules! runtime_args {
    () => (RuntimeArgs::new());
    ( $($key:expr => $value:expr,)+ ) => (runtime_args!($($key => $value),+));
    ( $($key:expr => $value:expr),* ) => {
        {
            let mut named_args = RuntimeArgs::new();
            $(
                named_args.insert($key, $value);
            )*
            named_args
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_runtime_args() {
        let arg1 = CLValue::from_t(1).unwrap();
        let arg2 = CLValue::from_t("Foo").unwrap();
        let arg3 = CLValue::from_t(Some(1)).unwrap();
        let args = {
            let mut map = BTreeMap::new();
            map.insert("bar".into(), arg2.clone());
            map.insert("foo".into(), arg1.clone());
            map.insert("qwer".into(), arg3.clone());
            map
        };
        let runtime_args = RuntimeArgs::from(args);
        assert_eq!(runtime_args.get("qwer"), Some(&arg3));
        assert_eq!(runtime_args.get("foo"), Some(&arg1));
        assert_eq!(runtime_args.get("bar"), Some(&arg2));
        assert_eq!(runtime_args.get("aaa"), None);

        // Ensure macro works

        let runtime_args_2 = runtime_args! {
            "bar" => "Foo",
            "foo" => 1i32,
            "qwer" => Some(1i32),
        };
        assert_eq!(runtime_args, runtime_args_2);
    }

    #[test]
    fn empty_macro() {
        assert_eq!(runtime_args! {}, RuntimeArgs::new());
    }

    #[test]
    fn btreemap_compat() {
        // This test assumes same serialization format as BTreeMap
        let runtime_args_1 = runtime_args! {
            "bar" => "Foo",
            "foo" => 1i32,
            "qwer" => Some(1i32),
        };
        let tagless = runtime_args_1.to_bytes().unwrap().to_vec();

        let mut runtime_args_2 = BTreeMap::new();
        runtime_args_2.insert(String::from("bar"), CLValue::from_t("Foo").unwrap());
        runtime_args_2.insert(String::from("foo"), CLValue::from_t(1i32).unwrap());
        runtime_args_2.insert(String::from("qwer"), CLValue::from_t(Some(1i32)).unwrap());

        assert_eq!(tagless, runtime_args_2.to_bytes().unwrap());
    }

    #[test]
    fn named_serialization_roundtrip() {
        let args = runtime_args! {
            "foo" => 1i32,
        };
        bytesrepr::test_serialization_roundtrip(&args);
    }
}