pyth-lazer-protocol 0.40.0

Pyth Lazer SDK - protocol types.
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
use std::{
    cmp::Ordering,
    fmt::Display,
    ops::{Deref, DerefMut},
};

use derive_more::From;
use itertools::Itertools as _;
use serde::{de::Error, Deserialize, Serialize};
use serde_with::{hex::Hex, serde_as};

use crate::{
    payload::AggregatedPriceFeedData,
    time::{DurationUs, FixedRate, TimestampUs},
    ChannelId, Price, PriceFeedId, PriceFeedProperty, Rate,
};

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "utoipa", schema(examples(LatestPriceRequestRepr::example1)))]
pub struct LatestPriceRequestRepr {
    /// List of feed IDs.
    /// Either feed ids or symbols must be specified.
    pub price_feed_ids: Option<Vec<PriceFeedId>>,
    /// List of feed symbols.
    /// Either feed ids or symbols must be specified.
    pub symbols: Option<Vec<String>>,
    /// List of feed properties the sender is interested in.
    pub properties: Vec<PriceFeedProperty>,
    // "chains" was renamed to "formats". "chains" is still supported for compatibility.
    /// Requested formats of the payload.
    #[serde(alias = "chains")]
    pub formats: Vec<Format>,
    #[serde(default)]
    pub json_binary_encoding: JsonBinaryEncoding,
    /// If `true`, the response will contain a JSON object containing
    /// all data of the update.
    #[serde(default = "default_parsed")]
    pub parsed: bool,
    /// Channel determines frequency of updates.
    pub channel: Channel,
}

#[cfg(feature = "utoipa")]
impl LatestPriceRequestRepr {
    fn example1() -> Self {
        Self {
            price_feed_ids: None,
            symbols: Some(vec!["Crypto.BTC/USD".into()]),
            properties: vec![PriceFeedProperty::Price, PriceFeedProperty::Confidence],
            formats: vec![Format::Evm],
            json_binary_encoding: JsonBinaryEncoding::Hex,
            parsed: true,
            channel: Channel::RealTime,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct LatestPriceRequest(LatestPriceRequestRepr);

impl<'de> Deserialize<'de> for LatestPriceRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = LatestPriceRequestRepr::deserialize(deserializer)?;
        Self::new(value).map_err(Error::custom)
    }
}

impl LatestPriceRequest {
    pub fn new(value: LatestPriceRequestRepr) -> Result<Self, &'static str> {
        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.price_feed_ids,
            "no price feed ids specified",
            "duplicate price feed ids specified",
        )?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.symbols,
            "no symbols specified",
            "duplicate symbols specified",
        )?;
        validate_formats(&value.formats)?;
        validate_properties(&value.properties)?;
        Ok(Self(value))
    }
}

impl Deref for LatestPriceRequest {
    type Target = LatestPriceRequestRepr;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for LatestPriceRequest {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct PriceRequestRepr {
    /// Requested timestamp of the update.
    pub timestamp: TimestampUs,
    /// List of feed IDs.
    /// Either feed ids or symbols must be specified.
    pub price_feed_ids: Option<Vec<PriceFeedId>>,
    /// List of feed symbols.
    /// Either feed ids or symbols must be specified.
    #[cfg_attr(feature = "utoipa", schema(default))]
    pub symbols: Option<Vec<String>>,
    /// List of feed properties the sender is interested in.
    pub properties: Vec<PriceFeedProperty>,
    /// Requested formats of the payload.
    pub formats: Vec<Format>,
    #[serde(default)]
    pub json_binary_encoding: JsonBinaryEncoding,
    /// If `true`, the stream update will contain a JSON object containing
    /// all data of the update.
    #[serde(default = "default_parsed")]
    pub parsed: bool,
    /// Channel determines frequency of updates.
    pub channel: Channel,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct PriceRequest(PriceRequestRepr);

impl<'de> Deserialize<'de> for PriceRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = PriceRequestRepr::deserialize(deserializer)?;
        Self::new(value).map_err(Error::custom)
    }
}

impl PriceRequest {
    pub fn new(value: PriceRequestRepr) -> Result<Self, &'static str> {
        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.price_feed_ids,
            "no price feed ids specified",
            "duplicate price feed ids specified",
        )?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.symbols,
            "no symbols specified",
            "duplicate symbols specified",
        )?;
        validate_formats(&value.formats)?;
        validate_properties(&value.properties)?;
        Ok(Self(value))
    }
}

