o2-sdk 0.2.0

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
/// REST API client for O2 Exchange.
///
/// Typed wrappers for every REST endpoint from the O2 API reference.
/// Uses reqwest for HTTP with JSON support.
use std::any::type_name;

use log::debug;
use reqwest::Client;
use serde_json::json;

use crate::config::NetworkConfig;
use crate::errors::O2Error;
use crate::models::*;

/// Low-level REST API client for the O2 Exchange.
#[derive(Debug, Clone)]
pub struct O2Api {
    client: Client,
    config: NetworkConfig,
}

impl O2Api {
    /// Create a new API client with the given network configuration.
    pub fn new(config: NetworkConfig) -> Self {
        Self {
            client: Client::new(),
            config,
        }
    }

    /// Parse an API response, detecting error codes and returning typed errors.
    async fn parse_response<T: serde::de::DeserializeOwned>(
        &self,
        response: reqwest::Response,
    ) -> Result<T, O2Error> {
        let status = response.status();
        let text = response.text().await?;
        let target_type = type_name::<T>();
        debug!(
            "api.parse_response status={} target_type={} body_len={}",
            status,
            target_type,
            text.len()
        );

        if !status.is_success() {
            debug!(
                "api.parse_response non_success status={} body={}",
                status, text
            );
            // Try to parse as API error
            if let Ok(err) = serde_json::from_str::<serde_json::Value>(&text) {
                if let Some(code) = err.get("code").and_then(|c| c.as_u64()) {
                    let raw_message = err
                        .get("message")
                        .or_else(|| err.get("error"))
                        .and_then(|m| m.as_str())
                        .unwrap_or("Unknown error");
                    // Augment revert messages even on code-based errors —
                    // the backend sometimes returns code=1000 with revert
                    // info in the message field.
                    let message = if raw_message.contains("Revert")
                        || raw_message.contains("revert")
                        || raw_message.contains("Panic")
                    {
                        let reason = err.get("reason").and_then(|r| r.as_str()).unwrap_or("");
                        let receipts = err.get("receipts").cloned();
                        crate::onchain_revert::augment_revert_reason(
                            raw_message,
                            reason,
                            receipts.as_ref(),
                        )
                    } else {
                        raw_message.to_string()
                    };
                    return Err(O2Error::from_code(code as u32, message));
                }
                if let Some(message) = err
                    .get("message")
                    .or_else(|| err.get("error"))
                    .and_then(|m| m.as_str())
                {
                    let raw_reason = err.get("reason").and_then(|r| r.as_str()).unwrap_or("");
                    let receipts = err.get("receipts").cloned();
                    let has_receipts = receipts.as_ref().is_some_and(|v| !v.is_null());
                    let has_revert_evidence = raw_reason.contains("Revert")
                        || raw_reason.to_lowercase().contains("receipt")
                        || message.to_lowercase().contains("transaction");

                    // Only classify as OnChainRevert when there's evidence of
                    // an on-chain transaction.  Plain API errors (e.g. analytics
                    // 500) should be generic HttpError, not OnChainRevert.
                    if has_receipts || has_revert_evidence {
                        let reason = crate::onchain_revert::augment_revert_reason(
                            message,
                            raw_reason,
                            receipts.as_ref(),
                        );
                        return Err(O2Error::OnChainRevert {
                            message: message.to_string(),
                            reason,
                            receipts,
                        });
                    }

                    return Err(O2Error::HttpError(format!("HTTP {}: {}", status, message)));
                }
            }
            return Err(O2Error::HttpError(format!("HTTP {}: {}", status, text)));
        }

        match serde_json::from_str(&text) {
            Ok(parsed) => {
                debug!("api.parse_response decode_ok target_type={}", target_type);
                Ok(parsed)
            }
            Err(e) => {
                debug!(
                    "api.parse_response decode_failed target_type={} error={}",
                    target_type, e
                );
                Err(O2Error::JsonError(format!(
                    "Failed to parse response: {e}\nBody: {}",
                    &text[..text.len().min(500)]
                )))
            }
        }
    }

