casper-contract-sdk 0.1.2

Casper contract sdk package
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use core::mem;

use crate::prelude::{
    collections,
    collections::{BTreeMap, BTreeSet, HashMap, LinkedList},
    str::FromStr,
};
use impl_trait_for_tuples::impl_for_tuples;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct EnumVariant {
    pub name: String,
    pub discriminant: u64,
    pub decl: Declaration,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct StructField {
    pub name: String,
    pub decl: Declaration,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub enum Primitive {
    Char,
    U8,
    I8,
    U16,
    I16,
    U32,
    I32,
    U64,
    I64,
    U128,
    I128,
    F32,
    F64,
    Bool,
}

impl FromStr for Primitive {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use Primitive::*;
        match s {
            "Char" => Ok(Char),
            "U8" => Ok(U8),
            "I8" => Ok(I8),
            "U16" => Ok(U16),
            "I16" => Ok(I16),
            "U32" => Ok(U32),
            "I32" => Ok(I32),
            "U64" => Ok(U64),
            "I64" => Ok(I64),
            "U128" => Ok(U128),
            "I128" => Ok(I128),
            "F32" => Ok(F32),
            "F64" => Ok(F64),
            "Bool" => Ok(Bool),
            _ => Err("Unknown primitive type"),
        }
    }
}

pub trait Keyable {
    const PRIMITIVE: Primitive;
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
#[serde(tag = "type")]
pub enum Definition {
    /// Primitive type.
    ///
    /// Examples: u64, i32, f32, bool, etc
    Primitive(Primitive),
    /// A mapping.
    ///
    /// Example Rust types: BTreeMap<K, V>.
    Mapping {
        key: Declaration,
        value: Declaration,
    },
    /// Arbitrary sequence of values.
    ///
    /// Example Rust types: `Vec<T>`, `&[T]`, `[T; N]`, `Box<[T]>`
    Sequence {
        /// If length is known, then it specifies that this definition should be be represented as
        /// an array of a fixed size.
        decl: Declaration,
    },
    FixedSequence {
        /// If length is known, then it specifies that this definition should be be represented as
        /// an array of a fixed size.
        length: u32, // None -> Vec<T> Some(N) [T; N]
        decl: Declaration,
    },
    /// A tuple of multiple values of various types.
    ///
    /// Can be also used to represent a heterogeneous list.
    Tuple {
        items: Vec<Declaration>,
    },
    Enum {
        items: Vec<EnumVariant>,
    },
    Struct {
        items: Vec<StructField>,
    },
}

impl Definition {
    pub fn unit() -> Self {
        // Empty struct should be equivalent to `()` in Rust in other languages.
        Definition::Tuple { items: Vec::new() }
    }

    pub fn as_struct(&self) -> Option<&[StructField]> {
        if let Self::Struct { items } = self {
            Some(items.as_slice())
        } else {
            None
        }
    }

    pub fn as_enum(&self) -> Option<&[EnumVariant]> {
        if let Self::Enum { items } = self {
            Some(items.as_slice())
        } else {
            None
        }
    }

    pub fn as_tuple(&self) -> Option<&[Declaration]> {
        if let Self::Tuple { items } = self {
            Some(items.as_slice())
        } else {
            None
        }
    }
}

#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Definitions(BTreeMap<Declaration, Definition>);

impl Definitions {
    pub fn populate_one<T: CasperABI>(&mut self) {
        T::populate_definitions(self);

        let decl = T::declaration();
        let def = T::definition();

        self.populate_custom(decl, def);
    }

    pub fn populate_custom(&mut self, decl: Declaration, def: Definition) {
        let previous = self.0.insert(decl.clone(), def.clone());
        if previous.is_some() && previous != Some(def.clone()) {
            panic!("Type {decl} has multiple definitions ({previous:?} != {def:?}).");
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = (&Declaration, &Definition)> {
        self.0.iter()
    }

    pub fn get(&self, decl: &str) -> Option<&Definition> {
        self.0.get(decl)
    }

    pub fn first(&self) -> Option<(&Declaration, &Definition)> {
        self.0.iter().next()
    }

    /// Returns true if the given declaration has a definition in this set.
    pub fn has_definition(&self, decl: &Declaration) -> bool {
        self.0.contains_key(decl)
    }
}

impl IntoIterator for Definitions {
    type Item = (Declaration, Definition);
    type IntoIter = collections::btree_map::IntoIter<Declaration, Definition>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

pub type Declaration = String;

pub trait CasperABI {
    fn populate_definitions(definitions: &mut Definitions);
    fn declaration() -> Declaration; // "String"
    fn definition() -> Definition; // Sequence { Char }
}

impl<T> CasperABI for &T
where
    T: CasperABI,
{
    fn populate_definitions(definitions: &mut Definitions) {
        T::populate_definitions(definitions);
    }

    fn declaration() -> Declaration {
        T::declaration()
    }

    fn definition() -> Definition {
        T::definition()
    }
}

impl<T> CasperABI for Box<T>
where
    T: CasperABI,
{
    fn populate_definitions(definitions: &mut Definitions) {
        T::populate_definitions(definitions);
    }

    fn declaration() -> Declaration {
        T::declaration()
    }

    fn definition() -> Definition {
        T::definition()
    }
}

macro_rules! impl_abi_for_types {
    // Accepts following syntax: impl_abi_for_types(u8, u16, u32, u64, String => "string", f32, f64)
    ($($ty:ty $(=> $name:expr)?,)* ) => {
        $(
            impl_abi_for_types!(@impl $ty $(=> $name)?);
        )*
    };

    (@impl $ty:ty ) => {
       impl_abi_for_types!(@impl $ty => stringify!($ty));
    };

    (@impl $ty:ty => $def:expr ) => {
        impl CasperABI for $ty {
            fn populate_definitions(_definitions: &mut Definitions) {
            }

            fn declaration() -> Declaration {
                stringify!($def).into()
            }

            fn definition() -> Definition {
                use Primitive::*;
                const PRIMITIVE: Primitive = $def;
                Definition::Primitive(PRIMITIVE)
            }
        }

        impl Keyable for $ty {
            const PRIMITIVE: Primitive = {
                use Primitive::*;
                $def
            };
        }
    };
}

impl CasperABI for () {
    fn populate_definitions(_definitions: &mut Definitions) {}

    fn declaration() -> Declaration {
        "()".into()
    }

    fn definition() -> Definition {
        Definition::unit()
    }
}

impl_abi_for_types!(
    char => Char,
    bool => Bool,
    u8 => U8,
    u16 => U16,
    u32 => U32,
    u64 => U64,
    u128 => U128,
    i8 => I8,
    i16 => I16,
    i32 => I32,
    i64 => I64,
    f32 => F32,
    f64 => F64,
    i128 => I128,
);

#[impl_for_tuples(1, 12)]
impl CasperABI for Tuple {
    fn populate_definitions(_definitions: &mut Definitions) {
        for_tuples!( #( _definitions.populate_one::<Tuple>(); )* )
    }

    fn declaration() -> Declaration {
        let items = <[_]>::into_vec(Box::new([for_tuples!( #( Tuple::declaration() ),* )]));
        format!("({})", items.join(", "))
    }

    fn definition() -> Definition {
        let items = <[_]>::into_vec(Box::new([for_tuples!( #( Tuple::declaration() ),* )]));
        Definition::Tuple { items }
    }
}

impl<T: CasperABI, E: CasperABI> CasperABI for Result<T, E> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<T>();
        definitions.populate_one::<E>();
    }

    fn declaration() -> Declaration {
        let t_decl = T::declaration();
        let e_decl = E::declaration();
        format!("Result<{t_decl}, {e_decl}>")
    }

    fn definition() -> Definition {
        Definition::Enum {
            items: vec![
                EnumVariant {
                    name: "Ok".into(),
                    discriminant: 0,
                    decl: T::declaration(),
                },
                EnumVariant {
                    name: "Err".into(),
                    discriminant: 1,
                    decl: E::declaration(),
                },
            ],
        }
    }
}

impl<T: CasperABI> CasperABI for Option<T> {
    fn declaration() -> Declaration {
        format!("Option<{}>", T::declaration())
    }
    fn definition() -> Definition {
        Definition::Enum {
            items: vec![
                EnumVariant {
                    name: "None".into(),
                    discriminant: 0,
                    decl: <()>::declaration(),
                },
                EnumVariant {
                    name: "Some".into(),
                    discriminant: 1,
                    decl: T::declaration(),
                },
            ],
        }
    }

    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<()>();
        definitions.populate_one::<T>();
    }
}

impl<T: CasperABI> CasperABI for Vec<T> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<T>();
    }

    fn declaration() -> Declaration {
        format!("Vec<{}>", T::declaration())
    }
    fn definition() -> Definition {
        Definition::Sequence {
            decl: T::declaration(),
        }
    }
}

impl<T: CasperABI, const N: usize> CasperABI for [T; N] {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<T>();
    }

    fn declaration() -> Declaration {
        format!("[{}; {N}]", T::declaration())
    }
    fn definition() -> Definition {
        Definition::FixedSequence {
            length: N.try_into().expect("N is too big"),
            decl: T::declaration(),
        }
    }
}

impl<K: CasperABI, V: CasperABI> CasperABI for BTreeMap<K, V> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<K>();
        definitions.populate_one::<V>();
    }

    fn declaration() -> Declaration {
        format!("BTreeMap<{}, {}>", K::declaration(), V::declaration())
    }

    fn definition() -> Definition {
        Definition::Mapping {
            key: K::declaration(),
            value: V::declaration(),
        }
    }
}

impl<K: CasperABI, V: CasperABI> CasperABI for HashMap<K, V> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<K>();
        definitions.populate_one::<V>();
    }

    fn declaration() -> Declaration {
        format!("HashMap<{}, {}>", K::declaration(), V::declaration())
    }

    fn definition() -> Definition {
        Definition::Mapping {
            key: K::declaration(),
            value: V::declaration(),
        }
    }
}

impl CasperABI for String {
    fn populate_definitions(_definitions: &mut Definitions) {}

    fn declaration() -> Declaration {
        "String".into()
    }
    fn definition() -> Definition {
        Definition::Sequence {
            decl: char::declaration(),
        }
    }
}

impl CasperABI for str {
    fn populate_definitions(_definitions: &mut Definitions) {}

    fn declaration() -> Declaration {
        "String".into()
    }
    fn definition() -> Definition {
        Definition::Sequence {
            decl: char::declaration(),
        }
    }
}

impl CasperABI for &str {
    fn populate_definitions(_definitions: &mut Definitions) {}

    fn declaration() -> Declaration {
        "String".into()
    }

    fn definition() -> Definition {
        Definition::Sequence {
            decl: char::declaration(),
        }
    }
}

impl<T: CasperABI> CasperABI for LinkedList<T> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<T>();
    }

    fn declaration() -> Declaration {
        format!("LinkedList<{}>", T::declaration())
    }
    fn definition() -> Definition {
        Definition::Sequence {
            decl: T::declaration(),
        }
    }
}

impl<T: CasperABI> CasperABI for BTreeSet<T> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<T>();
    }

    fn declaration() -> Declaration {
        format!("BTreeSet<{}>", T::declaration())
    }
    fn definition() -> Definition {
        Definition::Sequence {
            decl: T::declaration(),
        }
    }
}

impl<const N: usize> CasperABI for bnum::BUint<N> {
    fn populate_definitions(definitions: &mut Definitions) {
        definitions.populate_one::<u64>();
    }

    fn declaration() -> Declaration {
        let width_bytes: usize = mem::size_of::<bnum::BUint<N>>();
        let width_bits: usize = width_bytes * 8;
        format!("U{width_bits}")
    }

    fn definition() -> Definition {
        let length: u32 = N.try_into().expect("N is too big");
        Definition::FixedSequence {
            length,
            decl: u64::declaration(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        abi::{CasperABI, Definition},
        types::U256,
    };

    #[test]
    fn u256_schema() {
        assert_eq!(U256::declaration(), "U256");
        assert_eq!(
            U256::definition(),
            Definition::FixedSequence {
                length: 4,
                decl: u64::declaration()
            }
        );

        let mut value = U256::from(u128::MAX);
        value += U256::from(1u64);
        let bytes = borsh::to_vec(&value).unwrap();
        // Ensure bnum's borsh serialize/deserialize is what we consider "FixedSequence"
        let bytes_back: [u64; 4] = borsh::from_slice(&bytes).unwrap();
        let value_back = U256::from_digits(bytes_back);
        assert_eq!(value, value_back);
    }
}