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
use parity_scale_codec::{Decode, Encode};
use scale_info::prelude::{boxed::Box, vec::Vec};

#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};

// For more info refer to:
// https://github.com/fragcolor-xyz/shards/blob/devel/include/shards.h

#[cfg(not(feature = "std"))]
type String = Vec<u8>;

#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Copy, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub enum TriState {
    Either,
    True,
    False,
}

/// Enum that represents the Code Type.
///
/// Note: There can only be 2 Code Types:
/// 1. A Shard
/// 2. A Wire
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Copy, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub enum CodeType {
    /// A list of shards, to be injected into more complex blocks of code or wires
    Shards,
    /// An actual wire
    Wire { looped: TriState },
}

/// Struct represents the information about a Code (Note: There are only 2 Code Types: A Shard or a Wire. See the enum `CodeType` above to understand more)
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct CodeInfo {
    /// The Type of the Code (i.e the Code Type)
    pub kind: CodeType,
    /// List of variables that must be available to the Code's code context, before the Code even executes. Otherwise, the
    ///
    /// Note: Each variable is represented as a tuple of its name and its type.
    pub requires: Vec<(String, VariableType)>,
    /// List of variables that are in the Code's code context. Each variable is represented as a tuple of its name and its type.
    pub exposes: Vec<(String, VariableType)>,
    /// List of variable types that are inputted into the Code
    pub inputs: Vec<VariableType>,
    /// The variable type of the output of the Code
    pub output: VariableType,
}

#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct TableInfo {
    /// Tha name of the keys, an empty key represent any name, allowing multiple instances of the corresponding index type
    pub keys: Vec<String>,
    /// Following keys array (should be same len), the types expected
    pub types: Vec<Vec<VariableType>>,
}

/// Enum represents all the possible types that a variable can be
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub enum VariableType {
    None,
    Any,
    /// VendorID, TypeID
    Enum {
        vendor_id: u32,
        type_id: u32,
    },
    Bool,
    /// A 64bits int
    Int,
    /// A vector of 2 64bits ints
    Int2,
    /// A vector of 3 32bits ints
    Int3,
    /// A vector of 4 32bits ints
    Int4,
    /// A vector of 8 16bits ints
    Int8,
    /// A vector of 16 8bits ints
    Int16,
    /// A 64bits float
    Float,
    /// A vector of 2 64bits floats
    Float2,
    /// A vector of 3 32bits floats
    Float3,
    /// A vector of 4 32bits floats
    Float4,
    /// A vector of 4 uint8
    Color,
    // Non Blittables
    Bytes,
    String,
    Image,
    Seq(Vec<VariableType>),
    Table(TableInfo),
    /// VendorID, TypeID
    Object {
        vendor_id: u32,
        type_id: u32,
    },
    Audio,
    Code(Box<CodeInfo>),
    Mesh,
    Channel(Box<VariableType>),
}

/// Struct contains information about a variable type
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct VariableTypeInfo {
    /// The variable type
    #[cfg_attr(feature = "std", serde(alias = "type"))]
    pub type_: VariableType,
    /// Raw-bytes representation of the default value of the variable type (optional)
    pub default: Option<Vec<u8>>,
}

/// TODO Review - Definition
/// A Trait Attribute's Type
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub enum RecordInfo {
    SingleType(VariableTypeInfo),
    MultipleTypes(Vec<VariableTypeInfo>),
}