impl Deref for PriceRequest {
    type Target = PriceRequestRepr;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for PriceRequest {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ReducePriceRequest {
    /// Feed update previously received from WebSocket or from "Fetch price"
    /// or "Fetch latest price" endpoints.
    pub payload: JsonUpdate,
    /// List of feeds that should be preserved in the output update.
    pub price_feed_ids: Vec<PriceFeedId>,
}

pub type LatestPriceResponse = JsonUpdate;
pub type ReducePriceResponse = JsonUpdate;
pub type PriceResponse = JsonUpdate;

pub fn default_parsed() -> bool {
    true
}

pub fn schema_default_symbols() -> Option<Vec<String>> {
    None
}
pub fn schema_default_price_feed_ids() -> Option<Vec<PriceFeedId>> {
    Some(vec![PriceFeedId(1)])
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum DeliveryFormat {
    /// Deliver stream updates as JSON text messages.
    #[default]
    Json,
    /// Deliver stream updates as binary messages.
    Binary,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum Format {
    Evm,
    Solana,
    LeEcdsa,
    LeUnsigned,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum JsonBinaryEncoding {
    #[default]
    Base64,
    Hex,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum ChannelSchemaRepr {
    #[serde(rename = "real_time")]
    RealTime,
    #[serde(rename = "fixed_rate@50ms")]
    FixedRate50ms,
    #[serde(rename = "fixed_rate@200ms")]
    FixedRate200ms,
    #[serde(rename = "fixed_rate@1000ms")]
    FixedRate1000ms,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, From)]
pub enum Channel {
    FixedRate(FixedRate),
    RealTime,
}

#[cfg(feature = "utoipa")]
impl utoipa::PartialSchema for Channel {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        ChannelSchemaRepr::schema()
    }
}

#[cfg(feature = "utoipa")]
impl utoipa::ToSchema for Channel {
    fn name() -> std::borrow::Cow<'static, str> {
        ChannelSchemaRepr::name()
    }

    fn schemas(
        schemas: &mut Vec<(
            String,
            utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
        )>,
    ) {
        ChannelSchemaRepr::schemas(schemas)
    }
}

impl PartialOrd for Channel {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let rate_left = match self {
            Channel::FixedRate(rate) => rate.duration().as_micros(),
            Channel::RealTime => FixedRate::MIN.duration().as_micros(),
        };
        let rate_right = match other {
            Channel::FixedRate(rate) => rate.duration().as_micros(),
            Channel::RealTime => FixedRate::MIN.duration().as_micros(),
        };
        Some(rate_left.cmp(&rate_right))
    }
}

impl Serialize for Channel {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Channel::FixedRate(fixed_rate) => serializer.serialize_str(&format!(
                "fixed_rate@{}ms",
                fixed_rate.duration().as_millis()
            )),
            Channel::RealTime => serializer.serialize_str("real_time"),
        }
    }
}

impl Display for Channel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Channel::FixedRate(fixed_rate) => {
                write!(f, "fixed_rate@{}ms", fixed_rate.duration().as_millis())
            }
            Channel::RealTime => write!(f, "real_time"),
        }
    }
}

impl Channel {
    pub fn id(&self) -> ChannelId {
        match self {
            Channel::FixedRate(fixed_rate) => match fixed_rate.duration().as_millis() {
                50 => ChannelId::FIXED_RATE_50,
                200 => ChannelId::FIXED_RATE_200,
                1000 => ChannelId::FIXED_RATE_1000,
                _ => panic!("unknown channel: {self:?}"),
            },
            Channel::RealTime => ChannelId::REAL_TIME,
        }
    }
}

impl TryFrom<ChannelId> for Channel {
    type Error = ChannelId;

