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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
#![allow(deprecated)]

use core::fmt;

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

use codec::{Decode, Encode};

#[cfg(not(feature = "std"))]
use alloc::{format, string::String};
use sp_std::prelude::*;

pub use scale_info::{form::PortableForm, TypeDefPrimitive};

#[derive(Clone, Debug, Default)]
pub struct TypeForm;

impl scale_info::form::Form for TypeForm {
  type Type = TypeId;
  type String = String;
}

#[derive(Clone, Debug, Default, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Path {
  pub segments: Vec<String>,
}

impl fmt::Display for Path {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.segments.join("::"))
  }
}

impl Path {
  pub fn new(ident: &str, module_path: &str) -> Self {
    let mut segments = module_path
      .split("::")
      .filter(|s| !s.is_empty())
      .map(|s| s.into())
      .collect::<Vec<_>>();
    if ident != "" {
      segments.push(ident.into());
    }
    Self { segments }
  }

  pub fn is_empty(&self) -> bool {
    self.segments.is_empty()
  }

  pub fn ident(&self) -> Option<&str> {
    self.segments.last().map(|s| s.as_str())
  }

  pub fn namespace(&self) -> &[String] {
    self.segments.split_last().map(|(_, ns)| ns).unwrap_or(&[])
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeParameter {
  pub name: String,
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub ty: Option<TypeId>,
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Type {
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Path::is_empty", default)
  )]
  pub path: Path,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub type_params: Vec<TypeParameter>,
  #[cfg_attr(feature = "serde", serde(rename = "def"))]
  pub type_def: TypeDef,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub docs: Vec<String>,
}

impl Type {
  pub fn new(name: &str, type_def: TypeDef) -> Self {
    Self {
      path: Path::new(name, ""),
      type_def,
      type_params: Default::default(),
      docs: Default::default(),
    }
  }

  pub fn path(&self) -> &Path {
    &self.path
  }

  pub fn type_params(&self) -> &[TypeParameter] {
    self.type_params.as_slice()
  }

  pub fn type_def(&self) -> &TypeDef {
    &self.type_def
  }

  pub fn is_u8(&self) -> bool {
    match &self.type_def {
      TypeDef::Primitive(TypeDefPrimitive::U8) => true,
      _ => false,
    }
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Field {
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Option::is_none", default)
  )]
  pub name: Option<String>,
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub ty: TypeId,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Option::is_none", default)
  )]
  pub type_name: Option<String>,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub docs: Vec<String>,
}

impl Field {
  pub fn new(ty: TypeId) -> Self {
    Self {
      name: None,
      ty,
      type_name: None,
      docs: Vec::new(),
    }
  }

  pub fn new_named(name: &str, ty: TypeId, type_name: Option<String>) -> Self {
    Self {
      name: Some(name.into()),
      ty,
      type_name,
      docs: Vec::new(),
    }
  }
}

#[derive(Clone, Debug, Default, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Variant {
  pub name: String,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub fields: Vec<Field>,
  pub index: u8,
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub docs: Vec<String>,
}

impl Variant {
  pub fn new(name: &str, fields: Vec<Field>, index: u8) -> Self {
    Self {
      name: name.into(),
      fields,
      index,
      docs: Vec::new(),
    }
  }

  /// Check if the variant is a tuple enum variant or struct enum variant (all fields need to have names).
  pub fn is_struct(&self) -> bool {
    named_fields(self.fields.as_slice())
  }
}

#[derive(Clone, Debug, Default, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeDefVariant {
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub variants: Vec<Variant>,
}

impl TypeDefVariant {
  pub fn new() -> Self {
    Self::default()
  }

  pub fn new_variants(variants: Vec<Variant>) -> Self {
    Self { variants }
  }

  pub fn new_option(ty: TypeId) -> Self {
    Self {
      variants: vec![
        Variant::new("None", vec![], 0),
        Variant::new("Some", vec![Field::new(ty)], 1),
      ],
    }
  }

  pub fn new_result(ok_ty: TypeId, err_ty: TypeId) -> Self {
    Self {
      variants: vec![
        Variant::new("Ok", vec![Field::new(ok_ty)], 0),
        Variant::new("Err", vec![Field::new(err_ty)], 1),
      ],
    }
  }

  pub fn insert(&mut self, index: u8, name: &str, field: Option<TypeId>) {
    self.variants.push(Variant {
      name: name.into(),
      index,
      fields: field.into_iter().map(|id| Field::new(id)).collect(),
      docs: vec![],
    })
  }

  pub fn get_by_idx(&self, index: u8) -> Option<&Variant> {
    // Try quick search.
    let variant = self
      .variants
      .get(index as usize)
      .filter(|v| v.index == index);
    if variant.is_some() {
      return variant;
    }
    // fallback to linear search.
    for variant in &self.variants {
      if variant.index == index {
        return Some(variant);
      }
    }
    // Not found.
    None
  }

  pub fn get_by_name(&self, name: &str) -> Option<&Variant> {
    self.variants.iter().find(|v| v.name == name)
  }
}

