ave-common 0.9.0

Averiun Ledger common library
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
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Governance update payloads.
//!
//! These types model member, role, schema and policy changes applied to a
//! governance subject. They are plain serializable data structures and are
//! shared by the API layer, the core ledger and TypeScript exports.

use std::{
    collections::{BTreeSet, HashSet},
    fmt,
    hash::Hash,
};

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

#[cfg(feature = "typescript")]
use ts_rs::TS;

use crate::identity::PublicKey;
use crate::{Namespace, SchemaType};

pub type MemberName = String;

/// Governance change set grouped by concern.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct GovernanceEvent {
    pub members: Option<MemberEvent>,
    pub roles: Option<RolesEvent>,
    pub schemas: Option<SchemasEvent>,
    pub policies: Option<PoliciesEvent>,
}

///// Members /////
/// Member additions and removals.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct MemberEvent {
    pub add: Option<HashSet<NewMember>>,
    pub remove: Option<HashSet<MemberName>>,
}

/// New member entry used in governance updates.
#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct NewMember {
    pub name: MemberName,
    #[cfg_attr(feature = "typescript", ts(type = "string"))]
    pub key: PublicKey,
}

///// Roles /////
/// Role updates grouped by role family.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct RolesEvent {
    pub governance: Option<GovRoleEvent>,
    pub tracker_schemas: Option<TrackerSchemasRoleEvent>,
    pub schema: Option<HashSet<SchemaIdRole>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct GovRoleEvent {
    pub add: Option<GovRolesEvent>,
    pub remove: Option<GovRolesEvent>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaIdRole {
    pub schema_id: SchemaType,
    pub add: Option<SchemaRolesAddEvent>,
    pub remove: Option<SchemaRolesRemoveEvent>,
    pub change: Option<SchemaRolesChangeEvent>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct TrackerSchemasRoleEvent {
    pub add: Option<TrackerSchemasRolesAddEvent>,
    pub remove: Option<TrackerSchemasRolesRemoveEvent>,
    pub change: Option<TrackerSchemasRolesChangeEvent>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct GovRolesEvent {
    pub approver: Option<BTreeSet<MemberName>>,
    pub evaluator: Option<BTreeSet<MemberName>>,
    pub validator: Option<BTreeSet<MemberName>>,
    pub witness: Option<BTreeSet<MemberName>>,
    pub issuer: Option<BTreeSet<MemberName>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct TrackerSchemasRolesAddEvent {
    pub evaluator: Option<BTreeSet<Role>>,
    pub validator: Option<BTreeSet<Role>>,
    pub witness: Option<BTreeSet<Role>>,
    pub issuer: Option<BTreeSet<Role>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaRolesAddEvent {
    pub evaluator: Option<BTreeSet<Role>>,
    pub validator: Option<BTreeSet<Role>>,
    pub witness: Option<BTreeSet<Role>>,
    pub creator: Option<BTreeSet<RoleCreator>>,
    pub issuer: Option<BTreeSet<Role>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct TrackerSchemasRolesRemoveEvent {
    pub evaluator: Option<BTreeSet<Role>>,
    pub validator: Option<BTreeSet<Role>>,
    pub witness: Option<BTreeSet<Role>>,
    pub issuer: Option<BTreeSet<Role>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaRolesRemoveEvent {
    pub evaluator: Option<BTreeSet<Role>>,
    pub validator: Option<BTreeSet<Role>>,
    pub witness: Option<BTreeSet<Role>>,
    pub creator: Option<BTreeSet<Role>>,
    pub issuer: Option<BTreeSet<Role>>,
}

#[derive(
    Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, PartialOrd, Ord,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct TrackerSchemasRolesChangeEvent {
    pub evaluator: Option<BTreeSet<RoleChange>>,
    pub validator: Option<BTreeSet<RoleChange>>,
    pub witness: Option<BTreeSet<RoleChange>>,
    pub issuer: Option<BTreeSet<RoleChange>>,
}

#[derive(
    Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, PartialOrd, Ord,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaRolesChangeEvent {
    pub evaluator: Option<BTreeSet<RoleChange>>,
    pub validator: Option<BTreeSet<RoleChange>>,
    pub witness: Option<BTreeSet<RoleChange>>,
    pub creator: Option<BTreeSet<RoleCreatorChange>>,
    pub issuer: Option<BTreeSet<RoleChange>>,
}

#[derive(
    Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, PartialOrd, Ord,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct RoleCreatorChange {
    pub actual_name: MemberName,
    pub actual_namespace: Namespace,
    pub new_namespace: Option<Namespace>,
    pub new_witnesses: Option<BTreeSet<CreatorWitness>>,
    pub new_quantity: Option<CreatorQuantity>,
}

#[derive(
    Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, PartialOrd, Ord,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct RoleChange {
    pub actual_name: MemberName,
    pub actual_namespace: Namespace,
    pub new_namespace: Namespace,
}

///// Schemas /////
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemasEvent {
    pub add: Option<HashSet<SchemaAdd>>,
    pub remove: Option<HashSet<SchemaType>>,
    pub change: Option<HashSet<SchemaChange>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaAdd {
    pub id: SchemaType,
    pub contract: String,
    pub initial_value: Value,
    #[serde(default)]
    pub viewpoints: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaChange {
    pub actual_id: SchemaType,
    pub new_contract: Option<String>,
    pub new_initial_value: Option<Value>,
    #[serde(default)]
    pub new_viewpoints: Option<Vec<String>>,
}

///// Policies /////
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct PoliciesEvent {
    pub governance: Option<GovPolicieEvent>,
    pub schema: Option<HashSet<SchemaIdPolicie>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaIdPolicie {
    pub schema_id: SchemaType,
    pub change: SchemaPolicieChange,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct GovPolicieEvent {
    pub change: GovPolicieChange,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct GovPolicieChange {
    pub approve: Option<Quorum>,
    pub evaluate: Option<Quorum>,
    pub validate: Option<Quorum>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SchemaPolicieChange {
    pub evaluate: Option<Quorum>,
    pub validate: Option<Quorum>,
}

/// Governance-wide quorum policy.
/// Governance quorum.
#[derive(
    Debug,
    Clone,
    Default,
    Serialize,
    Deserialize,
    PartialEq,
    Hash,
    Eq,
    BorshDeserialize,
    BorshSerialize,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
#[serde(rename_all = "lowercase")]
pub enum Quorum {
    #[default]
    Majority,
    Fixed(u32),
    Percentage(u8),
}

#[derive(
    Debug,
    Clone,
    Eq,
    PartialEq,
    Hash,
    PartialOrd,
    Ord,
    BorshDeserialize,
    BorshSerialize,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, type = "number | \"infinity\""))]
pub enum CreatorQuantity {
    Quantity(u32),
    Infinity,
}

impl<'de> Deserialize<'de> for CreatorQuantity {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;

        match value {
            serde_json::Value::String(s) if s == "infinity" => {
                Ok(Self::Infinity)
            }
            serde_json::Value::Number(n) if n.is_u64() => {
                Ok(Self::Quantity(n.as_u64().ok_or_else(|| {
                    serde::de::Error::custom(
                        "Quantity must be a number or 'infinity'",
                    )
                })? as u32))
            }
            _ => Err(serde::de::Error::custom(
                "Quantity must be a number or 'infinity'",
            )),
        }
    }
}

impl Serialize for CreatorQuantity {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Quantity(n) => serializer.serialize_u32(*n),
            Self::Infinity => serializer.serialize_str("infinity"),
        }
    }
}

impl CreatorQuantity {
    pub const fn check(&self) -> bool {
        match self {
            Self::Quantity(quantity) => *quantity != 0,
            Self::Infinity => true,
        }
    }
}

#[derive(
    Debug,
    Serialize,
    Deserialize,
    Clone,
    PartialEq,
    Hash,
    Eq,
    PartialOrd,
    Ord,
    BorshDeserialize,
    BorshSerialize,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct Role {
    pub name: String,
    pub namespace: Namespace,
}

#[derive(
    Debug,
    Serialize,
    Clone,
    PartialEq,
    Hash,
    Eq,
    PartialOrd,
    Ord,
    BorshDeserialize,
    BorshSerialize,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct CreatorWitness {
    pub name: String,
    #[cfg_attr(feature = "typescript", ts(type = "string[] | undefined"))]
    pub viewpoints: BTreeSet<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct UniqueViewpoints(BTreeSet<String>);

impl From<UniqueViewpoints> for BTreeSet<String> {
    fn from(value: UniqueViewpoints) -> Self {
        value.0
    }
}

impl<'de> Deserialize<'de> for UniqueViewpoints {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let viewpoints =
            <Vec<String> as serde::Deserialize>::deserialize(deserializer)?;
        let mut unique = BTreeSet::new();

        for viewpoint in viewpoints {
            if !unique.insert(viewpoint.clone()) {
                return Err(serde::de::Error::custom(format!(
                    "duplicated viewpoint '{viewpoint}'"
                )));
            }
        }

        Ok(Self(unique))
    }
}

#[derive(Deserialize)]
struct CreatorWitnessDef {
    name: String,
    #[serde(default)]
    viewpoints: UniqueViewpoints,
}

impl<'de> Deserialize<'de> for CreatorWitness {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let CreatorWitnessDef { name, viewpoints } =
            CreatorWitnessDef::deserialize(deserializer)?;

        Ok(Self {
            name,
            viewpoints: viewpoints.into(),
        })
    }
}

fn default_creator_witnesses() -> BTreeSet<CreatorWitness> {
    BTreeSet::from([CreatorWitness {
        name: "Witnesses".to_owned(),
        viewpoints: BTreeSet::from(["AllViewpoints".to_owned()]),
    }])
}

#[derive(Deserialize)]
#[serde(untagged)]
enum CreatorWitnessInput {
    Name(String),
    Detailed(CreatorWitness),
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CreatorWitnesses(BTreeSet<CreatorWitness>);

impl From<CreatorWitnesses> for BTreeSet<CreatorWitness> {
    fn from(value: CreatorWitnesses) -> Self {
        value.0
    }
}

impl<'de> Deserialize<'de> for CreatorWitnesses {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let values =
            <Vec<CreatorWitnessInput> as serde::Deserialize>::deserialize(
                deserializer,
            )?;
        let mut by_name = HashSet::new();
        let mut out = BTreeSet::new();

        for value in values {
            let witness = match value {
                CreatorWitnessInput::Name(name) => CreatorWitness {
                    name,
                    viewpoints: BTreeSet::new(),
                },
                CreatorWitnessInput::Detailed(witness) => witness,
            };

            if !by_name.insert(witness.name.clone()) {
                return Err(serde::de::Error::custom(format!(
                    "duplicated creator witness '{}'",
                    witness.name
                )));
            }

            out.insert(witness);
        }

        Ok(Self(out))
    }
}

#[derive(Debug, Serialize, Clone, BorshDeserialize, BorshSerialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct RoleCreator {
    pub name: String,
    pub namespace: Namespace,
    #[cfg_attr(
        feature = "typescript",
        ts(type = "(string | CreatorWitness)[] | undefined")
    )]
    pub witnesses: BTreeSet<CreatorWitness>,
    pub quantity: CreatorQuantity,
}

#[derive(Deserialize)]
struct RoleCreatorDef {
    name: String,
    pub namespace: Namespace,
    #[serde(default)]
    witnesses: Option<CreatorWitnesses>,
    pub quantity: CreatorQuantity,
}

impl<'de> Deserialize<'de> for RoleCreator {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let RoleCreatorDef {
            name,
            namespace,
            witnesses,
            quantity,
        } = RoleCreatorDef::deserialize(deserializer)?;

        let witnesses = witnesses
            .map_or_else(default_creator_witnesses, |values| values.into());

        Ok(Self {
            name,
            namespace,
            witnesses,
            quantity,
        })
    }
}

impl Hash for RoleCreator {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.namespace.hash(state);
    }
}

impl PartialOrd for RoleCreator {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RoleCreator {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (self.name.clone(), self.namespace.clone())
            .cmp(&(other.name.clone(), other.namespace.clone()))
    }
}

impl PartialEq for RoleCreator {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.namespace == other.namespace
    }
}