    fn try_from(id: ChannelId) -> Result<Self, Self::Error> {
        match id {
            ChannelId::REAL_TIME => Ok(Channel::RealTime),
            ChannelId::FIXED_RATE_50 => Ok(Channel::FixedRate(FixedRate::RATE_50_MS)),
            ChannelId::FIXED_RATE_200 => Ok(Channel::FixedRate(FixedRate::RATE_200_MS)),
            ChannelId::FIXED_RATE_1000 => Ok(Channel::FixedRate(FixedRate::RATE_1000_MS)),
            _ => Err(id),
        }
    }
}

#[test]
fn id_supports_all_fixed_rates() {
    for rate in FixedRate::ALL {
        Channel::FixedRate(rate).id();
    }
}

#[test]
fn from_id_round_trips_with_id() {
    let all_channels = [
        Channel::RealTime,
        Channel::FixedRate(FixedRate::RATE_50_MS),
        Channel::FixedRate(FixedRate::RATE_200_MS),
        Channel::FixedRate(FixedRate::RATE_1000_MS),
    ];
    for channel in all_channels {
        assert_eq!(Channel::try_from(channel.id()), Ok(channel));
    }
}

#[test]
fn from_id_returns_none_for_unknown_ids() {
    assert!(Channel::try_from(ChannelId(0)).is_err());
    assert!(Channel::try_from(ChannelId(5)).is_err());
    assert!(Channel::try_from(ChannelId(255)).is_err());
}

#[test]
fn parse_channel_accepts_numeric_ids() {
    assert_eq!(parse_channel("1"), Some(Channel::RealTime));
    assert_eq!(
        parse_channel("2"),
        Some(Channel::FixedRate(FixedRate::RATE_50_MS))
    );
    assert_eq!(
        parse_channel("3"),
        Some(Channel::FixedRate(FixedRate::RATE_200_MS))
    );
    assert_eq!(
        parse_channel("4"),
        Some(Channel::FixedRate(FixedRate::RATE_1000_MS))
    );
}

#[test]
fn parse_channel_rejects_invalid_numeric_ids() {
    assert_eq!(parse_channel("0"), None);
    assert_eq!(parse_channel("5"), None); // Unsupported channel ID for now. Remove this test when we add support for it.
    assert_eq!(parse_channel("99"), None);
}

