1use ahash::AHashMap;
19#[cfg(test)]
20use nautilus_core::string::secret::REDACTED;
21use nautilus_core::{
22 serialization::{
23 deserialize_decimal, deserialize_decimal_from_str, deserialize_decimal_native,
24 deserialize_decimal_or_zero, deserialize_optional_decimal,
25 },
26 string::secret::SecretString,
27};
28use nautilus_model::{
29 data::{
30 Bar, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate, OrderBookDeltas, OrderBookDepth,
31 QuoteTick, TradeTick,
32 },
33 events::AccountState,
34 reports::PositionStatusReport,
35};
36use rust_decimal::Decimal;
37use serde::{
38 Deserialize, Serialize,
39 de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor},
40};
41use serde_json::value::RawValue;
42use ustr::Ustr;
43use zeroize::Zeroize;
44
45use crate::{
46 common::enums::{LighterCandleResolution, LighterTxStatus},
47 http::models::{LighterOrder, LighterPriceLevel, LighterTrade},
48};
49
50pub(crate) const TX_BATCH_ID_PREFIX: &str = "tx-batch:";
51
52#[derive(Debug, Clone)]
61pub enum NautilusWsMessage {
62 Trades(Vec<TradeTick>),
63 Quote(QuoteTick),
64 Deltas(OrderBookDeltas),
65 Depth(Box<OrderBookDepth>),
66 Bar(Bar),
67 MarkPrice(MarkPriceUpdate),
68 IndexPrice(IndexPriceUpdate),
69 FundingRate(FundingRateUpdate),
70 ExecutionReports(Vec<ExecutionReport>),
71 PositionSnapshot {
72 reports: Vec<PositionStatusReport>,
73 skipped_market_ids: Vec<i64>,
74 },
75 PositionUpdate {
76 reports: Vec<PositionStatusReport>,
77 closed_market_ids: Vec<i64>,
78 skipped_market_ids: Vec<i64>,
79 },
80 AccountState(Box<AccountState>),
81 SendTxAck {
82 connection_epoch: u64,
83 tx_hash: Option<String>,
84 code: i64,
85 },
86 SendTxRejected {
87 connection_epoch: u64,
88 source: SendTxRejectionSource,
89 code: Option<i64>,
90 message: String,
91 tx_hash: Option<String>,
92 },
93 SendTxBatchResult {
94 connection_epoch: u64,
95 id: String,
96 code: i64,
97 message: String,
98 tx_hashes: Vec<String>,
99 },
100 AccountTx {
101 connection_epoch: u64,
102 txs: Vec<LighterWsTx>,
103 },
104 Raw(serde_json::Value),
105 Reconnected {
106 connection_epoch: u64,
107 },
108 AccountStreamFirstFrame(AccountStream),
114}
115
116impl NautilusWsMessage {
117 #[must_use]
118 pub(crate) fn with_connection_epoch(self, connection_epoch: u64) -> Self {
119 match self {
120 Self::AccountTx { txs, .. } => Self::AccountTx {
121 connection_epoch,
122 txs,
123 },
124 Self::SendTxAck { tx_hash, code, .. } => Self::SendTxAck {
125 connection_epoch,
126 tx_hash,
127 code,
128 },
129 Self::SendTxRejected {
130 source,
131 code,
132 message,
133 tx_hash,
134 ..
135 } => Self::SendTxRejected {
136 connection_epoch,
137 source,
138 code,
139 message,
140 tx_hash,
141 },
142 Self::SendTxBatchResult {
143 id,
144 code,
145 message,
146 tx_hashes,
147 ..
148 } => Self::SendTxBatchResult {
149 connection_epoch,
150 id,
151 code,
152 message,
153 tx_hashes,
154 },
155 other => other,
156 }
157 }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162pub enum AccountStream {
163 Orders,
164 Trades,
165 Positions,
166 Assets,
167 UserStats,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum SendTxRejectionSource {
180 Ack,
181 BareError,
182}
183
184#[derive(Debug, Clone)]
197#[allow(
198 clippy::large_enum_variant,
199 reason = "payload variants are short-lived and consumed once on the venue-message channel"
200)]
201pub enum ExecutionReport {
202 Order(LighterOrder),
203 Fill(LighterTrade),
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207#[serde(tag = "type")]
208pub enum LighterWsRequest {
209 #[serde(rename = "subscribe")]
210 Subscribe {
211 channel: String,
212 #[serde(skip_serializing_if = "Option::is_none")]
213 auth: Option<SecretString>,
214 },
215 #[serde(rename = "unsubscribe")]
216 Unsubscribe { channel: String },
217 #[serde(rename = "jsonapi/sendtx")]
218 SendTx { data: LighterWsSendTx },
219 #[serde(rename = "jsonapi/sendtxbatch")]
220 SendTxBatch { data: LighterWsSendTxBatch },
221}
222
223impl Zeroize for LighterWsRequest {
224 fn zeroize(&mut self) {
225 if let Self::Subscribe { auth, .. } = self {
226 auth.zeroize();
227 }
228 }
229}
230
231impl LighterWsRequest {
232 #[must_use]
233 pub fn subscribe(channel: impl Into<String>) -> Self {
234 Self::Subscribe {
235 channel: channel.into(),
236 auth: None,
237 }
238 }
239
240 #[must_use]
241 pub fn subscribe_auth(channel: impl Into<String>, auth: impl Into<SecretString>) -> Self {
242 Self::Subscribe {
243 channel: channel.into(),
244 auth: Some(auth.into()),
245 }
246 }
247
248 #[must_use]
249 pub fn unsubscribe(channel: impl Into<String>) -> Self {
250 Self::Unsubscribe {
251 channel: channel.into(),
252 }
253 }
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct LighterWsSendTx {
264 pub tx_type: u8,
265 pub tx_info: Box<RawValue>,
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct LighterWsSendTxBatch {
275 pub id: String,
276 pub tx_types: String,
277 pub tx_infos: String,
278}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
286pub enum LighterWsChannelKind {
287 OrderBook,
288 Ticker,
289 Trade,
290 Candle,
291 MarketStats,
292 SpotMarketStats,
293 AccountAll,
294 AccountOrders,
295 AccountAllOrders,
296 AccountAllTrades,
297 AccountAllPositions,
298 AccountAllAssets,
299 AccountTx,
300 UserStats,
301 Height,
302}
303
304impl LighterWsChannelKind {
305 #[must_use]
307 pub const fn as_wire_str(self) -> &'static str {
308 match self {
309 Self::OrderBook => "order_book",
310 Self::Ticker => "ticker",
311 Self::Trade => "trade",
312 Self::Candle => "candle",
313 Self::MarketStats => "market_stats",
314 Self::SpotMarketStats => "spot_market_stats",
315 Self::AccountAll => "account_all",
316 Self::AccountOrders => "account_orders",
317 Self::AccountAllOrders => "account_all_orders",
318 Self::AccountAllTrades => "account_all_trades",
319 Self::AccountAllPositions => "account_all_positions",
320 Self::AccountAllAssets => "account_all_assets",
321 Self::AccountTx => "account_tx",
322 Self::UserStats => "user_stats",
323 Self::Height => "height",
324 }
325 }
326
327 #[must_use]
329 pub fn from_wire_str(wire_str: &str) -> Option<Self> {
330 match wire_str {
331 "order_book" => Some(Self::OrderBook),
332 "ticker" => Some(Self::Ticker),
333 "trade" => Some(Self::Trade),
334 "candle" => Some(Self::Candle),
335 "market_stats" => Some(Self::MarketStats),
336 "spot_market_stats" => Some(Self::SpotMarketStats),
337 "account_all" => Some(Self::AccountAll),
338 "account_orders" => Some(Self::AccountOrders),
339 "account_all_orders" => Some(Self::AccountAllOrders),
340 "account_all_trades" => Some(Self::AccountAllTrades),
341 "account_all_positions" => Some(Self::AccountAllPositions),
342 "account_all_assets" => Some(Self::AccountAllAssets),
343 "account_tx" => Some(Self::AccountTx),
344 "user_stats" => Some(Self::UserStats),
345 "height" => Some(Self::Height),
346 _ => None,
347 }
348 }
349}
350
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub enum LighterWsChannel {
353 OrderBook(i64),
354 Ticker(i64),
355 MarketStats(LighterMarketSelection),
356 SpotMarketStats(LighterMarketSelection),
357 Trade(i64),
358 Candle {
359 market_index: i64,
360 resolution: LighterCandleResolution,
361 },
362 AccountAll(i64),
363 AccountOrders {
364 market_index: i64,
365 account_index: i64,
366 },
367 AccountAllOrders(i64),
368 AccountAllTrades(i64),
369 AccountAllPositions(i64),
370 AccountAllAssets(i64),
371 AccountTx(i64),
372 UserStats(i64),
373 Height,
374}
375
376impl LighterWsChannel {
377 #[must_use]
379 pub const fn kind(&self) -> LighterWsChannelKind {
380 match self {
381 Self::OrderBook(_) => LighterWsChannelKind::OrderBook,
382 Self::Ticker(_) => LighterWsChannelKind::Ticker,
383 Self::Trade(_) => LighterWsChannelKind::Trade,
384 Self::Candle { .. } => LighterWsChannelKind::Candle,
385 Self::MarketStats(_) => LighterWsChannelKind::MarketStats,
386 Self::SpotMarketStats(_) => LighterWsChannelKind::SpotMarketStats,
387 Self::AccountAll(_) => LighterWsChannelKind::AccountAll,
388 Self::AccountOrders { .. } => LighterWsChannelKind::AccountOrders,
389 Self::AccountAllOrders(_) => LighterWsChannelKind::AccountAllOrders,
390 Self::AccountAllTrades(_) => LighterWsChannelKind::AccountAllTrades,
391 Self::AccountAllPositions(_) => LighterWsChannelKind::AccountAllPositions,
392 Self::AccountAllAssets(_) => LighterWsChannelKind::AccountAllAssets,
393 Self::AccountTx(_) => LighterWsChannelKind::AccountTx,
394 Self::UserStats(_) => LighterWsChannelKind::UserStats,
395 Self::Height => LighterWsChannelKind::Height,
396 }
397 }
398
399 #[must_use]
400 pub fn subscription_channel(&self) -> String {
401 let kind = self.kind().as_wire_str();
402
403 match self {
404 Self::OrderBook(market_index)
405 | Self::Ticker(market_index)
406 | Self::Trade(market_index) => format!("{kind}/{market_index}"),
407 Self::Candle {
408 market_index,
409 resolution,
410 } => format!("{kind}/{market_index}/{}", resolution.as_str()),
411 Self::MarketStats(selection) | Self::SpotMarketStats(selection) => {
412 format!("{kind}/{}", selection.subscription_value())
413 }
414 Self::AccountAll(account_index)
415 | Self::AccountAllOrders(account_index)
416 | Self::AccountAllTrades(account_index)
417 | Self::AccountAllPositions(account_index)
418 | Self::AccountAllAssets(account_index)
419 | Self::AccountTx(account_index)
420 | Self::UserStats(account_index) => format!("{kind}/{account_index}"),
421 Self::AccountOrders {
422 market_index,
423 account_index,
424 } => format!("{kind}/{market_index}/{account_index}"),
425 Self::Height => kind.to_string(),
426 }
427 }
428
429 #[must_use]
437 pub fn topic_key(&self) -> String {
438 self.subscription_channel().replace('/', ":")
439 }
440
441 #[must_use]
443 pub const fn requires_auth(&self) -> bool {
444 matches!(
445 self,
446 Self::AccountAll(_)
447 | Self::AccountOrders { .. }
448 | Self::AccountAllOrders(_)
449 | Self::AccountAllTrades(_)
450 | Self::AccountAllPositions(_)
451 | Self::AccountAllAssets(_)
452 | Self::AccountTx(_)
453 | Self::UserStats(_)
454 )
455 }
456}
457
458#[derive(Debug, Copy, Clone, PartialEq, Eq)]
459pub enum LighterMarketSelection {
460 All,
461 Market(i64),
462}
463
464impl LighterMarketSelection {
465 fn subscription_value(self) -> String {
466 match self {
467 Self::All => "all".to_string(),
468 Self::Market(market_index) => market_index.to_string(),
469 }
470 }
471}
472
473#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
475pub struct LighterWsTx {
476 pub hash: String,
477 pub status: LighterTxStatus,
478 pub event_info: String,
479}
480
481#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
485#[serde(tag = "type")]
486pub enum LighterWsFrame {
487 #[serde(rename = "shutdown")]
488 Shutdown { close_in_ms: u64 },
489 #[serde(rename = "subscribed/order_book")]
490 OrderBookSnapshot {
491 channel: Ustr,
492 #[serde(default)]
493 last_updated_at: u64,
494 offset: i64,
495 order_book: LighterWsOrderBook,
496 timestamp: u64,
497 },
498 #[serde(rename = "update/order_book")]
499 OrderBook {
500 channel: Ustr,
501 last_updated_at: u64,
502 offset: i64,
503 order_book: LighterWsOrderBook,
504 timestamp: u64,
505 },
506 #[serde(rename = "subscribed/ticker")]
507 TickerSnapshot {
508 channel: Ustr,
509 #[serde(default)]
510 last_updated_at: u64,
511 nonce: i64,
512 ticker: LighterTicker,
513 timestamp: u64,
514 },
515 #[serde(rename = "update/ticker")]
516 Ticker {
517 channel: Ustr,
518 last_updated_at: u64,
519 nonce: i64,
520 ticker: LighterTicker,
521 timestamp: u64,
522 },
523 #[serde(rename = "update/market_stats", alias = "subscribed/market_stats")]
524 MarketStats {
525 channel: Ustr,
526 market_stats: LighterMarketStatsPayload,
527 timestamp: u64,
528 },
529 #[serde(
530 rename = "update/spot_market_stats",
531 alias = "subscribed/spot_market_stats"
532 )]
533 SpotMarketStats {
534 channel: Ustr,
535 spot_market_stats: LighterSpotMarketStatsPayload,
536 timestamp: u64,
537 },
538 #[serde(rename = "subscribed/trade")]
539 TradeSnapshot {
540 channel: Ustr,
541 #[serde(default, deserialize_with = "deserialize_trade_vec")]
542 liquidation_trades: Vec<LighterTrade>,
543 nonce: i64,
544 #[serde(default, deserialize_with = "deserialize_trade_vec")]
545 trades: Vec<LighterTrade>,
546 },
547 #[serde(rename = "update/trade")]
548 Trade {
549 channel: Ustr,
550 #[serde(default, deserialize_with = "deserialize_trade_vec")]
551 liquidation_trades: Vec<LighterTrade>,
552 nonce: i64,
553 #[serde(default, deserialize_with = "deserialize_trade_vec")]
554 trades: Vec<LighterTrade>,
555 },
556 #[serde(rename = "update/account_orders", alias = "subscribed/account_orders")]
557 AccountOrders {
558 account: i64,
559 channel: Ustr,
560 nonce: i64,
561 orders: AHashMap<Ustr, Vec<LighterOrder>>,
562 },
563 #[serde(
564 rename = "update/account_all_orders",
565 alias = "subscribed/account_all_orders"
566 )]
567 AccountAllOrders {
568 channel: Ustr,
569 orders: AHashMap<Ustr, Vec<LighterOrder>>,
570 },
571 #[serde(rename = "subscribed/account_tx")]
572 AccountTxSubscribed { channel: Ustr },
573 #[serde(rename = "update/account_tx")]
574 AccountTx {
575 channel: Ustr,
576 txs: Vec<LighterWsTx>,
577 },
578 #[serde(rename = "subscribed/account_all_trades")]
579 AccountAllTradesSnapshot {
580 channel: Ustr,
581 #[serde(default, deserialize_with = "deserialize_trade_vec")]
582 trades: Vec<LighterTrade>,
583 #[serde(deserialize_with = "deserialize_decimal")]
584 total_volume: Decimal,
585 #[serde(deserialize_with = "deserialize_decimal")]
586 monthly_volume: Decimal,
587 #[serde(deserialize_with = "deserialize_decimal")]
588 weekly_volume: Decimal,
589 #[serde(deserialize_with = "deserialize_decimal")]
590 daily_volume: Decimal,
591 },
592 #[serde(rename = "update/account_all_trades")]
593 AccountAllTrades {
594 channel: Ustr,
595 trades: AHashMap<Ustr, Vec<LighterTrade>>,
596 },
597 #[serde(rename = "subscribed/account_all_positions")]
598 AccountAllPositionsSnapshot {
599 channel: Ustr,
600 positions: AHashMap<Ustr, LighterPosition>,
601 #[serde(default)]
602 shares: Vec<LighterPoolShares>,
603 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
604 last_funding_round: Option<AHashMap<Ustr, Decimal>>,
605 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
606 last_funding_discount: Option<AHashMap<Ustr, Decimal>>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
608 transaction_time: Option<i64>,
609 },
610 #[serde(rename = "update/account_all_positions")]
611 AccountAllPositions {
612 channel: Ustr,
613 positions: AHashMap<Ustr, LighterPosition>,
614 #[serde(default)]
615 shares: Vec<LighterPoolShares>,
616 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
617 last_funding_round: Option<AHashMap<Ustr, Decimal>>,
618 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
619 last_funding_discount: Option<AHashMap<Ustr, Decimal>>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
621 transaction_time: Option<i64>,
622 },
623 #[serde(
624 rename = "update/account_all_assets",
625 alias = "subscribed/account_all_assets"
626 )]
627 AccountAllAssets {
628 assets: AHashMap<Ustr, LighterAsset>,
629 channel: Ustr,
630 timestamp: u64,
631 #[serde(default, skip_serializing_if = "Option::is_none")]
632 transaction_time: Option<i64>,
633 },
634 #[serde(rename = "update/user_stats", alias = "subscribed/user_stats")]
635 UserStats {
636 channel: Ustr,
637 stats: LighterUserStats,
638 timestamp: u64,
639 },
640 #[serde(rename = "update/height", alias = "subscribed/height")]
641 Height {
642 channel: Ustr,
643 height: i64,
644 timestamp: u64,
645 },
646 #[serde(rename = "subscribed/candle")]
647 CandleSnapshot {
648 channel: Ustr,
649 candles: Vec<LighterWsCandle>,
650 timestamp: u64,
651 },
652 #[serde(rename = "update/candle")]
653 Candle {
654 channel: Ustr,
655 candles: Vec<LighterWsCandle>,
656 timestamp: u64,
657 },
658}
659
660#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
661pub struct LighterWsCandle {
662 pub t: i64,
663 #[serde(deserialize_with = "deserialize_decimal")]
664 pub o: Decimal,
665 #[serde(deserialize_with = "deserialize_decimal")]
666 pub h: Decimal,
667 #[serde(deserialize_with = "deserialize_decimal")]
668 pub l: Decimal,
669 #[serde(deserialize_with = "deserialize_decimal")]
670 pub c: Decimal,
671 #[serde(deserialize_with = "deserialize_decimal")]
672 pub v: Decimal,
673 #[serde(default, rename = "V", deserialize_with = "deserialize_decimal")]
674 pub quote_volume: Decimal,
675 #[serde(default)]
676 pub i: i64,
677}
678
679#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
680pub struct LighterWsOrderBook {
681 pub code: i32,
682 pub asks: Vec<LighterPriceLevel>,
683 pub bids: Vec<LighterPriceLevel>,
684 pub offset: i64,
685 pub nonce: i64,
686 pub last_updated_at: u64,
687 pub begin_nonce: i64,
688}
689
690#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
691pub struct LighterTicker {
692 pub s: Ustr,
693 pub a: LighterPriceLevel,
694 pub b: LighterPriceLevel,
695 pub last_updated_at: u64,
696}
697
698#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
699#[serde(untagged)]
700pub enum LighterMarketStatsPayload {
701 All(AHashMap<Ustr, LighterMarketStats>),
702 One(Box<LighterMarketStats>),
703}
704
705#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
706pub struct LighterMarketStats {
707 pub symbol: Ustr,
708 pub market_id: i64,
709 #[serde(deserialize_with = "deserialize_decimal_from_str")]
710 pub index_price: Decimal,
711 #[serde(deserialize_with = "deserialize_decimal_from_str")]
712 pub mark_price: Decimal,
713 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
714 pub mid_price: Decimal,
715 #[serde(deserialize_with = "deserialize_decimal_from_str")]
716 pub open_interest: Decimal,
717 #[serde(deserialize_with = "deserialize_decimal_from_str")]
718 pub open_interest_limit: Decimal,
719 #[serde(deserialize_with = "deserialize_decimal_from_str")]
720 pub funding_clamp_small: Decimal,
721 #[serde(deserialize_with = "deserialize_decimal_from_str")]
722 pub funding_clamp_big: Decimal,
723 #[serde(deserialize_with = "deserialize_decimal_from_str")]
724 pub last_trade_price: Decimal,
725 #[serde(deserialize_with = "deserialize_decimal_from_str")]
726 pub current_funding_rate: Decimal,
727 #[serde(deserialize_with = "deserialize_decimal_from_str")]
728 pub funding_rate: Decimal,
729 pub funding_timestamp: u64,
730 #[serde(deserialize_with = "deserialize_decimal")]
731 pub daily_base_token_volume: Decimal,
732 #[serde(deserialize_with = "deserialize_decimal")]
733 pub daily_quote_token_volume: Decimal,
734 #[serde(deserialize_with = "deserialize_decimal")]
735 pub daily_price_low: Decimal,
736 #[serde(deserialize_with = "deserialize_decimal")]
737 pub daily_price_high: Decimal,
738 #[serde(deserialize_with = "deserialize_decimal")]
739 pub daily_price_change: Decimal,
740}
741
742#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
743#[serde(untagged)]
744pub enum LighterSpotMarketStatsPayload {
745 All(AHashMap<Ustr, LighterSpotMarketStats>),
746 One(Box<LighterSpotMarketStats>),
747}
748
749#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
750pub struct LighterSpotMarketStats {
751 pub symbol: Ustr,
752 pub market_id: i64,
753 #[serde(deserialize_with = "deserialize_decimal_from_str")]
754 pub index_price: Decimal,
755 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
756 pub mid_price: Decimal,
757 #[serde(deserialize_with = "deserialize_decimal_from_str")]
758 pub last_trade_price: Decimal,
759 #[serde(deserialize_with = "deserialize_decimal")]
760 pub daily_base_token_volume: Decimal,
761 #[serde(deserialize_with = "deserialize_decimal")]
762 pub daily_quote_token_volume: Decimal,
763 #[serde(deserialize_with = "deserialize_decimal")]
764 pub daily_price_low: Decimal,
765 #[serde(deserialize_with = "deserialize_decimal")]
766 pub daily_price_high: Decimal,
767 #[serde(deserialize_with = "deserialize_decimal")]
768 pub daily_price_change: Decimal,
769}
770
771#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
772pub struct LighterPosition {
773 pub market_id: i64,
774 pub symbol: Ustr,
775 #[serde(deserialize_with = "deserialize_decimal_from_str")]
776 pub initial_margin_fraction: Decimal,
777 pub open_order_count: i64,
778 pub pending_order_count: i64,
779 pub position_tied_order_count: i64,
780 pub sign: i8,
781 #[serde(deserialize_with = "deserialize_decimal_from_str")]
782 pub position: Decimal,
783 #[serde(deserialize_with = "deserialize_decimal_from_str")]
784 pub avg_entry_price: Decimal,
785 #[serde(deserialize_with = "deserialize_decimal_from_str")]
786 pub position_value: Decimal,
787 #[serde(deserialize_with = "deserialize_decimal_from_str")]
788 pub unrealized_pnl: Decimal,
789 #[serde(deserialize_with = "deserialize_decimal_from_str")]
790 pub realized_pnl: Decimal,
791 #[serde(deserialize_with = "deserialize_decimal_from_str")]
792 pub liquidation_price: Decimal,
793 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
794 pub total_funding_paid_out: Option<Decimal>,
795 pub margin_mode: i32,
796 #[serde(deserialize_with = "deserialize_decimal_from_str")]
797 pub allocated_margin: Decimal,
798 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
799 pub total_discount: Option<Decimal>,
800}
801
802#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
803pub struct LighterPoolShares {
804 pub public_pool_index: i64,
805 pub shares_amount: i64,
806 #[serde(deserialize_with = "deserialize_decimal_from_str")]
807 pub entry_usdc: Decimal,
808 #[serde(deserialize_with = "deserialize_decimal_from_str")]
809 pub principal_amount: Decimal,
810 pub entry_timestamp: u64,
811}
812
813#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
817pub struct LighterUserStatsScoped {
818 #[serde(deserialize_with = "deserialize_decimal_from_str")]
819 pub available_balance: Decimal,
820 #[serde(deserialize_with = "deserialize_decimal_from_str")]
821 pub buying_power: Decimal,
822 #[serde(deserialize_with = "deserialize_decimal_from_str")]
823 pub collateral: Decimal,
824 #[serde(deserialize_with = "deserialize_decimal_from_str")]
825 pub leverage: Decimal,
826 #[serde(deserialize_with = "deserialize_decimal_from_str")]
827 pub margin_usage: Decimal,
828 #[serde(deserialize_with = "deserialize_decimal_from_str")]
829 pub portfolio_value: Decimal,
830}
831
832#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
835pub struct LighterUserStats {
836 #[serde(default)]
837 pub account_trading_mode: i32,
838 #[serde(deserialize_with = "deserialize_decimal_from_str")]
839 pub available_balance: Decimal,
840 #[serde(deserialize_with = "deserialize_decimal_from_str")]
841 pub buying_power: Decimal,
842 #[serde(deserialize_with = "deserialize_decimal_from_str")]
843 pub collateral: Decimal,
844 #[serde(deserialize_with = "deserialize_decimal_from_str")]
845 pub leverage: Decimal,
846 #[serde(deserialize_with = "deserialize_decimal_from_str")]
847 pub margin_usage: Decimal,
848 #[serde(deserialize_with = "deserialize_decimal_from_str")]
849 pub portfolio_value: Decimal,
850 pub cross_stats: Option<LighterUserStatsScoped>,
851 pub total_stats: Option<LighterUserStatsScoped>,
852}
853
854#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
855pub struct LighterAsset {
856 pub symbol: Ustr,
857 pub asset_id: i16,
858 #[serde(deserialize_with = "deserialize_decimal_from_str")]
860 pub balance: Decimal,
861 #[serde(deserialize_with = "deserialize_decimal_from_str")]
863 pub locked_balance: Decimal,
864 #[serde(default, deserialize_with = "deserialize_decimal_from_str")]
867 pub margin_balance: Decimal,
868 #[serde(default)]
871 pub margin_mode: Ustr,
872}
873
874#[derive(Deserialize)]
875struct JsonDecimal(#[serde(deserialize_with = "deserialize_decimal_native")] Decimal);
876
877fn deserialize_optional_decimal_map<'de, D: serde::Deserializer<'de>>(
878 deserializer: D,
879) -> Result<Option<AHashMap<Ustr, Decimal>>, D::Error> {
880 let values = Option::<AHashMap<Ustr, JsonDecimal>>::deserialize(deserializer)?;
881 Ok(values.map(|values| {
882 values
883 .into_iter()
884 .map(|(key, value)| (key, value.0))
885 .collect()
886 }))
887}
888
889fn deserialize_trade_vec<'de, D>(deserializer: D) -> Result<Vec<LighterTrade>, D::Error>
890where
891 D: serde::Deserializer<'de>,
892{
893 struct TradeVecVisitor;
894
895 impl<'de> Visitor<'de> for TradeVecVisitor {
896 type Value = Vec<LighterTrade>;
897
898 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899 formatter.write_str("trade array, object keyed by market, or null")
900 }
901
902 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
903 Ok(Vec::new())
904 }
905
906 fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
907 Ok(Vec::new())
908 }
909
910 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
911 let mut trades = Vec::with_capacity(seq.size_hint().unwrap_or(0));
912 while let Some(trade) = seq.next_element::<LighterTrade>()? {
913 trades.push(trade);
914 }
915 Ok(trades)
916 }
917
918 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
919 let mut trades = Vec::new();
920 while let Some((_, mut market_trades)) =
921 map.next_entry::<IgnoredAny, Vec<LighterTrade>>()?
922 {
923 trades.append(&mut market_trades);
924 }
925 Ok(trades)
926 }
927 }
928
929 deserializer.deserialize_any(TradeVecVisitor)
930}
931
932#[cfg(test)]
933mod tests {
934 use std::str::FromStr;
935
936 use rstest::rstest;
937 use serde_json::Value;
938
939 use super::*;
940 use crate::common::enums::{
941 LighterOrderKind, LighterOrderStatus, LighterOrderTimeInForce, LighterTradeType,
942 LighterTriggerStatus,
943 };
944
945 const WS_ORDER_BOOK_UPDATE: &str = include_str!("../../test_data/ws_order_book_update.json");
946 const WS_ORDER_BOOK_SUBSCRIBED: &str =
947 include_str!("../../test_data/ws_order_book_subscribed.json");
948 const WS_ORDER_BOOK_SUBSCRIBED_EMPTY: &str =
949 include_str!("../../test_data/ws_order_book_subscribed_empty.json");
950 const WS_TRADE_UPDATE: &str = include_str!("../../test_data/ws_trade_update.json");
951 const WS_TRADE_SUBSCRIBED: &str = include_str!("../../test_data/ws_trade_subscribed.json");
952 const WS_TICKER_UPDATE: &str = include_str!("../../test_data/ws_ticker_update.json");
953 const WS_TICKER_SUBSCRIBED: &str = include_str!("../../test_data/ws_ticker_subscribed.json");
954 const WS_TICKER_SUBSCRIBED_EMPTY: &str =
955 include_str!("../../test_data/ws_ticker_subscribed_empty.json");
956 const WS_MARKET_STATS_UPDATE_SINGLE: &str =
957 include_str!("../../test_data/ws_market_stats_update_single.json");
958 const WS_MARKET_STATS_SUBSCRIBED_SINGLE: &str =
959 include_str!("../../test_data/ws_market_stats_subscribed_single.json");
960 const WS_MARKET_STATS_UPDATE_ALL: &str =
961 include_str!("../../test_data/ws_market_stats_update_all.json");
962 const WS_MARKET_STATS_UPDATE_SINGLE_WIDENED: &str =
963 include_str!("../../test_data/ws_market_stats_update_single_widened.json");
964 const WS_SPOT_MARKET_STATS_UPDATE_SINGLE: &str =
965 include_str!("../../test_data/ws_spot_market_stats_update_single.json");
966 const WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE: &str =
967 include_str!("../../test_data/ws_spot_market_stats_subscribed_single.json");
968 const WS_SPOT_MARKET_STATS_UPDATE_ALL: &str =
969 include_str!("../../test_data/ws_spot_market_stats_update_all.json");
970 const WS_SPOT_MARKET_STATS_UPDATE_SINGLE_WIDENED: &str =
971 include_str!("../../test_data/ws_spot_market_stats_update_single_widened.json");
972 const WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE_EMPTY_MID: &str =
973 include_str!("../../test_data/ws_spot_market_stats_subscribed_single_empty_mid.json");
974 const WS_ACCOUNT_ALL_ASSETS_UPDATE: &str =
975 include_str!("../../test_data/ws_account_all_assets_update.json");
976 const WS_ACCOUNT_ORDERS_UPDATE: &str =
977 include_str!("../../test_data/ws_account_orders_update.json");
978 const WS_ACCOUNT_ALL_TRADES_UPDATE: &str =
979 include_str!("../../test_data/ws_account_all_trades_update.json");
980 const WS_ACCOUNT_ALL_POSITIONS_UPDATE: &str =
981 include_str!("../../test_data/ws_account_all_positions_update.json");
982 const WS_HEIGHT_UPDATE: &str = include_str!("../../test_data/ws_height_update.json");
983 const WS_CANDLE_SUBSCRIBED: &str = include_str!("../../test_data/ws_candle_subscribed.json");
984 const WS_CANDLE_UPDATE: &str = include_str!("../../test_data/ws_candle_update.json");
985
986 #[rstest]
987 #[case("subscribed/account_all_positions")]
988 #[case("update/account_all_positions")]
989 fn test_funding_decimal_maps(#[case] kind: &str) {
990 let value = serde_json::json!({
991 "type": kind,
992 "channel": "account_all_positions:7",
993 "positions": {},
994 "last_funding_round": {"1": 9007199254740993u64, "3": 1.25},
995 "last_funding_discount": {
996 "2": "0.1234567890123456789012345678",
997 "4": "0.12345678901234567890123456789"
998 }
999 });
1000 let text = value.to_string();
1001
1002 for frame in [
1003 serde_json::from_str::<LighterWsFrame>(&text).unwrap(),
1004 serde_json::from_value(value).unwrap(),
1005 ] {
1006 let (round, discount) = funding_maps(frame);
1007 assert_eq!(
1008 round.unwrap(),
1009 AHashMap::from_iter([
1010 (Ustr::from("1"), Decimal::from(9_007_199_254_740_993u64)),
1011 (Ustr::from("3"), Decimal::new(125, 2))
1012 ])
1013 );
1014 assert_eq!(
1015 discount.unwrap(),
1016 AHashMap::from_iter([
1017 (
1018 Ustr::from("2"),
1019 Decimal::from_str_exact("0.1234567890123456789012345678").unwrap()
1020 ),
1021 (
1022 Ustr::from("4"),
1023 Decimal::from_str_exact("0.1234567890123456789012345679").unwrap()
1024 ),
1025 ])
1026 );
1027 }
1028 }
1029
1030 #[rstest]
1031 fn test_funding_decimal_maps_absent(
1032 #[values("subscribed/account_all_positions", "update/account_all_positions")] kind: &str,
1033 #[values(false, true)] explicit_null: bool,
1034 ) {
1035 let mut value = serde_json::json!({
1036 "type": kind,
1037 "channel": "account_all_positions:7",
1038 "positions": {},
1039 });
1040
1041 if explicit_null {
1042 value["last_funding_round"] = serde_json::Value::Null;
1043 value["last_funding_discount"] = serde_json::Value::Null;
1044 }
1045
1046 let text = value.to_string();
1047
1048 for frame in [
1049 serde_json::from_str::<LighterWsFrame>(&text).unwrap(),
1050 serde_json::from_value(value).unwrap(),
1051 ] {
1052 assert_eq!(funding_maps(frame), (None, None));
1053 }
1054 }
1055
1056 type FundingMap = Option<AHashMap<Ustr, Decimal>>;
1057
1058 fn funding_maps(frame: LighterWsFrame) -> (FundingMap, FundingMap) {
1059 match frame {
1060 LighterWsFrame::AccountAllPositionsSnapshot {
1061 last_funding_round,
1062 last_funding_discount,
1063 ..
1064 }
1065 | LighterWsFrame::AccountAllPositions {
1066 last_funding_round,
1067 last_funding_discount,
1068 ..
1069 } => (last_funding_round, last_funding_discount),
1070 _ => panic!("expected account positions"),
1071 }
1072 }
1073
1074 #[rstest]
1075 fn test_subscription_request_serializes_public_channel() {
1076 let channel = LighterWsChannel::OrderBook(0).subscription_channel();
1077 let request = LighterWsRequest::subscribe(channel);
1078
1079 let json = serde_json::to_string(&request).unwrap();
1080
1081 assert_eq!(
1082 serde_json::from_str::<Value>(&json).unwrap(),
1083 serde_json::json!({
1084 "type": "subscribe",
1085 "channel": "order_book/0",
1086 }),
1087 );
1088 }
1089
1090 #[rstest]
1091 fn test_subscription_request_serializes_auth_channel() {
1092 let channel = LighterWsChannel::AccountOrders {
1093 market_index: 0,
1094 account_index: 1234,
1095 }
1096 .subscription_channel();
1097 let request = LighterWsRequest::subscribe_auth(channel, "token");
1098
1099 let json = serde_json::to_string(&request).unwrap();
1100
1101 assert_eq!(
1102 serde_json::from_str::<Value>(&json).unwrap(),
1103 serde_json::json!({
1104 "type": "subscribe",
1105 "channel": "account_orders/0/1234",
1106 "auth": "token",
1107 }),
1108 );
1109 }
1110
1111 #[rstest]
1112 fn test_subscribe_request_debug_redacts_auth_token() {
1113 let token = "schnorr-signature-bytes-do-not-leak";
1114 let mut request = LighterWsRequest::subscribe_auth("account_all/123", token);
1115
1116 let dbg = format!("{request:?}");
1117
1118 assert!(
1119 !dbg.contains(token),
1120 "Debug output must not contain the auth token, found: {dbg}",
1121 );
1122 assert!(dbg.contains(REDACTED));
1123
1124 request.zeroize();
1125 assert!(matches!(
1126 &request,
1127 LighterWsRequest::Subscribe { auth: None, .. }
1128 ));
1129 }
1130
1131 #[rstest]
1132 #[case(LighterWsChannelKind::OrderBook)]
1133 #[case(LighterWsChannelKind::Ticker)]
1134 #[case(LighterWsChannelKind::Trade)]
1135 #[case(LighterWsChannelKind::Candle)]
1136 #[case(LighterWsChannelKind::MarketStats)]
1137 #[case(LighterWsChannelKind::SpotMarketStats)]
1138 #[case(LighterWsChannelKind::AccountAll)]
1139 #[case(LighterWsChannelKind::AccountOrders)]
1140 #[case(LighterWsChannelKind::AccountAllOrders)]
1141 #[case(LighterWsChannelKind::AccountAllTrades)]
1142 #[case(LighterWsChannelKind::AccountAllPositions)]
1143 #[case(LighterWsChannelKind::AccountAllAssets)]
1144 #[case(LighterWsChannelKind::Height)]
1145 fn test_channel_kind_wire_round_trip(#[case] kind: LighterWsChannelKind) {
1146 assert_eq!(
1147 LighterWsChannelKind::from_wire_str(kind.as_wire_str()),
1148 Some(kind),
1149 );
1150 }
1151
1152 #[rstest]
1153 #[case("unknown_channel")]
1154 #[case("ORDER_BOOK")]
1155 #[case("")]
1156 #[case("order_book:0")]
1157 fn test_channel_kind_unknown_returns_none(#[case] input: &str) {
1158 assert_eq!(LighterWsChannelKind::from_wire_str(input), None);
1159 }
1160
1161 #[rstest]
1162 fn test_order_book_frame_deserializes() {
1163 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_UPDATE).unwrap();
1164
1165 match frame {
1166 LighterWsFrame::OrderBook {
1167 channel,
1168 order_book,
1169 timestamp,
1170 ..
1171 } => {
1172 assert_eq!(channel, Ustr::from("order_book:0"));
1173 assert_eq!(order_book.asks.len(), 1);
1174 assert_eq!(
1175 order_book.asks[0].price,
1176 Decimal::from_str("2064.54").unwrap()
1177 );
1178 assert_eq!(timestamp, 1_774_884_082_326);
1179 }
1180 _ => panic!("expected order book frame"),
1181 }
1182 }
1183
1184 #[rstest]
1185 fn test_trade_frame_deserializes() {
1186 let frame: LighterWsFrame = serde_json::from_str(WS_TRADE_UPDATE).unwrap();
1187
1188 match frame {
1189 LighterWsFrame::Trade { trades, nonce, .. } => {
1190 assert_eq!(nonce, 8_630_448_841);
1191 assert_eq!(trades.len(), 1);
1192 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1193 }
1194 _ => panic!("expected trade frame"),
1195 }
1196 }
1197
1198 #[rstest]
1199 fn test_trade_frame_deserializes_null_liquidations() {
1200 let payload = serde_json::json!({
1201 "type": "update/trade",
1202 "channel": "trade:1",
1203 "liquidation_trades": null,
1204 "nonce": 1,
1205 "trades": []
1206 });
1207
1208 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1209
1210 match frame {
1211 LighterWsFrame::Trade {
1212 liquidation_trades,
1213 trades,
1214 ..
1215 } => {
1216 assert!(liquidation_trades.is_empty());
1217 assert!(trades.is_empty());
1218 }
1219 _ => panic!("expected trade frame"),
1220 }
1221 }
1222
1223 #[rstest]
1224 fn test_trade_frame_deserializes_object_trades() {
1225 let mut payload: Value = serde_json::from_str(WS_TRADE_UPDATE).unwrap();
1226 let trades = payload.get_mut("trades").unwrap().take();
1227 payload["trades"] = serde_json::json!({ "0": trades });
1228
1229 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1230
1231 match frame {
1232 LighterWsFrame::Trade { trades, .. } => {
1233 assert_eq!(trades.len(), 1);
1234 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1235 }
1236 _ => panic!("expected trade frame"),
1237 }
1238 }
1239
1240 #[rstest]
1241 fn test_ticker_frame_deserializes() {
1242 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_UPDATE).unwrap();
1243
1244 match frame {
1245 LighterWsFrame::Ticker {
1246 channel,
1247 nonce,
1248 ticker,
1249 timestamp,
1250 ..
1251 } => {
1252 assert_eq!(channel, Ustr::from("ticker:0"));
1253 assert_eq!(nonce, 9_182_390_020);
1254 assert_eq!(ticker.s, Ustr::from("ETH"));
1255 assert_eq!(ticker.a.price, Decimal::from_str("2064.48").unwrap());
1256 assert_eq!(ticker.b.size, Decimal::from_str("1.0392").unwrap());
1257 assert_eq!(timestamp, 1_774_883_844_933);
1258 }
1259 _ => panic!("expected ticker frame"),
1260 }
1261 }
1262
1263 #[rstest]
1268 fn test_order_book_snapshot_frame_deserializes() {
1269 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_SUBSCRIBED).unwrap();
1270
1271 match frame {
1272 LighterWsFrame::OrderBookSnapshot {
1273 channel,
1274 order_book,
1275 timestamp,
1276 ..
1277 } => {
1278 assert_eq!(channel, Ustr::from("order_book:0"));
1279 assert_eq!(order_book.bids.len(), 1);
1280 assert_eq!(
1281 order_book.bids[0].price,
1282 Decimal::from_str("2000.00").unwrap()
1283 );
1284 assert_eq!(order_book.asks.len(), 2);
1285 assert_eq!(
1286 order_book.asks[0].price,
1287 Decimal::from_str("2325.00").unwrap()
1288 );
1289 assert_eq!(order_book.nonce, 904_845);
1290 assert_eq!(timestamp, 1_778_138_582_602);
1291 }
1292 _ => panic!("expected order book snapshot frame, was {frame:?}"),
1293 }
1294 }
1295
1296 #[rstest]
1297 fn test_empty_order_book_snapshot_frame_deserializes() {
1298 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_SUBSCRIBED_EMPTY).unwrap();
1299
1300 match frame {
1301 LighterWsFrame::OrderBookSnapshot {
1302 channel,
1303 last_updated_at,
1304 order_book,
1305 timestamp,
1306 ..
1307 } => {
1308 assert_eq!(channel, Ustr::from("order_book:39"));
1309 assert_eq!(last_updated_at, 0);
1310 assert!(order_book.asks.is_empty());
1311 assert!(order_book.bids.is_empty());
1312 assert_eq!(order_book.offset, 1);
1313 assert_eq!(order_book.nonce, 0);
1314 assert_eq!(timestamp, 1_778_138_582_602);
1315 }
1316 _ => panic!("expected empty order book snapshot frame, was {frame:?}"),
1317 }
1318 }
1319
1320 #[rstest]
1321 fn test_ticker_snapshot_frame_deserializes() {
1322 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_SUBSCRIBED).unwrap();
1323
1324 match frame {
1325 LighterWsFrame::TickerSnapshot {
1326 channel,
1327 nonce,
1328 ticker,
1329 timestamp,
1330 ..
1331 } => {
1332 assert_eq!(channel, Ustr::from("ticker:0"));
1333 assert_eq!(nonce, 904_895);
1334 assert_eq!(ticker.s, Ustr::from("ETH"));
1335 assert_eq!(ticker.a.price, Decimal::from_str("2325.00").unwrap());
1336 assert_eq!(ticker.b.price, Decimal::from_str("2000.00").unwrap());
1337 assert_eq!(timestamp, 1_778_138_582_640);
1338 }
1339 _ => panic!("expected ticker snapshot frame, was {frame:?}"),
1340 }
1341 }
1342
1343 #[rstest]
1344 fn test_empty_ticker_snapshot_frame_deserializes() {
1345 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_SUBSCRIBED_EMPTY).unwrap();
1346
1347 match frame {
1348 LighterWsFrame::TickerSnapshot {
1349 channel,
1350 last_updated_at,
1351 nonce,
1352 ticker,
1353 timestamp,
1354 ..
1355 } => {
1356 assert_eq!(channel, Ustr::from("ticker:39"));
1357 assert_eq!(last_updated_at, 0);
1358 assert_eq!(nonce, 2_475_051);
1359 assert_eq!(ticker.s, Ustr::from("ADA"));
1360 assert_eq!(ticker.a.price, Decimal::ZERO);
1361 assert_eq!(ticker.a.size, Decimal::ZERO);
1362 assert_eq!(ticker.b.price, Decimal::ZERO);
1363 assert_eq!(ticker.b.size, Decimal::ZERO);
1364 assert_eq!(timestamp, 1_778_138_582_640);
1365 }
1366 _ => panic!("expected empty ticker snapshot frame, was {frame:?}"),
1367 }
1368 }
1369
1370 #[rstest]
1371 fn test_trade_snapshot_frame_deserializes() {
1372 let frame: LighterWsFrame = serde_json::from_str(WS_TRADE_SUBSCRIBED).unwrap();
1373
1374 match frame {
1375 LighterWsFrame::TradeSnapshot {
1376 channel,
1377 nonce,
1378 trades,
1379 ..
1380 } => {
1381 assert_eq!(channel, Ustr::from("trade:0"));
1382 assert_eq!(nonce, 8_630_448_841);
1383 assert_eq!(trades.len(), 1);
1384 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1385 }
1386 _ => panic!("expected trade snapshot frame, was {frame:?}"),
1387 }
1388 }
1389
1390 #[rstest]
1391 fn test_market_stats_frame_deserializes_single_payload() {
1392 let frame: LighterWsFrame = serde_json::from_str(WS_MARKET_STATS_UPDATE_SINGLE).unwrap();
1393
1394 match frame {
1395 LighterWsFrame::MarketStats {
1396 channel,
1397 market_stats: LighterMarketStatsPayload::One(stats),
1398 timestamp,
1399 } => {
1400 assert_eq!(channel, Ustr::from("market_stats:0"));
1401 assert_eq!(stats.symbol, Ustr::from("ETH"));
1402 assert_eq!(stats.market_id, 0);
1403 assert_eq!(stats.mark_price, Decimal::from_str("2064.47").unwrap());
1404 assert_eq!(
1405 stats.daily_base_token_volume,
1406 Decimal::new(1_999_586_931, 4),
1407 );
1408 assert_eq!(timestamp, 1_774_883_844_933);
1409 }
1410 _ => panic!("expected single market stats frame"),
1411 }
1412 }
1413
1414 #[rstest]
1415 fn test_market_stats_subscribed_frame_deserializes_single_payload() {
1416 let frame: LighterWsFrame =
1417 serde_json::from_str(WS_MARKET_STATS_SUBSCRIBED_SINGLE).unwrap();
1418
1419 match frame {
1420 LighterWsFrame::MarketStats {
1421 channel,
1422 market_stats: LighterMarketStatsPayload::One(stats),
1423 timestamp,
1424 } => {
1425 assert_eq!(channel, Ustr::from("market_stats:1"));
1426 assert_eq!(stats.symbol, Ustr::from("BTC"));
1427 assert_eq!(stats.market_id, 1);
1428 assert_eq!(stats.mark_price, Decimal::from_str("64356.3").unwrap());
1429 assert_eq!(timestamp, 1_780_546_209_291);
1430 }
1431 _ => panic!("expected subscribed market stats frame"),
1432 }
1433 }
1434
1435 #[rstest]
1436 fn test_market_stats_frame_deserializes_all_payload() {
1437 let frame: LighterWsFrame = serde_json::from_str(WS_MARKET_STATS_UPDATE_ALL).unwrap();
1438
1439 match frame {
1440 LighterWsFrame::MarketStats {
1441 market_stats: LighterMarketStatsPayload::All(stats),
1442 ..
1443 } => {
1444 assert_eq!(stats.len(), 1);
1445 let stats = stats.get(&Ustr::from("0")).unwrap();
1446 assert_eq!(stats.symbol, Ustr::from("ETH"));
1447 assert_eq!(
1448 stats.open_interest,
1449 Decimal::from_str("27250.8411").unwrap()
1450 );
1451 }
1452 _ => panic!("expected all market stats frame"),
1453 }
1454 }
1455
1456 #[rstest]
1457 fn test_market_stats_frame_deserializes_widened_market_id() {
1458 let frame: LighterWsFrame =
1459 serde_json::from_str(WS_MARKET_STATS_UPDATE_SINGLE_WIDENED).unwrap();
1460
1461 match frame {
1462 LighterWsFrame::MarketStats {
1463 channel,
1464 market_stats: LighterMarketStatsPayload::One(stats),
1465 timestamp,
1466 } => {
1467 assert_eq!(channel, Ustr::from("market_stats:40000"));
1468 assert_eq!(stats.symbol, Ustr::from("FUTURE"));
1469 assert_eq!(stats.market_id, 40_000);
1470 assert_eq!(stats.mark_price, Decimal::from_str("12.47").unwrap());
1471 assert_eq!(timestamp, 1_774_883_844_933);
1472 }
1473 _ => panic!("expected single market stats frame"),
1474 }
1475 }
1476
1477 #[rstest]
1478 fn test_spot_market_stats_frame_deserializes_widened_market_id() {
1479 let frame: LighterWsFrame =
1480 serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_SINGLE_WIDENED).unwrap();
1481
1482 match frame {
1483 LighterWsFrame::SpotMarketStats {
1484 channel,
1485 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1486 timestamp,
1487 } => {
1488 assert_eq!(channel, Ustr::from("spot_market_stats:50000"));
1489 assert_eq!(stats.symbol, Ustr::from("FUTURE/USDC"));
1490 assert_eq!(stats.market_id, 50_000);
1491 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1492 assert_eq!(timestamp, 1_774_883_844_933);
1493 }
1494 _ => panic!("expected single spot market stats frame"),
1495 }
1496 }
1497
1498 #[rstest]
1499 fn test_spot_market_stats_frame_deserializes_empty_mid_as_zero() {
1500 let frame: LighterWsFrame =
1501 serde_json::from_str(WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE_EMPTY_MID).unwrap();
1502
1503 match frame {
1504 LighterWsFrame::SpotMarketStats {
1505 channel,
1506 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1507 timestamp,
1508 } => {
1509 assert_eq!(channel, Ustr::from("spot_market_stats:4098"));
1510 assert_eq!(stats.symbol, Ustr::from("ETH/USDC"));
1511 assert_eq!(stats.market_id, 4098);
1512 assert_eq!(stats.mid_price, Decimal::ZERO);
1513 assert_eq!(stats.index_price, Decimal::from_str("2471.940000").unwrap());
1514 assert_eq!(timestamp, 1_789_706_424_060);
1515 }
1516 _ => panic!("expected single spot market stats frame"),
1517 }
1518 }
1519
1520 #[rstest]
1521 fn test_spot_market_stats_frame_deserializes_single_payload() {
1522 let frame: LighterWsFrame =
1523 serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_SINGLE).unwrap();
1524
1525 match frame {
1526 LighterWsFrame::SpotMarketStats {
1527 channel,
1528 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1529 timestamp,
1530 } => {
1531 assert_eq!(channel, Ustr::from("spot_market_stats:2048"));
1532 assert_eq!(stats.symbol, Ustr::from("USDC"));
1533 assert_eq!(stats.market_id, 2048);
1534 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1535 assert_eq!(stats.daily_base_token_volume, Decimal::from(1000));
1536 assert_eq!(timestamp, 1_774_883_844_933);
1537 }
1538 _ => panic!("expected single spot market stats frame"),
1539 }
1540 }
1541
1542 #[rstest]
1543 fn test_spot_market_stats_subscribed_frame_deserializes_single_payload() {
1544 let frame: LighterWsFrame =
1545 serde_json::from_str(WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE).unwrap();
1546
1547 match frame {
1548 LighterWsFrame::SpotMarketStats {
1549 channel,
1550 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1551 timestamp,
1552 } => {
1553 assert_eq!(channel, Ustr::from("spot_market_stats:2048"));
1554 assert_eq!(stats.symbol, Ustr::from("USDC"));
1555 assert_eq!(stats.market_id, 2048);
1556 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1557 assert_eq!(timestamp, 1_774_883_844_933);
1558 }
1559 _ => panic!("expected subscribed spot market stats frame"),
1560 }
1561 }
1562
1563 #[rstest]
1564 fn test_spot_market_stats_frame_deserializes_all_payload() {
1565 let frame: LighterWsFrame = serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_ALL).unwrap();
1566
1567 match frame {
1568 LighterWsFrame::SpotMarketStats {
1569 spot_market_stats: LighterSpotMarketStatsPayload::All(stats),
1570 ..
1571 } => {
1572 assert_eq!(stats.len(), 1);
1573 let stats = stats.get(&Ustr::from("2048")).unwrap();
1574 assert_eq!(stats.symbol, Ustr::from("USDC"));
1575 assert_eq!(
1576 stats.last_trade_price,
1577 Decimal::from_str("1.000002").unwrap()
1578 );
1579 }
1580 _ => panic!("expected all spot market stats frame"),
1581 }
1582 }
1583
1584 #[rstest]
1585 fn test_account_all_assets_frame_deserializes() {
1586 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_ASSETS_UPDATE).unwrap();
1590
1591 match frame {
1592 LighterWsFrame::AccountAllAssets {
1593 assets,
1594 channel,
1595 timestamp,
1596 transaction_time,
1597 } => {
1598 assert_eq!(channel, Ustr::from("account_all_assets:1234"));
1599 let asset = assets.get(&Ustr::from("3")).unwrap();
1600 assert_eq!(asset.symbol, Ustr::from("USDC"));
1601 assert_eq!(asset.asset_id, 3);
1602 assert_eq!(asset.balance, Decimal::from_str("10.000000").unwrap());
1603 assert_eq!(asset.locked_balance, Decimal::ZERO);
1604 assert_eq!(
1605 asset.margin_balance,
1606 Decimal::from_str("40.000000").unwrap()
1607 );
1608 assert_eq!(asset.margin_mode, Ustr::from("disabled"));
1609 assert_eq!(timestamp, 1_781_161_199_648);
1610 assert_eq!(transaction_time, None);
1611 }
1612 _ => panic!("expected account all assets frame"),
1613 }
1614 }
1615
1616 #[rstest]
1617 fn test_account_all_assets_subscribed_frame_deserializes() {
1618 let payload = serde_json::json!({
1619 "type": "subscribed/account_all_assets",
1620 "channel": "account_all_assets:1234",
1621 "timestamp": 1778751230509u64,
1622 "assets": {
1623 "3": {
1624 "asset_id": 3,
1625 "balance": "9.660200",
1626 "locked_balance": "0.000000",
1627 "margin_balance": "9.955800",
1628 "margin_mode": "disabled",
1629 "symbol": "USDC"
1630 }
1631 }
1632 });
1633
1634 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1635
1636 match frame {
1637 LighterWsFrame::AccountAllAssets { assets, .. } => {
1638 assert_eq!(
1639 assets.get(&Ustr::from("3")).unwrap().symbol,
1640 Ustr::from("USDC")
1641 );
1642 }
1643 _ => panic!("expected account all assets frame"),
1644 }
1645 }
1646
1647 #[rstest]
1648 fn test_account_orders_frame_deserializes() {
1649 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
1650
1651 match frame {
1652 LighterWsFrame::AccountOrders {
1653 account,
1654 channel,
1655 orders,
1656 ..
1657 } => {
1658 assert_eq!(account, 1234);
1659 assert_eq!(channel, Ustr::from("account_orders:0:1234"));
1660 let market_orders = orders.get(&Ustr::from("0")).unwrap();
1661 assert_eq!(market_orders.len(), 1);
1662 assert_eq!(market_orders[0].order_id, "281476929510110");
1663 assert_eq!(market_orders[0].nonce, 281_474_720_725_346);
1664 assert_eq!(
1665 market_orders[0].filled_base_amount,
1666 Decimal::from_str("0.0020").unwrap(),
1667 );
1668 }
1669 _ => panic!("expected account orders frame, was {frame:?}"),
1670 }
1671 }
1672
1673 #[rstest]
1674 fn test_account_orders_subscribed_frame_deserializes() {
1675 let mut payload: serde_json::Value =
1676 serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
1677 payload["type"] = serde_json::json!("subscribed/account_orders");
1678
1679 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1680
1681 assert!(matches!(frame, LighterWsFrame::AccountOrders { .. }));
1682 }
1683
1684 #[rstest]
1685 fn test_account_all_orders_subscribed_frame_deserializes_empty_side() {
1686 let frame: LighterWsFrame = serde_json::from_str(
1687 r#"{
1688 "type": "subscribed/account_all_orders",
1689 "channel": "account_all_orders:1234",
1690 "orders": {
1691 "3": [{
1692 "order_index": 1,
1693 "client_order_index": 2,
1694 "order_id": "1",
1695 "client_order_id": "2",
1696 "market_index": 3,
1697 "owner_account_index": 1234,
1698 "initial_base_amount": "100",
1699 "price": "0.100000",
1700 "nonce": 1,
1701 "remaining_base_amount": "100",
1702 "is_ask": false,
1703 "base_size": 100,
1704 "base_price": 100000,
1705 "filled_base_amount": "0",
1706 "filled_quote_amount": "0.000000",
1707 "side": "",
1708 "type": "limit",
1709 "time_in_force": "good-till-time",
1710 "reduce_only": false,
1711 "trigger_price": "0.000000",
1712 "order_expiry": 1781170441337,
1713 "status": "open",
1714 "trigger_status": "na",
1715 "trigger_time": 0,
1716 "parent_order_index": 0,
1717 "parent_order_id": "0",
1718 "to_trigger_order_id_0": "0",
1719 "to_trigger_order_id_1": "0",
1720 "to_cancel_order_id_0": "0",
1721 "integrator_fee_collector_index": "",
1722 "integrator_taker_fee": "",
1723 "integrator_maker_fee": "",
1724 "block_height": 1,
1725 "timestamp": 1778751241,
1726 "created_at": 1778751241,
1727 "updated_at": 1778751241,
1728 "transaction_time": 1778751241772524
1729 }]
1730 }
1731 }"#,
1732 )
1733 .unwrap();
1734
1735 match frame {
1736 LighterWsFrame::AccountAllOrders { orders, .. } => {
1737 let order = &orders.get(&Ustr::from("3")).unwrap()[0];
1738 assert_eq!(order.side, None);
1739 assert!(!order.is_ask);
1740 }
1741 _ => panic!("expected account all orders frame"),
1742 }
1743 }
1744
1745 #[rstest]
1746 fn test_account_all_trades_frame_deserializes() {
1747 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_TRADES_UPDATE).unwrap();
1748
1749 match frame {
1750 LighterWsFrame::AccountAllTrades { channel, trades } => {
1751 assert_eq!(channel, Ustr::from("account_all_trades:1234"));
1752 let market_trades = trades.get(&Ustr::from("0")).unwrap();
1753 assert_eq!(market_trades.len(), 1);
1754 assert_eq!(market_trades[0].bid_account_id, 1234);
1755 assert_eq!(market_trades[0].taker_fee, Some(196));
1756 }
1757 _ => panic!("expected account all trades frame, was {frame:?}"),
1758 }
1759 }
1760
1761 #[rstest]
1762 fn test_account_all_positions_frame_deserializes() {
1763 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_POSITIONS_UPDATE).unwrap();
1764
1765 match frame {
1766 LighterWsFrame::AccountAllPositions {
1767 channel, positions, ..
1768 } => {
1769 assert_eq!(channel, Ustr::from("account_all_positions:1234"));
1770 let position = positions.get(&Ustr::from("0")).unwrap();
1771 assert_eq!(position.market_id, 0);
1772 assert_eq!(position.position, Decimal::from_str("1.5000").unwrap());
1773 assert_eq!(position.sign, 1);
1774 }
1775 _ => panic!("expected account all positions frame, was {frame:?}"),
1776 }
1777 }
1778
1779 #[rstest]
1780 fn test_account_all_positions_snapshot_frame_deserializes() {
1781 let mut value: serde_json::Value =
1782 serde_json::from_str(WS_ACCOUNT_ALL_POSITIONS_UPDATE).unwrap();
1783 value["type"] = serde_json::json!("subscribed/account_all_positions");
1784 let frame: LighterWsFrame = serde_json::from_value(value).unwrap();
1785
1786 match frame {
1787 LighterWsFrame::AccountAllPositionsSnapshot {
1788 channel, positions, ..
1789 } => {
1790 assert_eq!(channel, Ustr::from("account_all_positions:1234"));
1791 let position = positions.get(&Ustr::from("0")).unwrap();
1792 assert_eq!(position.market_id, 0);
1793 assert_eq!(position.position, Decimal::from_str("1.5000").unwrap());
1794 assert_eq!(position.sign, 1);
1795 }
1796 _ => panic!("expected account all positions snapshot, was {frame:?}"),
1797 }
1798 }
1799
1800 #[rstest]
1801 #[case::absent(None, false)]
1802 #[case::null(None, true)]
1803 #[case::zero(Some(0), false)]
1804 #[case::negative(Some(-1), false)]
1805 #[case::micros(Some(1_791_406_944_316_056), false)]
1806 #[case::exact_integer(Some(9_007_199_254_740_993), false)]
1807 #[case::maximum(Some(i64::MAX), false)]
1808 fn test_account_transaction_time_round_trip(
1809 #[values("subscribed", "update")] prefix: &str,
1810 #[values("positions", "assets")] channel: &str,
1811 #[case] transaction_time: Option<i64>,
1812 #[case] explicit_null: bool,
1813 ) {
1814 let fixture = match channel {
1815 "positions" => {
1816 include_str!("../../test_data/ws_account_all_positions_transaction_time.json")
1817 }
1818 "assets" => include_str!("../../test_data/ws_account_all_assets_transaction_time.json"),
1819 _ => unreachable!(),
1820 };
1821
1822 let mut value: Value = serde_json::from_str(fixture).unwrap();
1823 value["type"] = serde_json::json!(format!("{prefix}/account_all_{channel}"));
1824 match transaction_time {
1825 Some(timestamp) => value["transaction_time"] = serde_json::json!(timestamp),
1826 None if explicit_null => value["transaction_time"] = Value::Null,
1827 None => {
1828 value.as_object_mut().unwrap().remove("transaction_time");
1829 }
1830 }
1831
1832 let text = value.to_string();
1833
1834 for frame in [
1835 serde_json::from_str::<LighterWsFrame>(&text).unwrap(),
1836 serde_json::from_value(value).unwrap(),
1837 ] {
1838 let preserved = match &frame {
1839 LighterWsFrame::AccountAllPositionsSnapshot {
1840 transaction_time, ..
1841 }
1842 | LighterWsFrame::AccountAllPositions {
1843 transaction_time, ..
1844 }
1845 | LighterWsFrame::AccountAllAssets {
1846 transaction_time, ..
1847 } => *transaction_time,
1848 _ => panic!("expected account position or asset frame"),
1849 };
1850
1851 let serialized = serde_json::to_value(&frame).unwrap();
1852
1853 assert_eq!(preserved, transaction_time);
1854 assert_eq!(
1855 serialized.get("transaction_time"),
1856 transaction_time
1857 .map(|timestamp| serde_json::json!(timestamp))
1858 .as_ref(),
1859 );
1860 assert_eq!(
1861 serde_json::from_value::<LighterWsFrame>(serialized).unwrap(),
1862 frame
1863 );
1864 }
1865 }
1866
1867 #[rstest]
1868 fn test_height_frame_deserializes() {
1869 let frame: LighterWsFrame = serde_json::from_str(WS_HEIGHT_UPDATE).unwrap();
1870
1871 match frame {
1872 LighterWsFrame::Height {
1873 channel,
1874 height,
1875 timestamp,
1876 } => {
1877 assert_eq!(channel, Ustr::from("height"));
1878 assert_eq!(height, 227_535_532);
1879 assert_eq!(timestamp, 1_774_883_844_933);
1880 }
1881 _ => panic!("expected height frame"),
1882 }
1883 }
1884
1885 #[rstest]
1886 fn test_height_subscribed_frame_deserializes() {
1887 let mut payload: serde_json::Value = serde_json::from_str(WS_HEIGHT_UPDATE).unwrap();
1888 payload["type"] = serde_json::json!("subscribed/height");
1889
1890 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1891
1892 assert!(matches!(frame, LighterWsFrame::Height { .. }));
1893 }
1894
1895 #[rstest]
1896 fn test_candle_channel_subscription_channel_uses_slash() {
1897 let channel = LighterWsChannel::Candle {
1898 market_index: 0,
1899 resolution: LighterCandleResolution::OneMinute,
1900 };
1901
1902 assert_eq!(channel.subscription_channel(), "candle/0/1m");
1903 }
1904
1905 #[rstest]
1906 fn test_candle_channel_topic_key_uses_colon() {
1907 let channel = LighterWsChannel::Candle {
1908 market_index: 7,
1909 resolution: LighterCandleResolution::FiveMinute,
1910 };
1911
1912 assert_eq!(channel.topic_key(), "candle:7:5m");
1913 }
1914
1915 #[rstest]
1916 fn test_candle_channel_does_not_require_auth() {
1917 let channel = LighterWsChannel::Candle {
1918 market_index: 0,
1919 resolution: LighterCandleResolution::OneMinute,
1920 };
1921
1922 assert!(!channel.requires_auth());
1923 }
1924
1925 #[rstest]
1926 fn test_candle_snapshot_frame_deserializes() {
1927 let frame: LighterWsFrame = serde_json::from_str(WS_CANDLE_SUBSCRIBED).unwrap();
1928
1929 match frame {
1930 LighterWsFrame::CandleSnapshot {
1931 channel,
1932 candles,
1933 timestamp,
1934 } => {
1935 assert_eq!(channel, Ustr::from("candle:0:1m"));
1936 assert_eq!(timestamp, 1_778_821_471_842);
1937 assert_eq!(candles.len(), 1);
1938 let candle = &candles[0];
1939 assert_eq!(candle.t, 1_778_821_440_000);
1940 assert_eq!(candle.o, Decimal::from_str("2264.2").unwrap());
1941 assert_eq!(candle.h, Decimal::from_str("2264.34").unwrap());
1942 assert_eq!(candle.l, Decimal::from_str("2263.36").unwrap());
1943 assert_eq!(candle.c, Decimal::from_str("2263.97").unwrap());
1944 let arbitrary_precision =
1945 serde_json::from_str::<serde_json::Number>("79228162514264337593543950335")
1946 .unwrap()
1947 .to_string()
1948 == "79228162514264337593543950335";
1949
1950 let (volume, quote_volume) = if arbitrary_precision {
1951 ("13.223699999999997", "29934.600011999984")
1952 } else {
1953 ("13.2237", "29934.60001199998")
1954 };
1955
1956 assert_eq!(candle.v, Decimal::from_str_exact(volume).unwrap());
1957 assert_eq!(
1958 candle.quote_volume,
1959 Decimal::from_str_exact(quote_volume).unwrap()
1960 );
1961 assert_eq!(candle.i, 19_993_571_166);
1962 }
1963 _ => panic!("expected candle snapshot frame"),
1964 }
1965 }
1966
1967 #[rstest]
1968 fn test_candle_update_frame_deserializes() {
1969 let frame: LighterWsFrame = serde_json::from_str(WS_CANDLE_UPDATE).unwrap();
1970
1971 match frame {
1972 LighterWsFrame::Candle {
1973 channel,
1974 candles,
1975 timestamp,
1976 } => {
1977 assert_eq!(channel, Ustr::from("candle:0:1m"));
1978 assert_eq!(timestamp, 1_778_821_473_331);
1979 assert_eq!(candles.len(), 1);
1980 assert_eq!(candles[0].t, 1_778_821_440_000);
1981 assert_eq!(candles[0].c, Decimal::from_str("2263.89").unwrap());
1982 }
1983 _ => panic!("expected candle update frame"),
1984 }
1985 }
1986
1987 #[rstest]
1988 #[case(0)]
1989 #[case(7350)]
1990 #[case(u64::MAX)]
1991 fn shutdown_notification_parses_deadline(#[case] close_in_ms: u64) {
1992 let frame: LighterWsFrame = serde_json::from_value(
1993 serde_json::json!({"type":"shutdown", "close_in_ms":close_in_ms}),
1994 )
1995 .unwrap();
1996
1997 match frame {
1998 LighterWsFrame::Shutdown {
1999 close_in_ms: actual,
2000 } => assert_eq!(actual, close_in_ms),
2001 other => panic!("expected shutdown, was {other:?}"),
2002 }
2003 }
2004
2005 #[rstest]
2006 #[case(serde_json::json!({"type":"shutdown"}))]
2007 #[case(serde_json::json!({"type":"shutdown", "close_in_ms":-1}))]
2008 #[case(serde_json::json!({"type":"shutdown", "close_in_ms":"7350"}))]
2009 fn shutdown_notification_rejects_invalid_deadline(#[case] frame: serde_json::Value) {
2010 assert!(serde_json::from_value::<LighterWsFrame>(frame).is_err());
2011 }
2012
2013 #[rstest]
2014 fn test_account_orders_frame_keeps_siblings_of_unfamiliar_classifications() {
2015 let mut payload: serde_json::Value =
2016 serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
2017 let mut unfamiliar = payload["orders"]["0"][0].clone();
2018 unfamiliar["order_id"] = serde_json::json!("900");
2019 unfamiliar["order_index"] = serde_json::json!(900);
2020 unfamiliar["type"] = serde_json::json!("future-type");
2021 unfamiliar["time_in_force"] = serde_json::json!("future-tif");
2022 unfamiliar["status"] = serde_json::json!("future-status");
2023 unfamiliar["trigger_status"] = serde_json::json!("future-trigger");
2024 payload["orders"]["0"]
2025 .as_array_mut()
2026 .unwrap()
2027 .insert(0, unfamiliar);
2028 let healthy: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
2029
2030 let LighterWsFrame::AccountOrders {
2031 orders: healthy, ..
2032 } = healthy
2033 else {
2034 panic!("expected account orders frame");
2035 };
2036
2037 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
2038
2039 let LighterWsFrame::AccountOrders { orders, .. } = frame else {
2040 panic!("expected account orders frame");
2041 };
2042
2043 let orders = &orders[&Ustr::from("0")];
2044 assert_eq!(orders.len(), 2);
2045 assert_eq!(orders[0].order_id, "900");
2046 assert_eq!(orders[0].order_type, LighterOrderKind::Other);
2047 assert_eq!(orders[0].time_in_force, LighterOrderTimeInForce::Unknown);
2048 assert_eq!(orders[0].status, LighterOrderStatus::Unknown);
2049 assert_eq!(orders[0].trigger_status, LighterTriggerStatus::Unknown);
2050 assert_eq!(orders[1], healthy[&Ustr::from("0")][0]);
2051 }
2052
2053 #[rstest]
2054 fn test_account_all_trades_frame_keeps_fill_data_of_unfamiliar_trade_type() {
2055 let mut payload: serde_json::Value =
2056 serde_json::from_str(WS_ACCOUNT_ALL_TRADES_UPDATE).unwrap();
2057 let mut unfamiliar = payload["trades"]["0"][0].clone();
2058 unfamiliar["trade_id"] = serde_json::json!(900);
2059 unfamiliar["trade_id_str"] = serde_json::json!("900");
2060 unfamiliar["type"] = serde_json::json!("future-trade");
2061 payload["trades"]["0"]
2062 .as_array_mut()
2063 .unwrap()
2064 .insert(0, unfamiliar);
2065 let healthy: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_TRADES_UPDATE).unwrap();
2066
2067 let LighterWsFrame::AccountAllTrades {
2068 trades: healthy, ..
2069 } = healthy
2070 else {
2071 panic!("expected account all trades frame");
2072 };
2073
2074 let healthy = &healthy[&Ustr::from("0")][0];
2075 let mut expected = healthy.clone();
2076 expected.trade_id = 900;
2077 expected.trade_id_str = Some("900".to_string());
2078 expected.trade_type = LighterTradeType::Other;
2079
2080 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
2081
2082 let LighterWsFrame::AccountAllTrades { trades, .. } = frame else {
2083 panic!("expected account all trades frame");
2084 };
2085
2086 let trades = &trades[&Ustr::from("0")];
2087 assert_eq!(trades.len(), 2);
2088 assert_eq!(trades[0], expected);
2089 assert_eq!(&trades[1], healthy);
2090 }
2091}