o2-sdk 0.0.1

Rust SDK for the O2 Exchange — a fully on-chain order book DEX on the Fuel Network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
/// Data models for O2 Exchange API types.
///
/// All models use serde for JSON serialization/deserialization.
/// String fields are used for large numeric values to avoid precision loss.
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;

use crate::decimal::UnsignedDecimal;

macro_rules! newtype_id {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            pub fn new(s: impl Into<String>) -> Self {
                Self(s.into())
            }
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl From<String> for $name {
            fn from(s: String) -> Self {
                Self(s)
            }
        }

        impl From<&str> for $name {
            fn from(s: &str) -> Self {
                Self(s.to_string())
            }
        }

        impl std::ops::Deref for $name {
            type Target = str;
            fn deref(&self) -> &str {
                &self.0
            }
        }
    };
}

newtype_id!(
    /// A market symbol pair like "FUEL/USDC".
    MarketSymbol
);
newtype_id!(
    /// A hex market ID.
    MarketId
);
newtype_id!(
    /// A hex order ID.
    OrderId
);
newtype_id!(
    /// A hex trade account ID.
    TradeAccountId
);
newtype_id!(
    /// A hex asset ID.
    AssetId
);

/// Deserialize a value that may be a JSON number or a string containing a number.
fn deserialize_string_or_u64<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de;

    struct StringOrU64;
    impl<'de> de::Visitor<'de> for StringOrU64 {
        type Value = u64;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a u64 or a string containing a u64")
        }
        fn visit_u64<E: de::Error>(self, v: u64) -> Result<u64, E> {
            Ok(v)
        }
        fn visit_str<E: de::Error>(self, v: &str) -> Result<u64, E> {
            v.parse().map_err(de::Error::custom)
        }
    }
    deserializer.deserialize_any(StringOrU64)
}

/// Deserialize an optional value that may be a JSON number or a string, storing as String.
fn deserialize_optional_string_or_number<'de, D>(
    deserializer: D,
) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<serde_json::Value> = Option::deserialize(deserializer)?;
    match value {
        Some(serde_json::Value::String(s)) => Ok(Some(s)),
        Some(serde_json::Value::Number(n)) => Ok(Some(n.to_string())),
        Some(serde_json::Value::Null) | None => Ok(None),
        Some(v) => Ok(Some(v.to_string())),
    }
}

// ---------------------------------------------------------------------------
// Public trading enums
// ---------------------------------------------------------------------------

/// Order side: Buy or Sell.
#[derive(Debug, Clone)]
pub enum Side {
    Buy,
    Sell,
}

impl Side {
    /// Returns the API string representation.
    pub fn as_str(&self) -> &str {
        match self {
            Side::Buy => "Buy",
            Side::Sell => "Sell",
        }
    }
}

/// High-level order type with associated data.
///
/// Used in `create_order` and `Action::CreateOrder` to provide compile-time
/// safety instead of raw `&str` matching. Limit and BoundedMarket variants
/// carry their required parameters.
#[derive(Debug, Clone)]
pub enum OrderType {
    Spot,
    Market,
    FillOrKill,
    PostOnly,
    Limit {
        price: UnsignedDecimal,
        timestamp: u64,
    },
    BoundedMarket {
        max_price: UnsignedDecimal,
        min_price: UnsignedDecimal,
    },
}

/// High-level action for use with `batch_actions`.
///
/// Converts to the low-level `CallArg` and JSON representations internally.
#[derive(Debug, Clone)]
pub enum Action {
    CreateOrder {
        side: Side,
        price: UnsignedDecimal,
        quantity: UnsignedDecimal,
        order_type: OrderType,
    },
    CancelOrder {
        order_id: OrderId,
    },
    SettleBalance,
    RegisterReferer {
        to: Identity,
    },
}