#[test]
fn channel_deserializes_from_json_string() {
    let channel: Channel = serde_json::from_str(r#""3""#).unwrap();
    assert_eq!(channel, Channel::FixedRate(FixedRate::RATE_200_MS));

    let channel: Channel = serde_json::from_str(r#""fixed_rate@200ms""#).unwrap();
    assert_eq!(channel, Channel::FixedRate(FixedRate::RATE_200_MS));
}

#[test]
fn channel_deserializes_from_json_number() {
    let channel: Channel = serde_json::from_str("3").unwrap();
    assert_eq!(channel, Channel::FixedRate(FixedRate::RATE_200_MS));

    let channel: Channel = serde_json::from_str("1").unwrap();
    assert_eq!(channel, Channel::RealTime);
}

#[test]
fn channel_rejects_invalid_json_number() {
    assert!(serde_json::from_str::<Channel>("0").is_err());
    assert!(serde_json::from_str::<Channel>("5").is_err());
    assert!(serde_json::from_str::<Channel>("999").is_err());
}

fn parse_channel(value: &str) -> Option<Channel> {
    if value == "real_time" {
        Some(Channel::RealTime)
    } else if let Some(rest) = value.strip_prefix("fixed_rate@") {
        let ms_value = rest.strip_suffix("ms")?;
        Some(Channel::FixedRate(FixedRate::from_millis(
            ms_value.parse().ok()?,
        )?))
    } else if let Ok(id) = value.parse::<u8>() {
        Channel::try_from(ChannelId(id)).ok()
    } else {
        None
    }
}

impl<'de> Deserialize<'de> for Channel {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct ChannelVisitor;

        impl<'de> serde::de::Visitor<'de> for ChannelVisitor {
            type Value = Channel;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a channel name string or numeric channel ID")
            }

            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Channel, E> {
                parse_channel(value).ok_or_else(|| E::custom("unknown channel"))
            }

            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Channel, E> {
                let id = u8::try_from(value).map_err(|_| E::custom("channel ID out of range"))?;
                Channel::try_from(ChannelId(id)).map_err(|_| E::custom("unknown channel ID"))
            }
        }

        deserializer.deserialize_any(ChannelVisitor)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscriptionParamsRepr {
    /// List of feed IDs.
    /// Either feed ids or symbols must be specified.
    pub price_feed_ids: Option<Vec<PriceFeedId>>,
    /// List of feed symbols.
    /// Either feed ids or symbols must be specified.
    #[cfg_attr(feature = "utoipa", schema(default))]
    pub symbols: Option<Vec<String>>,
    /// List of feed properties the sender is interested in.
    pub properties: Vec<PriceFeedProperty>,
    /// Requested formats of the payload.
    /// As part of each feed update, the server will send on-chain payloads required
    /// to validate these price updates on the specified chains.
    #[serde(alias = "chains")]
    pub formats: Vec<Format>,
    /// If `json` is selected, the server will send price updates as JSON objects
    /// (the on-chain payload will be encoded according to the `jsonBinaryEncoding` property).
    /// If `binary` is selected, the server will send price updates as binary messages.
    #[serde(default)]
    pub delivery_format: DeliveryFormat,
    /// For `deliveryFormat == "json"`, the on-chain payload will be encoded using the specified encoding.
    /// This option has no effect for  `deliveryFormat == "binary"`.
    #[serde(default)]
    pub json_binary_encoding: JsonBinaryEncoding,
    /// If `true`, the stream update will contain a `parsed` JSON field containing
    /// all data of the update.
    #[serde(default = "default_parsed")]
    pub parsed: bool,
    /// Channel determines frequency of updates.
    pub channel: Channel,
    /// If true, the subscription will ignore invalid feed IDs and subscribe to any valid feeds.
    /// Otherwise, the entire subscription will fail if any feed is invalid.
    #[serde(default, alias = "ignoreInvalidFeedIds")]
    pub ignore_invalid_feeds: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscriptionParams(SubscriptionParamsRepr);

impl<'de> Deserialize<'de> for SubscriptionParams {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = SubscriptionParamsRepr::deserialize(deserializer)?;
        Self::new(value).map_err(Error::custom)
    }
}

impl SubscriptionParams {
    pub fn new(value: SubscriptionParamsRepr) -> Result<Self, &'static str> {
        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.price_feed_ids,
            "no price feed ids specified",
            "duplicate price feed ids specified",
        )?;
        validate_optional_nonempty_vec_has_unique_elements(
            &value.symbols,
            "no symbols specified",
            "duplicate symbols specified",
        )?;
        validate_formats(&value.formats)?;
        validate_properties(&value.properties)?;
        Ok(Self(value))
    }
}