    // -----------------------------------------------------------------------
    // Market Data
    // -----------------------------------------------------------------------

    /// GET /v1/markets - List all markets.
    pub async fn get_markets(&self) -> Result<MarketsResponse, O2Error> {
        debug!("api.get_markets");
        let url = format!("{}/v1/markets", self.config.api_base);
        let resp = self.client.get(&url).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/markets/summary - 24-hour market statistics.
    pub async fn get_market_summary(&self, market_id: &str) -> Result<Vec<MarketSummary>, O2Error> {
        debug!("api.get_market_summary market_id={}", market_id);
        let url = format!("{}/v1/markets/summary", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("market_id", market_id)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/markets/ticker - Real-time ticker data.
    pub async fn get_market_ticker(&self, market_id: &str) -> Result<Vec<MarketTicker>, O2Error> {
        debug!("api.get_market_ticker market_id={}", market_id);
        let url = format!("{}/v1/markets/ticker", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("market_id", market_id)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

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

    /// GET /v1/depth - Order book depth.
    pub async fn get_depth(
        &self,
        market_id: &str,
        precision: u64,
        limit: Option<usize>,
    ) -> Result<DepthSnapshot, O2Error> {
        debug!(
            "api.get_depth market_id={} precision={} limit={:?}",
            market_id, precision, limit
        );
        let url = format!("{}/v1/depth", self.config.api_base);
        let precision_str = precision.to_string();
        let mut pairs: Vec<(&str, String)> = vec![
            ("market_id", market_id.to_string()),
            ("precision", precision_str),
        ];
        if let Some(lim) = limit {
            pairs.push(("limit", lim.to_string()));
        }
        let resp = self
            .client
            .get(&url)
            .query(
                &pairs
                    .iter()
                    .map(|(k, v)| (*k, v.as_str()))
                    .collect::<Vec<_>>(),
            )
            .send()
            .await?;
        let val: serde_json::Value = self.parse_response(resp).await?;
        // API wraps depth in "orders" or "view" field; unwrap it
        let depth = val
            .get("orders")
            .or_else(|| val.get("view"))
            .unwrap_or(&val);
        let mut snapshot: DepthSnapshot = serde_json::from_value(depth.clone())
            .map_err(|e| O2Error::JsonError(format!("Failed to parse depth: {e}")))?;
        // Client-side truncation: honour the limit even if the backend
        // doesn't support it yet.
        if let Some(lim) = limit {
            snapshot.bids.truncate(lim);
            snapshot.asks.truncate(lim);
        }
        Ok(snapshot)
    }

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

    /// GET /v1/trades - Recent trade history.
    pub async fn get_trades(
        &self,
        market_id: &str,
        direction: &str,
        count: u32,
        start_timestamp: Option<u64>,
        start_trade_id: Option<&str>,
        contract: Option<&str>,
    ) -> Result<TradesResponse, O2Error> {
        debug!(
            "api.get_trades market_id={} direction={} count={} contract={:?}",
            market_id, direction, count, contract
        );
        let url = format!("{}/v1/trades", self.config.api_base);
        let count_str = count.to_string();
        let start_timestamp_str = start_timestamp.map(|ts| ts.to_string());
        let mut query: Vec<(&str, &str)> = vec![
            ("market_id", market_id),
            ("direction", direction),
            ("count", count_str.as_str()),
        ];
        if let Some(ts) = start_timestamp_str.as_deref() {
            query.push(("start_timestamp", ts));
        }
        if let Some(tid) = start_trade_id {
            query.push(("start_trade_id", tid));
        }
        if let Some(c) = contract {
            query.push(("contract", c));
        }
        let resp = self.client.get(&url).query(&query).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/trades_by_account - Trades by account.
    pub async fn get_trades_by_account(
        &self,
        market_id: &str,
        contract: &str,
        direction: &str,
        count: u32,
        start_timestamp: Option<u64>,
        start_trade_id: Option<&str>,
    ) -> Result<TradesResponse, O2Error> {
        debug!(
            "api.get_trades_by_account market_id={} contract={} direction={} count={}",
            market_id, contract, direction, count
        );
        let url = format!("{}/v1/trades_by_account", self.config.api_base);
        let count_str = count.to_string();
        let start_timestamp_str = start_timestamp.map(|ts| ts.to_string());
        let mut query: Vec<(&str, &str)> = vec![
            ("market_id", market_id),
            ("contract", contract),
            ("direction", direction),
            ("count", count_str.as_str()),
        ];
        if let Some(ts) = start_timestamp_str.as_deref() {
            query.push(("start_timestamp", ts));
        }
        if let Some(tid) = start_trade_id {
            query.push(("start_trade_id", tid));
        }
        let resp = self.client.get(&url).query(&query).send().await?;
        self.parse_response(resp).await
    }

    /// Valid bar resolutions accepted by the API.
    const VALID_RESOLUTIONS: &'static [&'static str] = &[
        "1s", "1m", "2m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d",
        "3d", "1w", "1M", "3M",
    ];

    /// GET /v1/bars - OHLCV candlestick data.
    ///
    /// `from_ts` and `to_ts` are in **milliseconds** (not seconds).
    /// `resolution` must be one of: `1s`, `1m`, `2m`, `3m`, `5m`, `15m`, `30m`,
    /// `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`, `3d`, `1w`, `1M`, `3M`.
    pub async fn get_bars(
        &self,
        market_id: &str,
        from_ts: u64,
        to_ts: u64,
        resolution: &str,
    ) -> Result<Vec<Bar>, O2Error> {
        if !Self::VALID_RESOLUTIONS.contains(&resolution) {
            return Err(O2Error::InvalidRequest(format!(
                "Invalid bar resolution \"{resolution}\". Valid values: {:?}",
                Self::VALID_RESOLUTIONS
            )));
        }
        debug!(
            "api.get_bars market_id={} from_ts={} to_ts={} resolution={}",
            market_id, from_ts, to_ts, resolution
        );
        let url = format!("{}/v1/bars", self.config.api_base);
        let from_ts_str = from_ts.to_string();
        let to_ts_str = to_ts.to_string();
        let resp = self
            .client
            .get(&url)
            .query(&[
                ("market_id", market_id),
                ("from", from_ts_str.as_str()),
                ("to", to_ts_str.as_str()),
                ("resolution", resolution),
            ])
            .send()
            .await?;
        let val: serde_json::Value = self.parse_response(resp).await?;
        let bars_val = val.get("bars").unwrap_or(&val);
        serde_json::from_value(bars_val.clone())
            .map_err(|e| O2Error::JsonError(format!("Failed to parse bars: {e}")))
    }

    // -----------------------------------------------------------------------
    // Account & Balance
    // -----------------------------------------------------------------------

    /// POST /v1/accounts - Create a trading account.
    pub async fn create_account(
        &self,
        owner_address: &str,
    ) -> Result<CreateAccountResponse, O2Error> {
        debug!("api.create_account owner_address={}", owner_address);
        let url = format!("{}/v1/accounts", self.config.api_base);
        let body = json!({
            "identity": {
                "Address": owner_address
            }
        });
        let resp = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/accounts - Get account info by owner address.
    pub async fn get_account_by_owner(&self, owner: &str) -> Result<AccountResponse, O2Error> {
        debug!("api.get_account_by_owner owner={}", owner);
        let url = format!("{}/v1/accounts", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("owner", owner)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/accounts - Get account info by trade_account_id.
    pub async fn get_account_by_id(
        &self,
        trade_account_id: &str,
    ) -> Result<AccountResponse, O2Error> {
        debug!(
            "api.get_account_by_id trade_account_id={}",
            trade_account_id
        );
        let url = format!("{}/v1/accounts", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("trade_account_id", trade_account_id)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/balance - Get asset balance.
    pub async fn get_balance(
        &self,
        asset_id: &str,
        contract: Option<&str>,
        address: Option<&str>,
    ) -> Result<BalanceResponse, O2Error> {
        debug!(
            "api.get_balance asset_id={} contract={:?} address={:?}",
            asset_id, contract, address
        );
        let url = format!("{}/v1/balance", self.config.api_base);
        let mut query: Vec<(&str, &str)> = vec![("asset_id", asset_id)];
        if let Some(c) = contract {
            query.push(("contract", c));
        }
        if let Some(a) = address {
            query.push(("address", a));
        }
        let resp = self.client.get(&url).query(&query).send().await?;
        self.parse_response(resp).await
    }

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

    /// GET /v1/orders - Get order history.
    #[allow(clippy::too_many_arguments)]
    pub async fn get_orders(
        &self,
        market_id: &str,
        contract: &str,
        direction: &str,
        count: u32,
        is_open: Option<bool>,
        start_timestamp: Option<u64>,
        start_order_id: Option<&str>,
    ) -> Result<OrdersResponse, O2Error> {
        debug!(
            "api.get_orders market_id={} contract={} direction={} count={} is_open={:?} start_timestamp={:?} start_order_id={:?}",
            market_id, contract, direction, count, is_open, start_timestamp, start_order_id
        );
        let url = format!("{}/v1/orders", self.config.api_base);
        let count_str = count.to_string();
        let is_open_str = is_open.map(|open| open.to_string());
        let start_timestamp_str = start_timestamp.map(|ts| ts.to_string());
        let mut query: Vec<(&str, &str)> = vec![
            ("market_id", market_id),
            ("contract", contract),
            ("direction", direction),
            ("count", count_str.as_str()),
        ];
        if let Some(open) = is_open_str.as_deref() {
            query.push(("is_open", open));
        }
        if let Some(ts) = start_timestamp_str.as_deref() {
            query.push(("start_timestamp", ts));
        }
        if let Some(oid) = start_order_id {
            query.push(("start_order_id", oid));
        }
        let resp = self.client.get(&url).query(&query).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/order - Get a single order.
    pub async fn get_order(&self, market_id: &str, order_id: &str) -> Result<Order, O2Error> {
        debug!(
            "api.get_order market_id={} order_id={}",
            market_id, order_id
        );
        let url = format!("{}/v1/order", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("market_id", market_id), ("order_id", order_id)])
            .send()
            .await?;
        let val: serde_json::Value = self.parse_response(resp).await?;
        // API wraps order in an "order" key
        let order_val = val.get("order").unwrap_or(&val);
        serde_json::from_value(order_val.clone())
            .map_err(|e| O2Error::JsonError(format!("Failed to parse order: {e}")))
    }

    // -----------------------------------------------------------------------
    // Session Management
    // -----------------------------------------------------------------------

    /// PUT /v1/session - Create or update a trading session.
    pub async fn create_session(
        &self,
        owner_id: &str,
        request: &SessionRequest,
    ) -> Result<SessionResponse, O2Error> {
        debug!(
            "api.create_session owner_id={} contract_id={} nonce={} expiry={}",
            owner_id, request.contract_id, request.nonce, request.expiry
        );
        let url = format!("{}/v1/session", self.config.api_base);
        let resp = self
            .client
            .put(&url)
            .header("Content-Type", "application/json")
            .header("O2-Owner-Id", owner_id)
            .json(request)
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// POST /v1/session/actions - Execute trading actions.
    pub(crate) async fn submit_actions(
        &self,
        owner_id: &str,
        request: &SessionActionsRequest,
    ) -> Result<SessionActionsResponse, O2Error> {
        debug!(
            "api.submit_actions owner_id={} nonce={} markets={} collect_orders={:?}",
            owner_id,
            request.nonce,
            request.actions.len(),
            request.collect_orders
        );
        let url = format!("{}/v1/session/actions", self.config.api_base);
        let resp = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("O2-Owner-Id", owner_id)
            .json(request)
            .send()
            .await?;
        // Reuse standard status/error handling first; this ensures non-2xx
        // responses are mapped consistently with the rest of the SDK.
        let val: serde_json::Value = self.parse_response(resp).await?;

        // Parse as Value first for robustness, then extract fields.
        // The Order struct can have unexpected field types across API versions,
        // so we parse orders separately with a fallback.
        let tx_id = val.get("tx_id").and_then(|v| v.as_str()).map(TxId::from);
        let code = val.get("code").and_then(|v| v.as_u64()).map(|v| v as u32);
        let message = val
            .get("message")
            .and_then(|v| v.as_str())
            .map(String::from);
        let reason = val.get("reason").and_then(|v| v.as_str()).map(String::from);
        let receipts = val.get("receipts").cloned();
        let orders = val
            .get("orders")
            .and_then(|o| serde_json::from_value::<Vec<Order>>(o.clone()).ok());

        let parsed = SessionActionsResponse {
            tx_id,
            orders,
            code,
            message,
            reason,
            receipts,
        };

        // Check for errors
        if parsed.is_success() {
            debug!("api.submit_actions parsed=success tx_id={:?}", parsed.tx_id);
            Ok(parsed)
        } else if parsed.is_preflight_error() {
            let code = parsed.code.unwrap_or(0);
            let message = parsed.message.unwrap_or_default();
            debug!(
                "api.submit_actions parsed=preflight_error code={} message={}",
                code, message
            );
            Err(O2Error::from_code(code, message))
        } else if parsed.is_onchain_error() {
            debug!(
                "api.submit_actions parsed=onchain_error message={:?} reason={:?}",
                parsed.message, parsed.reason
            );
            let message = parsed.message.unwrap_or_default();
            let raw_reason = parsed.reason.unwrap_or_default();
            let reason = crate::onchain_revert::augment_revert_reason(
                &message,
                &raw_reason,
                parsed.receipts.as_ref(),
            );
            Err(O2Error::OnChainRevert {
                message,
                reason,
                receipts: parsed.receipts,
            })
        } else {
            // Ambiguous — return as-is for caller to handle
            debug!("api.submit_actions parsed=ambiguous returning_raw_response");
            Ok(parsed)
        }
    }

    // -----------------------------------------------------------------------
    // Account Operations
    // -----------------------------------------------------------------------

    /// POST /v1/accounts/withdraw - Withdraw assets.
    pub async fn withdraw(
        &self,
        owner_id: &str,
        request: &WithdrawRequest,
    ) -> Result<WithdrawResponse, O2Error> {
        debug!(
            "api.withdraw owner_id={} trade_account_id={} asset_id={} amount={} nonce={}",
            owner_id, request.trade_account_id, request.asset_id, request.amount, request.nonce
        );
        let url = format!("{}/v1/accounts/withdraw", self.config.api_base);
        let resp = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("O2-Owner-Id", owner_id)
            .json(request)
            .send()
            .await?;
        self.parse_response(resp).await
    }

    // -----------------------------------------------------------------------
    // Analytics
    // -----------------------------------------------------------------------

    /// POST /analytics/v1/whitelist - Whitelist a trading account.
    pub async fn whitelist_account(
        &self,
        trade_account_id: &str,
    ) -> Result<WhitelistResponse, O2Error> {
        debug!(
            "api.whitelist_account trade_account_id={}",
            trade_account_id
        );
        let url = format!("{}/analytics/v1/whitelist", self.config.api_base);
        let body = WhitelistRequest {
            trade_account: trade_account_id.to_string(),
        };
        let resp = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /analytics/v1/referral/code-info - Look up referral code.
    pub async fn get_referral_info(&self, code: &str) -> Result<ReferralInfo, O2Error> {
        debug!("api.get_referral_info code={}", code);
        let url = format!("{}/analytics/v1/referral/code-info", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("code", code)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    // -----------------------------------------------------------------------
    // Aggregated Endpoints
    // -----------------------------------------------------------------------

    /// GET /v1/aggregated/assets - List all trading assets.
    pub async fn get_aggregated_assets(&self) -> Result<AggregatedAssets, O2Error> {
        debug!("api.get_aggregated_assets");
        let url = format!("{}/v1/aggregated/assets", self.config.api_base);
        let resp = self.client.get(&url).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/orderbook - Order book depth by pair name.
    pub async fn get_aggregated_orderbook(
        &self,
        market_pair: &str,
        depth: u32,
        level: u32,
    ) -> Result<AggregatedOrderbook, O2Error> {
        debug!(
            "api.get_aggregated_orderbook market_pair={} depth={} level={}",
            market_pair, depth, level
        );
        let url = format!("{}/v1/aggregated/orderbook", self.config.api_base);
        let depth_str = depth.to_string();
        let level_str = level.to_string();
        let resp = self
            .client
            .get(&url)
            .query(&[
                ("market_pair", market_pair),
                ("depth", depth_str.as_str()),
                ("level", level_str.as_str()),
            ])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/coingecko/orderbook - CoinGecko orderbook depth by ticker ID.
    pub async fn get_aggregated_coingecko_orderbook(
        &self,
        ticker_id: &str,
        depth: u32,
    ) -> Result<CoingeckoAggregatedOrderbook, O2Error> {
        debug!(
            "api.get_aggregated_coingecko_orderbook ticker_id={} depth={}",
            ticker_id, depth
        );
        let url = format!("{}/v1/aggregated/coingecko/orderbook", self.config.api_base);
        let depth_str = depth.to_string();
        let resp = self
            .client
            .get(&url)
            .query(&[("ticker_id", ticker_id), ("depth", depth_str.as_str())])
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/summary - 24-hour stats for all pairs.
    pub async fn get_aggregated_summary(&self) -> Result<Vec<PairSummary>, O2Error> {
        debug!("api.get_aggregated_summary");
        let url = format!("{}/v1/aggregated/summary", self.config.api_base);
        let resp = self.client.get(&url).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/ticker - Real-time ticker for all pairs.
    pub async fn get_aggregated_ticker(&self) -> Result<AggregatedTicker, O2Error> {
        debug!("api.get_aggregated_ticker");
        let url = format!("{}/v1/aggregated/ticker", self.config.api_base);
        let resp = self.client.get(&url).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/coingecko/tickers - CoinGecko ticker format.
    pub async fn get_aggregated_coingecko_tickers(&self) -> Result<Vec<PairTicker>, O2Error> {
        debug!("api.get_aggregated_coingecko_tickers");
        let url = format!("{}/v1/aggregated/coingecko/tickers", self.config.api_base);
        let resp = self.client.get(&url).send().await?;
        self.parse_response(resp).await
    }

    /// GET /v1/aggregated/trades - Recent trades for a pair.
    pub async fn get_aggregated_trades(
        &self,
        market_pair: &str,
    ) -> Result<Vec<AggregatedTrade>, O2Error> {
        debug!("api.get_aggregated_trades market_pair={}", market_pair);
        let url = format!("{}/v1/aggregated/trades", self.config.api_base);
        let resp = self
            .client
            .get(&url)
            .query(&[("market_pair", market_pair)])
            .send()
            .await?;
        self.parse_response(resp).await
    }

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

    /// Mint tokens to a wallet address via the faucet (testnet/devnet only).
    pub async fn mint_to_address(&self, address: &str) -> Result<FaucetResponse, O2Error> {
        debug!("api.mint_to_address address={}", address);
        let faucet_url = self
            .config
            .faucet_url
            .as_ref()
            .ok_or_else(|| O2Error::Other("Faucet not available on this network".into()))?;

        let body = json!({ "address": address });
        let resp = self
            .client
            .post(faucet_url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?;
        self.parse_response(resp).await
    }

    /// Mint tokens directly to a trading account contract via the faucet (testnet/devnet only).
    pub async fn mint_to_contract(&self, contract_id: &str) -> Result<FaucetResponse, O2Error> {
        debug!("api.mint_to_contract contract_id={}", contract_id);
        let faucet_url = self
            .config
            .faucet_url
            .as_ref()
            .ok_or_else(|| O2Error::Other("Faucet not available on this network".into()))?;

        let body = json!({ "contract": contract_id });
        let resp = self
            .client
            .post(faucet_url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?;
        self.parse_response(resp).await
    }
}