/// Check if the variant is a tuple enum variant or struct enum variant (all fields need to have names).
fn named_fields(fields: &[Field]) -> bool {
  let mut named = true;
  for field in fields {
    if field.name.is_none() {
      // If there are any unnamed fields, then it is a tuple.
      named = false;
      break;
    }
  }
  named
}

#[derive(Clone, Debug, Default, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeDefComposite {
  #[cfg_attr(
    feature = "serde",
    serde(skip_serializing_if = "Vec::is_empty", default)
  )]
  pub fields: Vec<Field>,
}

impl TypeDefComposite {
  pub fn new(fields: Vec<Field>) -> Self {
    Self { fields }
  }

  /// Check if the composite is a tuple variant or struct variant (all fields need to have names).
  pub fn is_struct(&self) -> bool {
    named_fields(self.fields.as_slice())
  }
}

#[derive(Clone, Debug, Default, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct TypeDefTuple {
  pub fields: Vec<TypeId>,
}

impl TypeDefTuple {
  pub fn new(fields: Vec<TypeId>) -> Self {
    Self { fields }
  }

  pub fn new_type(field: TypeId) -> Self {
    Self {
      fields: vec![field],
    }
  }

  pub fn unit() -> Self {
    Self::new(vec![])
  }

  pub fn is_unit(&self) -> bool {
    self.fields.is_empty()
  }