impl OrderType {
    /// Convert to the low-level `OrderTypeEncoding` and JSON representation
    /// used by the encoding and API layers.
    pub fn to_encoding(
        &self,
        market: &Market,
    ) -> (crate::encoding::OrderTypeEncoding, serde_json::Value) {
        use crate::encoding::OrderTypeEncoding;
        match self {
            OrderType::Spot => (OrderTypeEncoding::Spot, serde_json::json!("Spot")),
            OrderType::Market => (OrderTypeEncoding::Market, serde_json::json!("Market")),
            OrderType::FillOrKill => (
                OrderTypeEncoding::FillOrKill,
                serde_json::json!("FillOrKill"),
            ),
            OrderType::PostOnly => (OrderTypeEncoding::PostOnly, serde_json::json!("PostOnly")),
            OrderType::Limit { price, timestamp } => {
                let scaled_price = market.scale_price(price);
                (
                    OrderTypeEncoding::Limit {
                        price: scaled_price,
                        timestamp: *timestamp,
                    },
                    serde_json::json!({ "Limit": [scaled_price.to_string(), timestamp.to_string()] }),
                )
            }
            OrderType::BoundedMarket {
                max_price,
                min_price,
            } => {
                let scaled_max = market.scale_price(max_price);
                let scaled_min = market.scale_price(min_price);
                (
                    OrderTypeEncoding::BoundedMarket {
                        max_price: scaled_max,
                        min_price: scaled_min,
                    },
                    serde_json::json!({ "BoundedMarket": { "max_price": scaled_max.to_string(), "min_price": scaled_min.to_string() } }),
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Identity
// ---------------------------------------------------------------------------

/// A Fuel Identity — either an Address or a ContractId.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Identity {
    Address(String),
    ContractId(String),
}

impl Identity {
    pub fn address_value(&self) -> &str {
        match self {
            Identity::Address(a) => a,
            Identity::ContractId(c) => c,
        }
    }
}

/// A signature wrapper.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Signature {
    Secp256k1(String),
}

// ---------------------------------------------------------------------------
// Market
// ---------------------------------------------------------------------------

/// Asset info within a market.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketAsset {
    pub symbol: String,
    pub asset: AssetId,
    pub decimals: u32,
    pub max_precision: u32,
}

/// A trading market.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Market {
    pub contract_id: String,
    pub market_id: MarketId,
    pub maker_fee: String,
    pub taker_fee: String,
    pub min_order: String,
    pub dust: String,
    #[serde(deserialize_with = "deserialize_string_or_u64")]
    pub price_window: u64,
    pub base: MarketAsset,
    pub quote: MarketAsset,
}

impl Market {
    /// Convert a chain-scaled price to human-readable.
    pub fn format_price(&self, chain_value: u64) -> UnsignedDecimal {
        let d = Decimal::from(chain_value) / Decimal::from(10u64.pow(self.quote.decimals));
        UnsignedDecimal::new(d).unwrap()
    }

    /// Convert a human-readable price to chain-scaled integer, truncated to max_precision.
    pub fn scale_price(&self, human_value: &UnsignedDecimal) -> u64 {
        let factor = Decimal::from(10u64.pow(self.quote.decimals));
        let scaled = (*human_value.inner() * factor)
            .floor()
            .to_string()
            .parse::<u64>()
            .unwrap_or(0);
        let truncate_factor = 10u64.pow(self.quote.decimals - self.quote.max_precision);
        (scaled / truncate_factor) * truncate_factor
    }

    /// Convert a chain-scaled quantity to human-readable.
    pub fn format_quantity(&self, chain_value: u64) -> UnsignedDecimal {
        let d = Decimal::from(chain_value) / Decimal::from(10u64.pow(self.base.decimals));
        UnsignedDecimal::new(d).unwrap()
    }

