Skip to main content

af_price_updates/
pyth_lazer.rs

1//! Pyth Lazer `leEcdsa` price update format and feed identifiers.
2
3pub use crate::pyth_lazer_id_set::PriceFeedIdSet;
4use crate::{
5    ParseError,
6    reader::{Reader, decode_base64},
7    sorted_set::SortedSetSlice,
8};
9use bytes::{Bytes, BytesMut};
10use serde::{Deserialize, Serialize};
11use std::io::{Error, ErrorKind};
12
13/// Pyth Lazer price feed ID, e.g. `1` for BTC/USD.
14#[derive(
15    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
16)]
17#[repr(transparent)]
18pub struct PriceFeedId(pub u32);
19
20impl std::fmt::Display for PriceFeedId {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        <u32 as std::fmt::Display>::fmt(&self.0, f)
23    }
24}
25
26impl std::str::FromStr for PriceFeedId {
27    type Err = std::num::ParseIntError;
28    fn from_str(s: &str) -> Result<Self, Self::Err> {
29        s.parse::<u32>().map(PriceFeedId)
30    }
31}
32
33/// A property of a Pyth Lazer feed, requested when subscribing.
34///
35/// Serialized, displayed and parsed by its Pyth Lazer name, e.g. `bestBidPrice`. See [`Feed`] for
36/// the meaning of each property.
37#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
38#[serde(rename_all = "camelCase")]
39#[non_exhaustive]
40pub enum FeedProperty {
41    /// See [`Feed::price`].
42    Price,
43    /// See [`Feed::best_bid_price`].
44    BestBidPrice,
45    /// See [`Feed::best_ask_price`].
46    BestAskPrice,
47    /// See [`Feed::publisher_count`].
48    PublisherCount,
49    /// See [`Feed::exponent`].
50    Exponent,
51    /// See [`Feed::confidence`].
52    Confidence,
53    /// See [`Feed::funding_rate`].
54    FundingRate,
55    /// See [`Feed::funding_timestamp`].
56    FundingTimestamp,
57    /// See [`Feed::funding_rate_interval`].
58    FundingRateInterval,
59    /// See [`Feed::market_session`].
60    MarketSession,
61    /// See [`Feed::ema_price`].
62    EmaPrice,
63    /// See [`Feed::ema_confidence`].
64    EmaConfidence,
65    /// See [`Feed::feed_update_timestamp`].
66    FeedUpdateTimestamp,
67}
68
69impl FeedProperty {
70    /// The Pyth Lazer name, as used by serde.
71    const fn name(self) -> &'static str {
72        match self {
73            Self::Price => "price",
74            Self::BestBidPrice => "bestBidPrice",
75            Self::BestAskPrice => "bestAskPrice",
76            Self::PublisherCount => "publisherCount",
77            Self::Exponent => "exponent",
78            Self::Confidence => "confidence",
79            Self::FundingRate => "fundingRate",
80            Self::FundingTimestamp => "fundingTimestamp",
81            Self::FundingRateInterval => "fundingRateInterval",
82            Self::MarketSession => "marketSession",
83            Self::EmaPrice => "emaPrice",
84            Self::EmaConfidence => "emaConfidence",
85            Self::FeedUpdateTimestamp => "feedUpdateTimestamp",
86        }
87    }
88}
89
90impl std::fmt::Display for FeedProperty {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.write_str(self.name())
93    }
94}
95
96impl std::str::FromStr for FeedProperty {
97    type Err = ParseError;
98    fn from_str(s: &str) -> Result<Self, Self::Err> {
99        ALL_FEED_PROPERTIES
100            .iter()
101            .copied()
102            .find(|property| property.name() == s)
103            .ok_or_else(|| ParseError::new(format!("unknown feed property: {s}")))
104    }
105}
106
107/// Every [`FeedProperty`], in the order of their Pyth Lazer property IDs.
108pub const ALL_FEED_PROPERTIES: &[FeedProperty] = &[
109    FeedProperty::Price,
110    FeedProperty::BestBidPrice,
111    FeedProperty::BestAskPrice,
112    FeedProperty::PublisherCount,
113    FeedProperty::Exponent,
114    FeedProperty::Confidence,
115    FeedProperty::FundingRate,
116    FeedProperty::FundingTimestamp,
117    FeedProperty::FundingRateInterval,
118    FeedProperty::MarketSession,
119    FeedProperty::EmaPrice,
120    FeedProperty::EmaConfidence,
121    FeedProperty::FeedUpdateTimestamp,
122];
123
124/// The rate at which Pyth Lazer sends updates.
125///
126/// Serialized, displayed and parsed by its Pyth Lazer name, e.g. `fixed_rate@200ms`.
127#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
128#[repr(u8)]
129#[non_exhaustive]
130pub enum Channel {
131    /// As soon as a price changes.
132    #[serde(rename = "real_time")]
133    RealTime = 1,
134    /// Every 50 milliseconds.
135    #[serde(rename = "fixed_rate@50ms")]
136    FixedRate50ms = 2,
137    /// Every 200 milliseconds.
138    #[serde(rename = "fixed_rate@200ms")]
139    FixedRate200ms = 3,
140    /// Every second.
141    #[serde(rename = "fixed_rate@1000ms")]
142    FixedRate1000ms = 4,
143}
144
145impl TryFrom<u8> for Channel {
146    type Error = Error;
147    fn try_from(value: u8) -> Result<Self, Self::Error> {
148        match value {
149            1 => Ok(Self::RealTime),
150            2 => Ok(Self::FixedRate50ms),
151            3 => Ok(Self::FixedRate200ms),
152            4 => Ok(Self::FixedRate1000ms),
153            _ => Err(Error::new(
154                ErrorKind::InvalidData,
155                format!("Pyth Lazer unknown channel value: {value}"),
156            )),
157        }
158    }
159}
160
161impl std::str::FromStr for Channel {
162    type Err = ParseError;
163    fn from_str(s: &str) -> Result<Self, Self::Err> {
164        match s {
165            "real_time" => Ok(Self::RealTime),
166            "fixed_rate@50ms" => Ok(Self::FixedRate50ms),
167            "fixed_rate@200ms" => Ok(Self::FixedRate200ms),
168            "fixed_rate@1000ms" => Ok(Self::FixedRate1000ms),
169            _ => Err(ParseError::new(format!("unknown channel: {s}"))),
170        }
171    }
172}
173
174impl std::fmt::Display for Channel {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            Self::RealTime => f.write_str("real_time"),
178            Self::FixedRate50ms => f.write_str("fixed_rate@50ms"),
179            Self::FixedRate200ms => f.write_str("fixed_rate@200ms"),
180            Self::FixedRate1000ms => f.write_str("fixed_rate@1000ms"),
181        }
182    }
183}
184
185/// The trading session of a feed's market, as reported by Pyth Lazer and Aftermath.
186///
187/// Converts to and from its `u16` wire value. Like the on-chain `af_verifier`, parsing accepts
188/// values without a named variant, such as sessions added later, as [`Self::Unknown`] instead of
189/// rejecting the whole update.
190#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
191#[non_exhaustive]
192pub enum MarketSession {
193    /// Regular trading hours.
194    #[default]
195    Regular,
196    /// Before regular trading hours.
197    PreMarket,
198    /// After regular trading hours.
199    PostMarket,
200    /// Overnight trading.
201    OverNight,
202    /// The market is closed.
203    Closed,
204    /// A wire value without a named variant.
205    ///
206    /// Converting from a `u16` never wraps a value that has a named variant, so `Unknown(4)` is
207    /// not equal to [`Self::Closed`]; build sessions from wire values with `From<u16>`.
208    Unknown(u16),
209}
210
211impl From<u16> for MarketSession {
212    fn from(value: u16) -> Self {
213        match value {
214            0 => Self::Regular,
215            1 => Self::PreMarket,
216            2 => Self::PostMarket,
217            3 => Self::OverNight,
218            4 => Self::Closed,
219            _ => Self::Unknown(value),
220        }
221    }
222}
223
224impl From<MarketSession> for u16 {
225    fn from(session: MarketSession) -> Self {
226        match session {
227            MarketSession::Regular => 0,
228            MarketSession::PreMarket => 1,
229            MarketSession::PostMarket => 2,
230            MarketSession::OverNight => 3,
231            MarketSession::Closed => 4,
232            MarketSession::Unknown(value) => value,
233        }
234    }
235}
236
237/// A Pyth Lazer update in the `leEcdsa` format: a signed payload of feeds.
238///
239/// Constructors check the layout only and never verify the signature, which is left to the
240/// on-chain Pyth Lazer verifier.
241#[derive(Clone, Debug, Eq, Hash, PartialEq)]
242pub struct PriceUpdates(Bytes);
243
244impl TryFrom<BytesMut> for PriceUpdates {
245    type Error = Error;
246    /// Copies the bytes, like [`PriceUpdates::from_slice`], so the update does not keep a larger
247    /// buffer that `bytes` may share alive.
248    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
249        Self::from_slice(&bytes)
250    }
251}
252
253impl PriceUpdates {
254    /// Checks and copies an update.
255    pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
256        check_bytes(bytes)?;
257        Ok(Self(Bytes::copy_from_slice(bytes)))
258    }
259    /// Checks an update and keeps `bytes` without copying.
260    ///
261    /// Use [`Self::from_slice`] instead to copy the update out of a larger buffer.
262    pub fn from_bytes(bytes: Bytes) -> Result<Self, Error> {
263        check_bytes(&bytes)?;
264        Ok(Self(bytes))
265    }
266    /// Decodes a standard, padded base64 update and checks it.
267    ///
268    /// Decodes in place when `base64` is the only owner of its buffer, such as a `String`, a
269    /// `Vec<u8>` or the bytes of an unshared `bytestring::ByteString`, and copies it otherwise.
270    pub fn from_base64(base64: impl Into<Bytes>) -> Result<Self, Error> {
271        Self::from_bytes(decode_base64(base64.into(), "Pyth Lazer")?)
272    }
273    /// The whole update, including its signature.
274    pub fn as_bytes(&self) -> &[u8] {
275        &self.0
276    }
277    /// The whole update, including its signature, to share without copying.
278    pub const fn bytes(&self) -> &Bytes {
279        &self.0
280    }
281    /// The whole update, including its signature, without copying.
282    pub fn into_bytes(self) -> Bytes {
283        self.0
284    }
285    /// The recoverable secp256k1 signature over [`Self::payload`].
286    pub fn signature(&self) -> &[u8; SIGNATURE_LEN] {
287        // Skip magic.
288        self.as_bytes()[4..]
289            .first_chunk()
290            .expect("checked on construction")
291    }
292    /// The signed payload, without its length prefix.
293    pub fn payload(&self) -> &[u8] {
294        // Skip magic, signature, payload length.
295        &self.as_bytes()[4 + SIGNATURE_LEN + 2..]
296    }
297    /// Timestamp of the update in microseconds.
298    pub fn timestamp(&self) -> u64 {
299        let mut reader = Reader(self.as_bytes());
300        // Skip magic, signature, payload length, payload magic.
301        reader
302            .skip(4 + SIGNATURE_LEN + 2 + 4)
303            .expect("checked on construction");
304        reader.take_u64().expect("checked on construction")
305    }
306    /// The channel the update was sent on.
307    pub fn channel(&self) -> Channel {
308        // Skip magic, signature, payload length, payload magic, timestamp.
309        self.as_bytes()[4 + SIGNATURE_LEN + 2 + 4 + 8]
310            .try_into()
311            .expect("checked on construction")
312    }
313    /// Number of feeds in the update.
314    pub fn feed_count(&self) -> usize {
315        // Skip magic, signature, payload length, payload magic, timestamp, channel.
316        usize::from(self.as_bytes()[4 + SIGNATURE_LEN + 2 + 4 + 8 + 1])
317    }
318    /// Feeds of the update, in the order sent.
319    pub fn feeds(&self) -> impl Clone + ExactSizeIterator<Item = Feed> {
320        let mut reader = Reader(self.as_bytes());
321        // Skip magic, signature, payload length, payload magic, timestamp, channel.
322        reader
323            .skip(4 + SIGNATURE_LEN + 2 + 4 + 8 + 1)
324            .expect("checked on construction");
325        let feed_count = usize::from(reader.take_u8().expect("checked on construction"));
326        (0..feed_count).map(move |_| take_feed(&mut reader).expect("checked on construction"))
327    }
328    /// The first feed with `feed_id`, if any.
329    pub fn feed(&self, feed_id: PriceFeedId) -> Option<Feed> {
330        self.feeds().find(|feed| feed.feed_id == feed_id)
331    }
332    /// Returns whether the update contains every ID in `feed_ids` exactly once and no other IDs.
333    ///
334    /// Pass a reference to a [`PriceFeedIdSet`], [`SortedSet`](crate::sorted_set::SortedSet), or
335    /// [`ArcSortedSet`](crate::sorted_set::ArcSortedSet); deref coercion borrows its
336    /// [`SortedSetSlice`] view. Feed order does not matter. This check does not allocate: it uses
337    /// the sorted indices of `feed_ids` and a fixed-size stack bitmap to detect repeated IDs.
338    pub fn matches_set(&self, feed_ids: &SortedSetSlice<PriceFeedId>) -> bool {
339        feed_ids.exactly_matches_bounded_iter(self.feeds().map(|feed| feed.feed_id))
340    }
341}
342
343/// A parsed Pyth Lazer feed.
344///
345/// A field is `None` when its property was **not requested**, or when Pyth Lazer reports it as
346/// **unavailable**, e.g. a price without enough publishers. Pyth Lazer encodes an unavailable
347/// price, best bid or ask price, confidence, EMA price or EMA confidence as zero, so, as in the
348/// on-chain Pyth Lazer parser, those fields are never `Some(0)`.
349#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
350pub struct Feed {
351    /// ID of the feed.
352    pub feed_id: PriceFeedId,
353    /// Aggregate market price (mantissa). Use with exponent for actual price.
354    pub price: Option<i64>,
355    /// Highest bid across publishers.
356    pub best_bid_price: Option<i64>,
357    /// Lowest ask across publishers.
358    pub best_ask_price: Option<i64>,
359    /// Number of contributing publishers.
360    pub publisher_count: Option<u16>,
361    /// Decimal exponent: `actual_price = mantissa * 10^exponent`.
362    pub exponent: Option<i16>,
363    /// Price uncertainty; higher = more disagreement.
364    pub confidence: Option<i64>,
365    /// Funding rate (perpetual futures).
366    pub funding_rate: Option<i64>,
367    /// When funding rate was last calculated (μs).
368    pub funding_timestamp: Option<u64>,
369    /// Interval between funding updates (μs).
370    pub funding_rate_interval: Option<u64>,
371    /// Session: regular, preMarket, postMarket, overNight, closed.
372    pub market_session: Option<MarketSession>,
373    /// Exponential moving average of the price.
374    pub ema_price: Option<i64>,
375    /// Exponential moving average of the confidence.
376    pub ema_confidence: Option<u64>,
377    /// Timestamp when price was last generated for this feed (μs).
378    pub feed_update_timestamp: Option<u64>,
379}
380
381impl Feed {
382    /// Returns `true` when the market session is reported as [`MarketSession::Closed`].
383    pub fn is_market_closed(&self) -> bool {
384        self.market_session == Some(MarketSession::Closed)
385    }
386}
387
388// Binary WebSocket frame magic (outer wrapper around the leEcdsa message).
389const BINARY_FRAME_MAGIC: u32 = 461_928_307;
390
391/// Parses a binary WebSocket frame received from Pyth Lazer when using
392/// `formats: ["leEcdsa"]` + `deliveryFormat: "binary"`.
393///
394/// The frame layout is:
395/// - 4 bytes LE: `BINARY_FRAME_MAGIC`
396/// - 8 bytes BE: `subscription_id`
397/// - 2 bytes BE: message length
398/// - message bytes: leEcdsa-signed `PriceUpdates`
399///
400/// Returns the subscription ID and the update, which shares `data` without copying.
401pub fn parse_binary_answer(data: Bytes) -> Result<(u64, PriceUpdates), Error> {
402    let mut reader = Reader(&data);
403    if reader.take_u32()? != BINARY_FRAME_MAGIC {
404        return Err(Error::new(
405            ErrorKind::InvalidData,
406            "Pyth Lazer invalid binary frame magic",
407        ));
408    }
409    let subscription_id = u64::from_be_bytes(reader.take_chunk()?);
410    // Message length is 2 bytes BE.
411    let msg_len = u16::from_be_bytes(reader.take_chunk()?) as usize;
412    let msg_start = data.len() - reader.0.len();
413    reader.skip(msg_len)?;
414    reader.assert_eof()?;
415    let updates = PriceUpdates::from_bytes(data.slice(msg_start..msg_start + msg_len))?;
416    Ok((subscription_id, updates))
417}
418
419const LE_ECDSA_FORMAT_MAGIC: u32 = 1_296_547_300;
420/// Length of the recoverable secp256k1 signature after the format magic.
421const SIGNATURE_LEN: usize = 65;
422const PAYLOAD_FORMAT_MAGIC: u32 = 2_479_346_549;
423
424fn take_feed(reader: &mut Reader<'_>) -> Result<Feed, Error> {
425    let feed_id = PriceFeedId(reader.take_u32()?);
426    let mut feed = Feed {
427        feed_id,
428        ..Default::default()
429    };
430    let property_count = reader.take_u8()?;
431    for _ in 0..property_count {
432        let property_id = reader.take_u8()?;
433        match property_id {
434            0 => feed.price = reader.take_nonzero_i64()?,
435            1 => feed.best_bid_price = reader.take_nonzero_i64()?,
436            2 => feed.best_ask_price = reader.take_nonzero_i64()?,
437            3 => feed.publisher_count = Some(reader.take_u16()?),
438            4 => feed.exponent = Some(reader.take_i16()?),
439            5 => feed.confidence = reader.take_nonzero_i64()?,
440            6 => feed.funding_rate = reader.take_option_u64()?.map(u64::cast_signed),
441            7 => feed.funding_timestamp = reader.take_option_u64()?,
442            8 => feed.funding_rate_interval = reader.take_option_u64()?,
443            9 => feed.market_session = Some(MarketSession::from(reader.take_u16()?)),
444            10 => feed.ema_price = reader.take_nonzero_i64()?,
445            11 => feed.ema_confidence = reader.take_nonzero_u64()?,
446            12 => feed.feed_update_timestamp = reader.take_option_u64()?,
447            _ => {
448                return Err(Error::new(
449                    ErrorKind::InvalidData,
450                    format!("Pyth Lazer invalid property ID: {property_id}"),
451                ));
452            }
453        }
454    }
455    Ok(feed)
456}
457
458fn check_bytes(bytes: &[u8]) -> Result<(), Error> {
459    let mut reader = Reader(bytes);
460    if reader.take_u32()? != LE_ECDSA_FORMAT_MAGIC {
461        return Err(Error::new(
462            ErrorKind::InvalidData,
463            "Pyth Lazer invalid format magic number",
464        ));
465    }
466    let _signature = reader.take(SIGNATURE_LEN)?;
467    let payload_len = reader.take_u16()?;
468    reader.assert_remain(payload_len as usize)?;
469
470    if reader.take_u32()? != PAYLOAD_FORMAT_MAGIC {
471        return Err(Error::new(
472            ErrorKind::InvalidData,
473            "Pyth Lazer invalid payload magic number",
474        ));
475    }
476    let _timestamp = reader.take_u64()?;
477    let _channel = Channel::try_from(reader.take_u8()?)?;
478    let feed_count = reader.take_u8()?;
479    for _ in 0..feed_count {
480        let _feed = take_feed(&mut reader)?;
481    }
482    reader.assert_eof()?;
483    Ok(())
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489
490    const BTC_USD: PriceFeedId = PriceFeedId(1);
491    const ETH_USD: PriceFeedId = PriceFeedId(2);
492    const USDC_USD: PriceFeedId = PriceFeedId(7);
493
494    fn price_updates_with_feed_ids(ids: &[PriceFeedId]) -> PriceUpdates {
495        let mut payload = Vec::new();
496        payload.extend_from_slice(&PAYLOAD_FORMAT_MAGIC.to_le_bytes());
497        payload.extend_from_slice(&0_u64.to_le_bytes());
498        payload.push(Channel::RealTime as u8);
499        payload.push(ids.len().try_into().unwrap());
500        for id in ids {
501            payload.extend_from_slice(&id.0.to_le_bytes());
502            payload.push(0); // No properties.
503        }
504
505        let mut bytes = Vec::new();
506        bytes.extend_from_slice(&LE_ECDSA_FORMAT_MAGIC.to_le_bytes());
507        bytes.extend_from_slice(&[0; 65]);
508        bytes.extend_from_slice(&u16::try_from(payload.len()).unwrap().to_le_bytes());
509        bytes.extend_from_slice(&payload);
510        PriceUpdates::from_slice(&bytes).unwrap()
511    }
512
513    const PYTH_LAZER_PRICE_UPDATES_BASE64: &str = "5L1HTSKo39Jq5IVP8R18EHxhJW/6aUm+sw06RHxZTx8WOrd8bIALgZi8Sk7GAzaHeP6UiN3Ew0cSVjHDPbGP3XE5hAgBtgB108eTAG0ZPF5MBgADAgEAAAANAGGlUjI5BgAAAYwFYS45BgAAAnoXaDk5BgAAAxIABPj/Ba04NSQAAAAABgAHAAgACQAACiA4I408BgAAC8COzYc8BgAADAEAbRk8XkwGAAcAAAANAADh9QUAAAAAATvX9QUAAAAAAkz+9QUAAAAAAwsABPj/BfYqAAAAAAAABgAHAAgACQAACovf9QUAAAAAC+ba9QUAAAAADAEAbRk8XkwGAA==";
514
515    /// Updates of the default feed properties, in the `leEcdsa` format.
516    const PYTH_LAZER_UPDATES: [&[u8]; 3] = [
517        &[
518            228, 189, 71, 77, 155, 77, 83, 126, 124, 37, 209, 194, 89, 114, 165, 72, 144, 13, 138,
519            152, 104, 189, 145, 58, 21, 106, 249, 217, 179, 135, 250, 6, 55, 213, 135, 87, 62, 10,
520            68, 204, 226, 52, 39, 178, 68, 42, 197, 79, 14, 105, 118, 26, 254, 95, 31, 109, 215,
521            106, 195, 181, 56, 11, 165, 82, 30, 94, 37, 64, 0, 53, 0, 117, 211, 199, 147, 64, 195,
522            236, 88, 4, 92, 6, 0, 3, 1, 1, 0, 0, 0, 5, 0, 128, 174, 218, 98, 232, 7, 0, 0, 4, 248,
523            255, 5, 82, 20, 217, 58, 0, 0, 0, 0, 9, 0, 0, 12, 1, 64, 195, 236, 88, 4, 92, 6, 0,
524        ],
525        &[
526            228, 189, 71, 77, 156, 67, 250, 57, 25, 123, 108, 85, 70, 172, 127, 78, 11, 106, 174,
527            99, 192, 165, 5, 199, 201, 233, 239, 14, 70, 183, 125, 192, 30, 143, 172, 68, 35, 83,
528            234, 247, 42, 117, 98, 219, 182, 174, 135, 223, 36, 221, 89, 178, 225, 91, 0, 70, 19,
529            179, 86, 183, 65, 162, 207, 225, 131, 133, 173, 175, 0, 53, 0, 117, 211, 199, 147, 0,
530            235, 245, 88, 4, 92, 6, 0, 3, 1, 2, 0, 0, 0, 5, 0, 49, 64, 201, 190, 64, 0, 0, 0, 4,
531            248, 255, 5, 51, 209, 65, 1, 0, 0, 0, 0, 9, 0, 0, 12, 1, 0, 235, 245, 88, 4, 92, 6, 0,
532        ],
533        &[
534            228, 189, 71, 77, 236, 8, 218, 33, 37, 205, 94, 170, 12, 46, 198, 24, 83, 197, 162, 46,
535            111, 236, 41, 123, 6, 204, 168, 37, 138, 187, 248, 41, 164, 110, 240, 243, 107, 102,
536            152, 246, 239, 139, 110, 98, 153, 129, 208, 228, 75, 224, 38, 27, 248, 96, 71, 242, 58,
537            244, 36, 97, 169, 209, 169, 112, 149, 109, 240, 83, 0, 92, 0, 117, 211, 199, 147, 192,
538            18, 255, 88, 4, 92, 6, 0, 3, 2, 1, 0, 0, 0, 5, 0, 248, 46, 41, 103, 232, 7, 0, 0, 4,
539            248, 255, 5, 202, 148, 39, 63, 0, 0, 0, 0, 9, 0, 0, 12, 1, 192, 18, 255, 88, 4, 92, 6,
540            0, 2, 0, 0, 0, 5, 0, 157, 195, 93, 191, 64, 0, 0, 0, 4, 248, 255, 5, 157, 218, 68, 1,
541            0, 0, 0, 0, 9, 0, 0, 12, 1, 192, 18, 255, 88, 4, 92, 6, 0,
542        ],
543    ];
544
545    const PYTH_LAZER_BINARY_ANSWER: &[u8] = &[
546        115, 119, 136, 27, 0, 0, 0, 0, 0, 0, 0, 1, 0, 253, 228, 189, 71, 77, 89, 217, 69, 65, 163,
547        37, 208, 162, 81, 207, 184, 53, 65, 210, 179, 94, 179, 237, 207, 222, 153, 60, 159, 208,
548        159, 56, 208, 6, 142, 51, 206, 197, 34, 185, 85, 169, 127, 172, 153, 15, 25, 166, 242, 168,
549        74, 241, 9, 209, 166, 104, 97, 96, 111, 206, 19, 50, 50, 38, 59, 157, 76, 49, 86, 146, 1,
550        182, 0, 117, 211, 199, 147, 64, 101, 36, 153, 94, 76, 6, 0, 3, 2, 1, 0, 0, 0, 13, 0, 20,
551        27, 209, 92, 42, 6, 0, 0, 1, 118, 101, 169, 92, 42, 6, 0, 0, 2, 162, 190, 23, 95, 42, 6, 0,
552        0, 3, 18, 0, 4, 248, 255, 5, 37, 151, 250, 18, 0, 0, 0, 0, 6, 0, 7, 0, 8, 0, 9, 0, 0, 10,
553        96, 225, 236, 86, 56, 6, 0, 0, 11, 192, 145, 134, 77, 56, 6, 0, 0, 12, 1, 64, 101, 36, 153,
554        94, 76, 6, 0, 7, 0, 0, 0, 13, 0, 255, 224, 245, 5, 0, 0, 0, 0, 1, 247, 206, 245, 5, 0, 0,
555        0, 0, 2, 171, 238, 245, 5, 0, 0, 0, 0, 3, 11, 0, 4, 248, 255, 5, 234, 44, 0, 0, 0, 0, 0, 0,
556        6, 0, 7, 0, 8, 0, 9, 0, 0, 10, 111, 222, 245, 5, 0, 0, 0, 0, 11, 149, 217, 245, 5, 0, 0, 0,
557        0, 12, 1, 64, 101, 36, 153, 94, 76, 6, 0,
558    ];
559    #[test]
560    fn pyth_lazer_price_updates() {
561        let updates = PriceUpdates::from_base64(PYTH_LAZER_PRICE_UPDATES_BASE64).unwrap();
562        assert_eq!(updates.feed_count(), 2);
563        assert!(updates.matches_set(&PriceFeedIdSet::from([USDC_USD, BTC_USD])));
564        assert_eq!(updates.timestamp(), 1_772_817_479_200_000);
565        assert_eq!(updates.channel(), Channel::FixedRate200ms);
566        assert_eq!(
567            updates.feeds().collect::<Vec<_>>(),
568            [
569                Feed {
570                    feed_id: BTC_USD,
571                    price: Some(6_842_727_179_617),
572                    best_bid_price: Some(6_842_661_012_876),
573                    best_ask_price: Some(6_842_846_025_594),
574                    publisher_count: Some(18),
575                    exponent: Some(-8),
576                    confidence: Some(607_467_693),
577                    // Requested but not reported.
578                    funding_rate: None,
579                    funding_timestamp: None,
580                    funding_rate_interval: None,
581                    market_session: Some(MarketSession::Regular),
582                    ema_price: Some(6_857_135_700_000),
583                    ema_confidence: Some(6_857_046_200_000),
584                    feed_update_timestamp: Some(1_772_817_479_200_000),
585                },
586                Feed {
587                    feed_id: USDC_USD,
588                    price: Some(100_000_000),
589                    best_bid_price: Some(99_997_499),
590                    best_ask_price: Some(100_007_500),
591                    publisher_count: Some(11),
592                    exponent: Some(-8),
593                    confidence: Some(10_998),
594                    funding_rate: None,
595                    funding_timestamp: None,
596                    funding_rate_interval: None,
597                    market_session: Some(MarketSession::Regular),
598                    ema_price: Some(99_999_627),
599                    ema_confidence: Some(99_998_438),
600                    feed_update_timestamp: Some(1_772_817_479_200_000),
601                },
602            ],
603        );
604    }
605
606    #[test]
607    fn matches_set_rejects_repeated_ids() {
608        let expected = PriceFeedIdSet::from([BTC_USD, USDC_USD]);
609
610        let reversed = price_updates_with_feed_ids(&[USDC_USD, BTC_USD]);
611        assert!(reversed.matches_set(&expected));
612
613        let repeated = price_updates_with_feed_ids(&[BTC_USD, BTC_USD]);
614        assert!(!repeated.matches_set(&expected));
615    }
616
617    #[test]
618    fn parse_default_properties() {
619        let expected = [
620            (
621                1_790_023_601_800_000,
622                &[(BTC_USD, 8_694_672_305_792, 987_305_042)][..],
623            ),
624            (
625                1_790_023_602_400_000,
626                &[(ETH_USD, 278_078_767_153, 21_090_611)],
627            ),
628            (
629                1_790_023_603_000_000,
630                &[
631                    (BTC_USD, 8_694_744_559_352, 1_059_558_602),
632                    (ETH_USD, 278_088_500_125, 21_289_629),
633                ],
634            ),
635        ];
636        for (bytes, (timestamp, feeds)) in PYTH_LAZER_UPDATES.into_iter().zip(expected) {
637            let updates = PriceUpdates::from_slice(bytes).unwrap();
638            let feeds: Vec<_> = feeds
639                .iter()
640                .map(|&(feed_id, price, confidence)| Feed {
641                    feed_id,
642                    price: Some(price),
643                    exponent: Some(-8),
644                    confidence: Some(confidence),
645                    market_session: Some(MarketSession::Regular),
646                    feed_update_timestamp: Some(timestamp),
647                    ..Default::default()
648                })
649                .collect();
650
651            assert_eq!(updates.timestamp(), timestamp);
652            assert_eq!(updates.channel(), Channel::FixedRate200ms);
653            assert_eq!(updates.feeds().collect::<Vec<_>>(), feeds);
654        }
655    }
656
657    #[test]
658    fn zero_prices_are_unavailable() {
659        // After the magic, signature, payload length, payload magic, timestamp, channel, feed
660        // count, feed ID, property count and the price property ID.
661        let price = 4 + 65 + 2 + 4 + 8 + 1 + 1 + 4 + 1 + 1;
662        // After the price, the exponent and the confidence property ID.
663        let confidence = price + 8 + (1 + 2) + 1;
664        let mut bytes = PYTH_LAZER_UPDATES[0].to_vec();
665        bytes[price..price + 8].fill(0);
666
667        let feed = PriceUpdates::from_slice(&bytes)
668            .unwrap()
669            .feeds()
670            .next()
671            .unwrap();
672        assert_eq!(feed.price, None);
673        assert_eq!(feed.exponent, Some(-8));
674        assert_eq!(feed.confidence, Some(987_305_042));
675
676        bytes[confidence..confidence + 8].fill(0);
677        let feed = PriceUpdates::from_slice(&bytes)
678            .unwrap()
679            .feeds()
680            .next()
681            .unwrap();
682        assert_eq!(feed.confidence, None);
683    }
684
685    #[test]
686    fn reject_invalid_updates() {
687        let valid = PYTH_LAZER_UPDATES[0];
688        let modified = |index: usize, byte: u8| {
689            let mut bytes = valid.to_vec();
690            bytes[index] = byte;
691            bytes
692        };
693        let mut trailing_data = valid.to_vec();
694        trailing_data.push(0);
695        // After the magic, signature and payload length.
696        let payload_start = 4 + 65 + 2;
697        // After the payload magic, timestamp and channel.
698        let feed_count = payload_start + 4 + 8 + 1;
699        // After the feed count, feed ID and property count.
700        let first_property = feed_count + 1 + 4 + 1;
701        // After price, exponent and confidence.
702        let market_session = first_property + (1 + 8) + (1 + 2) + (1 + 8);
703        // After the market session.
704        let feed_update_timestamp = market_session + 1 + 2;
705
706        let cases = [
707            ("invalid magic", modified(0, 0)),
708            ("invalid payload magic", modified(payload_start, 0)),
709            ("unknown channel", modified(feed_count - 1, 5)),
710            ("feed count too large", modified(feed_count, 2)),
711            ("invalid property", modified(first_property, 13)),
712            (
713                "invalid option flag",
714                modified(feed_update_timestamp + 1, 2),
715            ),
716            ("trailing data", trailing_data),
717            ("truncated", valid[..valid.len() - 1].to_vec()),
718        ];
719        for (name, bytes) in cases {
720            assert!(PriceUpdates::from_slice(&bytes).is_err(), "{name}");
721        }
722
723        let unknown_session = PriceUpdates::from_slice(&modified(market_session + 1, 5)).unwrap();
724        assert_eq!(
725            unknown_session.feeds().next().unwrap().market_session,
726            Some(MarketSession::Unknown(5)),
727        );
728    }
729
730    #[test]
731    fn market_session_round_trips_through_u16() {
732        for value in 0..=6_u16 {
733            assert_eq!(u16::from(MarketSession::from(value)), value);
734        }
735        assert_eq!(MarketSession::from(0), MarketSession::Regular);
736        assert_eq!(MarketSession::from(4), MarketSession::Closed);
737        assert_eq!(MarketSession::from(5), MarketSession::Unknown(5));
738        assert_eq!(u16::from(MarketSession::Unknown(u16::MAX)), u16::MAX);
739    }
740
741    #[test]
742    fn signature_payload_and_feed_by_id() {
743        let bytes = Bytes::from_static(PYTH_LAZER_UPDATES[0]);
744        let updates = PriceUpdates::from_bytes(bytes.clone()).unwrap();
745
746        assert_eq!(updates.signature(), &bytes[4..4 + 65]);
747        assert_eq!(updates.payload(), &bytes[4 + 65 + 2..]);
748        assert_eq!(updates.payload()[..4], PAYLOAD_FORMAT_MAGIC.to_le_bytes());
749        assert_eq!(updates.bytes().as_ptr(), bytes.as_ptr());
750
751        assert_eq!(updates.feed(BTC_USD).unwrap().feed_id, BTC_USD);
752        assert_eq!(updates.feed(USDC_USD), None);
753        assert_eq!(updates.into_bytes(), bytes);
754    }
755
756    #[test]
757    fn parse_binary_answer_with_subscription_id() {
758        let (subscription_id, updates) =
759            parse_binary_answer(Bytes::from_static(PYTH_LAZER_BINARY_ANSWER)).unwrap();
760        assert_eq!(subscription_id, 1);
761        assert_eq!(updates.feed_count(), 2);
762        let feeds: Vec<_> = updates.feeds().collect();
763        assert_eq!(feeds.len(), 2);
764        assert_eq!(feeds[0].feed_id, BTC_USD);
765        assert_eq!(feeds[0].price, Some(6_779_015_600_916));
766        assert_eq!(feeds[1].feed_id, USDC_USD);
767        assert_eq!(feeds[1].price, Some(99_999_999));
768        assert_eq!(updates.timestamp(), 1_772_819_040_200_000);
769    }
770
771    #[test]
772    fn reject_invalid_binary_answers() {
773        let mut invalid_magic = PYTH_LAZER_BINARY_ANSWER.to_vec();
774        invalid_magic[0] = 0;
775        let mut trailing_data = PYTH_LAZER_BINARY_ANSWER.to_vec();
776        trailing_data.push(0);
777        let truncated = PYTH_LAZER_BINARY_ANSWER[..PYTH_LAZER_BINARY_ANSWER.len() - 1].to_vec();
778
779        for (name, bytes) in [
780            ("invalid magic", invalid_magic),
781            ("trailing data", trailing_data),
782            ("truncated", truncated),
783        ] {
784            assert!(parse_binary_answer(bytes.into()).is_err(), "{name}");
785        }
786    }
787
788    #[test]
789    fn feed_properties_display_parse_and_serialize_by_name() {
790        for &property in ALL_FEED_PROPERTIES {
791            let name = property.to_string();
792            assert_eq!(name.parse(), Ok(property));
793            assert_eq!(
794                serde_json::to_string(&property).unwrap(),
795                format!("\"{name}\"")
796            );
797        }
798        assert_eq!(
799            "bestBidPrice".parse::<FeedProperty>(),
800            Ok(FeedProperty::BestBidPrice)
801        );
802        assert!("best_bid_price".parse::<FeedProperty>().is_err());
803    }
804
805    #[test]
806    fn channels_display_parse_and_serialize_by_name() {
807        for channel in [
808            Channel::RealTime,
809            Channel::FixedRate50ms,
810            Channel::FixedRate200ms,
811            Channel::FixedRate1000ms,
812        ] {
813            let name = channel.to_string();
814            assert_eq!(name.parse(), Ok(channel));
815            assert_eq!(
816                serde_json::to_string(&channel).unwrap(),
817                format!("\"{name}\"")
818            );
819        }
820        assert_eq!(
821            "fixed_rate@10ms".parse::<Channel>(),
822            Err(ParseError::new("unknown channel: fixed_rate@10ms"))
823        );
824    }
825}