1#![expect(
6 clippy::result_large_err,
7 reason = "these methods preserve the established unboxed public ClientError contract"
8)]
9use 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_MARGIN_MODE: &str = "/margin-mode";
68const API_ROUTE_LIQUIDATION_STATUS: &str = "/liquidation/status";
69const API_ROUTE_STANDARD_MARGIN_LIQUIDATION: &str = "/liquidation/standard-margin";
70const API_ROUTE_RFQ_REQUEST: &str = "/rfq/request";
71const API_ROUTE_RFQ_ACCEPT: &str = "/rfq/accept";
72
73#[derive(Debug, Clone, Default)]
74pub struct PublicLiquidationsQuery {
75 pub cursor: Option<String>,
76 pub limit: Option<usize>,
77 pub wallet: Option<String>,
78 pub status: Option<String>,
79 pub state: Option<String>,
80 pub margin_mode: Option<String>,
81 pub liquidation_mode: Option<String>,
82}
83
84async fn sonic_json<T: serde::de::DeserializeOwned>(response: reqwest::Response) -> Result<T> {
87 let bytes = response.bytes().await?;
88 sonic_rs::from_slice(&bytes).map_err(ClientError::from)
89}
90
91async fn reqwest_json<T: serde::de::DeserializeOwned>(response: reqwest::Response) -> Result<T> {
92 Ok(response.json().await?)
93}
94
95fn signed_side(side: Side) -> &'static str {
96 match side {
97 Side::Buy => "Buy",
98 Side::Sell => "Sell",
99 }
100}
101
102fn signed_tif(tif: TimeInForce) -> &'static str {
103 match tif {
104 TimeInForce::GTC => "gtc",
105 TimeInForce::IOC => "ioc",
106 TimeInForce::FOK => "fok",
107 }
108}
109
110fn generated_client_id(nonce: u64) -> String {
111 format!("cli_{nonce}")
112}
113
114fn mmp_enabled_or_default(options: &OrderOptions) -> bool {
115 options.mmp_enabled.unwrap_or(false)
116}
117
118fn optional_wallet_address(address: Option<AccountAddress>) -> Option<WalletAddress> {
119 address.map(AccountAddress::into_wallet_address)
120}
121
122mod sealed {
123 pub trait Sealed {}
124}
125
126pub trait OrderDecimalInput: sealed::Sealed {
127 fn into_order_decimal(self) -> Decimal;
128}
129
130impl sealed::Sealed for Decimal {}
131
132impl OrderDecimalInput for Decimal {
133 fn into_order_decimal(self) -> Decimal {
134 self
135 }
136}
137
138#[cfg(feature = "test-utils")]
139impl sealed::Sealed for f64 {}
140
141#[cfg(feature = "test-utils")]
142impl OrderDecimalInput for f64 {
143 fn into_order_decimal(self) -> Decimal {
144 Decimal::from_f64_retain(self).expect("test order price/size must convert to Decimal")
145 }
146}
147
148#[derive(Debug, Clone, Default)]
149pub struct OrderOptions {
150 pub route: Option<OrderRoute>,
151 pub client_id: Option<String>,
152 pub reduce_only: Option<bool>,
153 pub mmp_enabled: Option<bool>,
154 pub builder_code_address: Option<AccountAddress>,
155}
156
157#[derive(Debug, Clone)]
158pub struct PlaceOrderParams<'a> {
159 pub account: AccountAddress,
160 pub symbol: &'a str,
161 pub side: Side,
162 pub price: Decimal,
163 pub size: Decimal,
164 pub tif: TimeInForce,
165 pub nonce: Option<u64>,
166 pub options: OrderOptions,
167}
168
169#[derive(Debug, Clone)]
170pub struct ReplaceOrderParams<'a> {
171 pub account: AccountAddress,
172 pub order_id: u64,
173 pub symbol: &'a str,
174 pub side: Side,
175 pub price: Decimal,
176 pub size: Decimal,
177 pub tif: TimeInForce,
178 pub nonce: Option<u64>,
179 pub options: OrderOptions,
180}
181
182#[derive(Debug, Clone)]
183pub struct BulkOrderParams<'a> {
184 pub symbol: &'a str,
185 pub side: Side,
186 pub price: Decimal,
187 pub size: Decimal,
188 pub tif: TimeInForce,
189 pub options: OrderOptions,
190}
191
192#[derive(Debug, Clone)]
193pub struct BulkReplaceOrderParams<'a> {
194 pub order_id: u64,
195 pub symbol: &'a str,
196 pub side: Side,
197 pub price: Decimal,
198 pub size: Decimal,
199 pub tif: TimeInForce,
200 pub options: OrderOptions,
201}
202
203#[derive(Debug, Clone)]
204pub struct StandardMarginLiquidationParams {
205 pub liquidated_wallet: AccountAddress,
206 pub request_id: uuid::Uuid,
209 pub auction_id: String,
210 pub bid_usdc: String,
211 pub positions: Vec<StandardMarginLiquidationPositionRequest>,
212 pub portfolio_hash: String,
213 pub auction_terms_hash: String,
214 pub auction_version: u64,
215 pub valuation_timestamp_ms: u64,
216 pub bid_intent_hash: String,
217 pub nonce: Option<u64>,
218}
219
220#[derive(Clone)]
222pub struct HypercallClient {
223 client: Client,
224 base_url: String,
225 pub(crate) server_clock: crate::tee_perp::ServerClock,
228}
229
230impl HypercallClient {
231 pub fn new(base_url: impl Into<String>) -> Self {
233 Self::with_timeout(base_url, Duration::from_secs(30))
234 }
235
236 pub fn with_timeout(base_url: impl Into<String>, timeout: Duration) -> Self {
241 let client = Client::builder()
242 .redirect(RedirectPolicy::none())
243 .timeout(timeout)
244 .user_agent("hypercall-client/0.1")
245 .build()
246 .expect("failed to build reqwest client");
247
248 let base_url = base_url.into().trim_end_matches('/').to_string();
249 Self {
250 client,
251 base_url,
252 server_clock: crate::tee_perp::ServerClock::default(),
253 }
254 }
255
256 pub fn base_url(&self) -> &str {
258 &self.base_url
259 }
260
261 fn route_url(&self, route: &str) -> String {
262 format!("{}{}", self.base_url, route)
263 }
264
265 pub(crate) fn request(&self, method: Method, route: &str) -> RequestBuilder {
266 self.client.request(method, self.route_url(route))
267 }
268
269 async fn ensure_success(
270 response: reqwest::Response,
271 action: &str,
272 ) -> Result<reqwest::Response> {
273 if response.status().is_success() {
274 return Ok(response);
275 }
276 let status = response.status().as_u16();
277 let text = response.text().await.unwrap_or_default();
278 Err(ClientError::Api {
279 status,
280 message: format!("{action}: {text}"),
281 })
282 }
283
284 async fn send(request: RequestBuilder, action: &str) -> Result<reqwest::Response> {
285 Self::ensure_success(request.send().await?, action).await
286 }
287
288 pub(crate) async fn send_reqwest_json<T: serde::de::DeserializeOwned>(
289 request: RequestBuilder,
290 action: &str,
291 ) -> Result<T> {
292 reqwest_json(Self::send(request, action).await?).await
293 }
294
295 async fn send_sonic_json<T: serde::de::DeserializeOwned>(
296 request: RequestBuilder,
297 action: &str,
298 ) -> Result<T> {
299 sonic_json(Self::send(request, action).await?).await
300 }
301
302 pub(crate) async fn send_json_body<T, B>(
303 request: RequestBuilder,
304 body: &B,
305 action: &str,
306 ) -> Result<T>
307 where
308 T: serde::de::DeserializeOwned,
309 B: Serialize + ?Sized,
310 {
311 Self::send_reqwest_json(request.json(body), action).await
312 }
313
314 async fn post_json_sonic<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
315 where
316 T: serde::de::DeserializeOwned,
317 B: Serialize + ?Sized,
318 {
319 Self::send_sonic_json(self.request(Method::POST, route).json(body), action).await
320 }
321
322 pub async fn raw_post(&self, path: &str, body: &sonic_rs::Value) -> Result<reqwest::Response> {
324 let url = format!("{}{}", self.base_url, path);
325 let body_bytes = sonic_rs::to_vec(body)?;
326 Ok(self
327 .client
328 .post(&url)
329 .header("content-type", "application/json")
330 .body(body_bytes)
331 .send()
332 .await?)
333 }
334
335 pub async fn health_check(&self) -> Result<()> {
337 self.health_check_with_timeout(Duration::from_secs(30))
338 .await
339 }
340
341 pub async fn health_check_with_timeout(&self, timeout: Duration) -> Result<()> {
343 let response = self
344 .client
345 .get(format!("{}/health", self.base_url))
346 .timeout(timeout)
347 .send()
348 .await?;
349
350 if response.status().is_success() {
351 Ok(())
352 } else {
353 Err(ClientError::Api {
354 status: response.status().as_u16(),
355 message: "Health check failed".to_string(),
356 })
357 }
358 }
359
360 pub async fn ready_check(&self) -> Result<()> {
362 self.ready_check_with_timeout(Duration::from_secs(30)).await
363 }
364
365 pub async fn ready_check_with_timeout(&self, timeout: Duration) -> Result<()> {
367 let response = self
368 .client
369 .get(format!("{}/ready", self.base_url))
370 .timeout(timeout)
371 .send()
372 .await?;
373
374 if response.status().is_success() {
375 Ok(())
376 } else {
377 Err(ClientError::Api {
378 status: response.status().as_u16(),
379 message: "Readiness check failed".to_string(),
380 })
381 }
382 }
383
384 pub async fn get_exchange_info(&self) -> Result<ExchangeInfoResponse> {
386 Self::send_reqwest_json(
387 self.client.get(format!("{}/exchange-info", self.base_url)),
388 "get exchange info",
389 )
390 .await
391 }
392
393 pub async fn get_instrument_specs(
395 &self,
396 currency: &str,
397 ) -> Result<Vec<InstrumentSpecResponse>> {
398 let body: JsonRpcResponse<Vec<InstrumentSpecResponse>> = Self::send_reqwest_json(
399 self.client.get(format!(
400 "{}/instrument-specs?currency={}",
401 self.base_url, currency
402 )),
403 "get instrument specs",
404 )
405 .await?;
406 body.result.ok_or_else(|| ClientError::Api {
407 status: 200,
408 message: body
409 .error
410 .map(|err| err.message)
411 .unwrap_or_else(|| "No instrument specs returned".to_string()),
412 })
413 }
414
415 pub async fn get_markets(&self) -> Result<Vec<Market>> {
417 let markets_response: MarketsResponse = Self::send_reqwest_json(
418 self.client.get(format!("{}/markets", self.base_url)),
419 "get markets",
420 )
421 .await?;
422 if !markets_response.success {
423 return Err(ClientError::Api {
424 status: 200,
425 message: "Markets endpoint reported failure".to_string(),
426 });
427 }
428
429 let mut markets = Vec::new();
430 for market_info in markets_response.data {
431 for instrument in market_info.instruments {
432 markets.push(Market {
433 symbol: instrument.id.clone(),
434 strike: instrument.strike,
435 underlying: instrument.underlying.clone(),
436 expiry: instrument.expiry,
437 option_type: if instrument.option_type.eq_ignore_ascii_case("call") {
438 hypercall_sdk_types::OptionType::Call
439 } else {
440 hypercall_sdk_types::OptionType::Put
441 },
442 });
443 }
444 }
445 Ok(markets)
446 }
447
448 pub async fn place_order<P, Q>(
450 &self,
451 wallet: &HypercallWallet,
452 symbol: &str,
453 side: Side,
454 price: P,
455 size: Q,
456 tif: TimeInForce,
457 ) -> Result<OrderMessage>
458 where
459 P: OrderDecimalInput,
460 Q: OrderDecimalInput,
461 {
462 let nonce = wallet.next_nonce();
463 self.place_order_with_params(
464 wallet,
465 PlaceOrderParams {
466 account: wallet.address,
467 symbol,
468 side,
469 price: price.into_order_decimal(),
470 size: size.into_order_decimal(),
471 tif,
472 nonce: Some(nonce),
473 options: OrderOptions::default(),
474 },
475 )
476 .await
477 }
478
479 pub async fn place_order_with_nonce(
483 &self,
484 wallet: &HypercallWallet,
485 nonce: u64,
486 order: BulkOrderParams<'_>,
487 ) -> Result<OrderMessage> {
488 self.place_order_with_params(
489 wallet,
490 PlaceOrderParams {
491 account: wallet.address,
492 symbol: order.symbol,
493 side: order.side,
494 price: order.price,
495 size: order.size,
496 tif: order.tif,
497 nonce: Some(nonce),
498 options: order.options,
499 },
500 )
501 .await
502 }
503
504 pub async fn place_order_for_wallet(
506 &self,
507 signer: &HypercallWallet,
508 account: AccountAddress,
509 order: BulkOrderParams<'_>,
510 ) -> Result<OrderMessage> {
511 self.place_order_with_params(
512 signer,
513 PlaceOrderParams {
514 account,
515 symbol: order.symbol,
516 side: order.side,
517 price: order.price,
518 size: order.size,
519 tif: order.tif,
520 nonce: None,
521 options: order.options,
522 },
523 )
524 .await
525 }
526
527 pub async fn place_order_for_wallet_with_nonce(
529 &self,
530 signer: &HypercallWallet,
531 account: AccountAddress,
532 nonce: u64,
533 order: BulkOrderParams<'_>,
534 ) -> Result<OrderMessage> {
535 self.place_order_with_params(
536 signer,
537 PlaceOrderParams {
538 account,
539 symbol: order.symbol,
540 side: order.side,
541 price: order.price,
542 size: order.size,
543 tif: order.tif,
544 nonce: Some(nonce),
545 options: order.options,
546 },
547 )
548 .await
549 }
550
551 pub async fn place_order_with_params<S>(
552 &self,
553 signer: &S,
554 params: PlaceOrderParams<'_>,
555 ) -> Result<OrderMessage>
556 where
557 S: HypercallSigner + ?Sized,
558 {
559 let route = params.options.route.unwrap_or(OrderRoute::BestExecution);
560 let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
561 let side_str = signed_side(params.side);
562 let tif_str = signed_tif(params.tif);
563 let price_str = params.price.to_string();
564 let size_str = params.size.to_string();
565 let mmp_enabled = mmp_enabled_or_default(¶ms.options);
566 let reduce_only = params.options.reduce_only.unwrap_or(false);
567 let client_id = params
568 .options
569 .client_id
570 .unwrap_or_else(|| generated_client_id(nonce));
571
572 let signature = signer
573 .sign_place_order_payload(PlaceOrderSignature {
574 wallet: params.account,
575 symbol: params.symbol,
576 side: side_str,
577 size: &size_str,
578 price: &price_str,
579 tif: tif_str,
580 route,
581 client_id: &client_id,
582 reduce_only,
583 nonce,
584 })
585 .await?;
586
587 let request = PlaceOrderRequest {
588 wallet: params.account.into_wallet_address(),
589 price: price_str,
590 size: size_str,
591 symbol: params.symbol.to_string(),
592 side: params.side,
593 tif: params.tif,
594 route: Some(route),
595 client_id: Some(client_id),
596 nonce,
597 signature,
598 reduce_only,
599 mmp_enabled,
600 builder_code_address: optional_wallet_address(params.options.builder_code_address),
601 };
602
603 Self::send_json_body(
604 self.request(Method::POST, API_ROUTE_ORDER),
605 &request,
606 "place order",
607 )
608 .await
609 }
610
611 pub async fn cancel_order<S>(&self, wallet: &S, order_id: u64) -> Result<Value>
613 where
614 S: HypercallSigner + ?Sized,
615 {
616 self.cancel_order_for_wallet(wallet, wallet.address(), order_id)
617 .await
618 }
619
620 pub async fn cancel_order_for_wallet<S>(
622 &self,
623 signer: &S,
624 account: AccountAddress,
625 order_id: u64,
626 ) -> Result<Value>
627 where
628 S: HypercallSigner + ?Sized,
629 {
630 let nonce = signer.next_nonce();
631 self.cancel_order_for_wallet_with_nonce(signer, account, order_id, nonce)
632 .await
633 }
634
635 pub async fn cancel_order_for_wallet_with_nonce<S>(
637 &self,
638 signer: &S,
639 account: AccountAddress,
640 order_id: u64,
641 nonce: u64,
642 ) -> Result<Value>
643 where
644 S: HypercallSigner + ?Sized,
645 {
646 let order_id_str = order_id.to_string();
647
648 let signature = signer
649 .sign_cancel_order_payload(CancelOrderSignature {
650 wallet: account,
651 order_id: &order_id_str,
652 nonce,
653 })
654 .await?;
655
656 Self::send_sonic_json(
657 self.request(Method::DELETE, API_ROUTE_ORDER).json(&json!({
658 "wallet": account,
659 "order_id": order_id,
660 "nonce": nonce,
661 "signature": signature,
662 })),
663 "cancel order",
664 )
665 .await
666 }
667
668 pub async fn replace_order_with_params<S>(
670 &self,
671 signer: &S,
672 params: ReplaceOrderParams<'_>,
673 ) -> Result<OrderMessage>
674 where
675 S: HypercallSigner + ?Sized,
676 {
677 let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
678 let side_str = signed_side(params.side);
679 let tif_str = signed_tif(params.tif);
680 let price_str = params.price.to_string();
681 let size_str = params.size.to_string();
682 let order_id_str = params.order_id.to_string();
683 let mmp_enabled = mmp_enabled_or_default(¶ms.options);
684 let reduce_only = params.options.reduce_only.unwrap_or(false);
685 let client_id = params
686 .options
687 .client_id
688 .unwrap_or_else(|| generated_client_id(nonce));
689
690 let signature = signer
691 .sign_replace_order_payload(ReplaceOrderSignature {
692 wallet: params.account,
693 order_id: &order_id_str,
694 symbol: params.symbol,
695 side: side_str,
696 size: &size_str,
697 price: &price_str,
698 tif: tif_str,
699 client_id: &client_id,
700 reduce_only,
701 nonce,
702 })
703 .await?;
704
705 let request = ReplaceOrderRequest {
706 wallet: params.account.into_wallet_address(),
707 order_id: params.order_id,
708 price: price_str,
709 size: size_str,
710 symbol: params.symbol.to_string(),
711 side: params.side,
712 tif: params.tif,
713 client_id: Some(client_id),
714 nonce,
715 signature,
716 reduce_only,
717 mmp_enabled,
718 builder_code_address: optional_wallet_address(params.options.builder_code_address),
719 };
720
721 Self::send_json_body(
722 self.request(Method::PUT, API_ROUTE_ORDER),
723 &request,
724 "replace order",
725 )
726 .await
727 }
728
729 pub const MAX_BULK_CHUNK_SIZE: usize = 50;
731
732 pub async fn bulk_place_orders<S, P, Q>(
734 &self,
735 wallet: &S,
736 orders: Vec<(&str, Side, P, Q, TimeInForce)>,
737 ) -> Result<BulkPlaceOrderResponse>
738 where
739 S: HypercallSigner + ?Sized,
740 P: OrderDecimalInput,
741 Q: OrderDecimalInput,
742 {
743 let orders = orders
744 .into_iter()
745 .map(|(symbol, side, price, size, tif)| BulkOrderParams {
746 symbol,
747 side,
748 price: price.into_order_decimal(),
749 size: size.into_order_decimal(),
750 tif,
751 options: OrderOptions {
752 route: Some(OrderRoute::BookOnly),
753 ..OrderOptions::default()
754 },
755 })
756 .collect();
757 self.bulk_place_orders_with_params(wallet, orders).await
758 }
759
760 pub async fn bulk_place_orders_with_params<S>(
761 &self,
762 wallet: &S,
763 orders: Vec<BulkOrderParams<'_>>,
764 ) -> Result<BulkPlaceOrderResponse>
765 where
766 S: HypercallSigner + ?Sized,
767 {
768 info!("Placing {} orders in bulk", orders.len());
769
770 let mut order_requests = Vec::with_capacity(orders.len());
771
772 for order in orders {
773 let nonce = wallet.next_nonce();
774 let side_str = signed_side(order.side);
775 let tif_str = signed_tif(order.tif);
776 let price_str = order.price.to_string();
777 let size_str = order.size.to_string();
778 let mmp_enabled = mmp_enabled_or_default(&order.options);
779 let reduce_only = order.options.reduce_only.unwrap_or(false);
780 let client_id = order
781 .options
782 .client_id
783 .unwrap_or_else(|| generated_client_id(nonce));
784 let route = order.options.route.unwrap_or(OrderRoute::BookOnly);
785
786 let signature = wallet
787 .sign_place_order_payload(PlaceOrderSignature {
788 wallet: wallet.address(),
789 symbol: order.symbol,
790 side: side_str,
791 size: &size_str,
792 price: &price_str,
793 tif: tif_str,
794 route,
795 client_id: &client_id,
796 reduce_only,
797 nonce,
798 })
799 .await?;
800
801 order_requests.push(PlaceOrderRequest {
802 wallet: wallet.address().into_wallet_address(),
803 price: price_str,
804 size: size_str,
805 symbol: order.symbol.to_string(),
806 side: order.side,
807 tif: order.tif,
808 route: Some(route),
809 client_id: Some(client_id),
810 nonce,
811 signature,
812 reduce_only,
813 mmp_enabled,
814 builder_code_address: optional_wallet_address(order.options.builder_code_address),
815 });
816 }
817
818 let mut all_results = Vec::with_capacity(order_requests.len());
819
820 for chunk in order_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
821 let payload = BulkPlaceOrderRequest {
822 orders: chunk.to_vec(),
823 };
824
825 let bulk_response: BulkPlaceOrderResponse = Self::send_json_body(
826 self.request(Method::POST, API_ROUTE_BULK_ORDER),
827 &payload,
828 "place bulk orders",
829 )
830 .await?;
831 all_results.extend(bulk_response.results);
832 }
833
834 Ok(BulkPlaceOrderResponse {
835 results: all_results,
836 })
837 }
838
839 pub async fn bulk_cancel_orders<S>(
841 &self,
842 wallet: &S,
843 order_ids: Vec<u64>,
844 ) -> Result<BulkCancelOrderResponse>
845 where
846 S: HypercallSigner + ?Sized,
847 {
848 self.bulk_cancel_orders_for_wallet(wallet, wallet.address(), order_ids)
849 .await
850 }
851
852 pub async fn bulk_cancel_orders_for_wallet<S>(
854 &self,
855 signer: &S,
856 account: AccountAddress,
857 order_ids: Vec<u64>,
858 ) -> Result<BulkCancelOrderResponse>
859 where
860 S: HypercallSigner + ?Sized,
861 {
862 info!("Canceling {} orders in bulk", order_ids.len());
863
864 let mut cancel_requests = Vec::with_capacity(order_ids.len());
865
866 for order_id in &order_ids {
867 let nonce = signer.next_nonce();
868 let order_id_str = order_id.to_string();
869 let signature = signer
870 .sign_cancel_order_payload(CancelOrderSignature {
871 wallet: account,
872 order_id: &order_id_str,
873 nonce,
874 })
875 .await?;
876
877 cancel_requests.push(json!({
878 "wallet": account,
879 "order_id": order_id,
880 "nonce": nonce,
881 "signature": signature,
882 }));
883 }
884
885 let mut all_results = Vec::with_capacity(cancel_requests.len());
886
887 for chunk in cancel_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
888 let bulk_response: BulkCancelOrderResponse = Self::send_json_body(
889 self.request(Method::DELETE, API_ROUTE_BULK_ORDER),
890 &json!({ "cancels": chunk }),
891 "cancel bulk orders",
892 )
893 .await?;
894 all_results.extend(bulk_response.results);
895 }
896
897 Ok(BulkCancelOrderResponse {
898 results: all_results,
899 })
900 }
901
902 pub async fn bulk_replace_orders<S, P, Q>(
906 &self,
907 wallet: &S,
908 replacements: Vec<(u64, &str, Side, P, Q, TimeInForce)>,
909 ) -> Result<BulkPlaceOrderResponse>
910 where
911 S: HypercallSigner + ?Sized,
912 P: OrderDecimalInput,
913 Q: OrderDecimalInput,
914 {
915 let replacements = replacements
916 .into_iter()
917 .map(
918 |(order_id, symbol, side, price, size, tif)| BulkReplaceOrderParams {
919 order_id,
920 symbol,
921 side,
922 price: price.into_order_decimal(),
923 size: size.into_order_decimal(),
924 tif,
925 options: OrderOptions::default(),
926 },
927 )
928 .collect();
929 self.bulk_replace_orders_with_params(wallet, replacements)
930 .await
931 }
932
933 pub async fn bulk_replace_orders_with_params<S>(
934 &self,
935 wallet: &S,
936 replacements: Vec<BulkReplaceOrderParams<'_>>,
937 ) -> Result<BulkPlaceOrderResponse>
938 where
939 S: HypercallSigner + ?Sized,
940 {
941 info!("Replacing {} orders in bulk", replacements.len());
942
943 let mut replace_requests = Vec::with_capacity(replacements.len());
944
945 for replacement in replacements {
946 let nonce = wallet.next_nonce();
947 let side_str = signed_side(replacement.side);
948 let tif_str = signed_tif(replacement.tif);
949 let price_str = replacement.price.to_string();
950 let size_str = replacement.size.to_string();
951 let order_id_str = replacement.order_id.to_string();
952 let mmp_enabled = mmp_enabled_or_default(&replacement.options);
953 let reduce_only = replacement.options.reduce_only.unwrap_or(false);
954 let client_id = replacement
955 .options
956 .client_id
957 .unwrap_or_else(|| generated_client_id(nonce));
958
959 let signature = wallet
960 .sign_replace_order_payload(ReplaceOrderSignature {
961 wallet: wallet.address(),
962 order_id: &order_id_str,
963 symbol: replacement.symbol,
964 side: side_str,
965 size: &size_str,
966 price: &price_str,
967 tif: tif_str,
968 client_id: &client_id,
969 reduce_only,
970 nonce,
971 })
972 .await?;
973
974 replace_requests.push(ReplaceOrderRequest {
975 wallet: wallet.address().into_wallet_address(),
976 order_id: replacement.order_id,
977 price: price_str,
978 size: size_str,
979 symbol: replacement.symbol.to_string(),
980 side: replacement.side,
981 tif: replacement.tif,
982 client_id: Some(client_id),
983 nonce,
984 signature,
985 reduce_only,
986 mmp_enabled,
987 builder_code_address: optional_wallet_address(
988 replacement.options.builder_code_address,
989 ),
990 });
991 }
992
993 let mut all_results = Vec::with_capacity(replace_requests.len());
994
995 for chunk in replace_requests.chunks(Self::MAX_BULK_CHUNK_SIZE) {
996 let bulk_response: BulkPlaceOrderResponse = Self::send_sonic_json(
997 self.request(Method::PUT, API_ROUTE_BULK_ORDER)
998 .json(&sonic_rs::json!({ "replacements": chunk })),
999 "replace bulk orders",
1000 )
1001 .await?;
1002 all_results.extend(bulk_response.results);
1003 }
1004
1005 Ok(BulkPlaceOrderResponse {
1006 results: all_results,
1007 })
1008 }
1009
1010 pub async fn get_orders(
1012 &self,
1013 wallet: impl Into<AccountAddress>,
1014 status: Option<&str>,
1015 ) -> Result<Value> {
1016 let wallet = wallet.into();
1017 let mut url = format!("{}?wallet={}", self.route_url(API_ROUTE_ORDERS), wallet);
1018 if let Some(status_filter) = status {
1019 url.push_str(&format!("&status={}", status_filter));
1020 }
1021
1022 Self::send_sonic_json(self.client.get(&url), "get orders").await
1023 }
1024
1025 pub async fn get_orders_typed(
1027 &self,
1028 wallet: impl Into<AccountAddress>,
1029 status: Option<&str>,
1030 limit: Option<usize>,
1031 offset: Option<usize>,
1032 ) -> Result<OrdersApiResponse> {
1033 let wallet = wallet.into();
1034 let mut query = vec![("wallet", wallet.to_string())];
1035 if let Some(status_filter) = status {
1036 query.push(("status", status_filter.to_string()));
1037 }
1038 if let Some(limit) = limit {
1039 query.push(("limit", limit.to_string()));
1040 }
1041 if let Some(offset) = offset {
1042 query.push(("offset", offset.to_string()));
1043 }
1044 Self::send_reqwest_json(
1045 self.request(Method::GET, API_ROUTE_ORDERS).query(&query),
1046 "get typed orders",
1047 )
1048 .await
1049 }
1050
1051 pub async fn get_all_orders(
1053 &self,
1054 wallet: impl Into<AccountAddress>,
1055 status: Option<&str>,
1056 ) -> Result<Vec<Value>> {
1057 let wallet = wallet.into();
1058 let mut all_orders = Vec::new();
1059 let mut offset = 0;
1060
1061 loop {
1062 let mut url = format!(
1063 "{}/orders?wallet={}&offset={}",
1064 self.base_url, wallet, offset
1065 );
1066 if let Some(status_filter) = status {
1067 url.push_str(&format!("&status={}", status_filter));
1068 }
1069
1070 let result: Value = Self::send_sonic_json(self.client.get(&url), "get orders").await?;
1071 let pagination = result
1072 .get("pagination")
1073 .ok_or_else(|| invalid_orders_pagination("missing pagination object"))?;
1074 let returned_limit = pagination
1075 .get("limit")
1076 .and_then(|value| value.as_u64())
1077 .and_then(|value| usize::try_from(value).ok())
1078 .ok_or_else(|| invalid_orders_pagination("invalid pagination.limit"))?;
1079 let returned_offset = pagination
1080 .get("offset")
1081 .and_then(|value| value.as_u64())
1082 .and_then(|value| usize::try_from(value).ok())
1083 .ok_or_else(|| invalid_orders_pagination("invalid pagination.offset"))?;
1084 let data = result.get("data").unwrap_or(&result);
1085 let page: Vec<Value> = match data.as_array() {
1086 Some(arr) => arr.iter().cloned().collect(),
1087 None => break,
1088 };
1089
1090 let count = page.len();
1091 all_orders.extend(page);
1092 match next_orders_page_offset(offset, returned_offset, returned_limit, count)? {
1093 Some(next_offset) => offset = next_offset,
1094 None => break,
1095 }
1096 }
1097
1098 Ok(all_orders)
1099 }
1100
1101 pub async fn get_all_orders_typed(
1103 &self,
1104 wallet: impl Into<AccountAddress>,
1105 status: Option<&str>,
1106 ) -> Result<Vec<Order>> {
1107 let wallet = wallet.into();
1108 let mut orders = Vec::new();
1109 let mut offset = 0;
1110 loop {
1111 let page = self
1112 .get_orders_typed(wallet, status, None, Some(offset))
1113 .await?;
1114 let count = page.data.len();
1115 let next_offset = next_orders_page_offset(
1116 offset,
1117 page.pagination.offset,
1118 page.pagination.limit,
1119 count,
1120 )?;
1121 orders.extend(page.data);
1122 match next_offset {
1123 Some(next_offset) => offset = next_offset,
1124 None => break,
1125 }
1126 }
1127 Ok(orders)
1128 }
1129
1130 pub async fn get_fills(
1132 &self,
1133 wallet: impl Into<AccountAddress>,
1134 limit: Option<usize>,
1135 offset: Option<usize>,
1136 ) -> Result<Value> {
1137 let wallet = wallet.into();
1138 let mut url = format!("{}/fills?wallet={}", self.base_url, wallet);
1139 if let Some(limit_val) = limit {
1140 url.push_str(&format!("&limit={}", limit_val));
1141 }
1142 if let Some(offset_val) = offset {
1143 url.push_str(&format!("&offset={}", offset_val));
1144 }
1145
1146 Self::send_sonic_json(self.client.get(&url), "get fills").await
1147 }
1148
1149 pub async fn get_fills_typed(
1151 &self,
1152 wallet: impl Into<AccountAddress>,
1153 limit: Option<usize>,
1154 offset: Option<usize>,
1155 ) -> Result<hypercall_sdk_types::FillsResponse> {
1156 let wallet = wallet.into();
1157 let mut query = vec![("wallet", wallet.to_string())];
1158 if let Some(limit) = limit {
1159 query.push(("limit", limit.to_string()));
1160 }
1161 if let Some(offset) = offset {
1162 query.push(("offset", offset.to_string()));
1163 }
1164 Self::send_reqwest_json(
1165 self.request(Method::GET, "/fills").query(&query),
1166 "get typed fills",
1167 )
1168 .await
1169 }
1170
1171 pub async fn get_portfolio(
1173 &self,
1174 wallet: impl Into<AccountAddress>,
1175 ) -> Result<PortfolioResponse> {
1176 let wallet = wallet.into();
1177 let result: ApiResponse<PortfolioResponse> = Self::send_reqwest_json(
1178 self.client
1179 .get(format!("{}/portfolio?wallet={}", self.base_url, wallet)),
1180 "get portfolio",
1181 )
1182 .await?;
1183 if !result.success {
1184 return Err(ClientError::Api {
1185 status: 200,
1186 message: result
1187 .error
1188 .unwrap_or_else(|| "Portfolio request failed".to_string()),
1189 });
1190 }
1191 result.data.ok_or_else(|| ClientError::Api {
1192 status: 200,
1193 message: result
1194 .error
1195 .unwrap_or_else(|| "No portfolio data returned".to_string()),
1196 })
1197 }
1198
1199 pub async fn get_portfolio_snapshot(
1201 &self,
1202 wallet: impl Into<AccountAddress>,
1203 ) -> Result<Portfolio> {
1204 let wallet = wallet.into();
1205 let result: hypercall_sdk_types::CanonicalApiResponse<Portfolio> = Self::send_reqwest_json(
1206 self.request(Method::GET, "/portfolio")
1207 .query(&[("wallet", wallet.to_string())]),
1208 "get canonical portfolio",
1209 )
1210 .await?;
1211 if !result.success {
1212 return Err(ClientError::Api {
1213 status: 200,
1214 message: result
1215 .error
1216 .unwrap_or_else(|| "Portfolio request failed".to_string()),
1217 });
1218 }
1219 result.data.ok_or_else(|| ClientError::Api {
1220 status: 200,
1221 message: result
1222 .error
1223 .unwrap_or_else(|| "No portfolio data returned".to_string()),
1224 })
1225 }
1226
1227 pub async fn get_public_liquidations(
1229 &self,
1230 query: &PublicLiquidationsQuery,
1231 ) -> Result<PublicLiquidationsResponse> {
1232 let mut params = Vec::new();
1233 if let Some(cursor) = &query.cursor {
1234 params.push(("cursor", cursor.clone()));
1235 }
1236 if let Some(limit) = query.limit {
1237 params.push(("limit", limit.to_string()));
1238 }
1239 if let Some(wallet) = &query.wallet {
1240 params.push(("wallet", wallet.clone()));
1241 }
1242 if let Some(status) = &query.status {
1243 params.push(("status", status.clone()));
1244 }
1245 if let Some(state) = &query.state {
1246 params.push(("state", state.clone()));
1247 }
1248 if let Some(margin_mode) = &query.margin_mode {
1249 params.push(("margin_mode", margin_mode.clone()));
1250 }
1251 if let Some(liquidation_mode) = &query.liquidation_mode {
1252 params.push(("liquidation_mode", liquidation_mode.clone()));
1253 }
1254
1255 let mut request = self.client.get(format!("{}/liquidations", self.base_url));
1256 if !params.is_empty() {
1257 request = request.query(¶ms);
1258 }
1259 let response = request.send().await?;
1260
1261 if !response.status().is_success() {
1262 let status = response.status().as_u16();
1263 let text = response.text().await.unwrap_or_default();
1264 return Err(ClientError::Api {
1265 status,
1266 message: format!("Failed to get liquidations: {}", text),
1267 });
1268 }
1269
1270 let result: PublicLiquidationsResponse = sonic_json(response).await?;
1271 if !result.success {
1272 return Err(ClientError::Api {
1273 status: 200,
1274 message: result
1275 .error
1276 .clone()
1277 .unwrap_or_else(|| "Liquidations request failed".to_string()),
1278 });
1279 }
1280 Ok(result)
1281 }
1282
1283 pub async fn get_liquidation_status(
1285 &self,
1286 wallet: impl Into<AccountAddress>,
1287 ) -> Result<Option<LiquidationStatusData>> {
1288 let wallet = wallet.into();
1289 let result: LiquidationStatusResponse = Self::send_sonic_json(
1290 self.client
1291 .get(self.route_url(API_ROUTE_LIQUIDATION_STATUS))
1292 .query(&[("wallet", wallet.to_string())]),
1293 "get liquidation status",
1294 )
1295 .await?;
1296 if !result.success {
1297 return Err(ClientError::Api {
1298 status: 200,
1299 message: result
1300 .error
1301 .clone()
1302 .unwrap_or_else(|| "Liquidation status request failed".to_string()),
1303 });
1304 }
1305 Ok(result.data)
1306 }
1307
1308 pub async fn get_historical_pnl(
1314 &self,
1315 wallet: impl Into<AccountAddress>,
1316 interval: HistoricalPnlInterval,
1317 limit: Option<usize>,
1318 include_attribution: Option<bool>,
1319 ) -> Result<HistoricalPnlResponse> {
1320 let wallet = wallet.into();
1321 let mut request = self
1322 .client
1323 .get(format!("{}/historical-pnl", self.base_url))
1324 .query(&[
1325 ("wallet", wallet.to_string()),
1326 ("interval", interval.as_str().to_string()),
1327 ]);
1328
1329 if let Some(limit_value) = limit {
1330 request = request.query(&[("limit", limit_value.to_string())]);
1331 }
1332
1333 if let Some(true) = include_attribution {
1334 request = request.query(&[("include_attribution", "true")]);
1335 }
1336
1337 let result: ApiResponse<HistoricalPnlResponse> =
1338 Self::send_reqwest_json(request, "get historical pnl").await?;
1339 if !result.success {
1340 return Err(ClientError::Api {
1341 status: 200,
1342 message: result
1343 .error
1344 .unwrap_or_else(|| "Historical pnl request failed".to_string()),
1345 });
1346 }
1347
1348 result.data.ok_or_else(|| ClientError::Api {
1349 status: 200,
1350 message: result
1351 .error
1352 .unwrap_or_else(|| "No historical pnl data returned".to_string()),
1353 })
1354 }
1355
1356 pub async fn get_historical_theos(
1358 &self,
1359 instrument_name: &str,
1360 interval: HistoricalTheoInterval,
1361 limit: Option<usize>,
1362 ) -> Result<HistoricalTheoResponse> {
1363 let mut request = self
1364 .client
1365 .get(format!("{}/historical-theos", self.base_url))
1366 .query(&[
1367 ("instrument_name", instrument_name.to_string()),
1368 ("interval", interval.as_str().to_string()),
1369 ]);
1370
1371 if let Some(limit_value) = limit {
1372 request = request.query(&[("limit", limit_value.to_string())]);
1373 }
1374
1375 let result: ApiResponse<HistoricalTheoResponse> =
1376 Self::send_reqwest_json(request, "get historical theos").await?;
1377 if !result.success {
1378 return Err(ClientError::Api {
1379 status: 200,
1380 message: result
1381 .error
1382 .unwrap_or_else(|| "Historical theos request failed".to_string()),
1383 });
1384 }
1385
1386 result.data.ok_or_else(|| ClientError::Api {
1387 status: 200,
1388 message: result
1389 .error
1390 .unwrap_or_else(|| "No historical theo data returned".to_string()),
1391 })
1392 }
1393
1394 pub async fn set_margin_mode(
1396 &self,
1397 wallet: &HypercallWallet,
1398 margin_mode: &str,
1399 ) -> Result<Value> {
1400 info!(
1401 "Setting margin mode to {} for {}",
1402 margin_mode, wallet.address
1403 );
1404
1405 let nonce = wallet.next_nonce();
1406 let signature = wallet.sign_set_margin_mode(margin_mode, nonce).await?;
1407
1408 let response = self
1409 .client
1410 .post(self.route_url(API_ROUTE_MARGIN_MODE))
1411 .json(&json!({
1412 "wallet": wallet.address.to_string(),
1413 "margin_mode": margin_mode,
1414 "nonce": nonce,
1415 "signature": signature,
1416 }))
1417 .send()
1418 .await?;
1419
1420 if !response.status().is_success() {
1421 let status = response.status().as_u16();
1422 let text = response.text().await.unwrap_or_default();
1423 return Err(ClientError::Api {
1424 status,
1425 message: format!("Failed to set margin mode: {}", text),
1426 });
1427 }
1428
1429 let result: Value = sonic_json(response).await?;
1430 Ok(result)
1431 }
1432
1433 pub async fn set_margin_mode_typed(
1435 &self,
1436 wallet: &HypercallWallet,
1437 margin_mode: MarginMode,
1438 ) -> Result<Value> {
1439 self.set_margin_mode(wallet, margin_mode.as_str()).await
1440 }
1441
1442 pub async fn submit_standard_margin_liquidation_with_params<S>(
1443 &self,
1444 liquidator: &S,
1445 params: StandardMarginLiquidationParams,
1446 ) -> Result<StandardMarginLiquidationOrderResponse>
1447 where
1448 S: HypercallSigner + ?Sized,
1449 {
1450 let nonce = params.nonce.unwrap_or_else(|| liquidator.next_nonce());
1451 let request_id = params.request_id.to_string();
1452 let signature = liquidator
1453 .sign_standard_margin_liquidation_payload(StandardMarginLiquidationSignature {
1454 wallet: liquidator.address(),
1455 liquidated_wallet: params.liquidated_wallet,
1456 request_id: &request_id,
1457 auction_id: ¶ms.auction_id,
1458 bid_usdc: ¶ms.bid_usdc,
1459 portfolio_hash: ¶ms.portfolio_hash,
1460 auction_terms_hash: ¶ms.auction_terms_hash,
1461 bid_intent_hash: ¶ms.bid_intent_hash,
1462 auction_version: params.auction_version,
1463 nonce,
1464 })
1465 .await?;
1466 let request = StandardMarginLiquidationOrderRequest {
1467 wallet: liquidator.address().into_wallet_address(),
1468 liquidated_wallet: params.liquidated_wallet.into_wallet_address(),
1469 request_id: params.request_id,
1470 auction_id: params.auction_id,
1471 bid_usdc: params.bid_usdc,
1472 positions: params.positions,
1473 portfolio_hash: params.portfolio_hash,
1474 auction_terms_hash: params.auction_terms_hash,
1475 auction_version: params.auction_version,
1476 valuation_timestamp_ms: params.valuation_timestamp_ms,
1477 bid_intent_hash: params.bid_intent_hash,
1478 nonce,
1479 signature,
1480 };
1481
1482 let result: ApiResponse<StandardMarginLiquidationOrderResponse> = Self::send_json_body(
1483 self.request(Method::POST, API_ROUTE_STANDARD_MARGIN_LIQUIDATION),
1484 &request,
1485 "submit standard margin liquidation",
1486 )
1487 .await?;
1488 result.data.ok_or_else(|| ClientError::Api {
1489 status: 200,
1490 message: result
1491 .error
1492 .unwrap_or_else(|| "No liquidation response returned".to_string()),
1493 })
1494 }
1495
1496 pub async fn fetch_underlying_price(&self, currency: &str) -> Result<Option<f64>> {
1498 let response = match self
1499 .client
1500 .get(format!("{}/options-summary", self.base_url))
1501 .query(&[("currency", currency)])
1502 .send()
1503 .await
1504 {
1505 Ok(resp) => resp,
1506 Err(err) => {
1507 warn!("options-summary request failed for {}: {}", currency, err);
1508 return Ok(None);
1509 }
1510 };
1511
1512 if !response.status().is_success() {
1513 warn!(
1514 "options-summary returned {} for {}",
1515 response.status(),
1516 currency
1517 );
1518 return Ok(None);
1519 }
1520
1521 let body: JsonRpcResponse<Vec<OptionSummary>> = reqwest_json(response).await?;
1522 let price = body.result.and_then(|mut results| {
1523 results.iter_mut().find_map(|summary| {
1524 (summary.underlying_price > 0.0).then_some(summary.underlying_price)
1525 })
1526 });
1527
1528 Ok(price)
1529 }
1530
1531 pub async fn submit_rfq(
1537 &self,
1538 wallet: &HypercallWallet,
1539 rfq_id: &str,
1540 legs: Vec<hypercall_sdk_types::RfqLegRequest>,
1541 ) -> Result<Value> {
1542 let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1544 ClientError::RfqInput(RfqInputError::InvalidUuid {
1545 label: "Invalid rfq_id",
1546 source,
1547 })
1548 })?;
1549 let mut rfq_id_bytes = [0u8; 32];
1550 rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1551
1552 let legs_hash = compute_legs_hash(&legs)?;
1554
1555 let nonce = wallet.next_nonce();
1556 let signature = wallet
1557 .sign_submit_rfq(rfq_id_bytes, legs_hash, nonce)
1558 .await?;
1559
1560 let request = hypercall_sdk_types::SubmitRfqRequest {
1561 rfq_id: rfq_id.to_string(),
1562 legs,
1563 wallet_address: wallet.address.into_wallet_address(),
1564 nonce,
1565 signature,
1566 auto_accept_limit: None,
1567 };
1568
1569 self.post_json_sonic(API_ROUTE_RFQ_REQUEST, &request, "RFQ submission failed")
1570 .await
1571 }
1572
1573 pub async fn submit_auto_execute_rfq(
1581 &self,
1582 wallet: &HypercallWallet,
1583 rfq_id: &str,
1584 legs: Vec<hypercall_sdk_types::RfqLegRequest>,
1585 limit_price: rust_decimal::Decimal,
1586 ) -> Result<Value> {
1587 let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1588 ClientError::RfqInput(RfqInputError::InvalidUuid {
1589 label: "Invalid rfq_id",
1590 source,
1591 })
1592 })?;
1593 let mut rfq_id_bytes = [0u8; 32];
1594 rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1595
1596 let legs_hash = compute_legs_hash(&legs)?;
1597
1598 use rust_decimal::prelude::ToPrimitive;
1600 let limit_micro = (limit_price * Decimal::new(1_000_000, 0))
1601 .to_i64()
1602 .ok_or(ClientError::RfqInput(RfqInputError::LimitPriceOverflow))?;
1603 let limit_i256 = alloy::primitives::I256::try_from(limit_micro).map_err(|source| {
1604 ClientError::RfqInput(RfqInputError::LimitPriceConversion {
1605 source: Box::new(source),
1606 })
1607 })?;
1608
1609 let nonce = wallet.next_nonce();
1610 let signature = wallet
1611 .sign_submit_auto_execute_rfq(rfq_id_bytes, legs_hash, limit_i256, nonce)
1612 .await?;
1613
1614 let request = hypercall_sdk_types::SubmitRfqRequest {
1615 rfq_id: rfq_id.to_string(),
1616 legs,
1617 wallet_address: wallet.address.into_wallet_address(),
1618 nonce,
1619 signature,
1620 auto_accept_limit: Some(limit_price.to_string()),
1621 };
1622
1623 self.post_json_sonic(
1624 API_ROUTE_RFQ_REQUEST,
1625 &request,
1626 "Auto-execute RFQ submission failed",
1627 )
1628 .await
1629 }
1630
1631 pub async fn accept_rfq_quote(
1633 &self,
1634 wallet: &HypercallWallet,
1635 rfq_id: &str,
1636 quote_id: &str,
1637 net_premium: alloy::primitives::I256,
1638 ) -> Result<Value> {
1639 let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
1640 ClientError::RfqInput(RfqInputError::InvalidUuid {
1641 label: "Invalid rfq_id",
1642 source,
1643 })
1644 })?;
1645 let quote_uuid = uuid::Uuid::parse_str(quote_id).map_err(|source| {
1646 ClientError::RfqInput(RfqInputError::InvalidUuid {
1647 label: "Invalid quote_id",
1648 source,
1649 })
1650 })?;
1651 let mut rfq_id_bytes = [0u8; 32];
1652 rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
1653 let mut quote_id_bytes = [0u8; 32];
1654 quote_id_bytes[16..].copy_from_slice(quote_uuid.as_bytes());
1655
1656 let nonce = wallet.next_nonce();
1657 let signature = wallet
1658 .sign_accept_rfq_quote(rfq_id_bytes, quote_id_bytes, net_premium, nonce)
1659 .await?;
1660
1661 let request = hypercall_sdk_types::AcceptRfqRequest {
1662 rfq_id: rfq_id.to_string(),
1663 quote_id: quote_id.to_string(),
1664 wallet_address: wallet.address.into_wallet_address(),
1665 nonce,
1666 signature,
1667 };
1668
1669 self.post_json_sonic(API_ROUTE_RFQ_ACCEPT, &request, "RFQ accept failed")
1670 .await
1671 }
1672
1673 pub async fn get_rfq(&self, rfq_id: &str) -> Result<Value> {
1675 let response = self
1676 .client
1677 .get(format!("{}/rfq/{}", self.base_url, rfq_id))
1678 .send()
1679 .await?;
1680
1681 if !response.status().is_success() {
1682 let status = response.status().as_u16();
1683 let text = response.text().await.unwrap_or_default();
1684 return Err(ClientError::Api {
1685 status,
1686 message: format!("Get RFQ failed: {}", text),
1687 });
1688 }
1689
1690 let result: Value = sonic_json(response).await?;
1691 Ok(result)
1692 }
1693}
1694
1695fn compute_legs_hash(legs: &[hypercall_sdk_types::RfqLegRequest]) -> Result<[u8; 32]> {
1704 use sha3::Digest;
1705 let canonical = legs
1706 .iter()
1707 .map(|l| {
1708 let side = match l.side {
1709 hypercall_sdk_types::Side::Buy => "buy",
1710 hypercall_sdk_types::Side::Sell => "sell",
1711 };
1712 let size_canonical = l
1713 .size
1714 .parse::<Decimal>()
1715 .map_err(|source| {
1716 ClientError::RfqInput(RfqInputError::InvalidLegSize {
1717 label: "Invalid",
1718 value: l.size.clone(),
1719 source,
1720 })
1721 })?
1722 .to_string();
1723 Ok(format!("{}|{}|{}", l.instrument, side, size_canonical))
1724 })
1725 .collect::<Result<Vec<_>>>()?
1726 .join(";");
1727 let mut hasher = sha3::Keccak256::new();
1728 hasher.update(canonical.as_bytes());
1729 Ok(hasher.finalize().into())
1730}
1731
1732impl std::fmt::Debug for HypercallClient {
1733 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1734 f.debug_struct("HypercallClient")
1735 .field("base_url", &self.base_url)
1736 .finish()
1737 }
1738}
1739
1740fn invalid_orders_pagination(message: &str) -> ClientError {
1741 ClientError::Api {
1742 status: 200,
1743 message: format!("invalid orders pagination: {message}"),
1744 }
1745}
1746
1747fn next_orders_page_offset(
1748 requested_offset: usize,
1749 returned_offset: usize,
1750 returned_limit: usize,
1751 returned_count: usize,
1752) -> Result<Option<usize>> {
1753 if returned_limit == 0 {
1754 return Err(invalid_orders_pagination(
1755 "pagination.limit must be greater than zero",
1756 ));
1757 }
1758 if returned_count < returned_limit {
1759 return Ok(None);
1760 }
1761
1762 let next_offset = returned_offset
1763 .checked_add(returned_count)
1764 .ok_or_else(|| invalid_orders_pagination("next offset overflowed usize"))?;
1765 if next_offset <= requested_offset {
1766 return Err(invalid_orders_pagination(
1767 "returned page does not advance the offset",
1768 ));
1769 }
1770 Ok(Some(next_offset))
1771}
1772
1773#[cfg(test)]
1774#[path = "api_redirect_test.rs"]
1775mod redirect_tests;
1776
1777#[cfg(test)]
1778#[path = "api_replace_order_test.rs"]
1779mod replace_order_tests;
1780
1781#[cfg(test)]
1782#[path = "api_compression_test.rs"]
1783mod compression_tests;
1784
1785#[cfg(test)]
1786#[path = "api_test.rs"]
1787mod tests;