impl Deref for SubscriptionParams {
    type Target = SubscriptionParamsRepr;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for SubscriptionParams {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct JsonBinaryData {
    /// Encoding of the data. It will be the same as `jsonBinaryEncoding` specified in the `SubscriptionRequest`.
    pub encoding: JsonBinaryEncoding,
    /// Binary data encoded in base64 or hex, depending on the requested encoding.
    pub data: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct JsonUpdate {
    /// Parsed representation of the price update.
    /// Present unless `parsed = false` is specified in subscription params.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parsed: Option<ParsedPayload>,
    /// Signed on-chain payload for EVM. Only present if `Evm` is present in `formats` in subscription params.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evm: Option<JsonBinaryData>,
    /// Signed on-chain payload for Solana. Only present if `Solana` is present in `formats` in subscription params.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub solana: Option<JsonBinaryData>,
    /// Signed binary payload for off-chain verification. Only present if `LeEcdsa` is present in `formats` in subscription params.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub le_ecdsa: Option<JsonBinaryData>,
    /// Unsigned binary payload. Only present if `LeUnsigned` is present in `formats` in subscription params.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub le_unsigned: Option<JsonBinaryData>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ParsedPayload {
    /// Unix timestamp associated with the update (with microsecond precision).
    #[serde(with = "crate::serde_str::timestamp")]
    #[cfg_attr(feature = "utoipa", schema(value_type = String))]
    pub timestamp_us: TimestampUs,
    /// Values of the update for each feed.
    pub price_feeds: Vec<ParsedFeedPayload>,
}

/// Parsed representation of a feed update.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ParsedFeedPayload {
    /// Feed ID.
    pub price_feed_id: PriceFeedId,
    /// For price feeds: main price. For funding rate feeds: funding price.
    /// Only present if the `price` property was specified
    /// in the `SubscriptionRequest` and the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "crate::serde_str::option_price")]
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    pub price: Option<Price>,
    /// Best bid price for this price feed. Only present if the `bestBidPrice` property
    /// was specified in the `SubscriptionRequest` and this is a price feed and
    /// the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "crate::serde_str::option_price")]
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    pub best_bid_price: Option<Price>,
    /// Best ask price for this price feed. Only present if the `bestAskPrice` property was
    /// specified in the `SubscriptionRequest` and this is a price feed and
    /// the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "crate::serde_str::option_price")]
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    pub best_ask_price: Option<Price>,
    /// Number of publishers contributing to this feed update. Only present if the `publisherCount`
    /// property was specified in the `SubscriptionRequest`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub publisher_count: Option<u16>,
    /// Exponent for this feed. Only present if the `exponent` property was specified
    /// in the `SubscriptionRequest`. Each decimal field provided by the feed (price, fundingRate, etc)
    /// returns the mantissa of the value. The actual value can be calculated as
    /// `mantissa * 10^exponent`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub exponent: Option<i16>,
    /// Confidence for this price feed. Only present if the `confidence` property was
    /// specified in the `SubscriptionRequest` and this is a price feed and
    /// the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub confidence: Option<Price>,
    /// Perpetual future funding rate for this feed.
    /// Only present if the `fundingRate` property was specified in the `SubscriptionRequest`
    /// and this is a funding rate feed
    /// and the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub funding_rate: Option<Rate>,
    /// Most recent perpetual future funding rate timestamp for this feed.
    /// Only present if the `fundingTimestamp` property was specified in the `SubscriptionRequest`
    /// and this is a funding rate feed
    /// and the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub funding_timestamp: Option<TimestampUs>,
    /// Duration, in microseconds, between consecutive funding rate updates for this price feed.
    /// Only present if the `fundingRateInterval` property was requested in the `SubscriptionRequest`
    /// and this is a funding rate feed and the value is defined for that feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub funding_rate_interval: Option<DurationUs>,
    /// Market session for this price feed. Only present if the `marketSession` property was specified
    /// in the `SubscriptionRequest`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub market_session: Option<MarketSession>,
    /// Exponential moving average of the main price for this price feeds.
    /// Only present if the `emaPrice` property was specified
    /// in the `SubscriptionRequest`  and this is a price feed
    /// and the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "crate::serde_str::option_price")]
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    pub ema_price: Option<Price>,
    /// Exponential moving average of the confidence for this price feeds.
    /// Only present if the `emaConfidence` property was specified
    /// in the `SubscriptionRequest`  and this is a price feed
    /// and the value is currently available for this price feed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub ema_confidence: Option<Price>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub feed_update_timestamp: Option<TimestampUs>,
    // More fields may be added later.
}

impl ParsedFeedPayload {
    pub fn new(
        price_feed_id: PriceFeedId,
        data: &AggregatedPriceFeedData,
        properties: &[PriceFeedProperty],
    ) -> Self {
        let mut output = Self {
            price_feed_id,
            price: None,
            best_bid_price: None,
            best_ask_price: None,
            publisher_count: None,
            exponent: None,
            confidence: None,
            funding_rate: None,
            funding_timestamp: None,
            funding_rate_interval: None,
            market_session: None,
            ema_price: None,
            ema_confidence: None,
            feed_update_timestamp: None,
        };
        for &property in properties {
            match property {
                PriceFeedProperty::Price => {
                    output.price = data.price;
                }
                PriceFeedProperty::BestBidPrice => {
                    output.best_bid_price = data.best_bid_price;
                }
                PriceFeedProperty::BestAskPrice => {
                    output.best_ask_price = data.best_ask_price;
                }
                PriceFeedProperty::PublisherCount => {
                    output.publisher_count = Some(data.publisher_count);
                }
                PriceFeedProperty::Exponent => {
                    output.exponent = Some(data.exponent);
                }
                PriceFeedProperty::Confidence => {
                    output.confidence = data.confidence;
                }
                PriceFeedProperty::FundingRate => {
                    output.funding_rate = data.funding_rate;
                }
                PriceFeedProperty::FundingTimestamp => {
                    output.funding_timestamp = data.funding_timestamp;
                }
                PriceFeedProperty::FundingRateInterval => {
                    output.funding_rate_interval = data.funding_rate_interval;
                }
                PriceFeedProperty::MarketSession => {
                    output.market_session = Some(data.market_session);
                }
                PriceFeedProperty::EmaPrice => {
                    output.ema_price = data.ema_price;
                }
                PriceFeedProperty::EmaConfidence => {
                    output.ema_confidence = data.ema_confidence;
                }
                PriceFeedProperty::FeedUpdateTimestamp => {
                    output.feed_update_timestamp = data.feed_update_timestamp;
                }
            }
        }
        output
    }

    pub fn new_full(
        price_feed_id: PriceFeedId,
        exponent: Option<i16>,
        data: &AggregatedPriceFeedData,
    ) -> Self {
        Self {
            price_feed_id,
            price: data.price,
            best_bid_price: data.best_bid_price,
            best_ask_price: data.best_ask_price,
            publisher_count: Some(data.publisher_count),
            exponent,
            confidence: data.confidence,
            funding_rate: data.funding_rate,
            funding_timestamp: data.funding_timestamp,
            funding_rate_interval: data.funding_rate_interval,
            market_session: Some(data.market_session),
            ema_price: data.ema_price,
            ema_confidence: data.ema_confidence,
            feed_update_timestamp: data.feed_update_timestamp,
        }
    }
}

/// A WebSocket JSON message sent from the client to the server.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum WsRequest {
    Subscribe(SubscribeRequest),
    Unsubscribe(UnsubscribeRequest),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscriptionId(pub u64);

/// A subscription request.
///
/// After a successful subscription, the server will respond with a `SubscribedResponse`
/// or `SubscribedWithInvalidFeedIdsIgnoredResponse` message,
/// followed by `StreamUpdatedResponse` messages.
/// If a subscription cannot be made, the server will respond with a `SubscriptionError`
/// message containing the error message.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscribeRequest {
    /// A number chosen by the client to identify the new subscription.
    /// This identifier will be sent back in any responses related to this subscription.
    pub subscription_id: SubscriptionId,
    /// Properties of the new subscription.
    #[serde(flatten)]
    pub params: SubscriptionParams,
}

/// An unsubscription request.
///
/// After a successful unsubscription, the server will respond with a `UnsubscribedResponse` message
/// and stop sending `SubscriptionErrorResponse` messages for that subscription.
/// If the unsubscription cannot be made, the server will respond with a `SubscriptionError` message
/// containing the error text.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct UnsubscribeRequest {
    /// ID of the subscription that should be canceled.
    pub subscription_id: SubscriptionId,
}