impl Eq for RoleCreator {}

impl RoleCreator {
    pub fn create(name: &str, namespace: Namespace) -> Self {
        Self {
            name: name.to_owned(),
            namespace,
            witnesses: default_creator_witnesses(),
            quantity: CreatorQuantity::Infinity,
        }
    }
}

impl Quorum {
    pub fn check_values(&self) -> Result<(), String> {
        if let Self::Percentage(percentage) = self
            && (*percentage == 0_u8 || *percentage > 100_u8)
        {
            return Err("the percentage must be between 1 and 100".to_owned());
        }

        Ok(())
    }

    pub fn get_signers(&self, total_members: u32, pending: u32) -> u32 {
        let signers = match self {
            Self::Fixed(fixed) => {
                let min = std::cmp::min(fixed, &total_members);
                *min
            }
            Self::Majority => total_members / 2 + 1,
            Self::Percentage(percentage) => {
                total_members * (percentage / 100) as u32
            }
        };

        std::cmp::min(signers, pending)
    }

    pub fn check_quorum(&self, total_members: u32, signers: u32) -> bool {
        match self {
            Self::Fixed(fixed) => {
                let min = std::cmp::min(fixed, &total_members);
                signers >= *min
            }
            Self::Majority => signers > total_members / 2,
            Self::Percentage(percentage) => {
                signers >= (total_members * (percentage / 100) as u32)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CreatorWitness, RoleCreator, SchemaAdd, SchemaChange};
    use serde_json::json;
    use std::collections::BTreeSet;

    #[test]
    fn test_schema_add_allows_duplicated_viewpoints_deserialization() {
        let schema = serde_json::from_value::<SchemaAdd>(json!({
            "id": "Example",
            "contract": "contract",
            "initial_value": {},
            "viewpoints": ["agua", "agua"]
        }))
        .unwrap();

        assert_eq!(
            schema.viewpoints,
            vec!["agua".to_owned(), "agua".to_owned()]
        );
    }

    #[test]
    fn test_schema_change_allows_duplicated_viewpoints_deserialization() {
        let change = serde_json::from_value::<SchemaChange>(json!({
            "actual_id": "Example",
            "new_viewpoints": ["agua", "agua"]
        }))
        .unwrap();

        assert_eq!(
            change.new_viewpoints,
            Some(vec!["agua".to_owned(), "agua".to_owned()])
        );
    }

    #[test]
    fn test_creator_witness_rejects_duplicated_viewpoints() {
        let error = serde_json::from_value::<CreatorWitness>(json!({
            "name": "pepito",
            "viewpoints": ["agua", "agua"]
        }))
        .unwrap_err();

        assert!(error.to_string().contains("duplicated viewpoint"));
    }

    #[test]
    fn test_role_creator_defaults_to_generic_all_viewpoints() {
        let creator = serde_json::from_value::<RoleCreator>(json!({
            "name": "Owner",
            "namespace": [],
            "quantity": 1
        }))
        .unwrap();

        assert_eq!(
            creator.witnesses,
            BTreeSet::from([CreatorWitness {
                name: "Witnesses".to_owned(),
                viewpoints: BTreeSet::from(["AllViewpoints".to_owned()]),
            }])
        );
    }

    #[test]
    fn test_role_creator_allows_legacy_string_witnesses() {
        let creator = serde_json::from_value::<RoleCreator>(json!({
            "name": "Owner",
            "namespace": [],
            "witnesses": ["Alice"],
            "quantity": 1
        }))
        .unwrap();

        assert_eq!(
            creator.witnesses,
            BTreeSet::from([CreatorWitness {
                name: "Alice".to_owned(),
                viewpoints: BTreeSet::new(),
            }])
        );
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct Member {
    #[cfg_attr(feature = "typescript", ts(type = "string"))]
    pub id: PublicKey,
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum ProtocolTypes {
    Approval,
    Evaluation,
    Validation,
}

impl fmt::Display for ProtocolTypes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Approval => write!(f, "Approval"),
            Self::Evaluation => write!(f, "Evaluation"),
            Self::Validation => write!(f, "Validation"),
        }
    }
}