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)]
482#[serde(tag = "type")]
483pub enum LighterWsFrame {
484 #[serde(rename = "shutdown")]
485 Shutdown { close_in_ms: u64 },
486 #[serde(rename = "subscribed/order_book")]
487 OrderBookSnapshot {
488 channel: Ustr,
489 #[serde(default)]
490 last_updated_at: u64,
491 offset: i64,
492 order_book: LighterWsOrderBook,
493 timestamp: u64,
494 },
495 #[serde(rename = "update/order_book")]
496 OrderBook {
497 channel: Ustr,
498 last_updated_at: u64,
499 offset: i64,
500 order_book: LighterWsOrderBook,
501 timestamp: u64,
502 },
503 #[serde(rename = "subscribed/ticker")]
504 TickerSnapshot {
505 channel: Ustr,
506 #[serde(default)]
507 last_updated_at: u64,
508 nonce: i64,
509 ticker: LighterTicker,
510 timestamp: u64,
511 },
512 #[serde(rename = "update/ticker")]
513 Ticker {
514 channel: Ustr,
515 last_updated_at: u64,
516 nonce: i64,
517 ticker: LighterTicker,
518 timestamp: u64,
519 },
520 #[serde(rename = "update/market_stats", alias = "subscribed/market_stats")]
521 MarketStats {
522 channel: Ustr,
523 market_stats: LighterMarketStatsPayload,
524 timestamp: u64,
525 },
526 #[serde(
527 rename = "update/spot_market_stats",
528 alias = "subscribed/spot_market_stats"
529 )]
530 SpotMarketStats {
531 channel: Ustr,
532 spot_market_stats: LighterSpotMarketStatsPayload,
533 timestamp: u64,
534 },
535 #[serde(rename = "subscribed/trade")]
536 TradeSnapshot {
537 channel: Ustr,
538 #[serde(default, deserialize_with = "deserialize_trade_vec")]
539 liquidation_trades: Vec<LighterTrade>,
540 nonce: i64,
541 #[serde(default, deserialize_with = "deserialize_trade_vec")]
542 trades: Vec<LighterTrade>,
543 },
544 #[serde(rename = "update/trade")]
545 Trade {
546 channel: Ustr,
547 #[serde(default, deserialize_with = "deserialize_trade_vec")]
548 liquidation_trades: Vec<LighterTrade>,
549 nonce: i64,
550 #[serde(default, deserialize_with = "deserialize_trade_vec")]
551 trades: Vec<LighterTrade>,
552 },
553 #[serde(rename = "update/account_orders", alias = "subscribed/account_orders")]
554 AccountOrders {
555 account: i64,
556 channel: Ustr,
557 nonce: i64,
558 orders: AHashMap<Ustr, Vec<LighterOrder>>,
559 },
560 #[serde(
561 rename = "update/account_all_orders",
562 alias = "subscribed/account_all_orders"
563 )]
564 AccountAllOrders {
565 channel: Ustr,
566 orders: AHashMap<Ustr, Vec<LighterOrder>>,
567 },
568 #[serde(rename = "subscribed/account_tx")]
569 AccountTxSubscribed { channel: Ustr },
570 #[serde(rename = "update/account_tx")]
571 AccountTx {
572 channel: Ustr,
573 txs: Vec<LighterWsTx>,
574 },
575 #[serde(rename = "subscribed/account_all_trades")]
576 AccountAllTradesSnapshot {
577 channel: Ustr,
578 #[serde(default, deserialize_with = "deserialize_trade_vec")]
579 trades: Vec<LighterTrade>,
580 #[serde(deserialize_with = "deserialize_decimal")]
581 total_volume: Decimal,
582 #[serde(deserialize_with = "deserialize_decimal")]
583 monthly_volume: Decimal,
584 #[serde(deserialize_with = "deserialize_decimal")]
585 weekly_volume: Decimal,
586 #[serde(deserialize_with = "deserialize_decimal")]
587 daily_volume: Decimal,
588 },
589 #[serde(rename = "update/account_all_trades")]
590 AccountAllTrades {
591 channel: Ustr,
592 trades: AHashMap<Ustr, Vec<LighterTrade>>,
593 },
594 #[serde(rename = "subscribed/account_all_positions")]
595 AccountAllPositionsSnapshot {
596 channel: Ustr,
597 positions: AHashMap<Ustr, LighterPosition>,
598 #[serde(default)]
599 shares: Vec<LighterPoolShares>,
600 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
601 last_funding_round: Option<AHashMap<Ustr, Decimal>>,
602 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
603 last_funding_discount: Option<AHashMap<Ustr, Decimal>>,
604 },
605 #[serde(rename = "update/account_all_positions")]
606 AccountAllPositions {
607 channel: Ustr,
608 positions: AHashMap<Ustr, LighterPosition>,
609 #[serde(default)]
610 shares: Vec<LighterPoolShares>,
611 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
612 last_funding_round: Option<AHashMap<Ustr, Decimal>>,
613 #[serde(default, deserialize_with = "deserialize_optional_decimal_map")]
614 last_funding_discount: Option<AHashMap<Ustr, Decimal>>,
615 },
616 #[serde(
617 rename = "update/account_all_assets",
618 alias = "subscribed/account_all_assets"
619 )]
620 AccountAllAssets {
621 assets: AHashMap<Ustr, LighterAsset>,
622 channel: Ustr,
623 timestamp: u64,
624 },
625 #[serde(rename = "update/user_stats", alias = "subscribed/user_stats")]
626 UserStats {
627 channel: Ustr,
628 stats: LighterUserStats,
629 timestamp: u64,
630 },
631 #[serde(rename = "update/height", alias = "subscribed/height")]
632 Height {
633 channel: Ustr,
634 height: i64,
635 timestamp: u64,
636 },
637 #[serde(rename = "subscribed/candle")]
638 CandleSnapshot {
639 channel: Ustr,
640 candles: Vec<LighterWsCandle>,
641 timestamp: u64,
642 },
643 #[serde(rename = "update/candle")]
644 Candle {
645 channel: Ustr,
646 candles: Vec<LighterWsCandle>,
647 timestamp: u64,
648 },
649}
650
651#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
652pub struct LighterWsCandle {
653 pub t: i64,
654 #[serde(deserialize_with = "deserialize_decimal")]
655 pub o: Decimal,
656 #[serde(deserialize_with = "deserialize_decimal")]
657 pub h: Decimal,
658 #[serde(deserialize_with = "deserialize_decimal")]
659 pub l: Decimal,
660 #[serde(deserialize_with = "deserialize_decimal")]
661 pub c: Decimal,
662 #[serde(deserialize_with = "deserialize_decimal")]
663 pub v: Decimal,
664 #[serde(default, rename = "V", deserialize_with = "deserialize_decimal")]
665 pub quote_volume: Decimal,
666 #[serde(default)]
667 pub i: i64,
668}
669
670#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
671pub struct LighterWsOrderBook {
672 pub code: i32,
673 pub asks: Vec<LighterPriceLevel>,
674 pub bids: Vec<LighterPriceLevel>,
675 pub offset: i64,
676 pub nonce: i64,
677 pub last_updated_at: u64,
678 pub begin_nonce: i64,
679}
680
681#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
682pub struct LighterTicker {
683 pub s: Ustr,
684 pub a: LighterPriceLevel,
685 pub b: LighterPriceLevel,
686 pub last_updated_at: u64,
687}
688
689#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
690#[serde(untagged)]
691pub enum LighterMarketStatsPayload {
692 All(AHashMap<Ustr, LighterMarketStats>),
693 One(Box<LighterMarketStats>),
694}
695
696#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
697pub struct LighterMarketStats {
698 pub symbol: Ustr,
699 pub market_id: i64,
700 #[serde(deserialize_with = "deserialize_decimal_from_str")]
701 pub index_price: Decimal,
702 #[serde(deserialize_with = "deserialize_decimal_from_str")]
703 pub mark_price: Decimal,
704 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
705 pub mid_price: Decimal,
706 #[serde(deserialize_with = "deserialize_decimal_from_str")]
707 pub open_interest: Decimal,
708 #[serde(deserialize_with = "deserialize_decimal_from_str")]
709 pub open_interest_limit: Decimal,
710 #[serde(deserialize_with = "deserialize_decimal_from_str")]
711 pub funding_clamp_small: Decimal,
712 #[serde(deserialize_with = "deserialize_decimal_from_str")]
713 pub funding_clamp_big: Decimal,
714 #[serde(deserialize_with = "deserialize_decimal_from_str")]
715 pub last_trade_price: Decimal,
716 #[serde(deserialize_with = "deserialize_decimal_from_str")]
717 pub current_funding_rate: Decimal,
718 #[serde(deserialize_with = "deserialize_decimal_from_str")]
719 pub funding_rate: Decimal,
720 pub funding_timestamp: u64,
721 #[serde(deserialize_with = "deserialize_decimal")]
722 pub daily_base_token_volume: Decimal,
723 #[serde(deserialize_with = "deserialize_decimal")]
724 pub daily_quote_token_volume: Decimal,
725 #[serde(deserialize_with = "deserialize_decimal")]
726 pub daily_price_low: Decimal,
727 #[serde(deserialize_with = "deserialize_decimal")]
728 pub daily_price_high: Decimal,
729 #[serde(deserialize_with = "deserialize_decimal")]
730 pub daily_price_change: Decimal,
731}
732
733#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
734#[serde(untagged)]
735pub enum LighterSpotMarketStatsPayload {
736 All(AHashMap<Ustr, LighterSpotMarketStats>),
737 One(Box<LighterSpotMarketStats>),
738}
739
740#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
741pub struct LighterSpotMarketStats {
742 pub symbol: Ustr,
743 pub market_id: i64,
744 #[serde(deserialize_with = "deserialize_decimal_from_str")]
745 pub index_price: Decimal,
746 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
747 pub mid_price: Decimal,
748 #[serde(deserialize_with = "deserialize_decimal_from_str")]
749 pub last_trade_price: Decimal,
750 #[serde(deserialize_with = "deserialize_decimal")]
751 pub daily_base_token_volume: Decimal,
752 #[serde(deserialize_with = "deserialize_decimal")]
753 pub daily_quote_token_volume: Decimal,
754 #[serde(deserialize_with = "deserialize_decimal")]
755 pub daily_price_low: Decimal,
756 #[serde(deserialize_with = "deserialize_decimal")]
757 pub daily_price_high: Decimal,
758 #[serde(deserialize_with = "deserialize_decimal")]
759 pub daily_price_change: Decimal,
760}
761
762#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
763pub struct LighterPosition {
764 pub market_id: i64,
765 pub symbol: Ustr,
766 #[serde(deserialize_with = "deserialize_decimal_from_str")]
767 pub initial_margin_fraction: Decimal,
768 pub open_order_count: i64,
769 pub pending_order_count: i64,
770 pub position_tied_order_count: i64,
771 pub sign: i8,
772 #[serde(deserialize_with = "deserialize_decimal_from_str")]
773 pub position: Decimal,
774 #[serde(deserialize_with = "deserialize_decimal_from_str")]
775 pub avg_entry_price: Decimal,
776 #[serde(deserialize_with = "deserialize_decimal_from_str")]
777 pub position_value: Decimal,
778 #[serde(deserialize_with = "deserialize_decimal_from_str")]
779 pub unrealized_pnl: Decimal,
780 #[serde(deserialize_with = "deserialize_decimal_from_str")]
781 pub realized_pnl: Decimal,
782 #[serde(deserialize_with = "deserialize_decimal_from_str")]
783 pub liquidation_price: Decimal,
784 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
785 pub total_funding_paid_out: Option<Decimal>,
786 pub margin_mode: i32,
787 #[serde(deserialize_with = "deserialize_decimal_from_str")]
788 pub allocated_margin: Decimal,
789 #[serde(default, deserialize_with = "deserialize_optional_decimal")]
790 pub total_discount: Option<Decimal>,
791}
792
793#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
794pub struct LighterPoolShares {
795 pub public_pool_index: i64,
796 pub shares_amount: i64,
797 #[serde(deserialize_with = "deserialize_decimal_from_str")]
798 pub entry_usdc: Decimal,
799 #[serde(deserialize_with = "deserialize_decimal_from_str")]
800 pub principal_amount: Decimal,
801 pub entry_timestamp: u64,
802}
803
804#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
808pub struct LighterUserStatsScoped {
809 #[serde(deserialize_with = "deserialize_decimal_from_str")]
810 pub available_balance: Decimal,
811 #[serde(deserialize_with = "deserialize_decimal_from_str")]
812 pub buying_power: Decimal,
813 #[serde(deserialize_with = "deserialize_decimal_from_str")]
814 pub collateral: Decimal,
815 #[serde(deserialize_with = "deserialize_decimal_from_str")]
816 pub leverage: Decimal,
817 #[serde(deserialize_with = "deserialize_decimal_from_str")]
818 pub margin_usage: Decimal,
819 #[serde(deserialize_with = "deserialize_decimal_from_str")]
820 pub portfolio_value: Decimal,
821}
822
823#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
826pub struct LighterUserStats {
827 #[serde(default)]
828 pub account_trading_mode: i32,
829 #[serde(deserialize_with = "deserialize_decimal_from_str")]
830 pub available_balance: Decimal,
831 #[serde(deserialize_with = "deserialize_decimal_from_str")]
832 pub buying_power: Decimal,
833 #[serde(deserialize_with = "deserialize_decimal_from_str")]
834 pub collateral: Decimal,
835 #[serde(deserialize_with = "deserialize_decimal_from_str")]
836 pub leverage: Decimal,
837 #[serde(deserialize_with = "deserialize_decimal_from_str")]
838 pub margin_usage: Decimal,
839 #[serde(deserialize_with = "deserialize_decimal_from_str")]
840 pub portfolio_value: Decimal,
841 pub cross_stats: Option<LighterUserStatsScoped>,
842 pub total_stats: Option<LighterUserStatsScoped>,
843}
844
845#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
846pub struct LighterAsset {
847 pub symbol: Ustr,
848 pub asset_id: i16,
849 #[serde(deserialize_with = "deserialize_decimal_from_str")]
851 pub balance: Decimal,
852 #[serde(deserialize_with = "deserialize_decimal_from_str")]
854 pub locked_balance: Decimal,
855 #[serde(default, deserialize_with = "deserialize_decimal_from_str")]
858 pub margin_balance: Decimal,
859 #[serde(default)]
862 pub margin_mode: Ustr,
863}
864
865#[derive(Deserialize)]
866struct JsonDecimal(#[serde(deserialize_with = "deserialize_decimal_native")] Decimal);
867
868fn deserialize_optional_decimal_map<'de, D: serde::Deserializer<'de>>(
869 deserializer: D,
870) -> Result<Option<AHashMap<Ustr, Decimal>>, D::Error> {
871 let values = Option::<AHashMap<Ustr, JsonDecimal>>::deserialize(deserializer)?;
872 Ok(values.map(|values| {
873 values
874 .into_iter()
875 .map(|(key, value)| (key, value.0))
876 .collect()
877 }))
878}
879
880fn deserialize_trade_vec<'de, D>(deserializer: D) -> Result<Vec<LighterTrade>, D::Error>
881where
882 D: serde::Deserializer<'de>,
883{
884 struct TradeVecVisitor;
885
886 impl<'de> Visitor<'de> for TradeVecVisitor {
887 type Value = Vec<LighterTrade>;
888
889 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
890 formatter.write_str("trade array, object keyed by market, or null")
891 }
892
893 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
894 Ok(Vec::new())
895 }
896
897 fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
898 Ok(Vec::new())
899 }
900
901 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
902 let mut trades = Vec::with_capacity(seq.size_hint().unwrap_or(0));
903 while let Some(trade) = seq.next_element::<LighterTrade>()? {
904 trades.push(trade);
905 }
906 Ok(trades)
907 }
908
909 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
910 let mut trades = Vec::new();
911 while let Some((_, mut market_trades)) =
912 map.next_entry::<IgnoredAny, Vec<LighterTrade>>()?
913 {
914 trades.append(&mut market_trades);
915 }
916 Ok(trades)
917 }
918 }
919
920 deserializer.deserialize_any(TradeVecVisitor)
921}
922
923#[cfg(test)]
924mod tests {
925 use std::str::FromStr;
926
927 use rstest::rstest;
928 use serde_json::Value;
929
930 use super::*;
931
932 const WS_ORDER_BOOK_UPDATE: &str = include_str!("../../test_data/ws_order_book_update.json");
933 const WS_ORDER_BOOK_SUBSCRIBED: &str =
934 include_str!("../../test_data/ws_order_book_subscribed.json");
935 const WS_ORDER_BOOK_SUBSCRIBED_EMPTY: &str =
936 include_str!("../../test_data/ws_order_book_subscribed_empty.json");
937 const WS_TRADE_UPDATE: &str = include_str!("../../test_data/ws_trade_update.json");
938 const WS_TRADE_SUBSCRIBED: &str = include_str!("../../test_data/ws_trade_subscribed.json");
939 const WS_TICKER_UPDATE: &str = include_str!("../../test_data/ws_ticker_update.json");
940 const WS_TICKER_SUBSCRIBED: &str = include_str!("../../test_data/ws_ticker_subscribed.json");
941 const WS_TICKER_SUBSCRIBED_EMPTY: &str =
942 include_str!("../../test_data/ws_ticker_subscribed_empty.json");
943 const WS_MARKET_STATS_UPDATE_SINGLE: &str =
944 include_str!("../../test_data/ws_market_stats_update_single.json");
945 const WS_MARKET_STATS_SUBSCRIBED_SINGLE: &str =
946 include_str!("../../test_data/ws_market_stats_subscribed_single.json");
947 const WS_MARKET_STATS_UPDATE_ALL: &str =
948 include_str!("../../test_data/ws_market_stats_update_all.json");
949 const WS_MARKET_STATS_UPDATE_SINGLE_WIDENED: &str =
950 include_str!("../../test_data/ws_market_stats_update_single_widened.json");
951 const WS_SPOT_MARKET_STATS_UPDATE_SINGLE: &str =
952 include_str!("../../test_data/ws_spot_market_stats_update_single.json");
953 const WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE: &str =
954 include_str!("../../test_data/ws_spot_market_stats_subscribed_single.json");
955 const WS_SPOT_MARKET_STATS_UPDATE_ALL: &str =
956 include_str!("../../test_data/ws_spot_market_stats_update_all.json");
957 const WS_SPOT_MARKET_STATS_UPDATE_SINGLE_WIDENED: &str =
958 include_str!("../../test_data/ws_spot_market_stats_update_single_widened.json");
959 const WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE_EMPTY_MID: &str =
960 include_str!("../../test_data/ws_spot_market_stats_subscribed_single_empty_mid.json");
961 const WS_ACCOUNT_ALL_ASSETS_UPDATE: &str =
962 include_str!("../../test_data/ws_account_all_assets_update.json");
963 const WS_ACCOUNT_ORDERS_UPDATE: &str =
964 include_str!("../../test_data/ws_account_orders_update.json");
965 const WS_ACCOUNT_ALL_TRADES_UPDATE: &str =
966 include_str!("../../test_data/ws_account_all_trades_update.json");
967 const WS_ACCOUNT_ALL_POSITIONS_UPDATE: &str =
968 include_str!("../../test_data/ws_account_all_positions_update.json");
969 const WS_HEIGHT_UPDATE: &str = include_str!("../../test_data/ws_height_update.json");
970 const WS_CANDLE_SUBSCRIBED: &str = include_str!("../../test_data/ws_candle_subscribed.json");
971 const WS_CANDLE_UPDATE: &str = include_str!("../../test_data/ws_candle_update.json");
972
973 #[rstest]
974 #[case("subscribed/account_all_positions")]
975 #[case("update/account_all_positions")]
976 fn test_funding_decimal_maps(#[case] kind: &str) {
977 let value = serde_json::json!({
978 "type": kind,
979 "channel": "account_all_positions:7",
980 "positions": {},
981 "last_funding_round": {"1": 9007199254740993u64, "3": 1.25},
982 "last_funding_discount": {
983 "2": "0.1234567890123456789012345678",
984 "4": "0.12345678901234567890123456789"
985 }
986 });
987 let text = value.to_string();
988
989 for frame in [
990 serde_json::from_str::<LighterWsFrame>(&text).unwrap(),
991 serde_json::from_value(value).unwrap(),
992 ] {
993 let (round, discount) = funding_maps(frame);
994 assert_eq!(
995 round.unwrap(),
996 AHashMap::from_iter([
997 (Ustr::from("1"), Decimal::from(9_007_199_254_740_993u64)),
998 (Ustr::from("3"), Decimal::new(125, 2))
999 ])
1000 );
1001 assert_eq!(
1002 discount.unwrap(),
1003 AHashMap::from_iter([
1004 (
1005 Ustr::from("2"),
1006 Decimal::from_str_exact("0.1234567890123456789012345678").unwrap()
1007 ),
1008 (
1009 Ustr::from("4"),
1010 Decimal::from_str_exact("0.1234567890123456789012345679").unwrap()
1011 ),
1012 ])
1013 );
1014 }
1015 }
1016
1017 #[rstest]
1018 fn test_funding_decimal_maps_absent(
1019 #[values("subscribed/account_all_positions", "update/account_all_positions")] kind: &str,
1020 #[values(false, true)] explicit_null: bool,
1021 ) {
1022 let mut value = serde_json::json!({
1023 "type": kind,
1024 "channel": "account_all_positions:7",
1025 "positions": {},
1026 });
1027
1028 if explicit_null {
1029 value["last_funding_round"] = serde_json::Value::Null;
1030 value["last_funding_discount"] = serde_json::Value::Null;
1031 }
1032
1033 let text = value.to_string();
1034
1035 for frame in [
1036 serde_json::from_str::<LighterWsFrame>(&text).unwrap(),
1037 serde_json::from_value(value).unwrap(),
1038 ] {
1039 assert_eq!(funding_maps(frame), (None, None));
1040 }
1041 }
1042
1043 type FundingMap = Option<AHashMap<Ustr, Decimal>>;
1044
1045 fn funding_maps(frame: LighterWsFrame) -> (FundingMap, FundingMap) {
1046 match frame {
1047 LighterWsFrame::AccountAllPositionsSnapshot {
1048 last_funding_round,
1049 last_funding_discount,
1050 ..
1051 }
1052 | LighterWsFrame::AccountAllPositions {
1053 last_funding_round,
1054 last_funding_discount,
1055 ..
1056 } => (last_funding_round, last_funding_discount),
1057 _ => panic!("expected account positions"),
1058 }
1059 }
1060
1061 #[rstest]
1062 fn test_subscription_request_serializes_public_channel() {
1063 let channel = LighterWsChannel::OrderBook(0).subscription_channel();
1064 let request = LighterWsRequest::subscribe(channel);
1065
1066 let json = serde_json::to_string(&request).unwrap();
1067
1068 assert_eq!(
1069 serde_json::from_str::<Value>(&json).unwrap(),
1070 serde_json::json!({
1071 "type": "subscribe",
1072 "channel": "order_book/0",
1073 }),
1074 );
1075 }
1076
1077 #[rstest]
1078 fn test_subscription_request_serializes_auth_channel() {
1079 let channel = LighterWsChannel::AccountOrders {
1080 market_index: 0,
1081 account_index: 1234,
1082 }
1083 .subscription_channel();
1084 let request = LighterWsRequest::subscribe_auth(channel, "token");
1085
1086 let json = serde_json::to_string(&request).unwrap();
1087
1088 assert_eq!(
1089 serde_json::from_str::<Value>(&json).unwrap(),
1090 serde_json::json!({
1091 "type": "subscribe",
1092 "channel": "account_orders/0/1234",
1093 "auth": "token",
1094 }),
1095 );
1096 }
1097
1098 #[rstest]
1099 fn test_subscribe_request_debug_redacts_auth_token() {
1100 let token = "schnorr-signature-bytes-do-not-leak";
1101 let mut request = LighterWsRequest::subscribe_auth("account_all/123", token);
1102
1103 let dbg = format!("{request:?}");
1104
1105 assert!(
1106 !dbg.contains(token),
1107 "Debug output must not contain the auth token, found: {dbg}",
1108 );
1109 assert!(dbg.contains(REDACTED));
1110
1111 request.zeroize();
1112 assert!(matches!(
1113 &request,
1114 LighterWsRequest::Subscribe { auth: None, .. }
1115 ));
1116 }
1117
1118 #[rstest]
1119 #[case(LighterWsChannelKind::OrderBook)]
1120 #[case(LighterWsChannelKind::Ticker)]
1121 #[case(LighterWsChannelKind::Trade)]
1122 #[case(LighterWsChannelKind::Candle)]
1123 #[case(LighterWsChannelKind::MarketStats)]
1124 #[case(LighterWsChannelKind::SpotMarketStats)]
1125 #[case(LighterWsChannelKind::AccountAll)]
1126 #[case(LighterWsChannelKind::AccountOrders)]
1127 #[case(LighterWsChannelKind::AccountAllOrders)]
1128 #[case(LighterWsChannelKind::AccountAllTrades)]
1129 #[case(LighterWsChannelKind::AccountAllPositions)]
1130 #[case(LighterWsChannelKind::AccountAllAssets)]
1131 #[case(LighterWsChannelKind::Height)]
1132 fn test_channel_kind_wire_round_trip(#[case] kind: LighterWsChannelKind) {
1133 assert_eq!(
1134 LighterWsChannelKind::from_wire_str(kind.as_wire_str()),
1135 Some(kind),
1136 );
1137 }
1138
1139 #[rstest]
1140 #[case("unknown_channel")]
1141 #[case("ORDER_BOOK")]
1142 #[case("")]
1143 #[case("order_book:0")]
1144 fn test_channel_kind_unknown_returns_none(#[case] input: &str) {
1145 assert_eq!(LighterWsChannelKind::from_wire_str(input), None);
1146 }
1147
1148 #[rstest]
1149 fn test_order_book_frame_deserializes() {
1150 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_UPDATE).unwrap();
1151
1152 match frame {
1153 LighterWsFrame::OrderBook {
1154 channel,
1155 order_book,
1156 timestamp,
1157 ..
1158 } => {
1159 assert_eq!(channel, Ustr::from("order_book:0"));
1160 assert_eq!(order_book.asks.len(), 1);
1161 assert_eq!(
1162 order_book.asks[0].price,
1163 Decimal::from_str("2064.54").unwrap()
1164 );
1165 assert_eq!(timestamp, 1_774_884_082_326);
1166 }
1167 _ => panic!("expected order book frame"),
1168 }
1169 }
1170
1171 #[rstest]
1172 fn test_trade_frame_deserializes() {
1173 let frame: LighterWsFrame = serde_json::from_str(WS_TRADE_UPDATE).unwrap();
1174
1175 match frame {
1176 LighterWsFrame::Trade { trades, nonce, .. } => {
1177 assert_eq!(nonce, 8_630_448_841);
1178 assert_eq!(trades.len(), 1);
1179 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1180 }
1181 _ => panic!("expected trade frame"),
1182 }
1183 }
1184
1185 #[rstest]
1186 fn test_trade_frame_deserializes_null_liquidations() {
1187 let payload = serde_json::json!({
1188 "type": "update/trade",
1189 "channel": "trade:1",
1190 "liquidation_trades": null,
1191 "nonce": 1,
1192 "trades": []
1193 });
1194
1195 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1196
1197 match frame {
1198 LighterWsFrame::Trade {
1199 liquidation_trades,
1200 trades,
1201 ..
1202 } => {
1203 assert!(liquidation_trades.is_empty());
1204 assert!(trades.is_empty());
1205 }
1206 _ => panic!("expected trade frame"),
1207 }
1208 }
1209
1210 #[rstest]
1211 fn test_trade_frame_deserializes_object_trades() {
1212 let mut payload: Value = serde_json::from_str(WS_TRADE_UPDATE).unwrap();
1213 let trades = payload.get_mut("trades").unwrap().take();
1214 payload["trades"] = serde_json::json!({ "0": trades });
1215
1216 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1217
1218 match frame {
1219 LighterWsFrame::Trade { trades, .. } => {
1220 assert_eq!(trades.len(), 1);
1221 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1222 }
1223 _ => panic!("expected trade frame"),
1224 }
1225 }
1226
1227 #[rstest]
1228 fn test_ticker_frame_deserializes() {
1229 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_UPDATE).unwrap();
1230
1231 match frame {
1232 LighterWsFrame::Ticker {
1233 channel,
1234 nonce,
1235 ticker,
1236 timestamp,
1237 ..
1238 } => {
1239 assert_eq!(channel, Ustr::from("ticker:0"));
1240 assert_eq!(nonce, 9_182_390_020);
1241 assert_eq!(ticker.s, Ustr::from("ETH"));
1242 assert_eq!(ticker.a.price, Decimal::from_str("2064.48").unwrap());
1243 assert_eq!(ticker.b.size, Decimal::from_str("1.0392").unwrap());
1244 assert_eq!(timestamp, 1_774_883_844_933);
1245 }
1246 _ => panic!("expected ticker frame"),
1247 }
1248 }
1249
1250 #[rstest]
1255 fn test_order_book_snapshot_frame_deserializes() {
1256 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_SUBSCRIBED).unwrap();
1257
1258 match frame {
1259 LighterWsFrame::OrderBookSnapshot {
1260 channel,
1261 order_book,
1262 timestamp,
1263 ..
1264 } => {
1265 assert_eq!(channel, Ustr::from("order_book:0"));
1266 assert_eq!(order_book.bids.len(), 1);
1267 assert_eq!(
1268 order_book.bids[0].price,
1269 Decimal::from_str("2000.00").unwrap()
1270 );
1271 assert_eq!(order_book.asks.len(), 2);
1272 assert_eq!(
1273 order_book.asks[0].price,
1274 Decimal::from_str("2325.00").unwrap()
1275 );
1276 assert_eq!(order_book.nonce, 904_845);
1277 assert_eq!(timestamp, 1_778_138_582_602);
1278 }
1279 _ => panic!("expected order book snapshot frame, was {frame:?}"),
1280 }
1281 }
1282
1283 #[rstest]
1284 fn test_empty_order_book_snapshot_frame_deserializes() {
1285 let frame: LighterWsFrame = serde_json::from_str(WS_ORDER_BOOK_SUBSCRIBED_EMPTY).unwrap();
1286
1287 match frame {
1288 LighterWsFrame::OrderBookSnapshot {
1289 channel,
1290 last_updated_at,
1291 order_book,
1292 timestamp,
1293 ..
1294 } => {
1295 assert_eq!(channel, Ustr::from("order_book:39"));
1296 assert_eq!(last_updated_at, 0);
1297 assert!(order_book.asks.is_empty());
1298 assert!(order_book.bids.is_empty());
1299 assert_eq!(order_book.offset, 1);
1300 assert_eq!(order_book.nonce, 0);
1301 assert_eq!(timestamp, 1_778_138_582_602);
1302 }
1303 _ => panic!("expected empty order book snapshot frame, was {frame:?}"),
1304 }
1305 }
1306
1307 #[rstest]
1308 fn test_ticker_snapshot_frame_deserializes() {
1309 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_SUBSCRIBED).unwrap();
1310
1311 match frame {
1312 LighterWsFrame::TickerSnapshot {
1313 channel,
1314 nonce,
1315 ticker,
1316 timestamp,
1317 ..
1318 } => {
1319 assert_eq!(channel, Ustr::from("ticker:0"));
1320 assert_eq!(nonce, 904_895);
1321 assert_eq!(ticker.s, Ustr::from("ETH"));
1322 assert_eq!(ticker.a.price, Decimal::from_str("2325.00").unwrap());
1323 assert_eq!(ticker.b.price, Decimal::from_str("2000.00").unwrap());
1324 assert_eq!(timestamp, 1_778_138_582_640);
1325 }
1326 _ => panic!("expected ticker snapshot frame, was {frame:?}"),
1327 }
1328 }
1329
1330 #[rstest]
1331 fn test_empty_ticker_snapshot_frame_deserializes() {
1332 let frame: LighterWsFrame = serde_json::from_str(WS_TICKER_SUBSCRIBED_EMPTY).unwrap();
1333
1334 match frame {
1335 LighterWsFrame::TickerSnapshot {
1336 channel,
1337 last_updated_at,
1338 nonce,
1339 ticker,
1340 timestamp,
1341 ..
1342 } => {
1343 assert_eq!(channel, Ustr::from("ticker:39"));
1344 assert_eq!(last_updated_at, 0);
1345 assert_eq!(nonce, 2_475_051);
1346 assert_eq!(ticker.s, Ustr::from("ADA"));
1347 assert_eq!(ticker.a.price, Decimal::ZERO);
1348 assert_eq!(ticker.a.size, Decimal::ZERO);
1349 assert_eq!(ticker.b.price, Decimal::ZERO);
1350 assert_eq!(ticker.b.size, Decimal::ZERO);
1351 assert_eq!(timestamp, 1_778_138_582_640);
1352 }
1353 _ => panic!("expected empty ticker snapshot frame, was {frame:?}"),
1354 }
1355 }
1356
1357 #[rstest]
1358 fn test_trade_snapshot_frame_deserializes() {
1359 let frame: LighterWsFrame = serde_json::from_str(WS_TRADE_SUBSCRIBED).unwrap();
1360
1361 match frame {
1362 LighterWsFrame::TradeSnapshot {
1363 channel,
1364 nonce,
1365 trades,
1366 ..
1367 } => {
1368 assert_eq!(channel, Ustr::from("trade:0"));
1369 assert_eq!(nonce, 8_630_448_841);
1370 assert_eq!(trades.len(), 1);
1371 assert_eq!(trades[0].trade_id_str.as_deref(), Some("16164557907"));
1372 }
1373 _ => panic!("expected trade snapshot frame, was {frame:?}"),
1374 }
1375 }
1376
1377 #[rstest]
1378 fn test_market_stats_frame_deserializes_single_payload() {
1379 let frame: LighterWsFrame = serde_json::from_str(WS_MARKET_STATS_UPDATE_SINGLE).unwrap();
1380
1381 match frame {
1382 LighterWsFrame::MarketStats {
1383 channel,
1384 market_stats: LighterMarketStatsPayload::One(stats),
1385 timestamp,
1386 } => {
1387 assert_eq!(channel, Ustr::from("market_stats:0"));
1388 assert_eq!(stats.symbol, Ustr::from("ETH"));
1389 assert_eq!(stats.market_id, 0);
1390 assert_eq!(stats.mark_price, Decimal::from_str("2064.47").unwrap());
1391 assert_eq!(
1392 stats.daily_base_token_volume,
1393 Decimal::new(1_999_586_931, 4),
1394 );
1395 assert_eq!(timestamp, 1_774_883_844_933);
1396 }
1397 _ => panic!("expected single market stats frame"),
1398 }
1399 }
1400
1401 #[rstest]
1402 fn test_market_stats_subscribed_frame_deserializes_single_payload() {
1403 let frame: LighterWsFrame =
1404 serde_json::from_str(WS_MARKET_STATS_SUBSCRIBED_SINGLE).unwrap();
1405
1406 match frame {
1407 LighterWsFrame::MarketStats {
1408 channel,
1409 market_stats: LighterMarketStatsPayload::One(stats),
1410 timestamp,
1411 } => {
1412 assert_eq!(channel, Ustr::from("market_stats:1"));
1413 assert_eq!(stats.symbol, Ustr::from("BTC"));
1414 assert_eq!(stats.market_id, 1);
1415 assert_eq!(stats.mark_price, Decimal::from_str("64356.3").unwrap());
1416 assert_eq!(timestamp, 1_780_546_209_291);
1417 }
1418 _ => panic!("expected subscribed market stats frame"),
1419 }
1420 }
1421
1422 #[rstest]
1423 fn test_market_stats_frame_deserializes_all_payload() {
1424 let frame: LighterWsFrame = serde_json::from_str(WS_MARKET_STATS_UPDATE_ALL).unwrap();
1425
1426 match frame {
1427 LighterWsFrame::MarketStats {
1428 market_stats: LighterMarketStatsPayload::All(stats),
1429 ..
1430 } => {
1431 assert_eq!(stats.len(), 1);
1432 let stats = stats.get(&Ustr::from("0")).unwrap();
1433 assert_eq!(stats.symbol, Ustr::from("ETH"));
1434 assert_eq!(
1435 stats.open_interest,
1436 Decimal::from_str("27250.8411").unwrap()
1437 );
1438 }
1439 _ => panic!("expected all market stats frame"),
1440 }
1441 }
1442
1443 #[rstest]
1444 fn test_market_stats_frame_deserializes_widened_market_id() {
1445 let frame: LighterWsFrame =
1446 serde_json::from_str(WS_MARKET_STATS_UPDATE_SINGLE_WIDENED).unwrap();
1447
1448 match frame {
1449 LighterWsFrame::MarketStats {
1450 channel,
1451 market_stats: LighterMarketStatsPayload::One(stats),
1452 timestamp,
1453 } => {
1454 assert_eq!(channel, Ustr::from("market_stats:40000"));
1455 assert_eq!(stats.symbol, Ustr::from("FUTURE"));
1456 assert_eq!(stats.market_id, 40_000);
1457 assert_eq!(stats.mark_price, Decimal::from_str("12.47").unwrap());
1458 assert_eq!(timestamp, 1_774_883_844_933);
1459 }
1460 _ => panic!("expected single market stats frame"),
1461 }
1462 }
1463
1464 #[rstest]
1465 fn test_spot_market_stats_frame_deserializes_widened_market_id() {
1466 let frame: LighterWsFrame =
1467 serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_SINGLE_WIDENED).unwrap();
1468
1469 match frame {
1470 LighterWsFrame::SpotMarketStats {
1471 channel,
1472 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1473 timestamp,
1474 } => {
1475 assert_eq!(channel, Ustr::from("spot_market_stats:50000"));
1476 assert_eq!(stats.symbol, Ustr::from("FUTURE/USDC"));
1477 assert_eq!(stats.market_id, 50_000);
1478 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1479 assert_eq!(timestamp, 1_774_883_844_933);
1480 }
1481 _ => panic!("expected single spot market stats frame"),
1482 }
1483 }
1484
1485 #[rstest]
1486 fn test_spot_market_stats_frame_deserializes_empty_mid_as_zero() {
1487 let frame: LighterWsFrame =
1488 serde_json::from_str(WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE_EMPTY_MID).unwrap();
1489
1490 match frame {
1491 LighterWsFrame::SpotMarketStats {
1492 channel,
1493 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1494 timestamp,
1495 } => {
1496 assert_eq!(channel, Ustr::from("spot_market_stats:4098"));
1497 assert_eq!(stats.symbol, Ustr::from("ETH/USDC"));
1498 assert_eq!(stats.market_id, 4098);
1499 assert_eq!(stats.mid_price, Decimal::ZERO);
1500 assert_eq!(stats.index_price, Decimal::from_str("2471.940000").unwrap());
1501 assert_eq!(timestamp, 1_789_706_424_060);
1502 }
1503 _ => panic!("expected single spot market stats frame"),
1504 }
1505 }
1506
1507 #[rstest]
1508 fn test_spot_market_stats_frame_deserializes_single_payload() {
1509 let frame: LighterWsFrame =
1510 serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_SINGLE).unwrap();
1511
1512 match frame {
1513 LighterWsFrame::SpotMarketStats {
1514 channel,
1515 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1516 timestamp,
1517 } => {
1518 assert_eq!(channel, Ustr::from("spot_market_stats:2048"));
1519 assert_eq!(stats.symbol, Ustr::from("USDC"));
1520 assert_eq!(stats.market_id, 2048);
1521 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1522 assert_eq!(stats.daily_base_token_volume, Decimal::from(1000));
1523 assert_eq!(timestamp, 1_774_883_844_933);
1524 }
1525 _ => panic!("expected single spot market stats frame"),
1526 }
1527 }
1528
1529 #[rstest]
1530 fn test_spot_market_stats_subscribed_frame_deserializes_single_payload() {
1531 let frame: LighterWsFrame =
1532 serde_json::from_str(WS_SPOT_MARKET_STATS_SUBSCRIBED_SINGLE).unwrap();
1533
1534 match frame {
1535 LighterWsFrame::SpotMarketStats {
1536 channel,
1537 spot_market_stats: LighterSpotMarketStatsPayload::One(stats),
1538 timestamp,
1539 } => {
1540 assert_eq!(channel, Ustr::from("spot_market_stats:2048"));
1541 assert_eq!(stats.symbol, Ustr::from("USDC"));
1542 assert_eq!(stats.market_id, 2048);
1543 assert_eq!(stats.mid_price, Decimal::from_str("1.000001").unwrap());
1544 assert_eq!(timestamp, 1_774_883_844_933);
1545 }
1546 _ => panic!("expected subscribed spot market stats frame"),
1547 }
1548 }
1549
1550 #[rstest]
1551 fn test_spot_market_stats_frame_deserializes_all_payload() {
1552 let frame: LighterWsFrame = serde_json::from_str(WS_SPOT_MARKET_STATS_UPDATE_ALL).unwrap();
1553
1554 match frame {
1555 LighterWsFrame::SpotMarketStats {
1556 spot_market_stats: LighterSpotMarketStatsPayload::All(stats),
1557 ..
1558 } => {
1559 assert_eq!(stats.len(), 1);
1560 let stats = stats.get(&Ustr::from("2048")).unwrap();
1561 assert_eq!(stats.symbol, Ustr::from("USDC"));
1562 assert_eq!(
1563 stats.last_trade_price,
1564 Decimal::from_str("1.000002").unwrap()
1565 );
1566 }
1567 _ => panic!("expected all spot market stats frame"),
1568 }
1569 }
1570
1571 #[rstest]
1572 fn test_account_all_assets_frame_deserializes() {
1573 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_ASSETS_UPDATE).unwrap();
1577
1578 match frame {
1579 LighterWsFrame::AccountAllAssets {
1580 assets,
1581 channel,
1582 timestamp,
1583 } => {
1584 assert_eq!(channel, Ustr::from("account_all_assets:1234"));
1585 let asset = assets.get(&Ustr::from("3")).unwrap();
1586 assert_eq!(asset.symbol, Ustr::from("USDC"));
1587 assert_eq!(asset.asset_id, 3);
1588 assert_eq!(asset.balance, Decimal::from_str("10.000000").unwrap());
1589 assert_eq!(asset.locked_balance, Decimal::ZERO);
1590 assert_eq!(
1591 asset.margin_balance,
1592 Decimal::from_str("40.000000").unwrap()
1593 );
1594 assert_eq!(asset.margin_mode, Ustr::from("disabled"));
1595 assert_eq!(timestamp, 1_781_161_199_648);
1596 }
1597 _ => panic!("expected account all assets frame"),
1598 }
1599 }
1600
1601 #[rstest]
1602 fn test_account_all_assets_subscribed_frame_deserializes() {
1603 let payload = serde_json::json!({
1604 "type": "subscribed/account_all_assets",
1605 "channel": "account_all_assets:1234",
1606 "timestamp": 1778751230509u64,
1607 "assets": {
1608 "3": {
1609 "asset_id": 3,
1610 "balance": "9.660200",
1611 "locked_balance": "0.000000",
1612 "margin_balance": "9.955800",
1613 "margin_mode": "disabled",
1614 "symbol": "USDC"
1615 }
1616 }
1617 });
1618
1619 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1620
1621 match frame {
1622 LighterWsFrame::AccountAllAssets { assets, .. } => {
1623 assert_eq!(
1624 assets.get(&Ustr::from("3")).unwrap().symbol,
1625 Ustr::from("USDC")
1626 );
1627 }
1628 _ => panic!("expected account all assets frame"),
1629 }
1630 }
1631
1632 #[rstest]
1633 fn test_account_orders_frame_deserializes() {
1634 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
1635
1636 match frame {
1637 LighterWsFrame::AccountOrders {
1638 account,
1639 channel,
1640 orders,
1641 ..
1642 } => {
1643 assert_eq!(account, 1234);
1644 assert_eq!(channel, Ustr::from("account_orders:0:1234"));
1645 let market_orders = orders.get(&Ustr::from("0")).unwrap();
1646 assert_eq!(market_orders.len(), 1);
1647 assert_eq!(market_orders[0].order_id, "281476929510110");
1648 assert_eq!(market_orders[0].nonce, 281_474_720_725_346);
1649 assert_eq!(
1650 market_orders[0].filled_base_amount,
1651 Decimal::from_str("0.0020").unwrap(),
1652 );
1653 }
1654 _ => panic!("expected account orders frame, was {frame:?}"),
1655 }
1656 }
1657
1658 #[rstest]
1659 fn test_account_orders_subscribed_frame_deserializes() {
1660 let mut payload: serde_json::Value =
1661 serde_json::from_str(WS_ACCOUNT_ORDERS_UPDATE).unwrap();
1662 payload["type"] = serde_json::json!("subscribed/account_orders");
1663
1664 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1665
1666 assert!(matches!(frame, LighterWsFrame::AccountOrders { .. }));
1667 }
1668
1669 #[rstest]
1670 fn test_account_all_orders_subscribed_frame_deserializes_empty_side() {
1671 let frame: LighterWsFrame = serde_json::from_str(
1672 r#"{
1673 "type": "subscribed/account_all_orders",
1674 "channel": "account_all_orders:1234",
1675 "orders": {
1676 "3": [{
1677 "order_index": 1,
1678 "client_order_index": 2,
1679 "order_id": "1",
1680 "client_order_id": "2",
1681 "market_index": 3,
1682 "owner_account_index": 1234,
1683 "initial_base_amount": "100",
1684 "price": "0.100000",
1685 "nonce": 1,
1686 "remaining_base_amount": "100",
1687 "is_ask": false,
1688 "base_size": 100,
1689 "base_price": 100000,
1690 "filled_base_amount": "0",
1691 "filled_quote_amount": "0.000000",
1692 "side": "",
1693 "type": "limit",
1694 "time_in_force": "good-till-time",
1695 "reduce_only": false,
1696 "trigger_price": "0.000000",
1697 "order_expiry": 1781170441337,
1698 "status": "open",
1699 "trigger_status": "na",
1700 "trigger_time": 0,
1701 "parent_order_index": 0,
1702 "parent_order_id": "0",
1703 "to_trigger_order_id_0": "0",
1704 "to_trigger_order_id_1": "0",
1705 "to_cancel_order_id_0": "0",
1706 "integrator_fee_collector_index": "",
1707 "integrator_taker_fee": "",
1708 "integrator_maker_fee": "",
1709 "block_height": 1,
1710 "timestamp": 1778751241,
1711 "created_at": 1778751241,
1712 "updated_at": 1778751241,
1713 "transaction_time": 1778751241772524
1714 }]
1715 }
1716 }"#,
1717 )
1718 .unwrap();
1719
1720 match frame {
1721 LighterWsFrame::AccountAllOrders { orders, .. } => {
1722 let order = &orders.get(&Ustr::from("3")).unwrap()[0];
1723 assert_eq!(order.side, None);
1724 assert!(!order.is_ask);
1725 }
1726 _ => panic!("expected account all orders frame"),
1727 }
1728 }
1729
1730 #[rstest]
1731 fn test_account_all_trades_frame_deserializes() {
1732 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_TRADES_UPDATE).unwrap();
1733
1734 match frame {
1735 LighterWsFrame::AccountAllTrades { channel, trades } => {
1736 assert_eq!(channel, Ustr::from("account_all_trades:1234"));
1737 let market_trades = trades.get(&Ustr::from("0")).unwrap();
1738 assert_eq!(market_trades.len(), 1);
1739 assert_eq!(market_trades[0].bid_account_id, 1234);
1740 assert_eq!(market_trades[0].taker_fee, Some(196));
1741 }
1742 _ => panic!("expected account all trades frame, was {frame:?}"),
1743 }
1744 }
1745
1746 #[rstest]
1747 fn test_account_all_positions_frame_deserializes() {
1748 let frame: LighterWsFrame = serde_json::from_str(WS_ACCOUNT_ALL_POSITIONS_UPDATE).unwrap();
1749
1750 match frame {
1751 LighterWsFrame::AccountAllPositions {
1752 channel, positions, ..
1753 } => {
1754 assert_eq!(channel, Ustr::from("account_all_positions:1234"));
1755 let position = positions.get(&Ustr::from("0")).unwrap();
1756 assert_eq!(position.market_id, 0);
1757 assert_eq!(position.position, Decimal::from_str("1.5000").unwrap());
1758 assert_eq!(position.sign, 1);
1759 }
1760 _ => panic!("expected account all positions frame, was {frame:?}"),
1761 }
1762 }
1763
1764 #[rstest]
1765 fn test_account_all_positions_snapshot_frame_deserializes() {
1766 let mut value: serde_json::Value =
1767 serde_json::from_str(WS_ACCOUNT_ALL_POSITIONS_UPDATE).unwrap();
1768 value["type"] = serde_json::json!("subscribed/account_all_positions");
1769 let frame: LighterWsFrame = serde_json::from_value(value).unwrap();
1770
1771 match frame {
1772 LighterWsFrame::AccountAllPositionsSnapshot {
1773 channel, positions, ..
1774 } => {
1775 assert_eq!(channel, Ustr::from("account_all_positions:1234"));
1776 let position = positions.get(&Ustr::from("0")).unwrap();
1777 assert_eq!(position.market_id, 0);
1778 assert_eq!(position.position, Decimal::from_str("1.5000").unwrap());
1779 assert_eq!(position.sign, 1);
1780 }
1781 _ => panic!("expected account all positions snapshot, was {frame:?}"),
1782 }
1783 }
1784
1785 #[rstest]
1786 fn test_height_frame_deserializes() {
1787 let frame: LighterWsFrame = serde_json::from_str(WS_HEIGHT_UPDATE).unwrap();
1788
1789 match frame {
1790 LighterWsFrame::Height {
1791 channel,
1792 height,
1793 timestamp,
1794 } => {
1795 assert_eq!(channel, Ustr::from("height"));
1796 assert_eq!(height, 227_535_532);
1797 assert_eq!(timestamp, 1_774_883_844_933);
1798 }
1799 _ => panic!("expected height frame"),
1800 }
1801 }
1802
1803 #[rstest]
1804 fn test_height_subscribed_frame_deserializes() {
1805 let mut payload: serde_json::Value = serde_json::from_str(WS_HEIGHT_UPDATE).unwrap();
1806 payload["type"] = serde_json::json!("subscribed/height");
1807
1808 let frame: LighterWsFrame = serde_json::from_value(payload).unwrap();
1809
1810 assert!(matches!(frame, LighterWsFrame::Height { .. }));
1811 }
1812
1813 #[rstest]
1814 fn test_candle_channel_subscription_channel_uses_slash() {
1815 let channel = LighterWsChannel::Candle {
1816 market_index: 0,
1817 resolution: LighterCandleResolution::OneMinute,
1818 };
1819
1820 assert_eq!(channel.subscription_channel(), "candle/0/1m");
1821 }
1822
1823 #[rstest]
1824 fn test_candle_channel_topic_key_uses_colon() {
1825 let channel = LighterWsChannel::Candle {
1826 market_index: 7,
1827 resolution: LighterCandleResolution::FiveMinute,
1828 };
1829
1830 assert_eq!(channel.topic_key(), "candle:7:5m");
1831 }
1832
1833 #[rstest]
1834 fn test_candle_channel_does_not_require_auth() {
1835 let channel = LighterWsChannel::Candle {
1836 market_index: 0,
1837 resolution: LighterCandleResolution::OneMinute,
1838 };
1839
1840 assert!(!channel.requires_auth());
1841 }
1842
1843 #[rstest]
1844 fn test_candle_snapshot_frame_deserializes() {
1845 let frame: LighterWsFrame = serde_json::from_str(WS_CANDLE_SUBSCRIBED).unwrap();
1846
1847 match frame {
1848 LighterWsFrame::CandleSnapshot {
1849 channel,
1850 candles,
1851 timestamp,
1852 } => {
1853 assert_eq!(channel, Ustr::from("candle:0:1m"));
1854 assert_eq!(timestamp, 1_778_821_471_842);
1855 assert_eq!(candles.len(), 1);
1856 let candle = &candles[0];
1857 assert_eq!(candle.t, 1_778_821_440_000);
1858 assert_eq!(candle.o, Decimal::from_str("2264.2").unwrap());
1859 assert_eq!(candle.h, Decimal::from_str("2264.34").unwrap());
1860 assert_eq!(candle.l, Decimal::from_str("2263.36").unwrap());
1861 assert_eq!(candle.c, Decimal::from_str("2263.97").unwrap());
1862 let arbitrary_precision =
1863 serde_json::from_str::<serde_json::Number>("79228162514264337593543950335")
1864 .unwrap()
1865 .to_string()
1866 == "79228162514264337593543950335";
1867
1868 let (volume, quote_volume) = if arbitrary_precision {
1869 ("13.223699999999997", "29934.600011999984")
1870 } else {
1871 ("13.2237", "29934.60001199998")
1872 };
1873
1874 assert_eq!(candle.v, Decimal::from_str_exact(volume).unwrap());
1875 assert_eq!(
1876 candle.quote_volume,
1877 Decimal::from_str_exact(quote_volume).unwrap()
1878 );
1879 assert_eq!(candle.i, 19_993_571_166);
1880 }
1881 _ => panic!("expected candle snapshot frame"),
1882 }
1883 }
1884
1885 #[rstest]
1886 fn test_candle_update_frame_deserializes() {
1887 let frame: LighterWsFrame = serde_json::from_str(WS_CANDLE_UPDATE).unwrap();
1888
1889 match frame {
1890 LighterWsFrame::Candle {
1891 channel,
1892 candles,
1893 timestamp,
1894 } => {
1895 assert_eq!(channel, Ustr::from("candle:0:1m"));
1896 assert_eq!(timestamp, 1_778_821_473_331);
1897 assert_eq!(candles.len(), 1);
1898 assert_eq!(candles[0].t, 1_778_821_440_000);
1899 assert_eq!(candles[0].c, Decimal::from_str("2263.89").unwrap());
1900 }
1901 _ => panic!("expected candle update frame"),
1902 }
1903 }
1904
1905 #[rstest]
1906 #[case(0)]
1907 #[case(7350)]
1908 #[case(u64::MAX)]
1909 fn shutdown_notification_parses_deadline(#[case] close_in_ms: u64) {
1910 let frame: LighterWsFrame = serde_json::from_value(
1911 serde_json::json!({"type":"shutdown", "close_in_ms":close_in_ms}),
1912 )
1913 .unwrap();
1914
1915 match frame {
1916 LighterWsFrame::Shutdown {
1917 close_in_ms: actual,
1918 } => assert_eq!(actual, close_in_ms),
1919 other => panic!("expected shutdown, was {other:?}"),
1920 }
1921 }
1922
1923 #[rstest]
1924 #[case(serde_json::json!({"type":"shutdown"}))]
1925 #[case(serde_json::json!({"type":"shutdown", "close_in_ms":-1}))]
1926 #[case(serde_json::json!({"type":"shutdown", "close_in_ms":"7350"}))]
1927 fn shutdown_notification_rejects_invalid_deadline(#[case] frame: serde_json::Value) {
1928 assert!(serde_json::from_value::<LighterWsFrame>(frame).is_err());
1929 }
1930}