/// A WebSocket JSON message sent from the server to the client.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, From)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum WsResponse {
    Error(ErrorResponse),
    Subscribed(SubscribedResponse),
    SubscribedWithInvalidFeedIdsIgnored(SubscribedWithInvalidFeedIdsIgnoredResponse),
    Unsubscribed(UnsubscribedResponse),
    SubscriptionError(SubscriptionErrorResponse),
    StreamUpdated(StreamUpdatedResponse),
}

/// Sent from the server when a subscription succeeded and all specified feeds were valid.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscribedResponse {
    pub subscription_id: SubscriptionId,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct InvalidFeedSubscriptionDetails {
    /// List of price feed IDs that could not be found.
    pub unknown_ids: Vec<PriceFeedId>,
    /// List of price feed symbols that could not be found.
    pub unknown_symbols: Vec<String>,
    /// List of price feed IDs that do not support the requested channel.
    pub unsupported_channels: Vec<PriceFeedId>,
    /// List of unstable price feed IDs. Unstable feeds are not available for subscription.
    pub unstable: Vec<PriceFeedId>,
    /// List of price feed IDs that the API key is not entitled to access.
    #[serde(default)]
    pub not_entitled: Vec<PriceFeedId>,
}

/// Sent from the server when a subscription succeeded, but
/// some of the  specified feeds were invalid.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscribedWithInvalidFeedIdsIgnoredResponse {
    /// The value specified in the corresponding `SubscribeRequest`.
    pub subscription_id: SubscriptionId,
    /// IDs of valid feeds included in the established subscription.
    pub subscribed_feed_ids: Vec<PriceFeedId>,
    /// Map of failed feed IDs categorized by failure reason.
    pub ignored_invalid_feed_ids: InvalidFeedSubscriptionDetails,
}

