Skip to main content

hypercall_client/
api.rs

1//! HTTP client for the Hypercall REST API.
2//!
3//! [`HypercallClient`] provides typed methods for every REST endpoint:
4//! orders, markets, portfolio, margin mode, fills, and more.
5#![expect(
6    clippy::result_large_err,
7    reason = "these methods preserve the established unboxed public ClientError contract"
8)]
9//!
10//! # Example
11//!
12//! ```rust,no_run
13//! use hypercall_client::{HypercallClient, HypercallWallet};
14//! use hypercall_sdk_types::{Side, TimeInForce};
15//! use rust_decimal::Decimal;
16//!
17//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
18//! let api = HypercallClient::new("https://api.hypercall.xyz");
19//! let wallet = HypercallWallet::from_private_key("0x...", 999)?;
20//!
21//! // Get markets
22//! let markets = api.get_markets().await?;
23//!
24//! // Get portfolio
25//! let portfolio = api.get_portfolio(&wallet.address).await?;
26//!
27//! // Place an options order (typed args)
28//! let resp = api.place_order(&wallet, "BTC-20260501-76000-C", Side::Buy, Decimal::new(2000, 0), Decimal::new(5, 0), TimeInForce::IOC).await?;
29//!
30//! // Cancel an order
31//! api.cancel_order(&wallet, 12345).await?;
32//!
33//! // Set margin mode to the launch default.
34//! api.set_margin_mode(&wallet, "standard").await?;
35//! # Ok(())
36//! # }
37//! ```
38//!
39use std::time::Duration;
40
41use reqwest::{redirect::Policy as RedirectPolicy, Client, Method, RequestBuilder};
42use rust_decimal::Decimal;
43use serde::Serialize;
44use sonic_rs::{json, JsonContainerTrait, JsonValueTrait, Value};
45use tracing::{info, warn};
46
47use hypercall_sdk_types::{
48    api_models::MarketsResponse, ApiResponse, BulkCancelOrderResponse, BulkPlaceOrderRequest,
49    BulkPlaceOrderResponse, ExchangeInfoResponse, HistoricalPnlInterval, HistoricalPnlResponse,
50    HistoricalTheoInterval, HistoricalTheoResponse, InstrumentSpecResponse, JsonRpcResponse,
51    LiquidationStatusData, LiquidationStatusResponse, MarginMode, Market, OptionSummary, Order,
52    OrderMessage, OrderRoute, OrdersApiResponse, PlaceOrderRequest, Portfolio, PortfolioResponse,
53    PublicLiquidationsResponse, ReplaceOrderRequest, Side, StandardMarginLiquidationOrderRequest,
54    StandardMarginLiquidationOrderResponse, StandardMarginLiquidationPositionRequest, TimeInForce,
55    WalletAddress,
56};
57
58use crate::error::{ClientError, Result, RfqInputError};
59use crate::wallet::{
60    AccountAddress, CancelOrderSignature, HypercallSigner, HypercallWallet, PlaceOrderSignature,
61    ReplaceOrderSignature, StandardMarginLiquidationSignature,
62};
63
64const API_ROUTE_ORDER: &str = "/order";
65const API_ROUTE_BULK_ORDER: &str = "/bulk_order";
66const API_ROUTE_ORDERS: &str = "/orders";
67const API_ROUTE_USERNAME: &str = "/username";
68const API_ROUTE_MARGIN_MODE: &str = "/margin-mode";
69const API_ROUTE_LIQUIDATION_STATUS: &str = "/liquidation/status";
70const API_ROUTE_STANDARD_MARGIN_LIQUIDATION: &str = "/liquidation/standard-margin";
71const API_ROUTE_RFQ_REQUEST: &str = "/rfq/request";
72const API_ROUTE_RFQ_ACCEPT: &str = "/rfq/accept";
73
74#[derive(Debug, serde::Deserialize)]
75pub struct UsernameLookupResponse {
76    pub wallet_address: String,
77    pub username: String,
78}
79
80#[derive(Debug, Clone, Default)]
81pub struct PublicLiquidationsQuery {
82    pub cursor: Option<String>,
83    pub limit: Option<usize>,
84    pub wallet: Option<String>,
85    pub status: Option<String>,
86    pub state: Option<String>,
87    pub margin_mode: Option<String>,
88    pub liquidation_mode: Option<String>,
89}
90
91#[derive(Debug, serde::Deserialize)]
92#[serde(untagged)]
93enum UsernameLookupEnvelope {
94    Wrapped(ApiResponse<UsernameLookupResponse>),
95    Direct(UsernameLookupResponse),
96}
97
98/// Deserialize a reqwest response body using sonic-rs instead of reqwest's built-in serde_json.
99/// This is necessary because sonic_rs::Value cannot be deserialized by serde_json's deserializer.
100async fn sonic_json<T: serde::de::DeserializeOwned>(response: reqwest::Response) -> Result<T> {
101    let bytes = response.bytes().await?;
102    sonic_rs::from_slice(&bytes).map_err(ClientError::from)
103}
104
105async fn reqwest_json<T: serde::de::DeserializeOwned>(response: reqwest::Response) -> Result<T> {
106    Ok(response.json().await?)
107}
108
109fn non_empty_username(username: String) -> Option<String> {
110    let username = username.trim();
111    if username.is_empty() {
112        None
113    } else {
114        Some(username.to_string())
115    }
116}
117
118fn signed_side(side: Side) -> &'static str {
119    match side {
120        Side::Buy => "Buy",
121        Side::Sell => "Sell",
122    }
123}
124
125fn signed_tif(tif: TimeInForce) -> &'static str {
126    match tif {
127        TimeInForce::GTC => "gtc",
128        TimeInForce::IOC => "ioc",
129        TimeInForce::FOK => "fok",
130    }
131}
132
133fn generated_client_id(nonce: u64) -> String {
134    format!("cli_{nonce}")
135}
136
137fn mmp_enabled_or_default(options: &OrderOptions) -> bool {
138    options.mmp_enabled.unwrap_or(false)
139}
140
141fn optional_wallet_address(address: Option<AccountAddress>) -> Option<WalletAddress> {
142    address.map(AccountAddress::into_wallet_address)
143}
144
145mod sealed {
146    pub trait Sealed {}
147}
148
149pub trait OrderDecimalInput: sealed::Sealed {
150    fn into_order_decimal(self) -> Decimal;
151}
152
153impl sealed::Sealed for Decimal {}
154
155impl OrderDecimalInput for Decimal {
156    fn into_order_decimal(self) -> Decimal {
157        self
158    }
159}
160
161#[cfg(feature = "test-utils")]
162impl sealed::Sealed for f64 {}
163
164#[cfg(feature = "test-utils")]
165impl OrderDecimalInput for f64 {
166    fn into_order_decimal(self) -> Decimal {
167        Decimal::from_f64_retain(self).expect("test order price/size must convert to Decimal")
168    }
169}
170
171#[derive(Debug, Clone, Default)]
172pub struct OrderOptions {
173    pub route: Option<OrderRoute>,
174    pub client_id: Option<String>,
175    pub reduce_only: Option<bool>,
176    pub mmp_enabled: Option<bool>,
177    pub builder_code_address: Option<AccountAddress>,
178}
179
180#[derive(Debug, Clone)]
181pub struct PlaceOrderParams<'a> {
182    pub account: AccountAddress,
183    pub symbol: &'a str,
184    pub side: Side,
185    pub price: Decimal,
186    pub size: Decimal,
187    pub tif: TimeInForce,
188    pub nonce: Option<u64>,
189    pub options: OrderOptions,
190}
191
192#[derive(Debug, Clone)]
193pub struct ReplaceOrderParams<'a> {
194    pub account: AccountAddress,
195    pub order_id: u64,
196    pub symbol: &'a str,
197    pub side: Side,
198    pub price: Decimal,
199    pub size: Decimal,
200    pub tif: TimeInForce,
201    pub nonce: Option<u64>,
202    pub options: OrderOptions,
203}
204
205#[derive(Debug, Clone)]
206pub struct BulkOrderParams<'a> {
207    pub symbol: &'a str,
208    pub side: Side,
209    pub price: Decimal,
210    pub size: Decimal,
211    pub tif: TimeInForce,
212    pub options: OrderOptions,
213}
214
215#[derive(Debug, Clone)]
216pub struct BulkReplaceOrderParams<'a> {
217    pub order_id: u64,
218    pub symbol: &'a str,
219    pub side: Side,
220    pub price: Decimal,
221    pub size: Decimal,
222    pub tif: TimeInForce,
223    pub options: OrderOptions,
224}
225
226#[derive(Debug, Clone)]
227pub struct StandardMarginLiquidationParams {
228    pub liquidated_wallet: AccountAddress,
229    /// Idempotency key for this bid. The API requires a UUIDv7 created
230    /// within the last hour (`Uuid::now_v7()`); reuse it only for retries.
231    pub request_id: uuid::Uuid,
232    pub auction_id: String,
233    pub bid_usdc: String,
234    pub positions: Vec<StandardMarginLiquidationPositionRequest>,
235    pub portfolio_hash: String,
236    pub auction_terms_hash: String,
237    pub auction_version: u64,
238    pub valuation_timestamp_ms: u64,
239    pub bid_intent_hash: String,
240    pub nonce: Option<u64>,
241}
242
243/// HTTP API client for Hypercall.
244#[derive(Clone)]
245pub struct HypercallClient {
246    client: Client,
247    base_url: String,
248    /// Cached offset between this host's clock and the API server's clock,
249    /// shared by clones. TEE perp nonces are stamped on the server clock.
250    pub(crate) server_clock: crate::tee_perp::ServerClock,
251}
252
253impl HypercallClient {
254    /// Create a new API client. Requests time out after 30 seconds.
255    pub fn new(base_url: impl Into<String>) -> Self {
256        Self::with_timeout(base_url, Duration::from_secs(30))
257    }
258
259    /// Create an API client whose requests time out after `timeout`. A
260    /// mutation that times out has an unknown outcome; with the `rfq-v2`
261    /// feature, RFQ V2 reports it as `ClientError::RfqV2SubmissionAmbiguous`
262    /// for reconciliation.
263    pub fn with_timeout(base_url: impl Into<String>, timeout: Duration) -> Self {
264        let client = Client::builder()
265            .redirect(RedirectPolicy::none())
266            .timeout(timeout)
267            .user_agent("hypercall-client/0.1")
268            .build()
269            .expect("failed to build reqwest client");
270
271        Self {
272            client,
273            base_url: base_url.into().trim_end_matches('/').to_string(),
274            server_clock: crate::tee_perp::ServerClock::default(),
275        }
276    }
277
278    /// Base URL used by this client.
279    pub fn base_url(&self) -> &str {
280        &self.base_url
281    }
282
283    fn route_url(&self, route: &str) -> String {
284        format!("{}{}", self.base_url, route)
285    }
286
287    pub(crate) fn request(&self, method: Method, route: &str) -> RequestBuilder {
288        self.client.request(method, self.route_url(route))
289    }
290
291    async fn ensure_success(
292        response: reqwest::Response,
293        action: &str,
294    ) -> Result<reqwest::Response> {
295        if response.status().is_success() {
296            return Ok(response);
297        }
298        let status = response.status().as_u16();
299        let text = response.text().await.unwrap_or_default();
300        Err(ClientError::Api {
301            status,
302            message: format!("{action}: {text}"),
303        })
304    }
305
306    async fn send(request: RequestBuilder, action: &str) -> Result<reqwest::Response> {
307        Self::ensure_success(request.send().await?, action).await
308    }
309
310    pub(crate) async fn send_reqwest_json<T: serde::de::DeserializeOwned>(
311        request: RequestBuilder,
312        action: &str,
313    ) -> Result<T> {
314        reqwest_json(Self::send(request, action).await?).await
315    }
316
317    async fn send_sonic_json<T: serde::de::DeserializeOwned>(
318        request: RequestBuilder,
319        action: &str,
320    ) -> Result<T> {
321        sonic_json(Self::send(request, action).await?).await
322    }
323
324    pub(crate) async fn send_json_body<T, B>(
325        request: RequestBuilder,
326        body: &B,
327        action: &str,
328    ) -> Result<T>
329    where
330        T: serde::de::DeserializeOwned,
331        B: Serialize + ?Sized,
332    {
333        Self::send_reqwest_json(request.json(body), action).await
334    }
335
336    async fn post_json_sonic<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
337    where
338        T: serde::de::DeserializeOwned,
339        B: Serialize + ?Sized,
340    {
341        Self::send_sonic_json(self.request(Method::POST, route).json(body), action).await
342    }
343
344    /// Send a raw POST request to a path with a JSON body.
345    pub async fn raw_post(&self, path: &str, body: &sonic_rs::Value) -> Result<reqwest::Response> {
346        let url = format!("{}{}", self.base_url, path);
347        let body_bytes = sonic_rs::to_vec(body)?;
348        Ok(self
349            .client
350            .post(&url)
351            .header("content-type", "application/json")
352            .body(body_bytes)
353            .send()
354            .await?)
355    }
356
357    /// Check API health.
358    pub async fn health_check(&self) -> Result<()> {
359        self.health_check_with_timeout(Duration::from_secs(30))
360            .await
361    }
362
363    /// Check API health using a custom request timeout.
364    pub async fn health_check_with_timeout(&self, timeout: Duration) -> Result<()> {
365        let response = self
366            .client
367            .get(format!("{}/health", self.base_url))
368            .timeout(timeout)
369            .send()
370            .await?;
371
372        if response.status().is_success() {
373            Ok(())
374        } else {
375            Err(ClientError::Api {
376                status: response.status().as_u16(),
377                message: "Health check failed".to_string(),
378            })
379        }
380    }
381
382    /// Check API readiness.
383    pub async fn ready_check(&self) -> Result<()> {
384        self.ready_check_with_timeout(Duration::from_secs(30)).await
385    }
386
387    /// Check API readiness using a custom request timeout.
388    pub async fn ready_check_with_timeout(&self, timeout: Duration) -> Result<()> {
389        let response = self
390            .client
391            .get(format!("{}/ready", self.base_url))
392            .timeout(timeout)
393            .send()
394            .await?;
395
396        if response.status().is_success() {
397            Ok(())
398        } else {
399            Err(ClientError::Api {
400                status: response.status().as_u16(),
401                message: "Readiness check failed".to_string(),
402            })
403        }
404    }
405
406    /// Get the public exchange configuration used for funding and signing.
407    pub async fn get_exchange_info(&self) -> Result<ExchangeInfoResponse> {
408        Self::send_reqwest_json(
409            self.client.get(format!("{}/exchange-info", self.base_url)),
410            "get exchange info",
411        )
412        .await
413    }
414
415    /// Get canonical instrument specifications for a currency.
416    pub async fn get_instrument_specs(
417        &self,
418        currency: &str,
419    ) -> Result<Vec<InstrumentSpecResponse>> {
420        let body: JsonRpcResponse<Vec<InstrumentSpecResponse>> = Self::send_reqwest_json(
421            self.client.get(format!(
422                "{}/instrument-specs?currency={}",
423                self.base_url, currency
424            )),
425            "get instrument specs",
426        )
427        .await?;
428        body.result.ok_or_else(|| ClientError::Api {
429            status: 200,
430            message: body
431                .error
432                .map(|err| err.message)
433                .unwrap_or_else(|| "No instrument specs returned".to_string()),
434        })
435    }
436
437    /// Get all markets.
438    pub async fn get_markets(&self) -> Result<Vec<Market>> {
439        let markets_response: MarketsResponse = Self::send_reqwest_json(
440            self.client.get(format!("{}/markets", self.base_url)),
441            "get markets",
442        )
443        .await?;
444        if !markets_response.success {
445            return Err(ClientError::Api {
446                status: 200,
447                message: "Markets endpoint reported failure".to_string(),
448            });
449        }
450
451        let mut markets = Vec::new();
452        for market_info in markets_response.data {
453            for instrument in market_info.instruments {
454                markets.push(Market {
455                    symbol: instrument.id.clone(),
456                    strike: instrument.strike,
457                    underlying: instrument.underlying.clone(),
458                    expiry: instrument.expiry,
459                    option_type: if instrument.option_type.eq_ignore_ascii_case("call") {
460                        hypercall_sdk_types::OptionType::Call
461                    } else {
462                        hypercall_sdk_types::OptionType::Put
463                    },
464                });
465            }
466        }
467        Ok(markets)
468    }
469
470    /// Place an order.
471    pub async fn place_order<P, Q>(
472        &self,
473        wallet: &HypercallWallet,
474        symbol: &str,
475        side: Side,
476        price: P,
477        size: Q,
478        tif: TimeInForce,
479    ) -> Result<OrderMessage>
480    where
481        P: OrderDecimalInput,
482        Q: OrderDecimalInput,
483    {
484        let nonce = wallet.next_nonce();
485        self.place_order_with_params(
486            wallet,
487            PlaceOrderParams {
488                account: wallet.address,
489                symbol,
490                side,
491                price: price.into_order_decimal(),
492                size: size.into_order_decimal(),
493                tif,
494                nonce: Some(nonce),
495                options: OrderOptions::default(),
496            },
497        )
498        .await
499    }
500
501    /// Place an order with an explicit nonce. Use this when you need to control
502    /// the nonce directly (e.g., retrying with a known nonce, or testing replay
503    /// protection). For normal usage, prefer `place_order()` which auto-increments.
504    pub async fn place_order_with_nonce(
505        &self,
506        wallet: &HypercallWallet,
507        nonce: u64,
508        order: BulkOrderParams<'_>,
509    ) -> Result<OrderMessage> {
510        self.place_order_with_params(
511            wallet,
512            PlaceOrderParams {
513                account: wallet.address,
514                symbol: order.symbol,
515                side: order.side,
516                price: order.price,
517                size: order.size,
518                tif: order.tif,
519                nonce: Some(nonce),
520                options: order.options,
521            },
522        )
523        .await
524    }
525
526    /// Place an order for a managed wallet/account with an explicit signer.
527    pub async fn place_order_for_wallet(
528        &self,
529        signer: &HypercallWallet,
530        account: AccountAddress,
531        order: BulkOrderParams<'_>,
532    ) -> Result<OrderMessage> {
533        self.place_order_with_params(
534            signer,
535            PlaceOrderParams {
536                account,
537                symbol: order.symbol,
538                side: order.side,
539                price: order.price,
540                size: order.size,
541                tif: order.tif,
542                nonce: None,
543                options: order.options,
544            },
545        )
546        .await
547    }
548
549    /// Place an order for a managed wallet/account with an explicit nonce.
550    pub async fn place_order_for_wallet_with_nonce(
551        &self,
552        signer: &HypercallWallet,
553        account: AccountAddress,
554        nonce: u64,
555        order: BulkOrderParams<'_>,
556    ) -> Result<OrderMessage> {
557        self.place_order_with_params(
558            signer,
559            PlaceOrderParams {
560                account,
561                symbol: order.symbol,
562                side: order.side,
563                price: order.price,
564                size: order.size,
565                tif: order.tif,
566                nonce: Some(nonce),
567                options: order.options,
568            },
569        )
570        .await
571    }
572
573    pub async fn place_order_with_params<S>(
574        &self,
575        signer: &S,
576        params: PlaceOrderParams<'_>,
577    ) -> Result<OrderMessage>
578    where
579        S: HypercallSigner + ?Sized,
580    {
581        let route = params.options.route.unwrap_or(OrderRoute::BestExecution);
582        let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
583        let side_str = signed_side(params.side);
584        let tif_str = signed_tif(params.tif);
585        let price_str = params.price.to_string();
586        let size_str = params.size.to_string();
587        let mmp_enabled = mmp_enabled_or_default(&params.options);
588        let reduce_only = params.options.reduce_only.unwrap_or(false);
589        let client_id = params
590            .options
591            .client_id
592            .unwrap_or_else(|| generated_client_id(nonce));
593
594        let signature = signer
595            .sign_place_order_payload(PlaceOrderSignature {
596                wallet: params.account,
597                symbol: params.symbol,
598                side: side_str,
599                size: &size_str,
600                price: &price_str,
601                tif: tif_str,
602                route,
603                client_id: &client_id,
604                reduce_only,
605                nonce,
606            })
607            .await?;
608
609        let request = PlaceOrderRequest {
610            wallet: params.account.into_wallet_address(),
611            price: price_str,
612            size: size_str,
613            symbol: params.symbol.to_string(),
614            side: params.side,
615            tif: params.tif,
616            route: Some(route),
617            client_id: Some(client_id),
618            nonce,
619            signature,
620            reduce_only,
621            mmp_enabled,
622            builder_code_address: optional_wallet_address(params.options.builder_code_address),
623        };
624
625        Self::send_json_body(
626            self.request(Method::POST, API_ROUTE_ORDER),
627            &request,
628            "place order",
629        )
630        .await
631    }
632
633    /// Cancel an order.
634    pub async fn cancel_order<S>(&self, wallet: &S, order_id: u64) -> Result<Value>
635    where
636        S: HypercallSigner + ?Sized,
637    {
638        self.cancel_order_for_wallet(wallet, wallet.address(), order_id)
639            .await
640    }
641
642    /// Cancel an order for a managed wallet/account with an explicit signer.
643    pub async fn cancel_order_for_wallet<S>(
644        &self,
645        signer: &S,
646        account: AccountAddress,
647        order_id: u64,
648    ) -> Result<Value>
649    where
650        S: HypercallSigner + ?Sized,
651    {
652        let nonce = signer.next_nonce();
653        self.cancel_order_for_wallet_with_nonce(signer, account, order_id, nonce)
654            .await
655    }
656
657    /// Cancel an order for a managed wallet/account with an explicit nonce.
658    pub async fn cancel_order_for_wallet_with_nonce<S>(
659        &self,
660        signer: &S,
661        account: AccountAddress,
662        order_id: u64,
663        nonce: u64,
664    ) -> Result<Value>
665    where
666        S: HypercallSigner + ?Sized,
667    {
668        let order_id_str = order_id.to_string();
669
670        let signature = signer
671            .sign_cancel_order_payload(CancelOrderSignature {
672                wallet: account,
673                order_id: &order_id_str,
674                nonce,
675            })
676            .await?;
677
678        Self::send_sonic_json(
679            self.request(Method::DELETE, API_ROUTE_ORDER).json(&json!({
680                "wallet": account,
681                "order_id": order_id,
682                "nonce": nonce,
683                "signature": signature,
684            })),
685            "cancel order",
686        )
687        .await
688    }
689
690    /// Atomically cancel an order and place a new one.
691    pub async fn replace_order_with_params<S>(
692        &self,
693        signer: &S,
694        params: ReplaceOrderParams<'_>,
695    ) -> Result<OrderMessage>
696    where
697        S: HypercallSigner + ?Sized,
698    {
699        let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
700        let side_str = signed_side(params.side);
701        let tif_str = signed_tif(params.tif);
702        let price_str = params.price.to_string();
703        let size_str = params.size.to_string();
704        let order_id_str = params.order_id.to_string();
705        let mmp_enabled = mmp_enabled_or_default(&params.options);
706        let reduce_only = params.options.reduce_only.unwrap_or(false);
707        let client_id = params
708            .options
709            .client_id
710            .unwrap_or_else(|| generated_client_id(nonce));
711
712        let signature = signer
713            .sign_replace_order_payload(ReplaceOrderSignature {
714                wallet: params.account,
715                order_id: &order_id_str,
716                symbol: params.symbol,
717                side: side_str,
718                size: &size_str,
719                price: &price_str,
720                tif: tif_str,
721                client_id: &client_id,
722                reduce_only,
723                nonce,
724            })
725            .await?;
726
727        let request = ReplaceOrderRequest {
728            wallet: params.account.into_wallet_address(),
729            order_id: params.order_id,
730            price: price_str,
731            size: size_str,
732            symbol: params.symbol.to_string(),
733            side: params.side,
734            tif: params.tif,
735            client_id: Some(client_id),
736            nonce,
737            signature,
738            reduce_only,
739            mmp_enabled,
740            builder_code_address: optional_wallet_address(params.options.builder_code_address),
741        };
742
743        Self::send_json_body(
744            self.request(Method::PUT, API_ROUTE_ORDER),
745            &request,
746            "replace order",
747        )
748        .await
749    }
750
751    /// Maximum orders per bulk request.
752    pub const MAX_BULK_CHUNK_SIZE: usize = 50;
753
754    /// Place multiple orders in bulk, automatically chunking to stay within API limits.
755    pub async fn bulk_place_orders<S, P, Q>(
756        &self,
757        wallet: &S,
758        orders: Vec<(&str, Side, P, Q, TimeInForce)>,
759    ) -> Result<BulkPlaceOrderResponse>
760    where
761        S: HypercallSigner + ?Sized,
762        P: OrderDecimalInput,
763        Q: OrderDecimalInput,
764    {
765        let orders = orders
766            .into_iter()
767            .map(|(symbol, side, price, size, tif)| BulkOrderParams {
768                symbol,
769                side,
770                price: price.into_order_decimal(),
771                size: size.into_order_decimal(),
772                tif,
773                options: OrderOptions {
774                    route: Some(OrderRoute::BookOnly),
775                    ..OrderOptions::default()
776                },
777            })
778            .collect();
779        self.bulk_place_orders_with_params(wallet, orders).await
780    }
781
782    pub async fn bulk_place_orders_with_params<S>(
783        &self,
784        wallet: &S,
785        orders: Vec<BulkOrderParams<'_>>,
786    ) -> Result<BulkPlaceOrderResponse>
787    where
788        S: HypercallSigner + ?Sized,
789    {
790        info!("Placing {} orders in bulk", orders.len());
791
792        let mut order_requests = Vec::with_capacity(orders.len());
793
794        for order in orders {
795            let nonce = wallet.next_nonce();
796            let side_str = signed_side(order.side);
797            let tif_str = signed_tif(order.tif);
798            let price_str = order.price.to_string();
799            let size_str = order.size.to_string();
800            let mmp_enabled = mmp_enabled_or_default(&order.options);
801            let reduce_only = order.options.reduce_only.unwrap_or(false);
802            let client_id = order
803                .options
804                .client_id
805                .unwrap_or_else(|| generated_client_id(nonce));
806            let route = order.options.route.unwrap_or(OrderRoute::BookOnly);
807
808            let signature = wallet
809                .sign_place_order_payload(PlaceOrderSignature {
810                    wallet: wallet.address(),
811                    symbol: order.symbol,
812                    side: side_str,
813                    size: &size_str,
814                    price: &price_str,
815                    tif: tif_str,
816                    route,
817                    client_id: &client_id,
818                    reduce_only,
819                    nonce,
820                })
821                .await?;
822
823            order_requests.push(PlaceOrderRequest {
824                wallet: wallet.address().into_wallet_address(),
825                price: price_str,
826                size: size_str,
827                symbol: order.symbol.to_string(),
828                side: order.side,
829                tif: order.tif,
830                route: Some(route),
831                client_id: Some(client_id),
832                nonce,
833                signature,
834                reduce_only,
835                mmp_enabled,
836                builder_code_address: optional_wallet_address(order.options.builder_code_address),
837            });
838        }
839
840        let mut all_results = Vec::with_capacity(order_requests.len());
841
842        for chunk in order_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
843            let payload = BulkPlaceOrderRequest {
844                orders: chunk.to_vec(),
845            };
846
847            let bulk_response: BulkPlaceOrderResponse = Self::send_json_body(
848                self.request(Method::POST, API_ROUTE_BULK_ORDER),
849                &payload,
850                "place bulk orders",
851            )
852            .await?;
853            all_results.extend(bulk_response.results);
854        }
855
856        Ok(BulkPlaceOrderResponse {
857            results: all_results,
858        })
859    }
860
861    /// Cancel multiple orders in bulk, automatically chunking to stay within API limits.
862    pub async fn bulk_cancel_orders<S>(
863        &self,
864        wallet: &S,
865        order_ids: Vec<u64>,
866    ) -> Result<BulkCancelOrderResponse>
867    where
868        S: HypercallSigner + ?Sized,
869    {
870        self.bulk_cancel_orders_for_wallet(wallet, wallet.address(), order_ids)
871            .await
872    }
873
874    /// Cancel multiple orders for a managed wallet/account, automatically chunking.
875    pub async fn bulk_cancel_orders_for_wallet<S>(
876        &self,
877        signer: &S,
878        account: AccountAddress,
879        order_ids: Vec<u64>,
880    ) -> Result<BulkCancelOrderResponse>
881    where
882        S: HypercallSigner + ?Sized,
883    {
884        info!("Canceling {} orders in bulk", order_ids.len());
885
886        let mut cancel_requests = Vec::with_capacity(order_ids.len());
887
888        for order_id in &order_ids {
889            let nonce = signer.next_nonce();
890            let order_id_str = order_id.to_string();
891            let signature = signer
892                .sign_cancel_order_payload(CancelOrderSignature {
893                    wallet: account,
894                    order_id: &order_id_str,
895                    nonce,
896                })
897                .await?;
898
899            cancel_requests.push(json!({
900                "wallet": account,
901                "order_id": order_id,
902                "nonce": nonce,
903                "signature": signature,
904            }));
905        }
906
907        let mut all_results = Vec::with_capacity(cancel_requests.len());
908
909        for chunk in cancel_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
910            let bulk_response: BulkCancelOrderResponse = Self::send_json_body(
911                self.request(Method::DELETE, API_ROUTE_BULK_ORDER),
912                &json!({ "cancels": chunk }),
913                "cancel bulk orders",
914            )
915            .await?;
916            all_results.extend(bulk_response.results);
917        }
918
919        Ok(BulkCancelOrderResponse {
920            results: all_results,
921        })
922    }
923
924    /// Replace multiple orders in bulk, automatically chunking to stay within API limits.
925    ///
926    /// Each tuple is (cancel_order_id, symbol, side, price, size, tif).
927    pub async fn bulk_replace_orders<S, P, Q>(
928        &self,
929        wallet: &S,
930        replacements: Vec<(u64, &str, Side, P, Q, TimeInForce)>,
931    ) -> Result<BulkPlaceOrderResponse>
932    where
933        S: HypercallSigner + ?Sized,
934        P: OrderDecimalInput,
935        Q: OrderDecimalInput,
936    {
937        let replacements = replacements
938            .into_iter()
939            .map(
940                |(order_id, symbol, side, price, size, tif)| BulkReplaceOrderParams {
941                    order_id,
942                    symbol,
943                    side,
944                    price: price.into_order_decimal(),
945                    size: size.into_order_decimal(),
946                    tif,
947                    options: OrderOptions::default(),
948                },
949            )
950            .collect();
951        self.bulk_replace_orders_with_params(wallet, replacements)
952            .await
953    }
954
955    pub async fn bulk_replace_orders_with_params<S>(
956        &self,
957        wallet: &S,
958        replacements: Vec<BulkReplaceOrderParams<'_>>,
959    ) -> Result<BulkPlaceOrderResponse>
960    where
961        S: HypercallSigner + ?Sized,
962    {
963        info!("Replacing {} orders in bulk", replacements.len());
964
965        let mut replace_requests = Vec::with_capacity(replacements.len());
966
967        for replacement in replacements {
968            let nonce = wallet.next_nonce();
969            let side_str = signed_side(replacement.side);
970            let tif_str = signed_tif(replacement.tif);
971            let price_str = replacement.price.to_string();
972            let size_str = replacement.size.to_string();
973            let order_id_str = replacement.order_id.to_string();
974            let mmp_enabled = mmp_enabled_or_default(&replacement.options);
975            let reduce_only = replacement.options.reduce_only.unwrap_or(false);
976            let client_id = replacement
977                .options
978                .client_id
979                .unwrap_or_else(|| generated_client_id(nonce));
980
981            let signature = wallet
982                .sign_replace_order_payload(ReplaceOrderSignature {
983                    wallet: wallet.address(),
984                    order_id: &order_id_str,
985                    symbol: replacement.symbol,
986                    side: side_str,
987                    size: &size_str,
988                    price: &price_str,
989                    tif: tif_str,
990                    client_id: &client_id,
991                    reduce_only,
992                    nonce,
993                })
994                .await?;
995
996            replace_requests.push(ReplaceOrderRequest {
997                wallet: wallet.address().into_wallet_address(),
998                order_id: replacement.order_id,
999                price: price_str,
1000                size: size_str,
1001                symbol: replacement.symbol.to_string(),
1002                side: replacement.side,
1003                tif: replacement.tif,
1004                client_id: Some(client_id),
1005                nonce,
1006                signature,
1007                reduce_only,
1008                mmp_enabled,
1009                builder_code_address: optional_wallet_address(
1010                    replacement.options.builder_code_address,
1011                ),
1012            });
1013        }
1014
1015        let mut all_results = Vec::with_capacity(replace_requests.len());
1016
1017        for chunk in replace_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
1018            let bulk_response: BulkPlaceOrderResponse = Self::send_sonic_json(
1019                self.request(Method::PUT, API_ROUTE_BULK_ORDER)
1020                    .json(&sonic_rs::json!({ "replacements": chunk })),
1021                "replace bulk orders",
1022            )
1023            .await?;
1024            all_results.extend(bulk_response.results);
1025        }
1026
1027        Ok(BulkPlaceOrderResponse {
1028            results: all_results,
1029        })
1030    }
1031
1032    /// Get orders for a wallet (single page).
1033    pub async fn get_orders(
1034        &self,
1035        wallet: impl Into<AccountAddress>,
1036        status: Option<&str>,
1037    ) -> Result<Value> {
1038        let wallet = wallet.into();
1039        let mut url = format!("{}?wallet={}", self.route_url(API_ROUTE_ORDERS), wallet);
1040        if let Some(status_filter) = status {
1041            url.push_str(&format!("&status={}", status_filter));
1042        }
1043
1044        Self::send_sonic_json(self.client.get(&url), "get orders").await
1045    }
1046
1047    /// Get one typed page of option and perp orders.
1048    pub async fn get_orders_typed(
1049        &self,
1050        wallet: impl Into<AccountAddress>,
1051        status: Option<&str>,
1052        limit: Option<usize>,
1053        offset: Option<usize>,
1054    ) -> Result<OrdersApiResponse> {
1055        let wallet = wallet.into();
1056        let mut query = vec![("wallet", wallet.to_string())];
1057        if let Some(status_filter) = status {
1058            query.push(("status", status_filter.to_string()));
1059        }
1060        if let Some(limit) = limit {
1061            query.push(("limit", limit.to_string()));
1062        }
1063        if let Some(offset) = offset {
1064            query.push(("offset", offset.to_string()));
1065        }
1066        Self::send_reqwest_json(
1067            self.request(Method::GET, API_ROUTE_ORDERS).query(&query),
1068            "get typed orders",
1069        )
1070        .await
1071    }
1072
1073    /// Get the display username for a wallet.
1074    pub async fn get_username(&self, wallet: impl Into<AccountAddress>) -> Result<Option<String>> {
1075        let wallet = wallet.into();
1076        let response = self
1077            .client
1078            .get(format!(
1079                "{}?wallet={}",
1080                self.route_url(API_ROUTE_USERNAME),
1081                wallet
1082            ))
1083            .send()
1084            .await?;
1085
1086        if response.status() == reqwest::StatusCode::NOT_FOUND {
1087            return Ok(None);
1088        }
1089        if !response.status().is_success() {
1090            let status = response.status().as_u16();
1091            let text = response.text().await.unwrap_or_default();
1092            return Err(ClientError::Api {
1093                status,
1094                message: format!("Failed to get username: {}", text),
1095            });
1096        }
1097
1098        match response.json::<UsernameLookupEnvelope>().await? {
1099            UsernameLookupEnvelope::Direct(data) => Ok(non_empty_username(data.username)),
1100            UsernameLookupEnvelope::Wrapped(result) => {
1101                if !result.success {
1102                    return Err(ClientError::Api {
1103                        status: 200,
1104                        message: result
1105                            .error
1106                            .unwrap_or_else(|| "Username request failed".to_string()),
1107                    });
1108                }
1109                Ok(result
1110                    .data
1111                    .and_then(|data| non_empty_username(data.username)))
1112            }
1113        }
1114    }
1115
1116    /// Get ALL orders for a wallet, paginating through all pages.
1117    pub async fn get_all_orders(
1118        &self,
1119        wallet: impl Into<AccountAddress>,
1120        status: Option<&str>,
1121    ) -> Result<Vec<Value>> {
1122        let wallet = wallet.into();
1123        let mut all_orders = Vec::new();
1124        let mut offset = 0;
1125
1126        loop {
1127            let mut url = format!(
1128                "{}/orders?wallet={}&offset={}",
1129                self.base_url, wallet, offset
1130            );
1131            if let Some(status_filter) = status {
1132                url.push_str(&format!("&status={}", status_filter));
1133            }
1134
1135            let result: Value = Self::send_sonic_json(self.client.get(&url), "get orders").await?;
1136            let pagination = result
1137                .get("pagination")
1138                .ok_or_else(|| invalid_orders_pagination("missing pagination object"))?;
1139            let returned_limit = pagination
1140                .get("limit")
1141                .and_then(|value| value.as_u64())
1142                .and_then(|value| usize::try_from(value).ok())
1143                .ok_or_else(|| invalid_orders_pagination("invalid pagination.limit"))?;
1144            let returned_offset = pagination
1145                .get("offset")
1146                .and_then(|value| value.as_u64())
1147                .and_then(|value| usize::try_from(value).ok())
1148                .ok_or_else(|| invalid_orders_pagination("invalid pagination.offset"))?;
1149            let data = result.get("data").unwrap_or(&result);
1150            let page: Vec<Value> = match data.as_array() {
1151                Some(arr) => arr.iter().cloned().collect(),
1152                None => break,
1153            };
1154
1155            let count = page.len();
1156            all_orders.extend(page);
1157            match next_orders_page_offset(offset, returned_offset, returned_limit, count)? {
1158                Some(next_offset) => offset = next_offset,
1159                None => break,
1160            }
1161        }
1162
1163        Ok(all_orders)
1164    }
1165
1166    /// Get all option and perp orders as canonical typed rows.
1167    pub async fn get_all_orders_typed(
1168        &self,
1169        wallet: impl Into<AccountAddress>,
1170        status: Option<&str>,
1171    ) -> Result<Vec<Order>> {
1172        let wallet = wallet.into();
1173        let mut orders = Vec::new();
1174        let mut offset = 0;
1175        loop {
1176            let page = self
1177                .get_orders_typed(wallet, status, None, Some(offset))
1178                .await?;
1179            let count = page.data.len();
1180            let next_offset = next_orders_page_offset(
1181                offset,
1182                page.pagination.offset,
1183                page.pagination.limit,
1184                count,
1185            )?;
1186            orders.extend(page.data);
1187            match next_offset {
1188                Some(next_offset) => offset = next_offset,
1189                None => break,
1190            }
1191        }
1192        Ok(orders)
1193    }
1194
1195    /// Get fills for a wallet.
1196    pub async fn get_fills(
1197        &self,
1198        wallet: impl Into<AccountAddress>,
1199        limit: Option<usize>,
1200        offset: Option<usize>,
1201    ) -> Result<Value> {
1202        let wallet = wallet.into();
1203        let mut url = format!("{}/fills?wallet={}", self.base_url, wallet);
1204        if let Some(limit_val) = limit {
1205            url.push_str(&format!("&limit={}", limit_val));
1206        }
1207        if let Some(offset_val) = offset {
1208            url.push_str(&format!("&offset={}", offset_val));
1209        }
1210
1211        Self::send_sonic_json(self.client.get(&url), "get fills").await
1212    }
1213
1214    /// Get a typed page of option and perp fills.
1215    pub async fn get_fills_typed(
1216        &self,
1217        wallet: impl Into<AccountAddress>,
1218        limit: Option<usize>,
1219        offset: Option<usize>,
1220    ) -> Result<hypercall_sdk_types::FillsResponse> {
1221        let wallet = wallet.into();
1222        let mut query = vec![("wallet", wallet.to_string())];
1223        if let Some(limit) = limit {
1224            query.push(("limit", limit.to_string()));
1225        }
1226        if let Some(offset) = offset {
1227            query.push(("offset", offset.to_string()));
1228        }
1229        Self::send_reqwest_json(
1230            self.request(Method::GET, "/fills").query(&query),
1231            "get typed fills",
1232        )
1233        .await
1234    }
1235
1236    /// Get portfolio for a wallet.
1237    pub async fn get_portfolio(
1238        &self,
1239        wallet: impl Into<AccountAddress>,
1240    ) -> Result<PortfolioResponse> {
1241        let wallet = wallet.into();
1242        let result: ApiResponse<PortfolioResponse> = Self::send_reqwest_json(
1243            self.client
1244                .get(format!("{}/portfolio?wallet={}", self.base_url, wallet)),
1245            "get portfolio",
1246        )
1247        .await?;
1248        if !result.success {
1249            return Err(ClientError::Api {
1250                status: 200,
1251                message: result
1252                    .error
1253                    .unwrap_or_else(|| "Portfolio request failed".to_string()),
1254            });
1255        }
1256        result.data.ok_or_else(|| ClientError::Api {
1257            status: 200,
1258            message: result
1259                .error
1260                .unwrap_or_else(|| "No portfolio data returned".to_string()),
1261        })
1262    }
1263
1264    /// Get the canonical portfolio-margin-compatible snapshot.
1265    pub async fn get_portfolio_snapshot(
1266        &self,
1267        wallet: impl Into<AccountAddress>,
1268    ) -> Result<Portfolio> {
1269        let wallet = wallet.into();
1270        let result: hypercall_sdk_types::CanonicalApiResponse<Portfolio> = Self::send_reqwest_json(
1271            self.request(Method::GET, "/portfolio")
1272                .query(&[("wallet", wallet.to_string())]),
1273            "get canonical portfolio",
1274        )
1275        .await?;
1276        if !result.success {
1277            return Err(ClientError::Api {
1278                status: 200,
1279                message: result
1280                    .error
1281                    .unwrap_or_else(|| "Portfolio request failed".to_string()),
1282            });
1283        }
1284        result.data.ok_or_else(|| ClientError::Api {
1285            status: 200,
1286            message: result
1287                .error
1288                .unwrap_or_else(|| "No portfolio data returned".to_string()),
1289        })
1290    }
1291
1292    /// Get global public liquidation history.
1293    pub async fn get_public_liquidations(
1294        &self,
1295        query: &PublicLiquidationsQuery,
1296    ) -> Result<PublicLiquidationsResponse> {
1297        let mut params = Vec::new();
1298        if let Some(cursor) = &query.cursor {
1299            params.push(("cursor", cursor.clone()));
1300        }
1301        if let Some(limit) = query.limit {
1302            params.push(("limit", limit.to_string()));
1303        }
1304        if let Some(wallet) = &query.wallet {
1305            params.push(("wallet", wallet.clone()));
1306        }
1307        if let Some(status) = &query.status {
1308            params.push(("status", status.clone()));
1309        }
1310        if let Some(state) = &query.state {
1311            params.push(("state", state.clone()));
1312        }
1313        if let Some(margin_mode) = &query.margin_mode {
1314            params.push(("margin_mode", margin_mode.clone()));
1315        }
1316        if let Some(liquidation_mode) = &query.liquidation_mode {
1317            params.push(("liquidation_mode", liquidation_mode.clone()));
1318        }
1319
1320        let mut request = self.client.get(format!("{}/liquidations", self.base_url));
1321        if !params.is_empty() {
1322            request = request.query(&params);
1323        }
1324        let response = request.send().await?;
1325
1326        if !response.status().is_success() {
1327            let status = response.status().as_u16();
1328            let text = response.text().await.unwrap_or_default();
1329            return Err(ClientError::Api {
1330                status,
1331                message: format!("Failed to get liquidations: {}", text),
1332            });
1333        }
1334
1335        let result: PublicLiquidationsResponse = sonic_json(response).await?;
1336        if !result.success {
1337            return Err(ClientError::Api {
1338                status: 200,
1339                message: result
1340                    .error
1341                    .clone()
1342                    .unwrap_or_else(|| "Liquidations request failed".to_string()),
1343            });
1344        }
1345        Ok(result)
1346    }
1347
1348    /// Get liquidation status for a wallet.
1349    pub async fn get_liquidation_status(
1350        &self,
1351        wallet: impl Into<AccountAddress>,
1352    ) -> Result<Option<LiquidationStatusData>> {
1353        let wallet = wallet.into();
1354        let result: LiquidationStatusResponse = Self::send_sonic_json(
1355            self.client
1356                .get(self.route_url(API_ROUTE_LIQUIDATION_STATUS))
1357                .query(&[("wallet", wallet.to_string())]),
1358            "get liquidation status",
1359        )
1360        .await?;
1361        if !result.success {
1362            return Err(ClientError::Api {
1363                status: 200,
1364                message: result
1365                    .error
1366                    .clone()
1367                    .unwrap_or_else(|| "Liquidation status request failed".to_string()),
1368            });
1369        }
1370        Ok(result.data)
1371    }
1372
1373    /// Get historical equity snapshots for a wallet.
1374    ///
1375    /// `include_attribution`: pass `Some(true)` only when rendering the
1376    /// per-symbol breakdown. The default response omits attribution because it
1377    /// is substantially larger than the equity-only time series.
1378    pub async fn get_historical_pnl(
1379        &self,
1380        wallet: impl Into<AccountAddress>,
1381        interval: HistoricalPnlInterval,
1382        limit: Option<usize>,
1383        include_attribution: Option<bool>,
1384    ) -> Result<HistoricalPnlResponse> {
1385        let wallet = wallet.into();
1386        let mut request = self
1387            .client
1388            .get(format!("{}/historical-pnl", self.base_url))
1389            .query(&[
1390                ("wallet", wallet.to_string()),
1391                ("interval", interval.as_str().to_string()),
1392            ]);
1393
1394        if let Some(limit_value) = limit {
1395            request = request.query(&[("limit", limit_value.to_string())]);
1396        }
1397
1398        if let Some(true) = include_attribution {
1399            request = request.query(&[("include_attribution", "true")]);
1400        }
1401
1402        let result: ApiResponse<HistoricalPnlResponse> =
1403            Self::send_reqwest_json(request, "get historical pnl").await?;
1404        if !result.success {
1405            return Err(ClientError::Api {
1406                status: 200,
1407                message: result
1408                    .error
1409                    .unwrap_or_else(|| "Historical pnl request failed".to_string()),
1410            });
1411        }
1412
1413        result.data.ok_or_else(|| ClientError::Api {
1414            status: 200,
1415            message: result
1416                .error
1417                .unwrap_or_else(|| "No historical pnl data returned".to_string()),
1418        })
1419    }
1420
1421    /// Get historical theoretical-price snapshots for an option instrument.
1422    pub async fn get_historical_theos(
1423        &self,
1424        instrument_name: &str,
1425        interval: HistoricalTheoInterval,
1426        limit: Option<usize>,
1427    ) -> Result<HistoricalTheoResponse> {
1428        let mut request = self
1429            .client
1430            .get(format!("{}/historical-theos", self.base_url))
1431            .query(&[
1432                ("instrument_name", instrument_name.to_string()),
1433                ("interval", interval.as_str().to_string()),
1434            ]);
1435
1436        if let Some(limit_value) = limit {
1437            request = request.query(&[("limit", limit_value.to_string())]);
1438        }
1439
1440        let result: ApiResponse<HistoricalTheoResponse> =
1441            Self::send_reqwest_json(request, "get historical theos").await?;
1442        if !result.success {
1443            return Err(ClientError::Api {
1444                status: 200,
1445                message: result
1446                    .error
1447                    .unwrap_or_else(|| "Historical theos request failed".to_string()),
1448            });
1449        }
1450
1451        result.data.ok_or_else(|| ClientError::Api {
1452            status: 200,
1453            message: result
1454                .error
1455                .unwrap_or_else(|| "No historical theo data returned".to_string()),
1456        })
1457    }
1458
1459    /// Set margin mode for a wallet.
1460    pub async fn set_margin_mode(
1461        &self,
1462        wallet: &HypercallWallet,
1463        margin_mode: &str,
1464    ) -> Result<Value> {
1465        info!(
1466            "Setting margin mode to {} for {}",
1467            margin_mode, wallet.address
1468        );
1469
1470        let nonce = wallet.next_nonce();
1471        let signature = wallet.sign_set_margin_mode(margin_mode, nonce).await?;
1472
1473        let response = self
1474            .client
1475            .post(self.route_url(API_ROUTE_MARGIN_MODE))
1476            .json(&json!({
1477                "wallet": wallet.address.to_string(),
1478                "margin_mode": margin_mode,
1479                "nonce": nonce,
1480                "signature": signature,
1481            }))
1482            .send()
1483            .await?;
1484
1485        if !response.status().is_success() {
1486            let status = response.status().as_u16();
1487            let text = response.text().await.unwrap_or_default();
1488            return Err(ClientError::Api {
1489                status,
1490                message: format!("Failed to set margin mode: {}", text),
1491            });
1492        }
1493
1494        let result: Value = sonic_json(response).await?;
1495        Ok(result)
1496    }
1497
1498    /// Set an account's margin mode using the typed SDK enum.
1499    pub async fn set_margin_mode_typed(
1500        &self,
1501        wallet: &HypercallWallet,
1502        margin_mode: MarginMode,
1503    ) -> Result<Value> {
1504        self.set_margin_mode(wallet, margin_mode.as_str()).await
1505    }
1506
1507    pub async fn submit_standard_margin_liquidation_with_params<S>(
1508        &self,
1509        liquidator: &S,
1510        params: StandardMarginLiquidationParams,
1511    ) -> Result<StandardMarginLiquidationOrderResponse>
1512    where
1513        S: HypercallSigner + ?Sized,
1514    {
1515        let nonce = params.nonce.unwrap_or_else(|| liquidator.next_nonce());
1516        let request_id = params.request_id.to_string();
1517        let signature = liquidator
1518            .sign_standard_margin_liquidation_payload(StandardMarginLiquidationSignature {
1519                wallet: liquidator.address(),
1520                liquidated_wallet: params.liquidated_wallet,
1521                request_id: &request_id,
1522                auction_id: &params.auction_id,
1523                bid_usdc: &params.bid_usdc,
1524                portfolio_hash: &params.portfolio_hash,
1525                auction_terms_hash: &params.auction_terms_hash,
1526                bid_intent_hash: &params.bid_intent_hash,
1527                auction_version: params.auction_version,
1528                nonce,
1529            })
1530            .await?;
1531        let request = StandardMarginLiquidationOrderRequest {
1532            wallet: liquidator.address().into_wallet_address(),
1533            liquidated_wallet: params.liquidated_wallet.into_wallet_address(),
1534            request_id: params.request_id,
1535            auction_id: params.auction_id,
1536            bid_usdc: params.bid_usdc,
1537            positions: params.positions,
1538            portfolio_hash: params.portfolio_hash,
1539            auction_terms_hash: params.auction_terms_hash,
1540            auction_version: params.auction_version,
1541            valuation_timestamp_ms: params.valuation_timestamp_ms,
1542            bid_intent_hash: params.bid_intent_hash,
1543            nonce,
1544            signature,
1545        };
1546
1547        let result: ApiResponse<StandardMarginLiquidationOrderResponse> = Self::send_json_body(
1548            self.request(Method::POST, API_ROUTE_STANDARD_MARGIN_LIQUIDATION),
1549            &request,
1550            "submit standard margin liquidation",
1551        )
1552        .await?;
1553        result.data.ok_or_else(|| ClientError::Api {
1554            status: 200,
1555            message: result
1556                .error
1557                .unwrap_or_else(|| "No liquidation response returned".to_string()),
1558        })
1559    }
1560
1561    /// Fetch underlying price from options-summary endpoint.
1562    pub async fn fetch_underlying_price(&self, currency: &str) -> Result<Option<f64>> {
1563        let response = match self
1564            .client
1565            .get(format!("{}/options-summary", self.base_url))
1566            .query(&[("currency", currency)])
1567            .send()
1568            .await
1569        {
1570            Ok(resp) => resp,
1571            Err(err) => {
1572                warn!("options-summary request failed for {}: {}", currency, err);
1573                return Ok(None);
1574            }
1575        };
1576
1577        if !response.status().is_success() {
1578            warn!(
1579                "options-summary returned {} for {}",
1580                response.status(),
1581                currency
1582            );
1583            return Ok(None);
1584        }
1585
1586        let body: JsonRpcResponse<Vec<OptionSummary>> = reqwest_json(response).await?;
1587        let price = body.result.and_then(|mut results| {
1588            results.iter_mut().find_map(|summary| {
1589                (summary.underlying_price > 0.0).then_some(summary.underlying_price)
1590            })
1591        });
1592
1593        Ok(price)
1594    }
1595
1596    // =========================================================================
1597    // RFQ endpoints
1598    // =========================================================================
1599
1600    /// Submit an RFQ (taker-side).
1601    pub async fn submit_rfq(
1602        &self,
1603        wallet: &HypercallWallet,
1604        rfq_id: &str,
1605        legs: Vec<hypercall_sdk_types::RfqLegRequest>,
1606    ) -> Result<Value> {
1607        // Parse rfq_id to bytes for signing
1608        let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1609            ClientError::RfqInput(RfqInputError::InvalidUuid {
1610                label: "Invalid rfq_id",
1611                source,
1612            })
1613        })?;
1614        let mut rfq_id_bytes = [0u8; 32];
1615        rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1616
1617        // Compute legs hash (propagates parse errors for non-numeric sizes)
1618        let legs_hash = compute_legs_hash(&legs)?;
1619
1620        let nonce = wallet.next_nonce();
1621        let signature = wallet
1622            .sign_submit_rfq(rfq_id_bytes, legs_hash, nonce)
1623            .await?;
1624
1625        let request = hypercall_sdk_types::SubmitRfqRequest {
1626            rfq_id: rfq_id.to_string(),
1627            legs,
1628            wallet_address: wallet.address.into_wallet_address(),
1629            nonce,
1630            signature,
1631            auto_accept_limit: None,
1632        };
1633
1634        self.post_json_sonic(API_ROUTE_RFQ_REQUEST, &request, "RFQ submission failed")
1635            .await
1636    }
1637
1638    /// Submit an auto-execute RFQ (taker-side).
1639    ///
1640    /// Similar to `submit_rfq` but the taker pre-authorizes execution with
1641    /// `limit_price`. Buy RFQs use it as a max debit. Sell RFQs use it as a
1642    /// min credit. The first QP quote satisfying that directional limit
1643    /// triggers immediate execution without a separate accept RTT.
1644    /// Uses the `SubmitAutoExecuteRfq` EIP-712 type for signing.
1645    pub async fn submit_auto_execute_rfq(
1646        &self,
1647        wallet: &HypercallWallet,
1648        rfq_id: &str,
1649        legs: Vec<hypercall_sdk_types::RfqLegRequest>,
1650        limit_price: rust_decimal::Decimal,
1651    ) -> Result<Value> {
1652        let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1653            ClientError::RfqInput(RfqInputError::InvalidUuid {
1654                label: "Invalid rfq_id",
1655                source,
1656            })
1657        })?;
1658        let mut rfq_id_bytes = [0u8; 32];
1659        rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1660
1661        let legs_hash = compute_legs_hash(&legs)?;
1662
1663        // Convert limit_price to micro-units (multiply by 1_000_000) for I256
1664        use rust_decimal::prelude::ToPrimitive;
1665        let limit_micro = (limit_price * Decimal::new(1_000_000, 0))
1666            .to_i64()
1667            .ok_or(ClientError::RfqInput(RfqInputError::LimitPriceOverflow))?;
1668        let limit_i256 = alloy::primitives::I256::try_from(limit_micro).map_err(|source| {
1669            ClientError::RfqInput(RfqInputError::LimitPriceConversion {
1670                source: Box::new(source),
1671            })
1672        })?;
1673
1674        let nonce = wallet.next_nonce();
1675        let signature = wallet
1676            .sign_submit_auto_execute_rfq(rfq_id_bytes, legs_hash, limit_i256, nonce)
1677            .await?;
1678
1679        let request = hypercall_sdk_types::SubmitRfqRequest {
1680            rfq_id: rfq_id.to_string(),
1681            legs,
1682            wallet_address: wallet.address.into_wallet_address(),
1683            nonce,
1684            signature,
1685            auto_accept_limit: Some(limit_price.to_string()),
1686        };
1687
1688        self.post_json_sonic(
1689            API_ROUTE_RFQ_REQUEST,
1690            &request,
1691            "Auto-execute RFQ submission failed",
1692        )
1693        .await
1694    }
1695
1696    /// Accept an RFQ quote (taker-side).
1697    pub async fn accept_rfq_quote(
1698        &self,
1699        wallet: &HypercallWallet,
1700        rfq_id: &str,
1701        quote_id: &str,
1702        net_premium: alloy::primitives::I256,
1703    ) -> Result<Value> {
1704        let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1705            ClientError::RfqInput(RfqInputError::InvalidUuid {
1706                label: "Invalid rfq_id",
1707                source,
1708            })
1709        })?;
1710        let quote_uuid = uuid::Uuid::parse_str(quote_id).map_err(|source| {
1711            ClientError::RfqInput(RfqInputError::InvalidUuid {
1712                label: "Invalid quote_id",
1713                source,
1714            })
1715        })?;
1716        let mut rfq_id_bytes = [0u8; 32];
1717        rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1718        let mut quote_id_bytes = [0u8; 32];
1719        quote_id_bytes[16..].copy_from_slice(quote_uuid.as_bytes());
1720
1721        let nonce = wallet.next_nonce();
1722        let signature = wallet
1723            .sign_accept_rfq_quote(rfq_id_bytes, quote_id_bytes, net_premium, nonce)
1724            .await?;
1725
1726        let request = hypercall_sdk_types::AcceptRfqRequest {
1727            rfq_id: rfq_id.to_string(),
1728            quote_id: quote_id.to_string(),
1729            wallet_address: wallet.address.into_wallet_address(),
1730            nonce,
1731            signature,
1732        };
1733
1734        self.post_json_sonic(API_ROUTE_RFQ_ACCEPT, &request, "RFQ accept failed")
1735            .await
1736    }
1737
1738    /// Get RFQ status and quotes.
1739    pub async fn get_rfq(&self, rfq_id: &str) -> Result<Value> {
1740        let response = self
1741            .client
1742            .get(format!("{}/rfq/{}", self.base_url, rfq_id))
1743            .send()
1744            .await?;
1745
1746        if !response.status().is_success() {
1747            let status = response.status().as_u16();
1748            let text = response.text().await.unwrap_or_default();
1749            return Err(ClientError::Api {
1750                status,
1751                message: format!("Get RFQ failed: {}", text),
1752            });
1753        }
1754
1755        let result: Value = sonic_json(response).await?;
1756        Ok(result)
1757    }
1758}
1759
1760/// Compute keccak256 hash of RFQ legs for signing.
1761///
1762/// Canonical format: `"instrument|side|size"` joined by `";"`. `size` is
1763/// parsed to `Decimal` and re-formatted via `Decimal::to_string()` so the
1764/// signed hash matches Hypercall's public RFQ signing contract. Without this,
1765/// a non-canonical size string (`"01.0"`, `"+5"`, `"1.50"` etc.) would produce
1766/// a different `legs_hash`, and the submit would be rejected as a signature
1767/// mismatch.
1768fn compute_legs_hash(legs: &[hypercall_sdk_types::RfqLegRequest]) -> Result<[u8; 32]> {
1769    use sha3::Digest;
1770    let canonical = legs
1771        .iter()
1772        .map(|l| {
1773            let side = match l.side {
1774                hypercall_sdk_types::Side::Buy => "buy",
1775                hypercall_sdk_types::Side::Sell => "sell",
1776            };
1777            let size_canonical = l
1778                .size
1779                .parse::<Decimal>()
1780                .map_err(|source| {
1781                    ClientError::RfqInput(RfqInputError::InvalidLegSize {
1782                        label: "Invalid",
1783                        value: l.size.clone(),
1784                        source,
1785                    })
1786                })?
1787                .to_string();
1788            Ok(format!("{}|{}|{}", l.instrument, side, size_canonical))
1789        })
1790        .collect::<Result<Vec<_>>>()?
1791        .join(";");
1792    let mut hasher = sha3::Keccak256::new();
1793    hasher.update(canonical.as_bytes());
1794    Ok(hasher.finalize().into())
1795}
1796
1797impl std::fmt::Debug for HypercallClient {
1798    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1799        f.debug_struct("HypercallClient")
1800            .field("base_url", &self.base_url)
1801            .finish()
1802    }
1803}
1804
1805fn invalid_orders_pagination(message: &str) -> ClientError {
1806    ClientError::Api {
1807        status: 200,
1808        message: format!("invalid orders pagination: {message}"),
1809    }
1810}
1811
1812fn next_orders_page_offset(
1813    requested_offset: usize,
1814    returned_offset: usize,
1815    returned_limit: usize,
1816    returned_count: usize,
1817) -> Result<Option<usize>> {
1818    if returned_limit == 0 {
1819        return Err(invalid_orders_pagination(
1820            "pagination.limit must be greater than zero",
1821        ));
1822    }
1823    if returned_count < returned_limit {
1824        return Ok(None);
1825    }
1826
1827    let next_offset = returned_offset
1828        .checked_add(returned_count)
1829        .ok_or_else(|| invalid_orders_pagination("next offset overflowed usize"))?;
1830    if next_offset <= requested_offset {
1831        return Err(invalid_orders_pagination(
1832            "returned page does not advance the offset",
1833        ));
1834    }
1835    Ok(Some(next_offset))
1836}
1837
1838#[cfg(test)]
1839#[path = "api_redirect_test.rs"]
1840mod redirect_tests;
1841
1842#[cfg(test)]
1843#[path = "api_replace_order_test.rs"]
1844mod replace_order_tests;
1845
1846#[cfg(test)]
1847#[path = "api_compression_test.rs"]
1848mod compression_tests;
1849
1850#[cfg(test)]
1851mod tests {
1852    use super::*;
1853
1854    #[test]
1855    fn test_client_new() {
1856        let client = HypercallClient::new("http://localhost:3000");
1857        assert_eq!(client.base_url, "http://localhost:3000");
1858    }
1859
1860    #[test]
1861    fn test_client_new_trims_trailing_slash() {
1862        let client = HypercallClient::new("http://localhost:3000/");
1863        assert_eq!(client.base_url, "http://localhost:3000");
1864
1865        // trim_end_matches removes ALL trailing slashes
1866        let client2 = HypercallClient::new("http://localhost:3000///");
1867        assert_eq!(client2.base_url, "http://localhost:3000");
1868    }
1869
1870    #[test]
1871    fn test_client_new_from_string() {
1872        let client = HypercallClient::new(String::from("https://api.example.com"));
1873        assert_eq!(client.base_url, "https://api.example.com");
1874    }
1875
1876    #[test]
1877    fn test_client_debug() {
1878        let client = HypercallClient::new("http://localhost:3000");
1879        let debug = format!("{:?}", client);
1880        assert!(debug.contains("HypercallClient"));
1881        assert!(debug.contains("http://localhost:3000"));
1882    }
1883
1884    #[test]
1885    fn test_client_clone() {
1886        let client = HypercallClient::new("http://localhost:3000");
1887        let cloned = client.clone();
1888        assert_eq!(cloned.base_url, client.base_url);
1889    }
1890
1891    #[test]
1892    fn username_lookup_accepts_direct_response() {
1893        let response: UsernameLookupEnvelope = serde_json::from_value(serde_json::json!({
1894            "wallet_address": "0x0000000000000000000000000000000000000001",
1895            "username": "trader_1"
1896        }))
1897        .unwrap();
1898
1899        match response {
1900            UsernameLookupEnvelope::Direct(data) => assert_eq!(data.username, "trader_1"),
1901            UsernameLookupEnvelope::Wrapped(_) => panic!("expected direct username response"),
1902        }
1903    }
1904
1905    #[test]
1906    fn username_lookup_accepts_wrapped_response() {
1907        let response: UsernameLookupEnvelope = serde_json::from_value(serde_json::json!({
1908            "success": true,
1909            "data": {
1910                "wallet_address": "0x0000000000000000000000000000000000000001",
1911                "username": "trader_1"
1912            }
1913        }))
1914        .unwrap();
1915
1916        match response {
1917            UsernameLookupEnvelope::Wrapped(data) => {
1918                assert_eq!(data.data.unwrap().username, "trader_1")
1919            }
1920            UsernameLookupEnvelope::Direct(_) => panic!("expected wrapped username response"),
1921        }
1922    }
1923
1924    #[test]
1925    fn markets_response_deserializes_from_server_json() {
1926        let server_json = serde_json::json!({
1927            "success": true,
1928            "data": [{
1929                "underlying": "BTC",
1930                "expiry": 1735689600,
1931                "index_price": "95000",
1932                "atm_vol": "0.65",
1933                "instruments": [{
1934                    "instrument_id": 1,
1935                    "id": "BTC-20260101-100000-C",
1936                    "underlying": "BTC",
1937                    "strike": "100000",
1938                    "expiry": 1735689600,
1939                    "option_type": "call",
1940                    "option_token_address": null,
1941                    "mark_iv": "0.70",
1942                    "volume_24h": "1500",
1943                    "open_interest": "25000",
1944                    "updated_at": "2026-01-01T00:00:00Z",
1945                    "status": "ACTIVE",
1946                    "trading_mode": "orderbook"
1947                }],
1948                "total_volume_24h": "1500",
1949                "total_open_interest": "25000"
1950            }]
1951        });
1952
1953        let resp: MarketsResponse = serde_json::from_value(server_json).unwrap();
1954        assert!(resp.success);
1955        assert_eq!(resp.data.len(), 1);
1956        let inst = &resp.data[0].instruments[0];
1957        assert_eq!(inst.strike, Decimal::new(100000, 0));
1958        assert_eq!(inst.id, "BTC-20260101-100000-C");
1959    }
1960
1961    #[test]
1962    fn portfolio_response_deserializes_from_server_json() {
1963        let server_json = serde_json::json!({
1964            "success": true,
1965            "data": {
1966                "wallet_address": "0x0000000000000000000000000000000000000001",
1967                "positions": [{
1968                    "wallet_address": "0x0000000000000000000000000000000000000001",
1969                    "symbol": "BTC-20260101-100000-C",
1970                    "amount": "2",
1971                    "entry_price": "3000",
1972                    "margin_posted": "100",
1973                    "realized_pnl": "0",
1974                    "unrealized_pnl": "50",
1975                    "updated_at": "2026-01-01T00:00:00Z",
1976                    "notional_value": "6000",
1977                    "maintenance_margin": "0",
1978                    "liquidation_price": "0",
1979                    "margin_ratio": "0"
1980                }],
1981                "total_margin_used": "100",
1982                "available_balance": "900",
1983                "margin_mode": "standard"
1984            }
1985        });
1986
1987        let resp: ApiResponse<PortfolioResponse> = serde_json::from_value(server_json).unwrap();
1988        assert!(resp.success);
1989        let portfolio = resp.data.unwrap();
1990        assert_eq!(portfolio.positions.len(), 1);
1991        assert_eq!(portfolio.total_margin_used, Decimal::new(100, 0));
1992    }
1993}