/// Struct represents a Trait
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct Trait {
    /// Name of the Trait
    pub name: String,
    /// List of attributes of the Trait. An attribute is represented as a **tuple that contains the attribute's name and the attribute's type**.
    pub records: Vec<(String, RecordInfo)>,
}

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

    #[test]
    fn encode_decode_simple_1() {
        let mut trait1 = vec![(
            "int1".to_string(),
            RecordInfo::SingleType(VariableTypeInfo {
                type_: VariableType::Int,
                default: None,
            }),
        )];

        // THIS IS the way we reprocess the trait declaration before sorting it on chain and hashing it
        trait1 = trait1
            .into_iter()
            .map(|(name, info)| (name.to_lowercase(), info))
            .collect();
        trait1.dedup_by(|a, b| a.0 == b.0);
        // Note: "Strings are ordered lexicographically by their byte values ... This is not necessarily the same as “alphabetical” order, which varies by language and locale". Source: https://doc.rust-lang.org/std/primitive.str.html#impl-Ord-for-str
        trait1.sort_by(|a, b| a.0.cmp(&b.0));

        let trait1 = Trait {
            name: "Trait1".to_string(),
            records: trait1,
        };

        let e_trait1 = trait1.encode();

        let d_trait1 = Trait::decode(&mut e_trait1.as_slice()).unwrap();

        assert!(trait1 == d_trait1);
    }

    #[test]
    fn encode_decode_boxed_1() {
        let mut trait1 = vec![
            (
                "int1".to_string(),
                RecordInfo::SingleType(VariableTypeInfo {
                    type_: VariableType::Int,
                    default: None,
                }),
            ),
            (
                "boxed1".to_string(),
                RecordInfo::SingleType(VariableTypeInfo {
                    type_: VariableType::Code(Box::new(CodeInfo {
                        kind: CodeType::Wire {
                            looped: TriState::Either,
                        },
                        requires: vec![("int1".to_string(), VariableType::Int)],
                        exposes: vec![],
                        inputs: vec![],
                        output: VariableType::None,
                    })),
                    default: None,
                }),
            ),
        ];

        // THIS IS the way we reprocess the trait declaration before sorting it on chain and hashing it
        trait1 = trait1
            .into_iter()
            .map(|(name, info)| (name.to_lowercase(), info))
            .collect();
        trait1.dedup_by(|a, b| a.0 == b.0);
        trait1.sort_by(|a, b| a.0.cmp(&b.0));

        let trait1 = Trait {
            name: "Trait1".to_string(),
            records: trait1,
        };

        let e_trait1 = trait1.encode();

        let d_trait1 = Trait::decode(&mut e_trait1.as_slice()).unwrap();

        assert!(trait1 == d_trait1);
        assert!(d_trait1.records[0].0 == "boxed1".to_string());
        let requires = match d_trait1.records[0].1 {
            RecordInfo::SingleType(VariableTypeInfo {
                type_: VariableType::Code(ref code),
                default: None,
            }) => code.requires.clone(),
            _ => panic!("Expected a code"),
        };
        assert!(requires[0].0 == "int1".to_string());
    }

    #[test]
    fn test_json_simple_1() {
        let mut trait1 = vec![(
            "int1".to_string(),
            RecordInfo::SingleType(VariableTypeInfo {
                type_: VariableType::Int,
                default: None,
            }),
        )];

        // THIS IS the way we reprocess the trait declaration before sorting it on chain and hashing it
        trait1 = trait1
            .into_iter()
            .map(|(name, info)| (name.to_lowercase(), info))
            .collect();
        trait1.dedup_by(|a, b| a.0 == b.0);
        trait1.sort_by(|a, b| a.0.cmp(&b.0));

        let trait1 = Trait {
            name: "Trait1".to_string(),
            records: trait1,
        };

        let json_trait1 = serde_json::to_string(&trait1).unwrap();

        println!("json_trait1: {}", json_trait1);

        let d_trait1 = serde_json::from_str(&json_trait1).unwrap();

        assert!(trait1 == d_trait1);
    }

    #[test]
    fn test_json_boxed_1() {
        let mut trait1 = vec![
            (
                "int1".to_string(),
                RecordInfo::SingleType(VariableTypeInfo {
                    type_: VariableType::Int,
                    default: None,
                }),
            ),
            (
                "boxed1".to_string(),
                RecordInfo::SingleType(VariableTypeInfo {
                    type_: VariableType::Code(Box::new(CodeInfo {
                        kind: CodeType::Wire {
                            looped: TriState::Either,
                        },
                        requires: vec![("int1".to_string(), VariableType::Int)],
                        exposes: vec![],
                        inputs: vec![],
                        output: VariableType::None,
                    })),
                    default: None,
                }),
            ),
        ];

        // THIS IS the way we reprocess the trait declaration before sorting it on chain and hashing it
        trait1 = trait1
            .into_iter()
            .map(|(name, info)| (name.to_lowercase(), info))
            .collect();
        trait1.dedup_by(|a, b| a.0 == b.0);
        trait1.sort_by(|a, b| a.0.cmp(&b.0));

        let trait1 = Trait {
            name: "Trait1".to_string(),
            records: trait1,
        };

        let json_trait1 = serde_json::to_string(&trait1).unwrap();

        let d_trait1 = serde_json::from_str(&json_trait1).unwrap();

        assert!(trait1 == d_trait1);
        assert!(d_trait1.records[0].0 == "boxed1".to_string());
        let requires = match d_trait1.records[0].1 {
            RecordInfo::SingleType(VariableTypeInfo {
                type_: VariableType::Code(ref code),
                default: None,
            }) => code.requires.clone(),
            _ => panic!("Expected a code"),
        };
        assert!(requires[0].0 == "int1".to_string());
    }

    #[test]
    fn test_json_textual_from_str() {
        let trait1 = Trait {
            name: "Trait1".to_string(),
            records: vec![(
                "int1".to_string(),
                RecordInfo::SingleType(VariableTypeInfo {
                    type_: VariableType::Int,
                    default: None,
                }),
            )],
        };

        let json_trait1 = r#"{"name":"Trait1","records":[["int1",{"SingleType":{"type":"Int","default":null}}]]}"#;

        let d_trait1 = serde_json::from_str(&json_trait1).unwrap();

        assert!(trait1 == d_trait1);
    }
}