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
use crate::categories::Categories;
use parity_scale_codec::{Compact, Decode, Encode, Input, Output};
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>;

/// Struct representing limits on numbers (such has min and max values)
/// Sadly SCALE supports only unsigned integers, so we need to wrap the limits to u64 and unwrap them when decoding.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct Limits {
  /// The minimum value
  pub min: i64,
  /// The maximum value
  pub max: i64,
  /// Only used when we representing floating point numbers as integers
  /// The amount of scaling to apply to the fixed point value
  /// Convert the limit values to float by dividing the fixed point values with 10^scale.
  /// This allows us to derive a float representation of the limit values with the desired precision.
  pub scale: u32,
}

fn wrap_to_u64(x: i64) -> u64 {
  (x as u64).wrapping_add(u64::MAX / 2 + 1)
}

fn to_i64(x: u64) -> i64 {
  ((x as i64) ^ (1 << 63)) & (1 << 63) | (x & (u64::MAX >> 1)) as i64
}

impl Encode for Limits {
  fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
    Compact(wrap_to_u64(self.min)).encode_to(dest);
    Compact(wrap_to_u64(self.max)).encode_to(dest);
    Compact(self.scale).encode_to(dest);
  }
}

impl Decode for Limits {
  fn decode<I: Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
    Ok(Self {
      min: to_i64(Compact::<u64>::decode(input)?.into()),
      max: to_i64(Compact::<u64>::decode(input)?.into()),
      scale: Compact::<u32>::decode(input)?.into(),
    })
  }
}

/// Enum that represents the type of Code.
///
/// There are only two possible types of code:
/// 1. Shard
/// 2. Wire
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Copy, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub enum CodeType {
  /// A collection of shards that can be injected into more complex blocks of code or wires.
  Shards,
  /// A single wire that can be executed.
  Wire { looped: Option<bool> },
}

/// Struct that represents information about a Code.
///
/// Note: There are only two possible types of code: Shard and Wire.
/// See the `CodeType` enum for more information.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct CodeInfo {
  /// The type of code, either Shard or Wire.
  pub kind: CodeType,
  /// A list of variables that must be available to the code context before the code can be executed.
  /// Each variable is represented as a tuple of its name and its type.
  pub requires: Vec<(String, VariableType)>,
  /// A list of variables that are available in the code context.
  /// Each variable is represented as a tuple of its name and its type.
  pub exposes: Vec<(String, VariableType)>,
  /// A list of variable types that are inputted into the code.
  pub inputs: Vec<VariableType>,
  /// The variable type of the output generated by 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 {
  /// The names of the keys. An empty key represents any name and allows multiple instances of the corresponding index type.
  pub keys: Vec<String>,
  /// The types expected for each key, following the keys array (should be the same length).
  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 {
  // No type
  None,
  // Any type
  Any,
  // Boolean type
  Bool,
  // Color type (vector of 4 8-bit unsigned integers)
  Color,
  // Binary data type
  Bytes,
  // String type
  String,
  // Image type
  Image,
  // Audio type
  Audio,
  // Mesh type
  Mesh,

  // Enum type with vendor ID and type ID
  Enum {
    #[codec(compact)]
    vendor_id: u32,
    #[codec(compact)]
    type_id: u32,
  },

  // Integer type with optional limits
  Int(Option<Limits>),
  // Vector of 2 integers with optional limits
  Int2([Option<Limits>; 2]),
  // Vector of 3 integers with optional limits
  Int3([Option<Limits>; 3]),
  // Vector of 4 integers with optional limits
  Int4([Option<Limits>; 4]),
  // Vector of 8 integers with optional limits
  Int8([Option<Limits>; 8]),
  // Vector of 16 integers with optional limits
  Int16([Option<Limits>; 16]),

  // Float type with optional limits
  Float(Option<Limits>),
  // Vector of 2 floats with optional limits
  Float2([Option<Limits>; 2]),
  // Vector of 3 floats with optional limits
  Float3([Option<Limits>; 3]),
  // Vector of 4 floats with optional limits
  Float4([Option<Limits>; 4]),

  // Sequence of variable types with optional length limits
  Seq {
    types: Vec<VariableType>,
    length_limits: Option<Limits>,
  },

  // Table type
  Table(TableInfo),

  // Object type with vendor ID and type ID
  Object {
    #[codec(compact)]
    vendor_id: u32,
    #[codec(compact)]
    type_id: u32,
  },

  // Code type with information
  Code(Box<CodeInfo>),
  // Channel type with variable type
  Channel(Box<VariableType>),
  // Event type with variable type
  Event(Box<VariableType>),
  // Proto type with categories
  Proto(Categories),
}

/// 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>>,
}

