pyth_lazer_protocol/
api.rs

1use std::{
2    cmp::Ordering,
3    fmt::Display,
4    ops::{Deref, DerefMut},
5};
6
7use derive_more::derive::From;
8use itertools::Itertools as _;
9use serde::{de::Error, Deserialize, Serialize};
10use utoipa::ToSchema;
11
12use crate::{
13    payload::AggregatedPriceFeedData,
14    time::{DurationUs, FixedRate, TimestampUs},
15    ChannelId, Price, PriceFeedId, PriceFeedProperty, Rate,
16};
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
19#[serde(rename_all = "camelCase")]
20pub struct LatestPriceRequestRepr {
21    // Either price feed ids or symbols must be specified.
22    #[schema(example = json!([1]))]
23    pub price_feed_ids: Option<Vec<PriceFeedId>>,
24    #[schema(example = schema_default_symbols)]
25    pub symbols: Option<Vec<String>>,
26    pub properties: Vec<PriceFeedProperty>,
27    // "chains" was renamed to "formats". "chains" is still supported for compatibility.
28    #[serde(alias = "chains")]
29    pub formats: Vec<Format>,
30    #[serde(default)]
31    pub json_binary_encoding: JsonBinaryEncoding,
32    /// If `true`, the stream update will contain a JSON object containing
33    /// all data of the update.
34    #[serde(default = "default_parsed")]
35    pub parsed: bool,
36    pub channel: Channel,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema)]
40#[serde(rename_all = "camelCase")]
41pub struct LatestPriceRequest(LatestPriceRequestRepr);
42
43impl<'de> Deserialize<'de> for LatestPriceRequest {
44    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
45    where
46        D: serde::Deserializer<'de>,
47    {
48        let value = LatestPriceRequestRepr::deserialize(deserializer)?;
49        Self::new(value).map_err(Error::custom)
50    }
51}
52
53impl LatestPriceRequest {
54    pub fn new(value: LatestPriceRequestRepr) -> Result<Self, &'static str> {
55        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
56        validate_optional_nonempty_vec_has_unique_elements(
57            &value.price_feed_ids,
58            "no price feed ids specified",
59            "duplicate price feed ids specified",
60        )?;
61        validate_optional_nonempty_vec_has_unique_elements(
62            &value.symbols,
63            "no symbols specified",
64            "duplicate symbols specified",
65        )?;
66        validate_formats(&value.formats)?;
67        validate_properties(&value.properties)?;
68        Ok(Self(value))
69    }
70}
71
72impl Deref for LatestPriceRequest {
73    type Target = LatestPriceRequestRepr;
74
75    fn deref(&self) -> &Self::Target {
76        &self.0
77    }
78}
79impl DerefMut for LatestPriceRequest {
80    fn deref_mut(&mut self) -> &mut Self::Target {
81        &mut self.0
82    }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
86#[serde(rename_all = "camelCase")]
87pub struct PriceRequestRepr {
88    pub timestamp: TimestampUs,
89    // Either price feed ids or symbols must be specified.
90    pub price_feed_ids: Option<Vec<PriceFeedId>>,
91    #[schema(default)]
92    pub symbols: Option<Vec<String>>,
93    pub properties: Vec<PriceFeedProperty>,
94    pub formats: Vec<Format>,
95    #[serde(default)]
96    pub json_binary_encoding: JsonBinaryEncoding,
97    /// If `true`, the stream update will contain a JSON object containing
98    /// all data of the update.
99    #[serde(default = "default_parsed")]
100    pub parsed: bool,
101    pub channel: Channel,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema)]
105#[serde(rename_all = "camelCase")]
106pub struct PriceRequest(PriceRequestRepr);
107
108impl<'de> Deserialize<'de> for PriceRequest {
109    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
110    where
111        D: serde::Deserializer<'de>,
112    {
113        let value = PriceRequestRepr::deserialize(deserializer)?;
114        Self::new(value).map_err(Error::custom)
115    }
116}
117
118impl PriceRequest {
119    pub fn new(value: PriceRequestRepr) -> Result<Self, &'static str> {
120        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
121        validate_optional_nonempty_vec_has_unique_elements(
122            &value.price_feed_ids,
123            "no price feed ids specified",
124            "duplicate price feed ids specified",
125        )?;
126        validate_optional_nonempty_vec_has_unique_elements(
127            &value.symbols,
128            "no symbols specified",
129            "duplicate symbols specified",
130        )?;
131        validate_formats(&value.formats)?;
132        validate_properties(&value.properties)?;
133        Ok(Self(value))
134    }
135}
136
137impl Deref for PriceRequest {
138    type Target = PriceRequestRepr;
139
140    fn deref(&self) -> &Self::Target {
141        &self.0
142    }
143}
144impl DerefMut for PriceRequest {
145    fn deref_mut(&mut self) -> &mut Self::Target {
146        &mut self.0
147    }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
151#[serde(rename_all = "camelCase")]
152pub struct ReducePriceRequest {
153    pub payload: JsonUpdate,
154    pub price_feed_ids: Vec<PriceFeedId>,
155}
156
157pub type LatestPriceResponse = JsonUpdate;
158pub type ReducePriceResponse = JsonUpdate;
159pub type PriceResponse = JsonUpdate;
160
161pub fn default_parsed() -> bool {
162    true
163}
164
165pub fn schema_default_symbols() -> Option<Vec<String>> {
166    None
167}
168pub fn schema_default_price_feed_ids() -> Option<Vec<PriceFeedId>> {
169    Some(vec![PriceFeedId(1)])
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, ToSchema)]
173#[serde(rename_all = "camelCase")]
174pub enum DeliveryFormat {
175    /// Deliver stream updates as JSON text messages.
176    #[default]
177    Json,
178    /// Deliver stream updates as binary messages.
179    Binary,
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
183#[serde(rename_all = "camelCase")]
184pub enum Format {
185    Evm,
186    Solana,
187    LeEcdsa,
188    LeUnsigned,
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, ToSchema)]
192#[serde(rename_all = "camelCase")]
193pub enum JsonBinaryEncoding {
194    #[default]
195    Base64,
196    Hex,
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, From, ToSchema)]
200#[schema(example = "fixed_rate@200ms")]
201pub enum Channel {
202    FixedRate(FixedRate),
203    #[schema(rename = "real_time")]
204    RealTime,
205}
206
207impl PartialOrd for Channel {
208    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
209        let rate_left = match self {
210            Channel::FixedRate(rate) => rate.duration().as_micros(),
211            Channel::RealTime => FixedRate::MIN.duration().as_micros(),
212        };
213        let rate_right = match other {
214            Channel::FixedRate(rate) => rate.duration().as_micros(),
215            Channel::RealTime => FixedRate::MIN.duration().as_micros(),
216        };
217        Some(rate_left.cmp(&rate_right))
218    }
219}
220
221impl Serialize for Channel {
222    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
223    where
224        S: serde::Serializer,
225    {
226        match self {
227            Channel::FixedRate(fixed_rate) => serializer.serialize_str(&format!(
228                "fixed_rate@{}ms",
229                fixed_rate.duration().as_millis()
230            )),
231            Channel::RealTime => serializer.serialize_str("real_time"),
232        }
233    }
234}
235
236impl Display for Channel {
237    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238        match self {
239            Channel::FixedRate(fixed_rate) => {
240                write!(f, "fixed_rate@{}ms", fixed_rate.duration().as_millis())
241            }
242            Channel::RealTime => write!(f, "real_time"),
243        }
244    }
245}
246
247impl Channel {
248    pub fn id(&self) -> ChannelId {
249        match self {
250            Channel::FixedRate(fixed_rate) => match fixed_rate.duration().as_millis() {
251                50 => ChannelId::FIXED_RATE_50,
252                200 => ChannelId::FIXED_RATE_200,
253                1000 => ChannelId::FIXED_RATE_1000,
254                _ => panic!("unknown channel: {self:?}"),
255            },
256            Channel::RealTime => ChannelId::REAL_TIME,
257        }
258    }
259}
260
261#[test]
262fn id_supports_all_fixed_rates() {
263    for rate in FixedRate::ALL {
264        Channel::FixedRate(rate).id();
265    }
266}
267
268fn parse_channel(value: &str) -> Option<Channel> {
269    if value == "real_time" {
270        Some(Channel::RealTime)
271    } else if let Some(rest) = value.strip_prefix("fixed_rate@") {
272        let ms_value = rest.strip_suffix("ms")?;
273        Some(Channel::FixedRate(FixedRate::from_millis(
274            ms_value.parse().ok()?,
275        )?))
276    } else {
277        None
278    }
279}
280
281impl<'de> Deserialize<'de> for Channel {
282    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
283    where
284        D: serde::Deserializer<'de>,
285    {
286        let value = <String>::deserialize(deserializer)?;
287        parse_channel(&value).ok_or_else(|| Error::custom("unknown channel"))
288    }
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
292#[serde(rename_all = "camelCase")]
293pub struct SubscriptionParamsRepr {
294    // Either price feed ids or symbols must be specified.
295    pub price_feed_ids: Option<Vec<PriceFeedId>>,
296    #[schema(default)]
297    pub symbols: Option<Vec<String>>,
298    pub properties: Vec<PriceFeedProperty>,
299    // "chains" was renamed to "formats". "chains" is still supported for compatibility.
300    #[serde(alias = "chains")]
301    pub formats: Vec<Format>,
302    #[serde(default)]
303    pub delivery_format: DeliveryFormat,
304    #[serde(default)]
305    pub json_binary_encoding: JsonBinaryEncoding,
306    /// If `true`, the stream update will contain a `parsed` JSON field containing
307    /// all data of the update.
308    #[serde(default = "default_parsed")]
309    pub parsed: bool,
310    pub channel: Channel,
311    // "ignoreInvalidFeedIds" was renamed to "ignoreInvalidFeeds". "ignoreInvalidFeedIds" is still supported for compatibility.
312    #[serde(default, alias = "ignoreInvalidFeedIds")]
313    pub ignore_invalid_feeds: bool,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, ToSchema)]
317#[serde(rename_all = "camelCase")]
318pub struct SubscriptionParams(SubscriptionParamsRepr);
319
320impl<'de> Deserialize<'de> for SubscriptionParams {
321    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
322    where
323        D: serde::Deserializer<'de>,
324    {
325        let value = SubscriptionParamsRepr::deserialize(deserializer)?;
326        Self::new(value).map_err(Error::custom)
327    }
328}
329
330impl SubscriptionParams {
331    pub fn new(value: SubscriptionParamsRepr) -> Result<Self, &'static str> {
332        validate_price_feed_ids_or_symbols(&value.price_feed_ids, &value.symbols)?;
333        validate_optional_nonempty_vec_has_unique_elements(
334            &value.price_feed_ids,
335            "no price feed ids specified",
336            "duplicate price feed ids specified",
337        )?;
338        validate_optional_nonempty_vec_has_unique_elements(
339            &value.symbols,
340            "no symbols specified",
341            "duplicate symbols specified",
342        )?;
343        validate_formats(&value.formats)?;
344        validate_properties(&value.properties)?;
345        Ok(Self(value))
346    }
347}
348
349impl Deref for SubscriptionParams {
350    type Target = SubscriptionParamsRepr;
351
352    fn deref(&self) -> &Self::Target {
353        &self.0
354    }
355}
356impl DerefMut for SubscriptionParams {
357    fn deref_mut(&mut self) -> &mut Self::Target {
358        &mut self.0
359    }
360}
361
362#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
363#[serde(rename_all = "camelCase")]
364pub struct JsonBinaryData {
365    pub encoding: JsonBinaryEncoding,
366    pub data: String,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
370#[serde(rename_all = "camelCase")]
371pub struct JsonUpdate {
372    /// Present unless `parsed = false` is specified in subscription params.
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub parsed: Option<ParsedPayload>,
375    /// Only present if `Evm` is present in `formats` in subscription params.
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub evm: Option<JsonBinaryData>,
378    /// Only present if `Solana` is present in `formats` in subscription params.
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub solana: Option<JsonBinaryData>,
381    /// Only present if `LeEcdsa` is present in `formats` in subscription params.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub le_ecdsa: Option<JsonBinaryData>,
384    /// Only present if `LeUnsigned` is present in `formats` in subscription params.
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub le_unsigned: Option<JsonBinaryData>,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
390#[serde(rename_all = "camelCase")]
391pub struct ParsedPayload {
392    #[serde(with = "crate::serde_str::timestamp")]
393    pub timestamp_us: TimestampUs,
394    pub price_feeds: Vec<ParsedFeedPayload>,
395}
396
397#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
398#[serde(rename_all = "camelCase")]
399pub struct ParsedFeedPayload {
400    pub price_feed_id: PriceFeedId,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    #[serde(with = "crate::serde_str::option_price")]
403    #[serde(default)]
404    pub price: Option<Price>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    #[serde(with = "crate::serde_str::option_price")]
407    #[serde(default)]
408    pub best_bid_price: Option<Price>,
409    #[serde(skip_serializing_if = "Option::is_none")]
410    #[serde(with = "crate::serde_str::option_price")]
411    #[serde(default)]
412    pub best_ask_price: Option<Price>,
413    #[serde(skip_serializing_if = "Option::is_none")]
414    #[serde(default)]
415    pub publisher_count: Option<u16>,
416    #[serde(skip_serializing_if = "Option::is_none")]
417    #[serde(default)]
418    pub exponent: Option<i16>,
419    #[serde(skip_serializing_if = "Option::is_none")]
420    #[serde(default)]
421    pub confidence: Option<Price>,
422    #[serde(skip_serializing_if = "Option::is_none")]
423    #[serde(default)]
424    pub funding_rate: Option<Rate>,
425    #[serde(skip_serializing_if = "Option::is_none")]
426    #[serde(default)]
427    pub funding_timestamp: Option<TimestampUs>,
428    // More fields may be added later.
429    #[serde(skip_serializing_if = "Option::is_none")]
430    #[serde(default)]
431    pub funding_rate_interval: Option<DurationUs>,
432}
433
434impl ParsedFeedPayload {
435    pub fn new(
436        price_feed_id: PriceFeedId,
437        data: &AggregatedPriceFeedData,
438        properties: &[PriceFeedProperty],
439    ) -> Self {
440        let mut output = Self {
441            price_feed_id,
442            price: None,
443            best_bid_price: None,
444            best_ask_price: None,
445            publisher_count: None,
446            exponent: None,
447            confidence: None,
448            funding_rate: None,
449            funding_timestamp: None,
450            funding_rate_interval: None,
451        };
452        for &property in properties {
453            match property {
454                PriceFeedProperty::Price => {
455                    output.price = data.price;
456                }
457                PriceFeedProperty::BestBidPrice => {
458                    output.best_bid_price = data.best_bid_price;
459                }
460                PriceFeedProperty::BestAskPrice => {
461                    output.best_ask_price = data.best_ask_price;
462                }
463                PriceFeedProperty::PublisherCount => {
464                    output.publisher_count = Some(data.publisher_count);
465                }
466                PriceFeedProperty::Exponent => {
467                    output.exponent = Some(data.exponent);
468                }
469                PriceFeedProperty::Confidence => {
470                    output.confidence = data.confidence;
471                }
472                PriceFeedProperty::FundingRate => {
473                    output.funding_rate = data.funding_rate;
474                }
475                PriceFeedProperty::FundingTimestamp => {
476                    output.funding_timestamp = data.funding_timestamp;
477                }
478                PriceFeedProperty::FundingRateInterval => {
479                    output.funding_rate_interval = data.funding_rate_interval;
480                }
481            }
482        }
483        output
484    }
485
486    pub fn new_full(
487        price_feed_id: PriceFeedId,
488        exponent: Option<i16>,
489        data: &AggregatedPriceFeedData,
490    ) -> Self {
491        Self {
492            price_feed_id,
493            price: data.price,
494            best_bid_price: data.best_bid_price,
495            best_ask_price: data.best_ask_price,
496            publisher_count: Some(data.publisher_count),
497            exponent,
498            confidence: data.confidence,
499            funding_rate: data.funding_rate,
500            funding_timestamp: data.funding_timestamp,
501            funding_rate_interval: data.funding_rate_interval,
502        }
503    }
504}
505
506/// A request sent from the client to the server.
507#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
508#[serde(tag = "type")]
509#[serde(rename_all = "camelCase")]
510pub enum WsRequest {
511    Subscribe(SubscribeRequest),
512    Unsubscribe(UnsubscribeRequest),
513}
514
515#[derive(
516    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
517)]
518pub struct SubscriptionId(pub u64);
519
520#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
521#[serde(rename_all = "camelCase")]
522pub struct SubscribeRequest {
523    pub subscription_id: SubscriptionId,
524    #[serde(flatten)]
525    pub params: SubscriptionParams,
526}
527
528#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
529#[serde(rename_all = "camelCase")]
530pub struct UnsubscribeRequest {
531    pub subscription_id: SubscriptionId,
532}
533
534/// A JSON response sent from the server to the client.
535#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, From, ToSchema)]
536#[serde(tag = "type")]
537#[serde(rename_all = "camelCase")]
538pub enum WsResponse {
539    Error(ErrorResponse),
540    Subscribed(SubscribedResponse),
541    SubscribedWithInvalidFeedIdsIgnored(SubscribedWithInvalidFeedIdsIgnoredResponse),
542    Unsubscribed(UnsubscribedResponse),
543    SubscriptionError(SubscriptionErrorResponse),
544    StreamUpdated(StreamUpdatedResponse),
545}
546
547/// Sent from the server after a successul subscription.
548#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
549#[serde(rename_all = "camelCase")]
550pub struct SubscribedResponse {
551    pub subscription_id: SubscriptionId,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
555#[serde(rename_all = "camelCase")]
556pub struct InvalidFeedSubscriptionDetails {
557    pub unknown_ids: Vec<PriceFeedId>,
558    pub unknown_symbols: Vec<String>,
559    pub unsupported_channels: Vec<PriceFeedId>,
560    pub unstable: Vec<PriceFeedId>,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
564#[serde(rename_all = "camelCase")]
565pub struct SubscribedWithInvalidFeedIdsIgnoredResponse {
566    pub subscription_id: SubscriptionId,
567    pub subscribed_feed_ids: Vec<PriceFeedId>,
568    pub ignored_invalid_feed_ids: InvalidFeedSubscriptionDetails,
569}
570
571#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
572#[serde(rename_all = "camelCase")]
573pub struct UnsubscribedResponse {
574    pub subscription_id: SubscriptionId,
575}
576
577/// Sent from the server if the requested subscription or unsubscription request
578/// could not be fulfilled.
579#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
580#[serde(rename_all = "camelCase")]
581pub struct SubscriptionErrorResponse {
582    pub subscription_id: SubscriptionId,
583    pub error: String,
584}
585
586/// Sent from the server if an internal error occured while serving data for an existing subscription,
587/// or a client request sent a bad request.
588#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
589#[serde(rename_all = "camelCase")]
590pub struct ErrorResponse {
591    pub error: String,
592}
593
594/// Sent from the server when new data is available for an existing subscription
595/// (only if `delivery_format == Json`).
596#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
597#[serde(rename_all = "camelCase")]
598pub struct StreamUpdatedResponse {
599    pub subscription_id: SubscriptionId,
600    #[serde(flatten)]
601    pub payload: JsonUpdate,
602}
603
604// Common validation functions
605fn validate_price_feed_ids_or_symbols(
606    price_feed_ids: &Option<Vec<PriceFeedId>>,
607    symbols: &Option<Vec<String>>,
608) -> Result<(), &'static str> {
609    if price_feed_ids.is_none() && symbols.is_none() {
610        return Err("either price feed ids or symbols must be specified");
611    }
612    if price_feed_ids.is_some() && symbols.is_some() {
613        return Err("either price feed ids or symbols must be specified, not both");
614    }
615    Ok(())
616}
617
618fn validate_optional_nonempty_vec_has_unique_elements<T>(
619    vec: &Option<Vec<T>>,
620    empty_msg: &'static str,
621    duplicate_msg: &'static str,
622) -> Result<(), &'static str>
623where
624    T: Eq + std::hash::Hash,
625{
626    if let Some(ref items) = vec {
627        if items.is_empty() {
628            return Err(empty_msg);
629        }
630        if !items.iter().all_unique() {
631            return Err(duplicate_msg);
632        }
633    }
634    Ok(())
635}
636
637fn validate_properties(properties: &[PriceFeedProperty]) -> Result<(), &'static str> {
638    if properties.is_empty() {
639        return Err("no properties specified");
640    }
641    if !properties.iter().all_unique() {
642        return Err("duplicate properties specified");
643    }
644    Ok(())
645}
646
647fn validate_formats(formats: &[Format]) -> Result<(), &'static str> {
648    if !formats.iter().all_unique() {
649        return Err("duplicate formats or chains specified");
650    }
651    Ok(())
652}