    /// Convert a human-readable quantity to chain-scaled integer, truncated to max_precision.
    pub fn scale_quantity(&self, human_value: &UnsignedDecimal) -> u64 {
        let factor = Decimal::from(10u64.pow(self.base.decimals));
        let scaled = (*human_value.inner() * factor)
            .floor()
            .to_string()
            .parse::<u64>()
            .unwrap_or(0);
        let truncate_factor = 10u64.pow(self.base.decimals - self.base.max_precision);
        (scaled / truncate_factor) * truncate_factor
    }

    /// The symbol pair, e.g. "FUEL/USDC".
    pub fn symbol_pair(&self) -> MarketSymbol {
        MarketSymbol::new(format!("{}/{}", self.base.symbol, self.quote.symbol))
    }

    /// Adjust quantity downward so that `(price * quantity) % 10^base_decimals == 0`.
    /// Returns the original quantity if already valid.
    pub fn adjust_quantity(&self, price: u64, quantity: u64) -> u64 {
        let base_factor = 10u128.pow(self.base.decimals);
        let product = price as u128 * quantity as u128;
        let remainder = product % base_factor;
        if remainder == 0 {
            return quantity;
        }
        let adjusted_product = product - remainder;
        (adjusted_product / price as u128) as u64
    }

    /// Validate that a price*quantity satisfies min_order and FractionalPrice constraints.
    pub fn validate_order(&self, price: u64, quantity: u64) -> Result<(), String> {
        let base_factor = 10u128.pow(self.base.decimals);
        let quote_value = (price as u128 * quantity as u128) / base_factor;
        let min_order: u128 = self.min_order.parse().unwrap_or(0);
        if quote_value < min_order {
            return Err(format!(
                "Quote value {} below min_order {}",
                quote_value, min_order
            ));
        }
        // FractionalPrice check
        if (price as u128 * quantity as u128) % base_factor != 0 {
            return Err("FractionalPrice: (price * quantity) % 10^base_decimals != 0".into());
        }
        Ok(())
    }
}

/// Top-level response from GET /v1/markets.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketsResponse {
    pub books_registry_id: Option<String>,
    pub accounts_registry_id: Option<String>,
    pub trade_account_oracle_id: Option<String>,
    pub chain_id: Option<String>,
    pub base_asset_id: Option<String>,
    pub markets: Vec<Market>,
}

/// Market summary from GET /v1/markets/summary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketSummary {
    pub market_id: Option<String>,
    pub high: Option<String>,
    pub low: Option<String>,
    pub volume: Option<String>,
    pub price_change: Option<String>,
    pub last_price: Option<String>,
}

/// Market ticker from GET /v1/markets/ticker.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketTicker {
    pub market_id: Option<String>,
    pub best_bid: Option<String>,
    pub best_ask: Option<String>,
    pub last_price: Option<String>,
}

// ---------------------------------------------------------------------------
// Account
// ---------------------------------------------------------------------------

/// Trading account info from GET /v1/accounts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeAccount {
    pub last_modification: Option<u64>,
    pub nonce: Option<String>,
    pub owner: Option<Identity>,
    #[serde(default)]
    pub synced_with_network: Option<bool>,
    #[serde(default)]
    pub sync_state: Option<serde_json::Value>,
}

/// Account response from GET /v1/accounts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountResponse {
    pub trade_account_id: Option<TradeAccountId>,
    pub trade_account: Option<TradeAccount>,
    pub session: Option<SessionInfo>,
}

/// Session info within an account response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    pub session_id: Option<Identity>,
    pub expiry: Option<String>,
    pub contract_ids: Option<Vec<String>>,
}

/// Response from POST /v1/accounts (create account).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateAccountResponse {
    pub trade_account_id: Option<TradeAccountId>,
    pub nonce: Option<String>,
}

// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------

/// Request body for PUT /v1/session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionRequest {
    pub contract_id: String,
    pub session_id: Identity,
    pub signature: Signature,
    pub contract_ids: Vec<String>,
    pub nonce: String,
    pub expiry: String,
}

