Skip to main content

nautilus_lighter/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Request and response payload definitions for Lighter REST endpoints.
17
18use std::{collections::BTreeMap, str::FromStr};
19
20use nautilus_core::serialization::{
21    deserialize_decimal, deserialize_decimal_from_str, deserialize_decimal_or_zero,
22    deserialize_optional_decimal,
23};
24use rust_decimal::Decimal;
25use serde::{Deserialize, Serialize, de};
26use ustr::Ustr;
27use zeroize::ZeroizeOnDrop;
28
29use crate::common::enums::{
30    LighterCandleResolution, LighterFundingResolution, LighterMarketStatus, LighterOrderKind,
31    LighterOrderSide, LighterOrderStatus, LighterOrderTimeInForce, LighterPositionMarginMode,
32    LighterProductType, LighterTradeType, LighterTriggerStatus, LighterTxStatus,
33};
34
35#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
36pub struct LighterResultCode {
37    pub code: i32,
38    pub message: Option<String>,
39}
40
41/// Response payload of `GET /api/v1/nextNonce`.
42///
43/// The venue reports the next sequence number it expects on `sendTx` for the
44/// `(account_index, api_key_index)` pair. Pass this to
45/// [`crate::signing::nonce::NonceManager::refresh`] before the first signed
46/// transaction.
47#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
48pub struct LighterNextNonce {
49    pub code: i32,
50    pub message: Option<String>,
51    pub nonce: i64,
52}
53
54/// Response payload of `GET /api/v1/tx`.
55#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
56pub struct LighterTx {
57    pub code: i32,
58    pub message: Option<String>,
59    pub hash: String,
60    #[serde(rename = "type")]
61    pub tx_type: u8,
62    pub info: String,
63    pub event_info: String,
64    pub status: LighterTxStatus,
65    pub account_index: i64,
66    pub nonce: i64,
67    pub api_key_index: u8,
68}
69
70/// One account row from `GET /api/v1/account`.
71///
72/// Models only the fields the adapter consumes; the venue response carries
73/// many more, which are ignored on deserialization.
74#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, ZeroizeOnDrop)]
75pub struct LighterAccountDetail {
76    pub account_index: u64,
77    pub account_type: u8,
78    pub status: i32,
79    pub l1_address: String,
80}
81
82/// Response payload of `GET /api/v1/account`.
83#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
84pub struct LighterAccountsResponse {
85    pub code: i32,
86    pub message: Option<String>,
87    pub total: i64,
88    #[serde(default, deserialize_with = "deserialize_null_vec")]
89    pub accounts: Vec<LighterAccountDetail>,
90}
91
92/// Response payload of `GET /api/v1/getMakerOnlyApiKeys`.
93///
94/// Lighter restricts maker-only keys to the 0ms speed-bump lane (PostOnly
95/// creates, modifies on ALO orders, cancel / cancel-all). Any tx kind outside
96/// that allowlist - for example `ApproveIntegrator` (tx_type 45) - is rejected
97/// with venue code `62007`. The adapter pre-flights this endpoint before
98/// submitting the integrator auto-approval so it can skip the doomed tx with
99/// a clear log line instead of swallowing the misleading 62007.
100#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
101pub struct LighterMakerOnlyApiKeys {
102    pub code: i32,
103    pub message: Option<String>,
104    #[serde(default)]
105    pub api_key_indexes: Vec<i64>,
106}
107
108#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
109pub struct LighterSendTxRequest {
110    pub tx_type: u8,
111    pub tx_info: String,
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub price_protection: Option<bool>,
114}
115
116impl LighterSendTxRequest {
117    #[must_use]
118    pub fn new(tx_type: u8, tx_info: impl Into<String>) -> Self {
119        Self {
120            tx_type,
121            tx_info: tx_info.into(),
122            price_protection: None,
123        }
124    }
125
126    #[must_use]
127    pub const fn with_price_protection(mut self, price_protection: bool) -> Self {
128        self.price_protection = Some(price_protection);
129        self
130    }
131
132    pub(crate) fn form_fields(&self) -> Vec<(&'static str, String)> {
133        let mut fields = vec![
134            ("tx_type", self.tx_type.to_string()),
135            ("tx_info", self.tx_info.clone()),
136        ];
137
138        if let Some(price_protection) = self.price_protection {
139            fields.push(("price_protection", price_protection.to_string()));
140        }
141        fields
142    }
143}
144
145#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
146pub struct LighterSendTxBatchRequest {
147    pub tx_types: String,
148    pub tx_infos: String,
149}
150
151impl LighterSendTxBatchRequest {
152    #[must_use]
153    pub fn new(tx_types: impl Into<String>, tx_infos: impl Into<String>) -> Self {
154        Self {
155            tx_types: tx_types.into(),
156            tx_infos: tx_infos.into(),
157        }
158    }
159
160    pub(crate) fn form_fields(&self) -> Vec<(&'static str, String)> {
161        vec![
162            ("tx_types", self.tx_types.clone()),
163            ("tx_infos", self.tx_infos.clone()),
164        ]
165    }
166}
167
168#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
169pub struct LighterSendTxResponse {
170    pub code: i32,
171    pub message: Option<String>,
172    pub tx_hash: String,
173    pub predicted_execution_time_ms: i64,
174    pub volume_quota_remaining: Option<i64>,
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub remaining_send_tx: Option<i64>,
177}
178
179#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
180pub struct LighterSendTxBatchResponse {
181    pub code: i32,
182    pub message: Option<String>,
183    #[serde(default, deserialize_with = "deserialize_null_vec")]
184    pub tx_hash: Vec<String>,
185    pub predicted_execution_time_ms: i64,
186    pub volume_quota_remaining: Option<i64>,
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub remaining_send_tx: Option<i64>,
189}
190
191#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
192pub struct LighterOrderBooks {
193    pub code: i32,
194    pub message: Option<String>,
195    #[serde(default, deserialize_with = "deserialize_null_vec")]
196    pub order_books: Vec<LighterOrderBook>,
197}
198
199#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
200pub struct LighterOrderBook {
201    pub symbol: Ustr,
202    pub market_id: i64,
203    pub market_type: LighterProductType,
204    pub base_asset_id: i16,
205    pub quote_asset_id: i16,
206    pub status: LighterMarketStatus,
207    #[serde(deserialize_with = "deserialize_decimal_from_str")]
208    pub taker_fee: Decimal,
209    #[serde(deserialize_with = "deserialize_decimal_from_str")]
210    pub maker_fee: Decimal,
211    #[serde(deserialize_with = "deserialize_decimal_from_str")]
212    pub liquidation_fee: Decimal,
213    #[serde(deserialize_with = "deserialize_decimal_from_str")]
214    pub min_base_amount: Decimal,
215    #[serde(deserialize_with = "deserialize_decimal_from_str")]
216    pub min_quote_amount: Decimal,
217    #[serde(deserialize_with = "deserialize_decimal_from_str")]
218    pub order_quote_limit: Decimal,
219    pub supported_size_decimals: u8,
220    pub supported_price_decimals: u8,
221    pub supported_quote_decimals: u8,
222}
223
224#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
225pub struct LighterOrderBookDetails {
226    pub code: i32,
227    pub message: Option<String>,
228    #[serde(default, deserialize_with = "deserialize_null_vec")]
229    pub order_book_details: Vec<LighterPerpOrderBookDetail>,
230    #[serde(default, deserialize_with = "deserialize_null_vec")]
231    pub spot_order_book_details: Vec<LighterSpotOrderBookDetail>,
232}
233
234#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
235pub struct LighterPerpOrderBookDetail {
236    #[serde(flatten)]
237    pub order_book: LighterOrderBook,
238    pub size_decimals: u8,
239    pub price_decimals: u8,
240    pub quote_multiplier: i64,
241    pub default_initial_margin_fraction: u16,
242    pub min_initial_margin_fraction: u16,
243    pub maintenance_margin_fraction: u16,
244    pub closeout_margin_fraction: u16,
245    #[serde(deserialize_with = "deserialize_decimal")]
246    pub last_trade_price: Decimal,
247    pub daily_trades_count: i64,
248    #[serde(deserialize_with = "deserialize_decimal")]
249    pub daily_base_token_volume: Decimal,
250    #[serde(deserialize_with = "deserialize_decimal")]
251    pub daily_quote_token_volume: Decimal,
252    #[serde(deserialize_with = "deserialize_decimal")]
253    pub daily_price_low: Decimal,
254    #[serde(deserialize_with = "deserialize_decimal")]
255    pub daily_price_high: Decimal,
256    #[serde(deserialize_with = "deserialize_decimal")]
257    pub daily_price_change: Decimal,
258    #[serde(deserialize_with = "deserialize_decimal")]
259    pub open_interest: Decimal,
260    #[serde(deserialize_with = "deserialize_decimal_btree_map")]
261    pub daily_chart: BTreeMap<String, Decimal>,
262    pub market_config: LighterMarketConfig,
263    pub strategy_index: u8,
264}
265
266#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
267pub struct LighterSpotOrderBookDetail {
268    #[serde(flatten)]
269    pub order_book: LighterOrderBook,
270    pub size_decimals: u8,
271    pub price_decimals: u8,
272    #[serde(deserialize_with = "deserialize_decimal")]
273    pub last_trade_price: Decimal,
274    pub daily_trades_count: i64,
275    #[serde(deserialize_with = "deserialize_decimal")]
276    pub daily_base_token_volume: Decimal,
277    #[serde(deserialize_with = "deserialize_decimal")]
278    pub daily_quote_token_volume: Decimal,
279    #[serde(deserialize_with = "deserialize_decimal")]
280    pub daily_price_low: Decimal,
281    #[serde(deserialize_with = "deserialize_decimal")]
282    pub daily_price_high: Decimal,
283    #[serde(deserialize_with = "deserialize_decimal")]
284    pub daily_price_change: Decimal,
285    #[serde(deserialize_with = "deserialize_decimal_btree_map")]
286    pub daily_chart: BTreeMap<String, Decimal>,
287}
288
289#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
290pub struct LighterMarketConfig {
291    pub market_margin_mode: LighterPositionMarginMode,
292    pub insurance_fund_account_index: i64,
293    pub liquidation_mode: i32,
294    pub force_reduce_only: bool,
295    pub trading_hours: String,
296    pub funding_fee_discounts_enabled: bool,
297    pub hidden: bool,
298}
299
300#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
301pub struct LighterOrderBookOrders {
302    pub code: i32,
303    pub message: Option<String>,
304    pub total_asks: i64,
305    #[serde(default, deserialize_with = "deserialize_null_vec")]
306    pub asks: Vec<LighterSimpleOrder>,
307    pub total_bids: i64,
308    #[serde(default, deserialize_with = "deserialize_null_vec")]
309    pub bids: Vec<LighterSimpleOrder>,
310}
311
312#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
313pub struct LighterSimpleOrder {
314    pub order_index: i64,
315    pub order_id: String,
316    pub owner_account_index: i64,
317    #[serde(deserialize_with = "deserialize_decimal_from_str")]
318    pub initial_base_amount: Decimal,
319    #[serde(deserialize_with = "deserialize_decimal_from_str")]
320    pub remaining_base_amount: Decimal,
321    #[serde(deserialize_with = "deserialize_decimal_from_str")]
322    pub price: Decimal,
323    pub order_expiry: i64,
324    pub transaction_time: i64,
325}
326
327#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
328pub struct LighterOrderBookDepth {
329    pub code: i32,
330    pub message: Option<String>,
331    #[serde(default, deserialize_with = "deserialize_null_vec")]
332    pub asks: Vec<LighterPriceLevel>,
333    #[serde(default, deserialize_with = "deserialize_null_vec")]
334    pub bids: Vec<LighterPriceLevel>,
335    pub offset: i64,
336    pub nonce: i64,
337}
338
339/// A single book level returned by the order-book REST snapshot and the
340/// WebSocket ticker / order_book / order_book_depth frames.
341///
342/// Lighter sends empty strings on the bid or ask side of a ticker frame when
343/// that side currently has no resting orders; [`deserialize_decimal_or_zero`]
344/// maps those to [`Decimal::ZERO`]. Downstream parsers must treat a
345/// zero-priced (or zero-sized) level as an uninhabited side, not a literal
346/// zero quote.
347#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
348pub struct LighterPriceLevel {
349    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
350    pub price: Decimal,
351    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
352    pub size: Decimal,
353}
354
355#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
356pub struct LighterTrades {
357    pub code: i32,
358    pub message: Option<String>,
359    pub next_cursor: Option<String>,
360    #[serde(default, deserialize_with = "deserialize_null_vec")]
361    pub trades: Vec<LighterTrade>,
362}
363
364#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
365pub struct LighterCandles {
366    pub code: i32,
367    pub message: Option<String>,
368    #[serde(rename = "r")]
369    pub resolution: LighterCandleResolution,
370    #[serde(rename = "c", default, deserialize_with = "deserialize_null_vec")]
371    pub candles: Vec<LighterCandle>,
372}
373
374#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
375pub struct LighterCandle {
376    #[serde(rename = "t")]
377    pub timestamp: i64,
378    #[serde(rename = "o", default, deserialize_with = "deserialize_decimal")]
379    pub open: Decimal,
380    #[serde(rename = "h", default, deserialize_with = "deserialize_decimal")]
381    pub high: Decimal,
382    #[serde(rename = "l", default, deserialize_with = "deserialize_decimal")]
383    pub low: Decimal,
384    #[serde(rename = "c", default, deserialize_with = "deserialize_decimal")]
385    pub close: Decimal,
386    #[serde(rename = "v", default, deserialize_with = "deserialize_decimal")]
387    pub volume_base: Decimal,
388    #[serde(rename = "V", default, deserialize_with = "deserialize_decimal")]
389    pub volume_quote: Decimal,
390    #[serde(rename = "i")]
391    pub last_trade_id: i64,
392}
393
394#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
395pub struct LighterFundings {
396    pub code: i32,
397    pub message: Option<String>,
398    pub resolution: LighterFundingResolution,
399    #[serde(default, deserialize_with = "deserialize_null_vec")]
400    pub fundings: Vec<LighterFunding>,
401}
402
403#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
404pub struct LighterFunding {
405    pub timestamp: i64,
406    #[serde(deserialize_with = "deserialize_decimal")]
407    pub value: Decimal,
408    #[serde(deserialize_with = "deserialize_decimal")]
409    pub rate: Decimal,
410    pub direction: LighterFundingDirection,
411}
412
413#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
414#[serde(rename_all = "lowercase")]
415pub enum LighterFundingDirection {
416    Long,
417    Short,
418}
419
420#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
421pub struct LighterTrade {
422    pub trade_id: i64,
423    pub trade_id_str: Option<String>,
424    pub tx_hash: String,
425    #[serde(rename = "type")]
426    pub trade_type: LighterTradeType,
427    pub market_id: i64,
428    #[serde(deserialize_with = "deserialize_decimal_from_str")]
429    pub size: Decimal,
430    #[serde(deserialize_with = "deserialize_decimal_from_str")]
431    pub price: Decimal,
432    #[serde(deserialize_with = "deserialize_decimal_from_str")]
433    pub usd_amount: Decimal,
434    pub ask_id: i64,
435    pub ask_id_str: Option<String>,
436    pub bid_id: i64,
437    pub bid_id_str: Option<String>,
438    pub ask_client_id: i64,
439    pub ask_client_id_str: Option<String>,
440    pub bid_client_id: i64,
441    pub bid_client_id_str: Option<String>,
442    pub ask_account_id: i64,
443    pub bid_account_id: i64,
444    pub is_maker_ask: bool,
445    pub block_height: i64,
446    pub timestamp: i64,
447    pub taker_fee: Option<i32>,
448    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
449    pub taker_position_size_before: Option<Decimal>,
450    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
451    pub taker_entry_quote_before: Option<Decimal>,
452    pub taker_initial_margin_fraction_before: Option<u16>,
453    pub taker_position_sign_changed: Option<bool>,
454    pub maker_fee: Option<i32>,
455    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
456    pub maker_position_size_before: Option<Decimal>,
457    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
458    pub maker_entry_quote_before: Option<Decimal>,
459    pub maker_initial_margin_fraction_before: Option<u16>,
460    pub maker_position_sign_changed: Option<bool>,
461    pub transaction_time: i64,
462    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
463    pub ask_account_pnl: Option<Decimal>,
464    #[serde(default, deserialize_with = "deserialize_optional_decimal")]
465    pub bid_account_pnl: Option<Decimal>,
466}
467
468#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
469pub struct LighterOrders {
470    pub code: i32,
471    pub message: Option<String>,
472    pub next_cursor: Option<String>,
473    #[serde(default, deserialize_with = "deserialize_null_vec")]
474    pub orders: Vec<LighterOrder>,
475}
476
477#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
478pub struct LighterOrder {
479    pub order_index: i64,
480    pub client_order_index: i64,
481    pub order_id: String,
482    pub client_order_id: String,
483    pub market_index: i64,
484    pub owner_account_index: i64,
485    #[serde(deserialize_with = "deserialize_decimal_from_str")]
486    pub initial_base_amount: Decimal,
487    #[serde(deserialize_with = "deserialize_decimal_from_str")]
488    pub price: Decimal,
489    pub nonce: i64,
490    #[serde(deserialize_with = "deserialize_decimal_from_str")]
491    pub remaining_base_amount: Decimal,
492    pub is_ask: bool,
493    pub base_size: i64,
494    pub base_price: i32,
495    #[serde(deserialize_with = "deserialize_decimal_from_str")]
496    pub filled_base_amount: Decimal,
497    #[serde(deserialize_with = "deserialize_decimal_from_str")]
498    pub filled_quote_amount: Decimal,
499    #[serde(default, deserialize_with = "deserialize_order_side")]
500    pub side: Option<LighterOrderSide>,
501    #[serde(rename = "type")]
502    pub order_type: LighterOrderKind,
503    pub time_in_force: LighterOrderTimeInForce,
504    pub reduce_only: bool,
505    // Lighter sends an empty string when no trigger price is set.
506    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
507    pub trigger_price: Decimal,
508    pub order_expiry: i64,
509    pub status: LighterOrderStatus,
510    pub trigger_status: LighterTriggerStatus,
511    pub trigger_time: i64,
512    pub parent_order_index: i64,
513    pub parent_order_id: String,
514    pub to_trigger_order_id_0: String,
515    pub to_trigger_order_id_1: String,
516    pub to_cancel_order_id_0: String,
517    pub integrator_fee_collector_index: String,
518    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
519    pub integrator_taker_fee: Decimal,
520    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
521    pub integrator_maker_fee: Decimal,
522    pub block_height: i64,
523    pub timestamp: i64,
524    pub created_at: i64,
525    pub updated_at: i64,
526    pub transaction_time: i64,
527}
528
529#[derive(Deserialize)]
530struct DecimalFromAny(#[serde(deserialize_with = "deserialize_decimal")] Decimal);
531
532fn deserialize_decimal_btree_map<'de, D>(
533    deserializer: D,
534) -> Result<BTreeMap<String, Decimal>, D::Error>
535where
536    D: serde::Deserializer<'de>,
537{
538    BTreeMap::<String, DecimalFromAny>::deserialize(deserializer).map(|values| {
539        values
540            .into_iter()
541            .map(|(key, decimal)| (key, decimal.0))
542            .collect()
543    })
544}
545
546fn deserialize_null_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
547where
548    D: serde::Deserializer<'de>,
549    T: Deserialize<'de>,
550{
551    Option::<Vec<T>>::deserialize(deserializer).map(Option::unwrap_or_default)
552}
553
554fn deserialize_order_side<'de, D>(deserializer: D) -> Result<Option<LighterOrderSide>, D::Error>
555where
556    D: serde::Deserializer<'de>,
557{
558    let value = Option::<String>::deserialize(deserializer)?;
559    match value.as_deref() {
560        None | Some("") => Ok(None),
561        Some(s) => LighterOrderSide::from_str(s)
562            .map(Some)
563            .map_err(|_| de::Error::unknown_variant(s, &["buy", "sell", ""])),
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use rstest::rstest;
570
571    use super::*;
572
573    const HTTP_ORDER_BOOK_DETAILS: &str =
574        include_str!("../../test_data/http_order_book_details.json");
575    const HTTP_ORDER_BOOK_DETAILS_WIDENED_IDS: &str =
576        include_str!("../../test_data/http_order_book_details_widened_ids.json");
577    const HTTP_RECENT_TRADES: &str = include_str!("../../test_data/http_recent_trades.json");
578    const HTTP_RECENT_TRADES_MISSING: &str =
579        include_str!("../../test_data/http_recent_trades_missing.json");
580    const HTTP_RECENT_TRADES_NULL: &str =
581        include_str!("../../test_data/http_recent_trades_null.json");
582    const HTTP_ORDER_BOOKS: &str = include_str!("../../test_data/http_order_books.json");
583    const HTTP_ORDER_BOOKS_WIDENED_IDS: &str =
584        include_str!("../../test_data/http_order_books_widened_ids.json");
585    const HTTP_ORDER_BOOK_ORDERS: &str =
586        include_str!("../../test_data/http_order_book_orders.json");
587    const HTTP_ORDER_BOOK_DEPTH: &str = include_str!("../../test_data/http_order_book_depth.json");
588    const HTTP_ORDER_BOOK_DEPTH_NULL: &str =
589        include_str!("../../test_data/http_order_book_depth_null.json");
590    const HTTP_ORDERS: &str = include_str!("../../test_data/http_orders.json");
591    const HTTP_CANDLES: &str = include_str!("../../test_data/http_candles.json");
592    const HTTP_CANDLES_NULL: &str = include_str!("../../test_data/http_candles_null.json");
593    const HTTP_FUNDINGS: &str = include_str!("../../test_data/http_fundings.json");
594    const HTTP_ACCOUNT: &str = include_str!("../../test_data/http_account.json");
595    const HTTP_SEND_TX_WITH_HEADROOM: &str =
596        include_str!("../../test_data/http_send_tx_with_headroom.json");
597    const HTTP_SEND_TX_LEGACY: &str = include_str!("../../test_data/http_send_tx_legacy.json");
598    const HTTP_SEND_TX_BATCH_WITH_HEADROOM: &str =
599        include_str!("../../test_data/http_send_tx_batch_with_headroom.json");
600    const HTTP_SEND_TX_BATCH_LEGACY: &str =
601        include_str!("../../test_data/http_send_tx_batch_legacy.json");
602
603    #[rstest]
604    fn test_account_response_deserializes_live_shape() {
605        let response: LighterAccountsResponse = serde_json::from_str(HTTP_ACCOUNT).unwrap();
606
607        assert_eq!(response.code, 200);
608        assert_eq!(response.total, 1);
609        assert_eq!(response.accounts.len(), 1);
610        let account = &response.accounts[0];
611        assert_eq!(account.account_index, 123_456);
612        assert_eq!(account.account_type, 0);
613        assert_eq!(account.status, 1);
614        assert_eq!(
615            account.l1_address,
616            "0x0000000000000000000000000000000000000000"
617        );
618    }
619
620    #[rstest]
621    fn test_account_response_allows_missing_or_null_accounts() {
622        let missing = serde_json::json!({"code": 200, "total": 0});
623        let null = serde_json::json!({"code": 200, "total": 0, "accounts": null});
624
625        let missing: LighterAccountsResponse = serde_json::from_value(missing).unwrap();
626        let null: LighterAccountsResponse = serde_json::from_value(null).unwrap();
627
628        assert!(missing.accounts.is_empty());
629        assert!(null.accounts.is_empty());
630    }
631
632    #[rstest]
633    fn test_send_tx_batch_response_allows_missing_or_null_tx_hash() {
634        let missing = serde_json::json!({
635            "code": 200,
636            "predicted_execution_time_ms": 1_751_465_475,
637        });
638        let null = serde_json::json!({
639            "code": 200,
640            "tx_hash": null,
641            "predicted_execution_time_ms": 1_751_465_475,
642        });
643
644        let missing: LighterSendTxBatchResponse = serde_json::from_value(missing).unwrap();
645        let null: LighterSendTxBatchResponse = serde_json::from_value(null).unwrap();
646
647        assert!(missing.tx_hash.is_empty());
648        assert!(null.tx_hash.is_empty());
649    }
650
651    #[rstest]
652    #[case::with_headroom(HTTP_SEND_TX_WITH_HEADROOM, Some(17))]
653    #[case::legacy(HTTP_SEND_TX_LEGACY, None)]
654    fn test_send_tx_response_deserializes_optional_remaining_send_tx(
655        #[case] fixture: &str,
656        #[case] expected: Option<i64>,
657    ) {
658        let response: LighterSendTxResponse = serde_json::from_str(fixture).unwrap();
659
660        assert_eq!(response.code, 200);
661        assert_eq!(response.message, None);
662        assert_eq!(response.tx_hash, "0xabc");
663        assert_eq!(response.predicted_execution_time_ms, 1_751_465_474);
664        assert_eq!(response.volume_quota_remaining, Some(123));
665        assert_eq!(response.remaining_send_tx, expected);
666
667        let serialized = serde_json::to_value(&response).unwrap();
668        assert_eq!(
669            serialized.get("remaining_send_tx").is_some(),
670            expected.is_some()
671        );
672
673        if let Some(expected) = expected {
674            assert_eq!(serialized["remaining_send_tx"], expected);
675        }
676    }
677
678    #[rstest]
679    #[case::with_headroom(HTTP_SEND_TX_BATCH_WITH_HEADROOM, Some(18))]
680    #[case::legacy(HTTP_SEND_TX_BATCH_LEGACY, None)]
681    fn test_send_tx_batch_response_deserializes_optional_remaining_send_tx(
682        #[case] fixture: &str,
683        #[case] expected: Option<i64>,
684    ) {
685        let response: LighterSendTxBatchResponse = serde_json::from_str(fixture).unwrap();
686
687        assert_eq!(response.code, 200);
688        assert_eq!(response.message, None);
689        assert_eq!(response.tx_hash, vec!["0xabc", "0xdef"]);
690        assert_eq!(response.predicted_execution_time_ms, 1_751_465_475);
691        assert_eq!(response.volume_quota_remaining, Some(122));
692        assert_eq!(response.remaining_send_tx, expected);
693
694        let serialized = serde_json::to_value(&response).unwrap();
695        assert_eq!(
696            serialized.get("remaining_send_tx").is_some(),
697            expected.is_some()
698        );
699
700        if let Some(expected) = expected {
701            assert_eq!(serialized["remaining_send_tx"], expected);
702        }
703    }
704
705    #[rstest]
706    fn test_order_book_details_deserializes_live_shape() {
707        let details: LighterOrderBookDetails =
708            serde_json::from_str(HTTP_ORDER_BOOK_DETAILS).unwrap();
709
710        assert_eq!(details.code, 200);
711        assert_eq!(details.order_book_details.len(), 1);
712        assert_eq!(
713            details.order_book_details[0].order_book.market_type,
714            LighterProductType::Perp,
715        );
716        assert_eq!(details.order_book_details[0].price_decimals, 2);
717        assert_eq!(
718            details.order_book_details[0].last_trade_price,
719            Decimal::new(236_131, 2),
720        );
721        assert_eq!(
722            details.order_book_details[0].daily_base_token_volume,
723            Decimal::new(1_953_991_521, 4),
724        );
725        assert_eq!(
726            details.order_book_details[0]
727                .market_config
728                .market_margin_mode,
729            LighterPositionMarginMode::Cross,
730        );
731        assert!(details.spot_order_book_details.is_empty());
732    }
733
734    #[rstest]
735    fn test_order_book_details_deserializes_widened_market_ids() {
736        let details: LighterOrderBookDetails =
737            serde_json::from_str(HTTP_ORDER_BOOK_DETAILS_WIDENED_IDS).unwrap();
738
739        assert_eq!(details.code, 200);
740        assert_eq!(details.order_book_details.len(), 2);
741        assert_eq!(details.spot_order_book_details.len(), 2);
742
743        let perp_ids: Vec<i64> = details
744            .order_book_details
745            .iter()
746            .map(|d| d.order_book.market_id)
747            .collect();
748        assert_eq!(perp_ids, vec![4095, 40_000]);
749        assert!(
750            details
751                .order_book_details
752                .iter()
753                .all(|d| d.order_book.market_type == LighterProductType::Perp)
754        );
755
756        let spot_ids: Vec<i64> = details
757            .spot_order_book_details
758            .iter()
759            .map(|d| d.order_book.market_id)
760            .collect();
761        assert_eq!(spot_ids, vec![4098, 50_000]);
762        assert!(
763            details
764                .spot_order_book_details
765                .iter()
766                .all(|d| d.order_book.market_type == LighterProductType::Spot)
767        );
768    }
769
770    #[rstest]
771    fn test_recent_trades_allow_omitted_fee_fields() {
772        let trades: LighterTrades = serde_json::from_str(HTTP_RECENT_TRADES).unwrap();
773
774        assert_eq!(trades.trades.len(), 1);
775        assert_eq!(
776            trades.trades[0].trade_id_str.as_deref(),
777            Some("19211490282")
778        );
779        assert_eq!(trades.trades[0].taker_fee, None);
780        assert_eq!(trades.trades[0].maker_fee, Some(28));
781    }
782
783    #[rstest]
784    fn test_recent_trades_deserializes_null_trades_as_empty() {
785        let trades: LighterTrades = serde_json::from_str(HTTP_RECENT_TRADES_NULL).unwrap();
786
787        assert_eq!(trades.code, 200);
788        assert!(trades.trades.is_empty());
789    }
790
791    #[rstest]
792    fn test_recent_trades_deserializes_missing_trades_as_empty() {
793        let trades: LighterTrades = serde_json::from_str(HTTP_RECENT_TRADES_MISSING).unwrap();
794
795        assert_eq!(trades.code, 200);
796        assert!(trades.trades.is_empty());
797    }
798
799    #[rstest]
800    fn test_candles_deserializes_live_shape_with_omitted_raw_fields() {
801        let candles: LighterCandles = serde_json::from_str(HTTP_CANDLES).unwrap();
802
803        assert_eq!(candles.code, 200);
804        assert_eq!(candles.resolution, LighterCandleResolution::OneMinute);
805        assert_eq!(candles.candles.len(), 2);
806        assert_eq!(candles.candles[0].timestamp, 1_700_000_000_000);
807        assert_eq!(candles.candles[0].open, Decimal::new(236_111, 2));
808        assert_eq!(candles.candles[0].high, Decimal::new(236_222, 2));
809        assert_eq!(candles.candles[0].low, Decimal::new(236_000, 2));
810        assert_eq!(candles.candles[0].close, Decimal::new(236_131, 2));
811        assert_eq!(candles.candles[0].volume_base, Decimal::new(12_345, 4));
812        assert_eq!(candles.candles[0].last_trade_id, 19_211_490_282);
813    }
814
815    #[rstest]
816    fn test_candles_deserializes_null_candles_as_empty() {
817        let candles: LighterCandles = serde_json::from_str(HTTP_CANDLES_NULL).unwrap();
818
819        assert_eq!(candles.code, 200);
820        assert_eq!(candles.resolution, LighterCandleResolution::OneMinute);
821        assert!(candles.candles.is_empty());
822    }
823
824    #[rstest]
825    #[case("o")]
826    #[case("h")]
827    #[case("l")]
828    #[case("c")]
829    fn test_candle_missing_or_null_ohlc_deserializes_as_zero(#[case] field: &str) {
830        let base = serde_json::json!({
831            "t": 1_700_000_000_000_i64,
832            "o": "1",
833            "h": "1",
834            "l": "1",
835            "c": "1",
836            "v": "1",
837            "V": "1",
838            "i": 1,
839        });
840        let mut missing = base.clone();
841        missing.as_object_mut().unwrap().remove(field);
842        let mut null = base;
843        null[field] = serde_json::Value::Null;
844
845        let missing: LighterCandle = serde_json::from_value(missing).unwrap();
846        let null: LighterCandle = serde_json::from_value(null).unwrap();
847        let value_for = |candle: &LighterCandle| match field {
848            "o" => candle.open,
849            "h" => candle.high,
850            "l" => candle.low,
851            "c" => candle.close,
852            _ => unreachable!(),
853        };
854
855        assert_eq!(value_for(&missing), Decimal::ZERO);
856        assert_eq!(value_for(&null), Decimal::ZERO);
857    }
858
859    #[rstest]
860    fn test_fundings_deserializes_live_shape() {
861        let fundings: LighterFundings = serde_json::from_str(HTTP_FUNDINGS).unwrap();
862
863        assert_eq!(fundings.code, 200);
864        assert_eq!(fundings.resolution, LighterFundingResolution::OneHour);
865        assert_eq!(fundings.fundings.len(), 2);
866        assert_eq!(fundings.fundings[0].timestamp, 1_778_702_400);
867        assert_eq!(fundings.fundings[0].rate, Decimal::new(12, 4));
868        assert_eq!(
869            fundings.fundings[0].direction,
870            LighterFundingDirection::Long
871        );
872        assert_eq!(
873            fundings.fundings[1].direction,
874            LighterFundingDirection::Short
875        );
876    }
877
878    #[rstest]
879    fn test_order_books_deserializes_live_shape() {
880        let order_books: LighterOrderBooks = serde_json::from_str(HTTP_ORDER_BOOKS).unwrap();
881
882        assert_eq!(order_books.code, 200);
883        assert_eq!(order_books.order_books.len(), 1);
884        assert_eq!(order_books.order_books[0].symbol, Ustr::from("ETH"));
885        assert_eq!(
886            order_books.order_books[0].market_type,
887            LighterProductType::Perp
888        );
889        assert_eq!(
890            order_books.order_books[0].status,
891            LighterMarketStatus::Active
892        );
893        assert_eq!(order_books.order_books[0].supported_price_decimals, 2);
894    }
895
896    #[rstest]
897    fn test_order_books_deserializes_widened_market_ids() {
898        let order_books: LighterOrderBooks =
899            serde_json::from_str(HTTP_ORDER_BOOKS_WIDENED_IDS).unwrap();
900
901        assert_eq!(order_books.code, 200);
902        assert_eq!(order_books.order_books.len(), 2);
903        assert_eq!(order_books.order_books[0].market_id, 4095);
904        assert_eq!(
905            order_books.order_books[0].market_type,
906            LighterProductType::Perp
907        );
908        assert_eq!(order_books.order_books[1].market_id, 50_000);
909        assert_eq!(
910            order_books.order_books[1].market_type,
911            LighterProductType::Spot
912        );
913    }
914
915    #[rstest]
916    fn test_order_book_orders_deserializes_live_shape() {
917        let book: LighterOrderBookOrders = serde_json::from_str(HTTP_ORDER_BOOK_ORDERS).unwrap();
918
919        assert_eq!(book.total_asks, 1);
920        assert_eq!(book.asks[0].order_id, "281476929689581");
921        assert_eq!(book.asks[0].price, Decimal::from_str("2361.32").unwrap());
922        assert_eq!(book.total_bids, 1);
923        assert_eq!(
924            book.bids[0].remaining_base_amount,
925            Decimal::from_str("3.4125").unwrap(),
926        );
927    }
928
929    #[rstest]
930    fn test_order_book_depth_deserializes_live_shape() {
931        let depth: LighterOrderBookDepth = serde_json::from_str(HTTP_ORDER_BOOK_DEPTH).unwrap();
932
933        assert_eq!(depth.code, 200);
934        assert_eq!(depth.asks[0].price, Decimal::from_str("2352.74").unwrap());
935        assert_eq!(depth.bids[0].size, Decimal::from_str("0.2125").unwrap());
936        assert_eq!(depth.offset, 1_558_300);
937        assert_eq!(depth.nonce, 9_182_390_020);
938    }
939
940    #[rstest]
941    fn test_order_book_depth_deserializes_null_sides_as_empty() {
942        let depth: LighterOrderBookDepth =
943            serde_json::from_str(HTTP_ORDER_BOOK_DEPTH_NULL).unwrap();
944
945        assert_eq!(depth.code, 200);
946        assert!(depth.asks.is_empty());
947        assert!(depth.bids.is_empty());
948        assert_eq!(depth.offset, 1);
949        assert_eq!(depth.nonce, 0);
950    }
951
952    #[rstest]
953    fn test_orders_deserializes_live_shape() {
954        let orders: LighterOrders = serde_json::from_str(HTTP_ORDERS).unwrap();
955
956        assert_eq!(orders.next_cursor.as_deref(), Some("cursor-1"));
957        assert_eq!(orders.orders.len(), 1);
958        assert_eq!(orders.orders[0].order_type, LighterOrderKind::Limit);
959        assert_eq!(
960            orders.orders[0].time_in_force,
961            LighterOrderTimeInForce::GoodTillTime,
962        );
963        assert_eq!(orders.orders[0].status, LighterOrderStatus::Open);
964        assert_eq!(orders.orders[0].trigger_status, LighterTriggerStatus::Na);
965        assert_eq!(orders.orders[0].side, Some(LighterOrderSide::Sell));
966        assert!(orders.orders[0].is_ask);
967    }
968
969    #[rstest]
970    fn test_orders_allows_empty_side_with_is_ask() {
971        let mut value: serde_json::Value = serde_json::from_str(HTTP_ORDERS).unwrap();
972        value["orders"][0]["side"] = serde_json::Value::String(String::new());
973
974        let orders: LighterOrders = serde_json::from_value(value).unwrap();
975
976        assert_eq!(orders.orders[0].side, None);
977        assert!(orders.orders[0].is_ask);
978    }
979}