#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, scale_info::TypeInfo)]
pub struct Record {
  pub name: String,
  pub types: Vec<VariableTypeInfo>,
}

impl From<(String, Vec<VariableTypeInfo>)> for Record {
  fn from((name, types): (String, Vec<VariableTypeInfo>)) -> Self {
    Self { name, types }
  }
}

/// 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,
  /// Revision of the Trait
  #[codec(compact)]
  pub revision: u32,
  /// 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<Record>,
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::categories::{TextCategories, TextureCategories};

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

    // THIS IS the way we reprocess the trait declaration before sorting it on chain and hashing it
    trait1 = trait1
      .into_iter()
      .map(|r| (r.name.to_lowercase(), r.types).into())
      .collect();
    trait1.dedup_by(|a, b| a.name == b.name);
    // 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.name.cmp(&b.name));

    let trait1 = Trait {
      name: "Trait1".to_string(),
      revision: 1,
      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<Record> = vec![
      (
        "int1".to_string(),
        vec![VariableTypeInfo {
          type_: VariableType::Int(None),
          default: None,
        }],
      )
        .into(),
      (
        "boxed1".to_string(),
        vec![VariableTypeInfo {
          type_: VariableType::Code(Box::new(CodeInfo {
            kind: CodeType::Wire { looped: None },
            requires: vec![("int1".to_string(), VariableType::Int(None))],
            exposes: vec![],
            inputs: vec![],
            output: VariableType::None,
          })),
          default: None,
        }],
      )
        .into(),
    ];

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

    let trait1 = Trait {
      name: "Trait1".to_string(),
      revision: 1,
      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].name == "boxed1".to_string());
    let type_ = &d_trait1.records[0].types[0].type_;
    let requires = match type_ {
      VariableType::Code(code) => &code.requires,
      _ => panic!("Should be a code"),
    };
    assert!(requires[0].0 == "int1".to_string());
  }

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

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

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

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

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

    assert!(trait1 == d_trait1);
  }

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

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

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

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

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

    assert!(trait1 == d_trait1);
    assert!(d_trait1.records[0].name == "boxed1".to_string());
    let type_ = &d_trait1.records[0].types[0].type_;
    let requires = match type_ {
      VariableType::Code(code) => &code.requires,
      _ => panic!("Should be a code"),
    };
    assert!(requires[0].0 == "int1".to_string());
  }

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

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

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

    assert!(trait1 == d_trait1);
  }

  #[test]
  fn test_json_textual_from_str_ambal() {
    let json_trait1 = r#"{
      "name": "AmbalLoreFragment",
      "revision": 1,
      "records": [
        {
          "name": "banner",
          "types": [
            {"type": {"Proto": {"texture": "pngFile"}}},
            {"type": {"Proto": {"texture": "jpgFile"}}},
            {"type": "Image"}
          ]
        },
        {
          "name": "content",
          "types": [
            {"type": {"Proto": {"text": "plain"}}},
            {"type": "String"}
          ]
        }
      ]
    }"#;

    let trait1 = Trait {
      name: "AmbalLoreFragment".to_string(),
      revision: 1,
      records: vec![
        (
          "banner".to_string(),
          vec![
            VariableTypeInfo {
              type_: VariableType::Proto(Categories::Texture(TextureCategories::PngFile)),
              default: None,
            }
            .into(),
            VariableTypeInfo {
              type_: VariableType::Proto(Categories::Texture(TextureCategories::JpgFile)),
              default: None,
            }
            .into(),
            VariableTypeInfo {
              type_: VariableType::Image,
              default: None,
            }
            .into(),
          ],
        )
          .into(),
        (
          "content".to_string(),
          vec![
            VariableTypeInfo {
              type_: VariableType::Proto(Categories::Text(TextCategories::Plain)),
              default: None,
            }
            .into(),
            VariableTypeInfo {
              type_: VariableType::String,
              default: None,
            }
            .into(),
          ],
        )
          .into(),
      ],
    };

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

    assert!(trait1 == d_trait1);
  }

  #[test]
  fn test_limits() {
    let limits = Limits {
      min: -100,
      max: 100,
      scale: 2,
    };

    let expected_min = -1.0;
    let expected_max = 1.0;

    // Convert the limit values to float by dividing the fixed point values with 10^scale.
    // This allows us to derive a float representation of the limit values with the desired precision.
    let float_min = limits.min as f64 / 10u64.pow(limits.scale) as f64;
    let float_max = limits.max as f64 / 10u64.pow(limits.scale) as f64;

    assert_eq!(float_min, expected_min);
    assert_eq!(float_max, expected_max);

    let encoded = limits.encode();
    let decoded = Limits::decode(&mut encoded.as_slice()).unwrap();
    assert!(limits == decoded);
  }
}