/// Response from PUT /v1/session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionResponse {
    pub tx_id: Option<String>,
    pub trade_account_id: Option<String>,
    pub contract_ids: Option<Vec<String>>,
    pub session_id: Option<Identity>,
    pub session_expiry: Option<String>,
}

/// Local session state tracked by the client.
#[derive(Debug, Clone)]
pub struct Session {
    pub owner_address: [u8; 32],
    pub session_private_key: [u8; 32],
    pub session_address: [u8; 32],
    pub trade_account_id: TradeAccountId,
    pub contract_ids: Vec<String>,
    pub expiry: u64,
    pub nonce: u64,
}

// ---------------------------------------------------------------------------
// Orders
// ---------------------------------------------------------------------------

/// An order from the API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
    pub order_id: Option<OrderId>,
    pub side: Option<String>,
    pub order_type: Option<serde_json::Value>,
    #[serde(default, deserialize_with = "deserialize_optional_string_or_number")]
    pub quantity: Option<String>,
    #[serde(default, deserialize_with = "deserialize_optional_string_or_number")]
    pub quantity_fill: Option<String>,
    #[serde(default, deserialize_with = "deserialize_optional_string_or_number")]
    pub price: Option<String>,
    #[serde(default, deserialize_with = "deserialize_optional_string_or_number")]
    pub price_fill: Option<String>,
    pub timestamp: Option<serde_json::Value>,
    pub close: Option<bool>,
    pub partially_filled: Option<bool>,
    pub cancel: Option<bool>,
    #[serde(default)]
    pub desired_quantity: Option<serde_json::Value>,
    #[serde(default)]
    pub base_decimals: Option<u32>,
    #[serde(default)]
    pub account: Option<Identity>,
    #[serde(default)]
    pub fill: Option<serde_json::Value>,
    #[serde(default)]
    pub order_tx_history: Option<Vec<serde_json::Value>>,
    #[serde(default)]
    pub market_id: Option<MarketId>,
    #[serde(default)]
    pub owner: Option<Identity>,
    #[serde(default)]
    pub history: Option<Vec<serde_json::Value>>,
    #[serde(default)]
    pub fills: Option<Vec<serde_json::Value>>,
}

/// Response from GET /v1/orders.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrdersResponse {
    pub identity: Option<Identity>,
    pub market_id: Option<String>,
    pub orders: Option<Vec<Order>>,
}

// ---------------------------------------------------------------------------
// Trades
// ---------------------------------------------------------------------------

/// A trade from the API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trade {
    pub trade_id: Option<String>,
    pub side: Option<String>,
    pub total: Option<String>,
    pub quantity: Option<String>,
    pub price: Option<String>,
    pub timestamp: Option<String>,
    #[serde(default)]
    pub maker: Option<Identity>,
    #[serde(default)]
    pub taker: Option<Identity>,
}

/// Response from GET /v1/trades.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradesResponse {
    pub trades: Option<Vec<Trade>>,
    pub market_id: Option<String>,
}

// ---------------------------------------------------------------------------
// Balance
// ---------------------------------------------------------------------------

/// Order book balance entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderBookBalance {
    pub locked: Option<String>,
    pub unlocked: Option<String>,
}

/// Balance response from GET /v1/balance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceResponse {
    pub order_books: Option<HashMap<String, OrderBookBalance>>,
    pub total_locked: Option<String>,
    pub total_unlocked: Option<String>,
    pub trading_account_balance: Option<String>,
}

// ---------------------------------------------------------------------------
// Depth
// ---------------------------------------------------------------------------

/// A single depth level (price + quantity).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthLevel {
    pub price: String,
    pub quantity: String,
}

/// Depth snapshot from GET /v1/depth or WebSocket subscribe_depth.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthSnapshot {
    pub buys: Option<Vec<DepthLevel>>,
    pub sells: Option<Vec<DepthLevel>>,
}