/// Notification of a successful unsubscription.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct UnsubscribedResponse {
    /// The value specified in the corresponding `SubscribeRequest`.
    pub subscription_id: SubscriptionId,
}

/// Sent from the server if the requested subscription or unsubscription request
/// could not be fulfilled.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SubscriptionErrorResponse {
    /// The value specified in the corresponding `SubscribeRequest`.
    pub subscription_id: SubscriptionId,
    /// Text of the error.
    pub error: String,
}

/// Sent from the server if an internal error occured while serving data for an existing subscription,
/// or a client request sent a bad request.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ErrorResponse {
    /// Text of the error.
    pub error: String,
}

/// Sent from the server when new data is available for an existing subscription
/// (only if `delivery_format == Json`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StreamUpdatedResponse {
    /// The value specified in the corresponding `SubscribeRequest`.
    pub subscription_id: SubscriptionId,
    /// Content of the update.
    #[serde(flatten)]
    pub payload: JsonUpdate,
}

// Common validation functions
fn validate_price_feed_ids_or_symbols(
    price_feed_ids: &Option<Vec<PriceFeedId>>,
    symbols: &Option<Vec<String>>,
) -> Result<(), &'static str> {
    if price_feed_ids.is_none() && symbols.is_none() {
        return Err("either price feed ids or symbols must be specified");
    }
    if price_feed_ids.is_some() && symbols.is_some() {
        return Err("either price feed ids or symbols must be specified, not both");
    }
    Ok(())
}

fn validate_optional_nonempty_vec_has_unique_elements<T>(
    vec: &Option<Vec<T>>,
    empty_msg: &'static str,
    duplicate_msg: &'static str,
) -> Result<(), &'static str>
where
    T: Eq + std::hash::Hash,
{
    if let Some(items) = vec {
        if items.is_empty() {
            return Err(empty_msg);
        }
        if !items.iter().all_unique() {
            return Err(duplicate_msg);
        }
    }
    Ok(())
}

fn validate_properties(properties: &[PriceFeedProperty]) -> Result<(), &'static str> {
    if properties.is_empty() {
        return Err("no properties specified");
    }
    if !properties.iter().all_unique() {
        return Err("duplicate properties specified");
    }
    Ok(())
}

fn validate_formats(formats: &[Format]) -> Result<(), &'static str> {
    if !formats.iter().all_unique() {
        return Err("duplicate formats or chains specified");
    }
    Ok(())
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, From, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "utoipa", schema(example = "regular"))]
pub enum MarketSession {
    #[default]
    Regular,
    PreMarket,
    PostMarket,
    OverNight,
    Closed,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, From, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "utoipa", schema(example = "open"))]
pub enum TradingStatus {
    #[default]
    Open,
    Closed,
    Halted,
    CorpAction,
}

impl From<MarketSession> for i16 {
    fn from(s: MarketSession) -> i16 {
        match s {
            MarketSession::Regular => 0,
            MarketSession::PreMarket => 1,
            MarketSession::PostMarket => 2,
            MarketSession::OverNight => 3,
            MarketSession::Closed => 4,
        }
    }
}

impl TryFrom<i16> for MarketSession {
    type Error = anyhow::Error;

    fn try_from(value: i16) -> Result<MarketSession, Self::Error> {
        match value {
            0 => Ok(MarketSession::Regular),
            1 => Ok(MarketSession::PreMarket),
            2 => Ok(MarketSession::PostMarket),
            3 => Ok(MarketSession::OverNight),
            4 => Ok(MarketSession::Closed),
            _ => Err(anyhow::anyhow!("invalid MarketSession value: {}", value)),
        }
    }
}