  pub fn fields(&self) -> &[TypeId] {
    self.fields.as_slice()
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeDefSequence {
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub type_param: TypeId,
}

impl TypeDefSequence {
  pub fn new(type_param: TypeId) -> Self {
    Self { type_param }
  }

  pub fn type_param(&self) -> TypeId {
    self.type_param
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeDefArray {
  pub len: u32,
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub type_param: TypeId,
}

impl TypeDefArray {
  pub fn new(len: u32, type_param: TypeId) -> Self {
    Self { len, type_param }
  }

  pub fn type_param(&self) -> TypeId {
    self.type_param
  }

  pub fn len(&self) -> u32 {
    self.len
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeDefCompact {
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub type_param: TypeId,
}

impl TypeDefCompact {
  pub fn new(type_param: TypeId) -> Self {
    Self { type_param }
  }

  pub fn type_param(&self) -> TypeId {
    self.type_param
  }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeId(#[codec(compact)] pub u32);

impl TypeId {
  pub fn id(&self) -> u32 {
    self.0
  }

  pub fn inc(&mut self) {
    self.0 += 1;
  }
}

impl From<u32> for TypeId {
  fn from(id: u32) -> Self {
    Self(id)
  }
}

impl From<usize> for TypeId {
  fn from(id: usize) -> Self {
    Self(id as u32)
  }
}

impl From<TypeId> for usize {
  fn from(id: TypeId) -> Self {
    id.0 as Self
  }
}

impl core::ops::Deref for TypeId {
  type Target = u32;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum TypeDef {
  #[codec(index = 0)]
  Composite(TypeDefComposite),
  #[codec(index = 1)]
  Variant(TypeDefVariant),
  #[codec(index = 2)]
  Sequence(TypeDefSequence),
  #[codec(index = 3)]
  Array(TypeDefArray),
  #[codec(index = 4)]
  Tuple(TypeDefTuple),
  #[codec(index = 5)]
  Primitive(TypeDefPrimitive),
  #[codec(index = 6)]
  Compact(TypeDefCompact),
  // TODO: BitSequence
}

impl TypeDef {
  pub fn to_string(&mut self) -> String {
    format!("TypeDef: {:?}", self)
  }

  pub fn new_type(ty: TypeId) -> Self {
    Self::Tuple(TypeDefTuple::new_type(ty))
  }

  pub fn new_tuple(fields: Vec<TypeId>) -> Self {
    Self::Tuple(TypeDefTuple::new(fields))
  }
}

impl From<TypeDefComposite> for TypeDef {
  fn from(def: TypeDefComposite) -> Self {
    Self::Composite(def)
  }
}

impl From<TypeDefVariant> for TypeDef {
  fn from(def: TypeDefVariant) -> Self {
    Self::Variant(def)
  }
}

impl From<TypeDefSequence> for TypeDef {
  fn from(def: TypeDefSequence) -> Self {
    Self::Sequence(def)
  }
}

impl From<TypeDefArray> for TypeDef {
  fn from(def: TypeDefArray) -> Self {
    Self::Array(def)
  }
}

impl From<TypeDefTuple> for TypeDef {
  fn from(def: TypeDefTuple) -> Self {
    Self::Tuple(def)
  }
}

impl From<TypeDefPrimitive> for TypeDef {
  fn from(def: TypeDefPrimitive) -> Self {
    Self::Primitive(def)
  }
}

impl From<TypeDefCompact> for TypeDef {
  fn from(def: TypeDefCompact) -> Self {
    Self::Compact(def)
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PortableType {
  pub id: TypeId,
  #[cfg_attr(feature = "serde", serde(rename = "type"))]
  pub ty: Type,
}

impl PortableType {
  pub fn id(&self) -> TypeId {
    self.id
  }

  pub fn ty(&self) -> &Type {
    &self.ty
  }
}

#[derive(Clone, Debug, Decode, Encode)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PortableRegistry {
  pub types: Vec<PortableType>,
}

impl PortableRegistry {
  pub fn resolve<T: Into<TypeId>>(&self, id: T) -> Option<&Type> {
    let id = id.into();
    self.types.get(id.0 as usize).map(|t| t.ty())
  }

  pub fn types(&self) -> &[PortableType] {
    self.types.as_slice()
  }
}

impl From<&scale_info::PortableRegistry> for PortableRegistry {
  fn from(other: &scale_info::PortableRegistry) -> Self {
    Self {
      types: other
        .types()
        .iter()
        .map(|t| PortableType {
          id: t.id().into(),
          ty: t.ty().into(),
        })
        .collect(),
    }
  }
}

impl From<&scale_info::TypeParameter<PortableForm>> for TypeParameter {
  fn from(other: &scale_info::TypeParameter<PortableForm>) -> Self {
    Self {
      name: other.name().clone(),
      ty: other.ty().map(|t| t.id().into()),
    }
  }
}

impl From<&scale_info::Type<PortableForm>> for Type {
  fn from(other: &scale_info::Type<PortableForm>) -> Self {
    Self {
      path: other.path().into(),
      type_params: other.type_params().iter().map(|p| p.into()).collect(),
      type_def: other.type_def().into(),
      docs: other.docs().into(),
    }
  }
}

impl From<&scale_info::Path<PortableForm>> for Path {
  fn from(other: &scale_info::Path<PortableForm>) -> Self {
    Self {
      segments: other.segments().iter().cloned().collect(),
    }
  }
}

impl From<&scale_info::Field<PortableForm>> for Field {
  fn from(other: &scale_info::Field<PortableForm>) -> Self {
    Self {
      name: other.name().cloned().into(),
      ty: other.ty().id().into(),
      type_name: other.type_name().cloned().into(),
      docs: other.docs().into(),
    }
  }
}

impl From<&scale_info::Variant<PortableForm>> for Variant {
  fn from(other: &scale_info::Variant<PortableForm>) -> Self {
    Self {
      name: other.name().into(),
      fields: other.fields().iter().map(|f| f.into()).collect(),
      index: other.index().into(),
      docs: other.docs().into(),
    }
  }
}

impl From<&scale_info::TypeDefComposite<PortableForm>> for TypeDefComposite {
  fn from(other: &scale_info::TypeDefComposite<PortableForm>) -> Self {
    Self {
      fields: other.fields().iter().map(|v| v.into()).collect(),
    }
  }
}

impl From<&scale_info::TypeDefVariant<PortableForm>> for TypeDefVariant {
  fn from(other: &scale_info::TypeDefVariant<PortableForm>) -> Self {
    Self {
      variants: other.variants().iter().map(|v| v.into()).collect(),
    }
  }
}

impl From<&scale_info::TypeDefSequence<PortableForm>> for TypeDefSequence {
  fn from(other: &scale_info::TypeDefSequence<PortableForm>) -> Self {
    Self {
      type_param: other.type_param().id().into(),
    }
  }
}

impl From<&scale_info::TypeDefArray<PortableForm>> for TypeDefArray {
  fn from(other: &scale_info::TypeDefArray<PortableForm>) -> Self {
    Self {
      len: other.len(),
      type_param: other.type_param().id().into(),
    }
  }
}

impl From<&scale_info::TypeDefTuple<PortableForm>> for TypeDefTuple {
  fn from(other: &scale_info::TypeDefTuple<PortableForm>) -> Self {
    Self {
      fields: other.fields().iter().map(|v| v.id().into()).collect(),
    }
  }
}

impl From<&scale_info::TypeDefCompact<PortableForm>> for TypeDefCompact {
  fn from(other: &scale_info::TypeDefCompact<PortableForm>) -> Self {
    Self {
      type_param: other.type_param().id().into(),
    }
  }
}

impl From<&scale_info::TypeDef<PortableForm>> for TypeDef {
  fn from(other: &scale_info::TypeDef<PortableForm>) -> Self {
    match other {
      scale_info::TypeDef::Composite(c) => TypeDef::Composite(c.into()),
      scale_info::TypeDef::Variant(v) => TypeDef::Variant(v.into()),
      scale_info::TypeDef::Sequence(s) => TypeDef::Sequence(s.into()),
      scale_info::TypeDef::Array(a) => TypeDef::Array(a.into()),
      scale_info::TypeDef::Tuple(t) => TypeDef::Tuple(t.into()),
      scale_info::TypeDef::Primitive(p) => TypeDef::Primitive(p.clone()),
      scale_info::TypeDef::Compact(ty) => TypeDef::Compact(ty.into()),
      _ => {
        todo!();
      }
    }
  }
}