1pub 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#[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
38#[serde(rename_all = "camelCase")]
39#[non_exhaustive]
40pub enum FeedProperty {
41 Price,
43 BestBidPrice,
45 BestAskPrice,
47 PublisherCount,
49 Exponent,
51 Confidence,
53 FundingRate,
55 FundingTimestamp,
57 FundingRateInterval,
59 MarketSession,
61 EmaPrice,
63 EmaConfidence,
65 FeedUpdateTimestamp,
67}
68
69impl FeedProperty {
70 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
107pub 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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
128#[repr(u8)]
129#[non_exhaustive]
130pub enum Channel {
131 #[serde(rename = "real_time")]
133 RealTime = 1,
134 #[serde(rename = "fixed_rate@50ms")]
136 FixedRate50ms = 2,
137 #[serde(rename = "fixed_rate@200ms")]
139 FixedRate200ms = 3,
140 #[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#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
191#[non_exhaustive]
192pub enum MarketSession {
193 #[default]
195 Regular,
196 PreMarket,
198 PostMarket,
200 OverNight,
202 Closed,
204 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#[derive(Clone, Debug, Eq, Hash, PartialEq)]
242pub struct PriceUpdates(Bytes);
243
244impl TryFrom<BytesMut> for PriceUpdates {
245 type Error = Error;
246 fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
249 Self::from_slice(&bytes)
250 }
251}
252
253impl PriceUpdates {
254 pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
256 check_bytes(bytes)?;
257 Ok(Self(Bytes::copy_from_slice(bytes)))
258 }
259 pub fn from_bytes(bytes: Bytes) -> Result<Self, Error> {
263 check_bytes(&bytes)?;
264 Ok(Self(bytes))
265 }
266 pub fn from_base64(base64: impl Into<Bytes>) -> Result<Self, Error> {
271 Self::from_bytes(decode_base64(base64.into(), "Pyth Lazer")?)
272 }
273 pub fn as_bytes(&self) -> &[u8] {
275 &self.0
276 }
277 pub const fn bytes(&self) -> &Bytes {
279 &self.0
280 }
281 pub fn into_bytes(self) -> Bytes {
283 self.0
284 }
285 pub fn signature(&self) -> &[u8; SIGNATURE_LEN] {
287 self.as_bytes()[4..]
289 .first_chunk()
290 .expect("checked on construction")
291 }
292 pub fn payload(&self) -> &[u8] {
294 &self.as_bytes()[4 + SIGNATURE_LEN + 2..]
296 }
297 pub fn timestamp(&self) -> u64 {
299 let mut reader = Reader(self.as_bytes());
300 reader
302 .skip(4 + SIGNATURE_LEN + 2 + 4)
303 .expect("checked on construction");
304 reader.take_u64().expect("checked on construction")
305 }
306 pub fn channel(&self) -> Channel {
308 self.as_bytes()[4 + SIGNATURE_LEN + 2 + 4 + 8]
310 .try_into()
311 .expect("checked on construction")
312 }
313 pub fn feed_count(&self) -> usize {
315 usize::from(self.as_bytes()[4 + SIGNATURE_LEN + 2 + 4 + 8 + 1])
317 }
318 pub fn feeds(&self) -> impl Clone + ExactSizeIterator<Item = Feed> {
320 let mut reader = Reader(self.as_bytes());
321 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 pub fn feed(&self, feed_id: PriceFeedId) -> Option<Feed> {
330 self.feeds().find(|feed| feed.feed_id == feed_id)
331 }
332 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#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
350pub struct Feed {
351 pub feed_id: PriceFeedId,
353 pub price: Option<i64>,
355 pub best_bid_price: Option<i64>,
357 pub best_ask_price: Option<i64>,
359 pub publisher_count: Option<u16>,
361 pub exponent: Option<i16>,
363 pub confidence: Option<i64>,
365 pub funding_rate: Option<i64>,
367 pub funding_timestamp: Option<u64>,
369 pub funding_rate_interval: Option<u64>,
371 pub market_session: Option<MarketSession>,
373 pub ema_price: Option<i64>,
375 pub ema_confidence: Option<u64>,
377 pub feed_update_timestamp: Option<u64>,
379}
380
381impl Feed {
382 pub fn is_market_closed(&self) -> bool {
384 self.market_session == Some(MarketSession::Closed)
385 }
386}
387
388const BINARY_FRAME_MAGIC: u32 = 461_928_307;
390
391pub 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 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;
420const 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); }
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 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 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 let price = 4 + 65 + 2 + 4 + 8 + 1 + 1 + 4 + 1 + 1;
662 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 let payload_start = 4 + 65 + 2;
697 let feed_count = payload_start + 4 + 8 + 1;
699 let first_property = feed_count + 1 + 4 + 1;
701 let market_session = first_property + (1 + 8) + (1 + 2) + (1 + 8);
703 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}