/// Depth update from WebSocket subscribe_depth_update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthUpdate {
    pub action: Option<String>,
    pub changes: Option<DepthSnapshot>,
    #[serde(alias = "view")]
    pub view: Option<DepthSnapshot>,
    pub market_id: Option<String>,
    pub onchain_timestamp: Option<String>,
    pub seen_timestamp: Option<String>,
}

// ---------------------------------------------------------------------------
// Bars
// ---------------------------------------------------------------------------

/// OHLCV bar/candle data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bar {
    pub open: Option<String>,
    pub high: Option<String>,
    pub low: Option<String>,
    pub close: Option<String>,
    pub volume: Option<String>,
    pub timestamp: Option<serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Session Actions
// ---------------------------------------------------------------------------

/// A CreateOrder action payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateOrderAction {
    pub side: String,
    pub price: String,
    pub quantity: String,
    pub order_type: serde_json::Value,
}

/// A CancelOrder action payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelOrderAction {
    pub order_id: String,
}

/// A SettleBalance action payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SettleBalanceAction {
    pub to: Identity,
}

/// A single action in the actions request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ActionItem {
    CreateOrder {
        #[serde(rename = "CreateOrder")]
        create_order: CreateOrderAction,
    },
    CancelOrder {
        #[serde(rename = "CancelOrder")]
        cancel_order: CancelOrderAction,
    },
    SettleBalance {
        #[serde(rename = "SettleBalance")]
        settle_balance: SettleBalanceAction,
    },
    RegisterReferer {
        #[serde(rename = "RegisterReferer")]
        register_referer: SettleBalanceAction,
    },
}

/// A market-grouped set of actions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct MarketActions {
    pub market_id: MarketId,
    pub actions: Vec<serde_json::Value>,
}

/// Request body for POST /v1/session/actions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct SessionActionsRequest {
    pub actions: Vec<MarketActions>,
    pub signature: Signature,
    pub nonce: String,
    pub trade_account_id: TradeAccountId,
    pub session_id: Identity,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collect_orders: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variable_outputs: Option<u32>,
}

/// Response from POST /v1/session/actions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionActionsResponse {
    pub tx_id: Option<String>,
    pub orders: Option<Vec<Order>>,
    // Error fields
    pub code: Option<u32>,
    pub message: Option<String>,
    pub reason: Option<String>,
    pub receipts: Option<serde_json::Value>,
}

impl SessionActionsResponse {
    /// Returns true if the response indicates success (has tx_id).
    pub fn is_success(&self) -> bool {
        self.tx_id.is_some()
    }

    /// Returns true if this is a pre-flight validation error (has code field).
    pub fn is_preflight_error(&self) -> bool {
        self.code.is_some() && self.tx_id.is_none()
    }

    /// Returns true if this is an on-chain revert error (has message but no code).
    pub fn is_onchain_error(&self) -> bool {
        self.message.is_some() && self.code.is_none() && self.tx_id.is_none()
    }
}

// ---------------------------------------------------------------------------
// Withdraw
// ---------------------------------------------------------------------------

/// Request body for POST /v1/accounts/withdraw.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WithdrawRequest {
    pub trade_account_id: TradeAccountId,
    pub signature: Signature,
    pub nonce: String,
    pub to: Identity,
    pub asset_id: AssetId,
    pub amount: String,
}

/// Response from POST /v1/accounts/withdraw.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WithdrawResponse {
    pub tx_id: Option<String>,
    pub code: Option<u32>,
    pub message: Option<String>,
}

// ---------------------------------------------------------------------------
// Whitelist
// ---------------------------------------------------------------------------

/// Request body for POST /analytics/v1/whitelist.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhitelistRequest {
    #[serde(rename = "tradeAccount")]
    pub trade_account: String,
}