pub type GuardianIndex = u8;
pub type Slot = u64;
pub type MerkleTimestamp = u32;
pub type RawMerkleRoot = [u8; 20];
pub type RawMerkleSignature = [u8; 65];
pub type MerklePriceFeedId = [u8; 32];
pub type RawMerkleMessage = Vec<u8>;

#[serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SignedMerkleRoot {
    /// Hex-encoded 20-byte Keccak160 merkle root
    #[serde_as(as = "Hex")]
    #[cfg_attr(feature = "utoipa", schema(value_type = String, example = "0x1a2b3c..."))]
    pub root: Vec<u8>,

    pub slot: Slot,

    pub timestamp: u32,

    /// Hex-encoded 65-byte ECDSA signature (r || s || v)
    #[serde_as(as = "Hex")]
    #[cfg_attr(feature = "utoipa", schema(value_type = String, example = "0x1a2b3c..."))]
    pub signature: Vec<u8>,

    #[serde_as(as = "Vec<Hex>")]
    #[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>, example = json!(["00abcdef...", "00123456..."])))]
    pub messages: Vec<RawMerkleMessage>,
}

#[serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SignedGuardianSetUpgrade {
    /// Current guardian set index (the signing set)
    pub current_guardian_set_index: u32,
    /// New guardian set index
    pub new_guardian_set_index: u32,
    /// Hex-encoded new guardian keys (20 bytes each)
    #[serde_as(as = "Vec<Hex>")]
    pub new_guardian_keys: Vec<Vec<u8>>,
    /// Hex-encoded serialized VAA body bytes (for downstream VAA assembly)
    #[serde_as(as = "Hex")]
    #[cfg_attr(feature = "utoipa", schema(value_type = String, example = "0x1a2b3c..."))]
    pub body: Vec<u8>,
    /// Hex-encoded 65-byte ECDSA signature (r || s || v) over the body digest
    #[serde_as(as = "Hex")]
    #[cfg_attr(feature = "utoipa", schema(value_type = String, example = "0x1a2b3c..."))]
    pub signature: Vec<u8>,
}

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

    #[test]
    fn signed_merkle_root_json_serialization() {
        let root = SignedMerkleRoot {
            root: vec![
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
                0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
            ],
            slot: 34567890123,
            timestamp: 1700000000,
            signature: vec![0xaa; 65],
            messages: vec![vec![0x00, 0xab, 0xcd, 0xef], vec![0x00, 0x12, 0x34, 0x56]],
        };

        let json = serde_json::to_value(&root).unwrap();

        // root and signature are hex-encoded strings (no 0x prefix, lowercase)
        assert_eq!(json["root"], "0102030405060708090a0b0c0d0e0f1011121314");
        assert_eq!(json["slot"], 34567890123u64);
        assert_eq!(json["timestamp"], 1700000000u32);
        assert_eq!(json["signature"], "aa".repeat(65));
        assert_eq!(json["messages"], json!(["00abcdef", "00123456"]));

        // round-trip
        let deserialized: SignedMerkleRoot = serde_json::from_value(json).unwrap();
        assert_eq!(deserialized, root);
    }

    #[test]
    fn signed_guardian_set_upgrade_json_serialization() {
        let upgrade = SignedGuardianSetUpgrade {
            current_guardian_set_index: 4,
            new_guardian_set_index: 5,
            new_guardian_keys: vec![vec![0x11; 20], vec![0x22; 20]],
            body: vec![0xde, 0xad, 0xbe, 0xef],
            signature: vec![0xaa; 65],
        };

        let json = serde_json::to_value(&upgrade).unwrap();

        assert_eq!(json["current_guardian_set_index"], 4);
        assert_eq!(json["new_guardian_set_index"], 5);
        let keys = json["new_guardian_keys"].as_array().unwrap();
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0], "11".repeat(20));
        assert_eq!(keys[1], "22".repeat(20));
        assert_eq!(json["body"], "deadbeef");
        assert_eq!(json["signature"], "aa".repeat(65));

        // round-trip
        let deserialized: SignedGuardianSetUpgrade = serde_json::from_value(json).unwrap();
        assert_eq!(deserialized, upgrade);
    }
}