/// Response from POST /analytics/v1/whitelist.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhitelistResponse {
    pub success: Option<bool>,
    #[serde(rename = "tradeAccount")]
    pub trade_account: Option<String>,
    #[serde(rename = "alreadyWhitelisted")]
    pub already_whitelisted: Option<bool>,
}

// ---------------------------------------------------------------------------
// Faucet
// ---------------------------------------------------------------------------

/// Response from faucet mint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaucetResponse {
    pub message: Option<String>,
    pub error: Option<String>,
}

// ---------------------------------------------------------------------------
// Referral
// ---------------------------------------------------------------------------

/// Response from GET /analytics/v1/referral/code-info.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferralInfo {
    pub valid: Option<bool>,
    #[serde(rename = "ownerAddress")]
    pub owner_address: Option<String>,
    #[serde(rename = "isActive")]
    pub is_active: Option<bool>,
}

// ---------------------------------------------------------------------------
// Aggregated
// ---------------------------------------------------------------------------

/// Asset from GET /v1/aggregated/assets.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedAsset {
    pub id: Option<String>,
    pub symbol: Option<String>,
    pub name: Option<String>,
}

/// Aggregated orderbook from GET /v1/aggregated/orderbook.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedOrderbook {
    pub asks: Option<Vec<Vec<String>>>,
    pub bids: Option<Vec<Vec<String>>>,
    pub timestamp: Option<serde_json::Value>,
}

/// Pair summary from GET /v1/aggregated/summary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PairSummary {
    pub trading_pairs: Option<String>,
    pub last_price: Option<String>,
    pub lowest_ask: Option<String>,
    pub highest_bid: Option<String>,
    pub base_volume: Option<String>,
    pub quote_volume: Option<String>,
    pub price_change_percent_24h: Option<String>,
    pub highest_price_24h: Option<String>,
    pub lowest_price_24h: Option<String>,
}

/// Pair ticker from GET /v1/aggregated/ticker.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PairTicker {
    pub ticker_id: Option<String>,
    pub base_currency: Option<String>,
    pub target_currency: Option<String>,
    pub last_price: Option<String>,
    pub base_volume: Option<String>,
    pub target_volume: Option<String>,
    pub bid: Option<String>,
    pub ask: Option<String>,
    pub high: Option<String>,
    pub low: Option<String>,
}

// ---------------------------------------------------------------------------
// WebSocket messages
// ---------------------------------------------------------------------------

/// WebSocket order update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderUpdate {
    pub action: Option<String>,
    pub orders: Option<Vec<Order>>,
    pub onchain_timestamp: Option<String>,
    pub seen_timestamp: Option<String>,
}

/// WebSocket trade update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeUpdate {
    pub action: Option<String>,
    pub trades: Option<Vec<Trade>>,
    pub market_id: Option<String>,
    pub onchain_timestamp: Option<String>,
    pub seen_timestamp: Option<String>,
}

/// WebSocket balance entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceEntry {
    pub identity: Option<Identity>,
    pub asset_id: Option<String>,
    pub total_locked: Option<String>,
    pub total_unlocked: Option<String>,
    pub trading_account_balance: Option<String>,
    pub order_books: Option<HashMap<String, OrderBookBalance>>,
}

/// WebSocket balance update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceUpdate {
    pub action: Option<String>,
    pub balance: Option<Vec<BalanceEntry>>,
    pub onchain_timestamp: Option<String>,
    pub seen_timestamp: Option<String>,
}

/// WebSocket nonce update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NonceUpdate {
    pub action: Option<String>,
    pub contract_id: Option<String>,
    pub nonce: Option<String>,
    pub onchain_timestamp: Option<String>,
    pub seen_timestamp: Option<String>,
}

/// Generic WebSocket message for initial parsing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WsMessage {
    pub action: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Transaction result for simple operations (cancel, settle).
#[derive(Debug, Clone)]
pub struct TxResult {
    pub tx_id: String,
    pub orders: Vec<Order>,
}