Skip to main content

hypercall_client/
tee_perp.rs

1//! TEE perp trading: Hyperliquid perp orders signed by the account's app key
2//! (API wallet) and executed through Hypercall's TEE-held Hyperliquid API
3//! wallet.
4//!
5//! # Flow
6//!
7//! 1. **Enroll the TEE API wallet once** (manager wallet):
8//!    [`HypercallClient::enroll_tee_api_wallet`] requests the account's TEE
9//!    wallet, signs the `HLAddApiWallet` approval in the `HypercallManagerSign`
10//!    domain, submits it, and waits until Hyperliquid binds the wallet.
11//! 2. **Approve the Hypercall builder once** (manager wallet, HyperEVM
12//!    transaction): [`HypercallClient::approve_hypercall_builder`] calls
13//!    `Account.approveZeroFeeBuilder(builder)` (Account 0.2.4 or newer). Orders
14//!    are refused with [`TeePerpErrorCode::BuilderNotApproved`](crate::TeePerpErrorCode::BuilderNotApproved) until then.
15//! 3. **Trade** with the app key (an active Account API wallet). Every action
16//!    is EIP-712 signed in the `HypercallApiSign` domain.
17//!
18//! # Nonces
19//!
20//! The nonce is a Unix millisecond on the API server's clock. The server
21//! derives the venue expiry as `nonce + 9000` and accepts it only when it falls
22//! in `(server_now, server_now + 10000]`, so a nonce must lie in
23//! `(server_now - 9000, server_now + 1000]`. Methods that take
24//! `nonce: Option<u64>` stamp `None` from [`HypercallClient::next_tee_perp_nonce`],
25//! which reads the server clock from the `/health` `Date` header (cached for a
26//! minute) and keeps nonces strictly increasing per signer.
27//!
28//! # Outcomes
29//!
30//! A `200` response carries a [`TeePerpOrderStage`](crate::TeePerpOrderStage). `unknown` means the venue
31//! may have received the action: reconcile before acting again, and never
32//! resubmit the same intent through another route.
33//!
34//! A signed submission that fails in transit (transport error, timeout,
35//! `5xx`, or an undecodable `2xx`) returns
36//! [`ClientError::TeeSubmissionAmbiguous`] with the exact signed body. Resend
37//! those bytes with [`HypercallClient::resend_tee_submission`] or reconcile;
38//! calling the placing method again would sign a new nonce (and, for batches,
39//! new nonce-derived cloids), which is a second order.
40//!
41//! # Example
42//!
43//! ```rust,no_run
44//! use hypercall_client::{
45//!     AccountAddress, ApproveHypercallBuilderParams, HypercallClient, HypercallWallet,
46//!     HyperliquidInfoClient, PerpCancelByCloidParams, PerpLimitOrderParams, PerpPreviewAction,
47//!     PerpPreviewRequest, PerpTimeInForce, Side, TeeApiWalletEnrollmentPolling, TeePerpBracketEntry,
48//!     TeePerpBracketOrderParams, TeePerpExit, TeePerpLeverageParams, TeePerpMarketOrderParams,
49//!     TeePerpTpsl, TeePerpTriggerExecution, TeePerpTriggerOrderParams, PERP_MARKET_SLIPPAGE_BPS,
50//! };
51//! use rust_decimal::Decimal;
52//!
53//! #[tokio::main]
54//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
55//!     let client = HypercallClient::new("https://api.hypercall.xyz");
56//!     let manager = HypercallWallet::from_private_key("0xYOUR_MANAGER_KEY", 999)?;
57//!     let app_key = HypercallWallet::from_private_key("0xYOUR_API_WALLET_KEY", 999)?;
58//!     let account: AccountAddress = "0xYOUR_ACCOUNT_SOL_ADDRESS".parse()?;
59//!     let hyperliquid = HyperliquidInfoClient::mainnet();
60//!
61//!     // One-time setup with the manager wallet.
62//!     let enrollment = client
63//!         .enroll_tee_api_wallet(
64//!             &manager,
65//!             account,
66//!             &hyperliquid,
67//!             TeeApiWalletEnrollmentPolling::default(),
68//!         )
69//!         .await?;
70//!     println!("TEE API wallet: {}", enrollment.api_wallet);
71//!     client
72//!         .approve_hypercall_builder(
73//!             &manager,
74//!             ApproveHypercallBuilderParams {
75//!                 rpc_url: "https://rpc.hyperliquid.xyz/evm".into(),
76//!                 account,
77//!                 builder: None, // read from /exchange-info hl_builder_address
78//!             },
79//!         )
80//!         .await?;
81//!
82//!     // Market metadata and a read-only preview.
83//!     let markets = client.get_tee_perp_markets().await?;
84//!     let btc = markets
85//!         .by_hyperliquid_coin("BTC")
86//!         .ok_or("BTC is not configured")?;
87//!     let preview = client
88//!         .preview_tee_perp_action(&PerpPreviewRequest {
89//!             account: account.into_wallet_address(),
90//!             action: PerpPreviewAction::Leverage {
91//!                 asset: btc.asset_id,
92//!                 is_cross: true,
93//!                 leverage: 5,
94//!             },
95//!         })
96//!         .await?;
97//!     println!(
98//!         "{:?} {:?}, liquidation after {:?}",
99//!         preview.decision, preview.reason_code, preview.liquidation_px_after
100//!     );
101//!
102//!     // Leverage, then read the venue's setting back.
103//!     client
104//!         .update_tee_perp_leverage(
105//!             &app_key,
106//!             TeePerpLeverageParams {
107//!                 account,
108//!                 asset: btc.asset_id,
109//!                 is_cross: true,
110//!                 leverage: 5,
111//!                 nonce: None,
112//!             },
113//!         )
114//!         .await?;
115//!     let venue = hyperliquid
116//!         .active_asset_leverage(account, &btc.hyperliquid_coin)
117//!         .await?;
118//!     println!("venue leverage: {venue:?}");
119//!
120//!     // Limit (GTC, IOC, or ALO) and market (bounded IOC) orders.
121//!     let limit = client
122//!         .place_tee_perp_limit_order(
123//!             &app_key,
124//!             PerpLimitOrderParams {
125//!                 account,
126//!                 asset: btc.asset_id,
127//!                 side: Side::Buy,
128//!                 price: Decimal::new(95_000, 0),
129//!                 size: Decimal::new(1, 3),
130//!                 tif: PerpTimeInForce::Alo,
131//!                 reduce_only: false,
132//!                 client_order_id: Some(42),
133//!                 nonce: None,
134//!             },
135//!         )
136//!         .await?;
137//!     if limit.requires_builder_approval() {
138//!         return Err("approve the Hypercall builder first".into());
139//!     }
140//!     client
141//!         .place_tee_perp_market_order(
142//!             &app_key,
143//!             TeePerpMarketOrderParams {
144//!                 account,
145//!                 asset: btc.asset_id,
146//!                 side: Side::Buy,
147//!                 size: Decimal::new(1, 3),
148//!                 reference_price: Decimal::new(100_000, 0), // best ask
149//!                 size_decimals: 5,
150//!                 slippage_bps: Some(50),
151//!                 reduce_only: false,
152//!                 client_order_id: None,
153//!                 nonce: None,
154//!             },
155//!         )
156//!         .await?;
157//!
158//!     // A stop-market order, and an entry with attached TP/SL.
159//!     client
160//!         .place_tee_perp_trigger_order(
161//!             &app_key,
162//!             TeePerpTriggerOrderParams {
163//!                 account,
164//!                 asset: btc.asset_id,
165//!                 side: Side::Sell,
166//!                 size: Decimal::new(1, 3),
167//!                 trigger_price: Decimal::new(90_000, 0),
168//!                 tpsl: TeePerpTpsl::Sl,
169//!                 execution: TeePerpTriggerExecution::Market {
170//!                     size_decimals: 5,
171//!                     slippage_bps: None,
172//!                 },
173//!                 reduce_only: true,
174//!                 client_order_id: None,
175//!                 nonce: None,
176//!             },
177//!         )
178//!         .await?;
179//!     let exit = |trigger: i64| {
180//!         TeePerpExit::market(
181//!             Decimal::new(trigger, 0),
182//!             Side::Sell,
183//!             5,
184//!             PERP_MARKET_SLIPPAGE_BPS,
185//!         )
186//!     };
187//!     let bracket = client
188//!         .place_tee_perp_bracket_order(
189//!             &app_key,
190//!             TeePerpBracketOrderParams {
191//!                 account,
192//!                 entry: TeePerpBracketEntry {
193//!                     asset: btc.asset_id,
194//!                     side: Side::Buy,
195//!                     price: Decimal::new(99_000, 0),
196//!                     size: Decimal::new(1, 3),
197//!                     tif: PerpTimeInForce::Gtc,
198//!                     reduce_only: false,
199//!                 },
200//!                 take_profit: Some(exit(110_000)?),
201//!                 stop_loss: Some(exit(92_000)?),
202//!                 nonce: None,
203//!             },
204//!         )
205//!         .await?;
206//!     println!("bracket {:?}: {} children", bracket.stage, bracket.children.len());
207//!
208//!     client
209//!         .cancel_tee_perp_order_by_cloid(
210//!             &app_key,
211//!             PerpCancelByCloidParams {
212//!                 account,
213//!                 asset: btc.asset_id,
214//!                 client_order_id: 42,
215//!                 nonce: None,
216//!             },
217//!         )
218//!         .await?;
219//!     Ok(())
220//! }
221//! ```
222//!
223//! # Modify, batch modify and TWAP
224//!
225//! [`HypercallClient::modify_tee_perp_order`] and
226//! [`HypercallClient::batch_modify_tee_perp_orders`] replace resting limit
227//! orders; each batch child reports its own [`TeePerpOrderStage`](crate::TeePerpOrderStage) in
228//! [`TeePerpBatchModifyResponse::children`].
229//! [`HypercallClient::place_tee_perp_twap_order`] and
230//! [`HypercallClient::cancel_tee_perp_twap`] drive native TWAPs. TWAP and
231//! batch modify are enabled per enclave release; a deployment without them
232//! answers `400 unsupported_action` ([`ClientError::is_unsupported_action`]).
233//!
234//! Hyperliquid parity. TWAP submit and cancel carry every `twapOrder` and
235//! `twapCancel` field (`a`, `b`, `s`, `r`, `m`, `t`; `a`, `t`). Modify and batch
236//! modify have these scope cuts:
237//!
238//! - Modify replaces limit orders only (GTC, IOC, ALO). Hyperliquid's
239//!   `modify` can also turn an order into a trigger order; the TEE route does not
240//!   accept that, so a resting trigger order must be cancelled and re-placed.
241//! - The order is addressed by its cloid plus its engine `directiveId`, never by
242//!   `oid`, and the modify keeps the cloid. Hyperliquid also accepts an `oid`
243//!   target and a new cloid.
244//! - A batch modify carries at most the instance cap (50 by default, 100 at
245//!   most), where Hyperliquid documents no per-call limit.
246//! - No builder field: Hyperliquid documents none on `modify`, `batchModify`,
247//!   `twapOrder` or `twapCancel`.
248//!
249//! ```rust,no_run
250//! use hypercall_client::{
251//!     AccountAddress, HypercallClient, HypercallWallet, PerpTimeInForce, Side,
252//!     TeePerpBatchModifyParams, TeePerpModifyParams, TeePerpOrderReplacement, TeePerpOrderStage,
253//!     TeePerpTwapCancelParams, TeePerpTwapParams,
254//! };
255//! use rust_decimal::Decimal;
256//!
257//! #[tokio::main]
258//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
259//!     let client = HypercallClient::new("https://api.hypercall.xyz");
260//!     let app_key = HypercallWallet::from_private_key("0xYOUR_API_WALLET_KEY", 999)?;
261//!     let account: AccountAddress = "0xYOUR_ACCOUNT_SOL_ADDRESS".parse()?;
262//!
263//!     // `directiveId` and cloid returned when each order was placed.
264//!     let bid = TeePerpOrderReplacement {
265//!         asset: 0,
266//!         target_directive_id: "01999b5a-7c1e-7000-8000-000000000042".parse()?,
267//!         cloid: 42,
268//!         side: Side::Buy,
269//!         price: Decimal::new(99_500, 0),
270//!         size: Decimal::new(2, 3),
271//!         tif: PerpTimeInForce::Alo,
272//!         reduce_only: false,
273//!     };
274//!     let ask = TeePerpOrderReplacement {
275//!         target_directive_id: "01999b5a-7c1e-7000-8000-000000000043".parse()?,
276//!         cloid: 43,
277//!         side: Side::Sell,
278//!         price: Decimal::new(100_500, 0),
279//!         ..bid
280//!     };
281//!
282//!     // One order.
283//!     let single = client
284//!         .modify_tee_perp_order(
285//!             &app_key,
286//!             TeePerpModifyParams {
287//!                 account,
288//!                 replacement: bid,
289//!                 nonce: None,
290//!             },
291//!         )
292//!         .await?;
293//!     println!("modify {:?}", single.stage);
294//!
295//!     // Both quotes in one signed batchModify; each child settles on its own.
296//!     let batch = client
297//!         .batch_modify_tee_perp_orders(
298//!             &app_key,
299//!             TeePerpBatchModifyParams {
300//!                 account,
301//!                 replacements: vec![bid, ask],
302//!                 max_children: None, // the server default, 50
303//!                 nonce: None,
304//!             },
305//!         )
306//!         .await?;
307//!     for child in &batch.children {
308//!         match child.stage {
309//!             TeePerpOrderStage::Accepted => println!("{} moved", child.cloid),
310//!             TeePerpOrderStage::Rejected | TeePerpOrderStage::NotSubmitted => {
311//!                 println!("{} unchanged: the old order still rests", child.cloid)
312//!             }
313//!             _ => println!("{} unknown: reconcile before touching it", child.cloid),
314//!         }
315//!     }
316//!
317//!     // A native TWAP. Deployments that have not enabled it answer
318//!     // `400 unsupported_action`.
319//!     match client
320//!         .place_tee_perp_twap_order(
321//!             &app_key,
322//!             TeePerpTwapParams {
323//!                 account,
324//!                 asset: 0,
325//!                 side: Side::Sell,
326//!                 size: Decimal::new(5, 2),
327//!                 reduce_only: true,
328//!                 minutes: 30,
329//!                 randomize: true,
330//!                 nonce: None,
331//!             },
332//!         )
333//!         .await
334//!     {
335//!         Ok(twap) => {
336//!             if let Some(twap_id) = twap.twap_id {
337//!                 client
338//!                     .cancel_tee_perp_twap(
339//!                         &app_key,
340//!                         TeePerpTwapCancelParams {
341//!                             account,
342//!                             asset: 0,
343//!                             twap_id,
344//!                             nonce: None,
345//!                         },
346//!                     )
347//!                     .await?;
348//!             }
349//!         }
350//!         Err(error) if error.is_unsupported_action() => println!("TWAP is not enabled here"),
351//!         Err(error) => return Err(error.into()),
352//!     }
353//!     Ok(())
354//! }
355//! ```
356
357#![allow(
358    clippy::result_large_err,
359    reason = "these helpers preserve the established unboxed public ClientError contract"
360)]
361
362use std::collections::HashMap;
363use std::sync::{Arc, Mutex as StdMutex, OnceLock};
364use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
365
366use alloy::primitives::{Address, B256, U256};
367use alloy::providers::{Provider, ProviderBuilder};
368use alloy::sol;
369use alloy::sol_types::{Eip712Domain, SolStruct};
370use hypercall_sdk_types::tee_perp::{
371    TEE_API_WALLET_APPROVAL_REQUEST_ROUTE, TEE_API_WALLET_APPROVAL_ROUTE,
372    TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE, TEE_PERP_CANCEL_SUBMIT_ROUTE,
373    TEE_PERP_LEVERAGE_SUBMIT_ROUTE, TEE_PERP_MARKETS_ROUTE, TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
374    TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE, TEE_PERP_ORDER_MODIFY_ROUTE, TEE_PERP_ORDER_SUBMIT_ROUTE,
375    TEE_PERP_PREVIEW_ROUTE, TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE, TEE_PERP_TWAP_CANCEL_ROUTE,
376    TEE_PERP_TWAP_SUBMIT_ROUTE,
377};
378use hypercall_sdk_types::{
379    ApiResponse, DirectiveDeliveryStatus, DirectiveDomainStatus, DirectiveStatusResponse,
380    DirectiveSubmitRequest, DirectiveSubmitResponse, ExchangeInfoResponse, HlCancelByCloidAction,
381    HlCancelByOidAction, HlLimitOrderAction, PerpPreviewAction, PerpPreviewLimit, PerpPreviewOrder,
382    PerpPreviewOrderType, PerpPreviewRequest, PerpPreviewResponse, PerpPreviewTrigger,
383    PerpTimeInForce, Side, TeeApiWalletApprovalPackage, TeeApiWalletApprovalRequest,
384    TeeApiWalletApprovalSubmitRequest, TeePerpCancelResponse, TeePerpLeverageAction,
385    TeePerpLeverageResponse, TeePerpLimitOrderType, TeePerpMarketsResponse,
386    TeePerpOrderBatchAction, TeePerpOrderBatchResponse, TeePerpOrderGrouping, TeePerpOrderResponse,
387    TeePerpOrderType, TeePerpOrderWire, TeePerpTpsl, TeePerpTriggerOrderType,
388    TeePerpVenueActionResponse, WalletAddress, MAX_TEE_PERP_ORDER_BATCH_CHILDREN,
389    TEE_PERP_VENUE_TTL_MS,
390};
391use hypercall_sdk_types::{
392    TeePerpBatchModifyAction, TeePerpBatchModifyResponse, TeePerpModifyAction,
393    TeePerpModifyResponse, TeePerpTwapAction, TeePerpTwapCancelAction, TeePerpTwapResponse,
394    DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN, MAX_TEE_PERP_BATCH_MODIFY_CHILDREN,
395    TEE_PERP_TWAP_MAX_MINUTES, TEE_PERP_TWAP_MIN_MINUTES,
396};
397use reqwest::Method;
398use rust_decimal::Decimal;
399use serde::Deserialize;
400
401use crate::api::HypercallClient;
402use crate::error::{ClientError, Result};
403use crate::perp::{
404    to_perp_units, PerpCancelByCloidParams, PerpCancelByOidParams, PerpLimitOrderParams,
405};
406use crate::wallet::{
407    evm_submission_lock, AccountAddress, HypercallSigner, HypercallWallet,
408    PerpCancelByCloidSignature, PerpCancelByOidSignature, PerpDirectiveSigner,
409    PerpLimitOrderSignature,
410};
411
412/// Default market-order slippage bound used by the Hypercall order panel:
413/// an IOC limit 2000 bps (20%) through the reference price, rounded to a
414/// valid tick inside that bound. Pass a tighter bound where it matters.
415pub const PERP_MARKET_SLIPPAGE_BPS: u32 = 2_000;
416/// Hyperliquid perp prices carry at most five significant figures.
417pub const HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES: u32 = 5;
418/// Hyperliquid perp prices carry at most `6 - szDecimals` decimals.
419pub const HYPERLIQUID_PERP_MAX_PRICE_DECIMALS: u32 = 6;
420/// Scale orders split into this many legs at least.
421pub const PERP_SCALE_MIN_ORDERS: usize = 2;
422/// Scale orders split into this many legs at most.
423pub const PERP_SCALE_MAX_ORDERS: usize = 100;
424/// Hyperliquid info endpoint on mainnet.
425pub const HYPERLIQUID_MAINNET_INFO_URL: &str = "https://api.hyperliquid.xyz/info";
426/// Hyperliquid info endpoint on testnet.
427pub const HYPERLIQUID_TESTNET_INFO_URL: &str = "https://api.hyperliquid-testnet.xyz/info";
428
429const BPS_DENOMINATOR: u32 = 10_000;
430const SERVER_CLOCK_TTL: Duration = Duration::from_secs(60);
431const SCALE_WORKING_SCALE: u32 = 12;
432const MAX_BATCH_CLOID_INDEX: usize = 255;
433const HYPERCALL_API_DOMAIN: &str = "HypercallApiSign";
434const HYPERCALL_MANAGER_DOMAIN: &str = "HypercallManagerSign";
435
436sol! {
437    /// One signed order. A limit child signs its TIF byte with
438    /// `triggerPx = 0`, `isMarket = false`, `tpsl = 0`. A trigger child signs
439    /// `encodedTif = 0`, its trigger price, and `tpsl` 1 (TP) or 2 (SL).
440    #[derive(Debug, PartialEq, Eq)]
441    struct PerpOrderTerms {
442        uint32 asset;
443        bool isBuy;
444        uint64 limitPx;
445        uint64 sz;
446        bool reduceOnly;
447        uint8 encodedTif;
448        uint64 triggerPx;
449        bool isMarket;
450        uint8 tpsl;
451        uint128 cloid;
452    }
453
454    #[derive(Debug, PartialEq, Eq)]
455    struct HCPerpTriggerOrder {
456        address account;
457        uint64 nonce;
458        PerpOrderTerms order;
459    }
460
461    #[derive(Debug, PartialEq, Eq)]
462    struct HCPerpOrderBatch {
463        address account;
464        uint64 nonce;
465        uint8 grouping;
466        PerpOrderTerms[] orders;
467    }
468
469    #[derive(Debug, PartialEq, Eq)]
470    struct PerpLeverageChange {
471        uint32 asset;
472        bool isCross;
473        uint32 leverage;
474    }
475
476    #[derive(Debug, PartialEq, Eq)]
477    struct HCPerpLeverageChange {
478        address account;
479        uint64 nonce;
480        PerpLeverageChange action;
481    }
482
483    /// Replacement terms of one modify. `targetDirectiveId` is the UUID as a
484    /// big-endian u128. Field names and order match the server's
485    /// `PerpModifyTerms` exactly; the digest depends on both.
486    #[derive(Debug, PartialEq, Eq)]
487    struct PerpModifyTerms {
488        uint32 asset;
489        uint128 targetDirectiveId;
490        bool isBuy;
491        uint64 limitPx;
492        uint64 sz;
493        bool reduceOnly;
494        uint8 encodedTif;
495        uint128 cloid;
496    }
497
498    #[derive(Debug, PartialEq, Eq)]
499    struct HCPerpOrderModify {
500        address account;
501        uint64 nonce;
502        PerpModifyTerms action;
503    }
504
505    /// Every child's replacement terms, in request order.
506    #[derive(Debug, PartialEq, Eq)]
507    struct HCPerpOrderBatchModify {
508        address account;
509        uint64 nonce;
510        PerpModifyTerms[] modifies;
511    }
512
513    #[derive(Debug, PartialEq, Eq)]
514    struct PerpTwapTerms {
515        uint32 asset;
516        bool isBuy;
517        uint64 sz;
518        bool reduceOnly;
519        uint32 minutes;
520        bool randomize;
521    }
522
523    #[derive(Debug, PartialEq, Eq)]
524    struct HCPerpTwapOrder {
525        address account;
526        uint64 nonce;
527        PerpTwapTerms action;
528    }
529
530    #[derive(Debug, PartialEq, Eq)]
531    struct PerpTwapCancelTerms {
532        uint32 asset;
533        uint64 twapId;
534    }
535
536    #[derive(Debug, PartialEq, Eq)]
537    struct HCPerpTwapCancel {
538        address account;
539        uint64 nonce;
540        PerpTwapCancelTerms action;
541    }
542
543    #[derive(Debug, PartialEq, Eq)]
544    struct AddApiWallet {
545        address apiWalletAddress;
546        string apiWalletName;
547    }
548
549    #[derive(Debug, PartialEq, Eq)]
550    struct HLAddApiWallet {
551        address account;
552        uint64 nonce;
553        AddApiWallet action;
554    }
555
556    #[sol(rpc)]
557    interface HypercallAccountBuilderApproval {
558        function approveZeroFeeBuilder(address builder) external;
559    }
560}
561
562// ---------------------------------------------------------------------------
563// Signing
564// ---------------------------------------------------------------------------
565
566/// App-key payload for `POST /v1/tee-perp/orders/submit-trigger`.
567#[derive(Debug, Clone, Copy)]
568pub struct TeePerpTriggerOrderSignature {
569    pub account: AccountAddress,
570    pub nonce: u64,
571    pub order: TeePerpOrderWire,
572}
573
574/// App-key payload for `POST /v1/tee-perp/orders/submit-batch`.
575#[derive(Debug, Clone, Copy)]
576pub struct TeePerpOrderBatchSignature<'a> {
577    pub account: AccountAddress,
578    pub nonce: u64,
579    pub batch: &'a TeePerpOrderBatchAction,
580}
581
582/// App-key payload for `POST /v1/tee-perp/leverage/submit`.
583#[derive(Debug, Clone, Copy)]
584pub struct TeePerpLeverageSignature {
585    pub account: AccountAddress,
586    pub nonce: u64,
587    pub action: TeePerpLeverageAction,
588}
589
590/// App-key payload for `POST /v1/tee-perp/orders/modify` (`HCPerpOrderModify`).
591#[derive(Debug, Clone, Copy)]
592pub struct TeePerpModifySignature {
593    pub account: AccountAddress,
594    pub nonce: u64,
595    pub action: TeePerpModifyAction,
596}
597
598/// App-key payload for `POST /v1/tee-perp/orders/batch-modify`
599/// (`HCPerpOrderBatchModify`).
600#[derive(Debug, Clone, Copy)]
601pub struct TeePerpBatchModifySignature<'a> {
602    pub account: AccountAddress,
603    pub nonce: u64,
604    pub batch: &'a TeePerpBatchModifyAction,
605}
606
607/// App-key payload for `POST /v1/tee-perp/twap/submit` (`HCPerpTwapOrder`).
608#[derive(Debug, Clone, Copy)]
609pub struct TeePerpTwapSignature {
610    pub account: AccountAddress,
611    pub nonce: u64,
612    pub action: TeePerpTwapAction,
613}
614
615/// App-key payload for `POST /v1/tee-perp/twap/cancel` (`HCPerpTwapCancel`).
616#[derive(Debug, Clone, Copy)]
617pub struct TeePerpTwapCancelSignature {
618    pub account: AccountAddress,
619    pub nonce: u64,
620    pub action: TeePerpTwapCancelAction,
621}
622
623/// Manager payload approving the account's TEE API wallet on Hyperliquid.
624#[derive(Debug, Clone, Copy)]
625pub struct TeeApiWalletApprovalSignature<'a> {
626    pub account: AccountAddress,
627    pub nonce: u64,
628    pub api_wallet_address: AccountAddress,
629    pub api_wallet_name: &'a str,
630}
631
632/// App-key signer for TEE perp routes. Plain limit orders and cancels reuse
633/// the [`PerpDirectiveSigner`] schemas (`HLOrder`, `HLCancel`,
634/// `HLCancelByCloid`); triggers, batches, leverage, modifies and TWAPs use
635/// these.
636#[expect(
637    async_fn_in_trait,
638    reason = "signers are used generically, never as Send-bound trait objects"
639)]
640pub trait TeePerpSigner: PerpDirectiveSigner {
641    async fn sign_tee_perp_trigger_order_payload(
642        &self,
643        payload: TeePerpTriggerOrderSignature,
644    ) -> Result<String>;
645    async fn sign_tee_perp_order_batch_payload(
646        &self,
647        payload: TeePerpOrderBatchSignature<'_>,
648    ) -> Result<String>;
649    async fn sign_tee_perp_leverage_payload(
650        &self,
651        payload: TeePerpLeverageSignature,
652    ) -> Result<String>;
653    async fn sign_tee_perp_modify_payload(&self, payload: TeePerpModifySignature)
654        -> Result<String>;
655    async fn sign_tee_perp_batch_modify_payload(
656        &self,
657        payload: TeePerpBatchModifySignature<'_>,
658    ) -> Result<String>;
659    async fn sign_tee_perp_twap_payload(&self, payload: TeePerpTwapSignature) -> Result<String>;
660    async fn sign_tee_perp_twap_cancel_payload(
661        &self,
662        payload: TeePerpTwapCancelSignature,
663    ) -> Result<String>;
664}
665
666/// Manager signer for TEE API wallet enrollment.
667#[expect(
668    async_fn_in_trait,
669    reason = "signers are used generically, never as Send-bound trait objects"
670)]
671pub trait TeeApiWalletManagerSigner: HypercallSigner {
672    /// EIP-191 signature over Hypercall's timestamped authentication message.
673    async fn sign_authentication_payload(&self, timestamp: i64) -> Result<String>;
674    async fn sign_tee_api_wallet_approval_payload(
675        &self,
676        payload: TeeApiWalletApprovalSignature<'_>,
677    ) -> Result<String>;
678}
679
680fn perp_order_terms(order: &TeePerpOrderWire) -> PerpOrderTerms {
681    let (encoded_tif, trigger_px, is_market, tpsl) = match order.order_type {
682        TeePerpOrderType::Limit(limit) => (limit.tif.encoded(), 0, false, 0),
683        TeePerpOrderType::Trigger(trigger) => (
684            0,
685            trigger.trigger_px,
686            trigger.is_market,
687            trigger.tpsl.signed(),
688        ),
689    };
690    PerpOrderTerms {
691        asset: order.asset,
692        isBuy: order.is_buy,
693        limitPx: order.limit_px,
694        sz: order.sz,
695        reduceOnly: order.reduce_only,
696        encodedTif: encoded_tif,
697        triggerPx: trigger_px,
698        isMarket: is_market,
699        tpsl,
700        cloid: order.cloid,
701    }
702}
703
704fn trigger_order_message(payload: &TeePerpTriggerOrderSignature) -> Result<HCPerpTriggerOrder> {
705    if !matches!(payload.order.order_type, TeePerpOrderType::Trigger(_)) {
706        return Err(ClientError::InvalidInput(
707            "a TEE trigger submission needs a trigger order".into(),
708        ));
709    }
710    Ok(HCPerpTriggerOrder {
711        account: payload.account.as_wallet_address().inner(),
712        nonce: payload.nonce,
713        order: perp_order_terms(&payload.order),
714    })
715}
716
717fn order_batch_message(payload: &TeePerpOrderBatchSignature<'_>) -> Result<HCPerpOrderBatch> {
718    validate_batch(payload.batch)?;
719    Ok(HCPerpOrderBatch {
720        account: payload.account.as_wallet_address().inner(),
721        nonce: payload.nonce,
722        grouping: payload.batch.grouping.signed(),
723        orders: payload.batch.orders.iter().map(perp_order_terms).collect(),
724    })
725}
726
727fn leverage_message(payload: &TeePerpLeverageSignature) -> HCPerpLeverageChange {
728    HCPerpLeverageChange {
729        account: payload.account.as_wallet_address().inner(),
730        nonce: payload.nonce,
731        action: PerpLeverageChange {
732            asset: payload.action.asset,
733            isCross: payload.action.is_cross,
734            leverage: payload.action.leverage,
735        },
736    }
737}
738
739fn perp_modify_terms(action: &TeePerpModifyAction) -> PerpModifyTerms {
740    PerpModifyTerms {
741        asset: action.asset,
742        targetDirectiveId: action.target_directive_id.as_u128(),
743        isBuy: action.is_buy,
744        limitPx: action.limit_px,
745        sz: action.sz,
746        reduceOnly: action.reduce_only,
747        encodedTif: action.tif.encoded(),
748        cloid: action.cloid,
749    }
750}
751
752fn modify_message(payload: &TeePerpModifySignature) -> Result<HCPerpOrderModify> {
753    validate_modify_action(&payload.action)?;
754    Ok(HCPerpOrderModify {
755        account: payload.account.as_wallet_address().inner(),
756        nonce: payload.nonce,
757        action: perp_modify_terms(&payload.action),
758    })
759}
760
761fn batch_modify_message(
762    payload: &TeePerpBatchModifySignature<'_>,
763) -> Result<HCPerpOrderBatchModify> {
764    // The signer enforces only the wire bound; the instance cap is the
765    // request builder's and the server's to enforce.
766    validate_batch_modify(payload.batch, MAX_TEE_PERP_BATCH_MODIFY_CHILDREN)?;
767    Ok(HCPerpOrderBatchModify {
768        account: payload.account.as_wallet_address().inner(),
769        nonce: payload.nonce,
770        modifies: payload
771            .batch
772            .modifies
773            .iter()
774            .map(perp_modify_terms)
775            .collect(),
776    })
777}
778
779fn twap_message(payload: &TeePerpTwapSignature) -> Result<HCPerpTwapOrder> {
780    validate_twap_action(&payload.action)?;
781    let action = payload.action;
782    Ok(HCPerpTwapOrder {
783        account: payload.account.as_wallet_address().inner(),
784        nonce: payload.nonce,
785        action: PerpTwapTerms {
786            asset: action.asset,
787            isBuy: action.is_buy,
788            sz: action.sz,
789            reduceOnly: action.reduce_only,
790            minutes: action.minutes,
791            randomize: action.randomize,
792        },
793    })
794}
795
796fn twap_cancel_message(payload: &TeePerpTwapCancelSignature) -> Result<HCPerpTwapCancel> {
797    if payload.action.twap_id == 0 {
798        return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
799    }
800    Ok(HCPerpTwapCancel {
801        account: payload.account.as_wallet_address().inner(),
802        nonce: payload.nonce,
803        action: PerpTwapCancelTerms {
804            asset: payload.action.asset,
805            twapId: payload.action.twap_id,
806        },
807    })
808}
809
810fn approval_message(payload: &TeeApiWalletApprovalSignature<'_>) -> HLAddApiWallet {
811    HLAddApiWallet {
812        account: payload.account.as_wallet_address().inner(),
813        nonce: payload.nonce,
814        action: AddApiWallet {
815            apiWalletAddress: payload.api_wallet_address.as_wallet_address().inner(),
816            apiWalletName: payload.api_wallet_name.to_string(),
817        },
818    }
819}
820
821fn signing_domain(name: &'static str, chain_id: u64) -> Result<Eip712Domain> {
822    if !matches!(chain_id, 998 | 999) {
823        return Err(ClientError::InvalidInput(format!(
824            "unsupported directive chain id: {chain_id}"
825        )));
826    }
827    Ok(Eip712Domain {
828        name: Some(name.into()),
829        version: Some("1".into()),
830        chain_id: Some(U256::from(chain_id)),
831        verifying_contract: Some(Address::ZERO),
832        salt: None,
833    })
834}
835
836/// EIP-712 digest the app key signs for a TEE trigger order.
837pub fn tee_perp_trigger_order_signing_hash(
838    chain_id: u64,
839    payload: &TeePerpTriggerOrderSignature,
840) -> Result<B256> {
841    Ok(trigger_order_message(payload)?
842        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
843}
844
845/// EIP-712 digest the app key signs for a TEE order batch.
846pub fn tee_perp_order_batch_signing_hash(
847    chain_id: u64,
848    payload: &TeePerpOrderBatchSignature<'_>,
849) -> Result<B256> {
850    Ok(order_batch_message(payload)?
851        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
852}
853
854/// EIP-712 digest the app key signs for a TEE leverage change.
855pub fn tee_perp_leverage_signing_hash(
856    chain_id: u64,
857    payload: &TeePerpLeverageSignature,
858) -> Result<B256> {
859    Ok(leverage_message(payload)
860        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
861}
862
863/// EIP-712 digest the app key signs for a TEE single modify.
864pub fn tee_perp_modify_signing_hash(
865    chain_id: u64,
866    payload: &TeePerpModifySignature,
867) -> Result<B256> {
868    Ok(modify_message(payload)?
869        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
870}
871
872/// EIP-712 digest the app key signs for a TEE batch modify. Child order is
873/// signed.
874pub fn tee_perp_batch_modify_signing_hash(
875    chain_id: u64,
876    payload: &TeePerpBatchModifySignature<'_>,
877) -> Result<B256> {
878    Ok(batch_modify_message(payload)?
879        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
880}
881
882/// EIP-712 digest the app key signs for a TEE TWAP.
883pub fn tee_perp_twap_signing_hash(chain_id: u64, payload: &TeePerpTwapSignature) -> Result<B256> {
884    Ok(
885        twap_message(payload)?
886            .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?),
887    )
888}
889
890/// EIP-712 digest the app key signs for a TEE TWAP cancel.
891pub fn tee_perp_twap_cancel_signing_hash(
892    chain_id: u64,
893    payload: &TeePerpTwapCancelSignature,
894) -> Result<B256> {
895    Ok(twap_cancel_message(payload)?
896        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
897}
898
899/// EIP-712 digest the manager signs to approve the TEE API wallet.
900pub fn tee_api_wallet_approval_signing_hash(
901    chain_id: u64,
902    payload: &TeeApiWalletApprovalSignature<'_>,
903) -> Result<B256> {
904    Ok(approval_message(payload)
905        .eip712_signing_hash(&signing_domain(HYPERCALL_MANAGER_DOMAIN, chain_id)?))
906}
907
908impl TeePerpSigner for HypercallWallet {
909    async fn sign_tee_perp_trigger_order_payload(
910        &self,
911        payload: TeePerpTriggerOrderSignature,
912    ) -> Result<String> {
913        let message = trigger_order_message(&payload)?;
914        self.sign_directive(&message, "HCPerpTriggerOrder", HYPERCALL_API_DOMAIN)
915            .await
916    }
917
918    async fn sign_tee_perp_order_batch_payload(
919        &self,
920        payload: TeePerpOrderBatchSignature<'_>,
921    ) -> Result<String> {
922        let message = order_batch_message(&payload)?;
923        self.sign_directive(&message, "HCPerpOrderBatch", HYPERCALL_API_DOMAIN)
924            .await
925    }
926
927    async fn sign_tee_perp_leverage_payload(
928        &self,
929        payload: TeePerpLeverageSignature,
930    ) -> Result<String> {
931        let message = leverage_message(&payload);
932        self.sign_directive(&message, "HCPerpLeverageChange", HYPERCALL_API_DOMAIN)
933            .await
934    }
935
936    async fn sign_tee_perp_modify_payload(
937        &self,
938        payload: TeePerpModifySignature,
939    ) -> Result<String> {
940        let message = modify_message(&payload)?;
941        self.sign_directive(&message, "HCPerpOrderModify", HYPERCALL_API_DOMAIN)
942            .await
943    }
944
945    async fn sign_tee_perp_batch_modify_payload(
946        &self,
947        payload: TeePerpBatchModifySignature<'_>,
948    ) -> Result<String> {
949        let message = batch_modify_message(&payload)?;
950        self.sign_directive(&message, "HCPerpOrderBatchModify", HYPERCALL_API_DOMAIN)
951            .await
952    }
953
954    async fn sign_tee_perp_twap_payload(&self, payload: TeePerpTwapSignature) -> Result<String> {
955        let message = twap_message(&payload)?;
956        self.sign_directive(&message, "HCPerpTwapOrder", HYPERCALL_API_DOMAIN)
957            .await
958    }
959
960    async fn sign_tee_perp_twap_cancel_payload(
961        &self,
962        payload: TeePerpTwapCancelSignature,
963    ) -> Result<String> {
964        let message = twap_cancel_message(&payload)?;
965        self.sign_directive(&message, "HCPerpTwapCancel", HYPERCALL_API_DOMAIN)
966            .await
967    }
968}
969
970impl TeeApiWalletManagerSigner for HypercallWallet {
971    async fn sign_authentication_payload(&self, timestamp: i64) -> Result<String> {
972        self.sign_authentication_message(timestamp).await
973    }
974
975    async fn sign_tee_api_wallet_approval_payload(
976        &self,
977        payload: TeeApiWalletApprovalSignature<'_>,
978    ) -> Result<String> {
979        let message = approval_message(&payload);
980        self.sign_directive(&message, "HLAddApiWallet", HYPERCALL_MANAGER_DOMAIN)
981            .await
982    }
983}
984
985// ---------------------------------------------------------------------------
986// Server clock and nonces
987// ---------------------------------------------------------------------------
988
989#[derive(Debug, Clone, Copy)]
990struct ClockSample {
991    offset_ms: i64,
992    measured_at: Instant,
993}
994
995/// Shared cache of the API server's clock offset.
996#[derive(Debug, Clone, Default)]
997pub(crate) struct ServerClock(Arc<StdMutex<Option<ClockSample>>>);
998
999impl ServerClock {
1000    fn cached_offset(&self) -> Option<i64> {
1001        let sample = *self.0.lock().expect("server clock cache poisoned");
1002        sample
1003            .filter(|sample| sample.measured_at.elapsed() < SERVER_CLOCK_TTL)
1004            .map(|sample| sample.offset_ms)
1005    }
1006
1007    fn store(&self, offset_ms: i64) {
1008        *self.0.lock().expect("server clock cache poisoned") = Some(ClockSample {
1009            offset_ms,
1010            measured_at: Instant::now(),
1011        });
1012    }
1013}
1014
1015fn local_now_ms() -> i64 {
1016    let elapsed = SystemTime::now()
1017        .duration_since(UNIX_EPOCH)
1018        .expect("system clock is before the Unix epoch");
1019    i64::try_from(elapsed.as_millis()).expect("Unix milliseconds fit in i64")
1020}
1021
1022/// Server clock offset from one `Date` header: the header has one-second
1023/// resolution, so assume mid-second, and assume the server stamped it halfway
1024/// through the round trip.
1025pub(crate) fn server_clock_offset_ms(
1026    date_header: &str,
1027    sent_ms: i64,
1028    received_ms: i64,
1029) -> Option<i64> {
1030    let server_ms = parse_http_date_ms(date_header)?;
1031    if received_ms < sent_ms {
1032        return None;
1033    }
1034    Some(server_ms + 500 - (sent_ms + received_ms) / 2)
1035}
1036
1037/// Parse an RFC 9110 IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`).
1038pub(crate) fn parse_http_date_ms(value: &str) -> Option<i64> {
1039    let mut parts = value.trim().split_ascii_whitespace();
1040    let _weekday = parts.next()?;
1041    let day: i64 = parts.next()?.parse().ok()?;
1042    let month = match parts.next()? {
1043        "Jan" => 1,
1044        "Feb" => 2,
1045        "Mar" => 3,
1046        "Apr" => 4,
1047        "May" => 5,
1048        "Jun" => 6,
1049        "Jul" => 7,
1050        "Aug" => 8,
1051        "Sep" => 9,
1052        "Oct" => 10,
1053        "Nov" => 11,
1054        "Dec" => 12,
1055        _ => return None,
1056    };
1057    let year: i64 = parts.next()?.parse().ok()?;
1058    let mut time = parts.next()?.split(':');
1059    let hour: i64 = time.next()?.parse().ok()?;
1060    let minute: i64 = time.next()?.parse().ok()?;
1061    let second: i64 = time.next()?.parse().ok()?;
1062    if parts.next()? != "GMT" || parts.next().is_some() || time.next().is_some() {
1063        return None;
1064    }
1065    if !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
1066        return None;
1067    }
1068    // Days from civil (Howard Hinnant).
1069    let shifted_year = if month <= 2 { year - 1 } else { year };
1070    let era = shifted_year.div_euclid(400);
1071    let year_of_era = shifted_year - era * 400;
1072    let month_index = (month + 9) % 12;
1073    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
1074    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
1075    let days = era * 146_097 + day_of_era - 719_468;
1076    Some(((days * 24 + hour) * 60 + minute) * 60_000 + second * 1_000)
1077}
1078
1079fn nonce_registry() -> &'static StdMutex<HashMap<Address, u64>> {
1080    static NONCES: OnceLock<StdMutex<HashMap<Address, u64>>> = OnceLock::new();
1081    NONCES.get_or_init(|| StdMutex::new(HashMap::new()))
1082}
1083
1084/// Next nonce for `signer`: one past the larger of the last nonce issued in
1085/// this process and `server_now_ms`.
1086pub(crate) fn next_nonce_at(signer: Address, server_now_ms: u64) -> u64 {
1087    let mut nonces = nonce_registry().lock().expect("nonce registry poisoned");
1088    let last = nonces.entry(signer).or_insert(0);
1089    *last = (*last).max(server_now_ms) + 1;
1090    *last
1091}
1092
1093/// Venue expiry the server derives from a TEE perp nonce, or `None` when the
1094/// nonce is zero or overflows.
1095pub fn tee_perp_venue_expires_after_ms(nonce: u64) -> Option<u64> {
1096    if nonce == 0 {
1097        return None;
1098    }
1099    nonce.checked_add(TEE_PERP_VENUE_TTL_MS)
1100}
1101
1102/// Whether the server would accept `nonce` at `server_now_ms`.
1103pub fn tee_perp_nonce_in_window(nonce: u64, server_now_ms: u64) -> bool {
1104    tee_perp_venue_expires_after_ms(nonce).is_some_and(|expires| {
1105        expires > server_now_ms
1106            && expires
1107                <= server_now_ms.saturating_add(
1108                    hypercall_sdk_types::tee_perp::TEE_PERP_MAX_VENUE_EXPIRY_WINDOW_MS,
1109                )
1110    })
1111}
1112
1113// ---------------------------------------------------------------------------
1114// Price, size, and order construction
1115// ---------------------------------------------------------------------------
1116
1117fn decimal_units(value: Decimal) -> Result<(u128, u32)> {
1118    if value <= Decimal::ZERO {
1119        return Err(ClientError::InvalidInput(format!(
1120            "{value} must be positive"
1121        )));
1122    }
1123    let normalized = value.normalize();
1124    let mantissa = u128::try_from(normalized.mantissa())
1125        .map_err(|_| ClientError::InvalidInput(format!("{value} must be positive")))?;
1126    Ok((mantissa, normalized.scale()))
1127}
1128
1129fn units_to_decimal(units: u128, scale: u32) -> Result<Decimal> {
1130    let units = i128::try_from(units)
1131        .map_err(|_| ClientError::InvalidInput("price out of range".into()))?;
1132    Decimal::try_from_i128_with_scale(units, scale)
1133        .map(|value| value.normalize())
1134        .map_err(|error| ClientError::InvalidInput(format!("price out of range: {error}")))
1135}
1136
1137fn pow10(exponent: u32) -> Result<u128> {
1138    10_u128
1139        .checked_pow(exponent)
1140        .ok_or(ClientError::ArithmeticOverflow {
1141            operation: "perp price scaling",
1142        })
1143}
1144
1145fn validate_size_decimals(size_decimals: u32) -> Result<u32> {
1146    if size_decimals > HYPERLIQUID_PERP_MAX_PRICE_DECIMALS {
1147        return Err(ClientError::InvalidInput(format!(
1148            "size decimals {size_decimals} exceed {HYPERLIQUID_PERP_MAX_PRICE_DECIMALS}"
1149        )));
1150    }
1151    Ok(size_decimals)
1152}
1153
1154/// The IOC limit price of a market order (or market trigger): `reference`
1155/// moved `slippage_bps` against the trader, rounded to a valid Hyperliquid
1156/// tick inside that bound (buys round down, sells round up). `reference` is
1157/// the best ask for a buy and the best bid for a sell (or the trigger price).
1158///
1159/// Fails when the rounded price would no longer cross `reference`, the same
1160/// refusal as the Hypercall order panel.
1161pub fn perp_market_limit_price(
1162    reference: Decimal,
1163    side: Side,
1164    size_decimals: u32,
1165    slippage_bps: u32,
1166) -> Result<Decimal> {
1167    let size_decimals = validate_size_decimals(size_decimals)?;
1168    if slippage_bps >= BPS_DENOMINATOR {
1169        return Err(ClientError::InvalidInput(format!(
1170            "slippage {slippage_bps} bps must be below {BPS_DENOMINATOR}"
1171        )));
1172    }
1173    let (units, scale) = decimal_units(reference)?;
1174    let factor = match side {
1175        Side::Buy => BPS_DENOMINATOR + slippage_bps,
1176        Side::Sell => BPS_DENOMINATOR - slippage_bps,
1177    };
1178    let overflow = ClientError::ArithmeticOverflow {
1179        operation: "perp market price",
1180    };
1181    let numerator = units.checked_mul(u128::from(factor)).ok_or(overflow)?;
1182    let denominator = pow10(scale)?
1183        .checked_mul(u128::from(BPS_DENOMINATOR))
1184        .ok_or(ClientError::ArithmeticOverflow {
1185            operation: "perp market price",
1186        })?;
1187    let exponent: i64 = if numerator >= denominator {
1188        i64::try_from((numerator / denominator).to_string().len()).unwrap_or(i64::MAX) - 1
1189    } else {
1190        let mut scaled = numerator;
1191        let mut places = 0_i64;
1192        while scaled < denominator {
1193            scaled = scaled
1194                .checked_mul(10)
1195                .ok_or(ClientError::ArithmeticOverflow {
1196                    operation: "perp market price",
1197                })?;
1198            places += 1;
1199        }
1200        -places
1201    };
1202    let max_decimals = i64::from(HYPERLIQUID_PERP_MAX_PRICE_DECIMALS - size_decimals);
1203    let sig_fig_exponent = exponent - i64::from(HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES) + 1;
1204    let tick_exponent = sig_fig_exponent.min(0).max(-max_decimals);
1205    let tick_scale = u32::try_from(-tick_exponent).expect("tick scale is non-negative");
1206    let scaled_numerator =
1207        numerator
1208            .checked_mul(pow10(tick_scale)?)
1209            .ok_or(ClientError::ArithmeticOverflow {
1210                operation: "perp market price",
1211            })?;
1212    let quotient = scaled_numerator / denominator;
1213    let ticks = if matches!(side, Side::Buy) || scaled_numerator.is_multiple_of(denominator) {
1214        quotient
1215    } else {
1216        quotient + 1
1217    };
1218    let price = units_to_decimal(ticks, tick_scale)?;
1219    let crosses = match side {
1220        Side::Buy => price >= reference,
1221        Side::Sell => price <= reference,
1222    };
1223    if !crosses || price <= Decimal::ZERO {
1224        return Err(ClientError::InvalidInput(format!(
1225            "no marketable tick within {slippage_bps} bps of {reference}; use a limit order"
1226        )));
1227    }
1228    Ok(price)
1229}
1230
1231fn round_working_price_to_tick(units: u128, side: Side, size_decimals: u32) -> Result<Decimal> {
1232    let magnitude = i64::try_from(units.to_string().len()).unwrap_or(i64::MAX)
1233        - 1
1234        - i64::from(SCALE_WORKING_SCALE);
1235    let sig_fig_decimals =
1236        (i64::from(HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES) - 1 - magnitude).max(0);
1237    let decimals = sig_fig_decimals
1238        .min(i64::from(
1239            HYPERLIQUID_PERP_MAX_PRICE_DECIMALS - size_decimals,
1240        ))
1241        .max(0);
1242    let decimals = u32::try_from(decimals).expect("decimals are non-negative");
1243    let divisor = pow10(SCALE_WORKING_SCALE - decimals)?;
1244    let quotient = units / divisor;
1245    let ticks = if matches!(side, Side::Sell) && !units.is_multiple_of(divisor) {
1246        quotient + 1
1247    } else {
1248        quotient
1249    };
1250    units_to_decimal(ticks, decimals)
1251}
1252
1253fn to_working_units(value: Decimal, scale: u32, field: &str) -> Result<u128> {
1254    let (units, value_scale) = decimal_units(value)
1255        .map_err(|_| ClientError::InvalidInput(format!("{field} must be positive")))?;
1256    if value_scale > scale {
1257        Ok(units / pow10(value_scale - scale)?)
1258    } else {
1259        units
1260            .checked_mul(pow10(scale - value_scale)?)
1261            .ok_or(ClientError::ArithmeticOverflow {
1262                operation: "perp scale order",
1263            })
1264    }
1265}
1266
1267/// A price in working units, refusing digits past the working scale. Flooring
1268/// them would let a sell round to a tick below the caller's bound (for
1269/// example `1000.0000000000001` to `1000`).
1270fn to_working_price_units(value: Decimal, field: &str) -> Result<u128> {
1271    let (units, value_scale) = decimal_units(value)
1272        .map_err(|_| ClientError::InvalidInput(format!("{field} must be positive")))?;
1273    if value_scale > SCALE_WORKING_SCALE
1274        && !units.is_multiple_of(pow10(value_scale - SCALE_WORKING_SCALE)?)
1275    {
1276        return Err(ClientError::InvalidInput(format!(
1277            "{field} supports at most {SCALE_WORKING_SCALE} decimal places"
1278        )));
1279    }
1280    to_working_units(value, SCALE_WORKING_SCALE, field)
1281}
1282
1283/// Round `price` to Hyperliquid's tick for `side`: buys round down and sells
1284/// round up, so the result is never worse for the trader than `price`.
1285pub fn round_perp_price_to_tick(price: Decimal, side: Side, size_decimals: u32) -> Result<Decimal> {
1286    let size_decimals = validate_size_decimals(size_decimals)?;
1287    let units = to_working_price_units(price, "price")?;
1288    round_working_price_to_tick(units, side, size_decimals)
1289}
1290
1291/// One resting limit leg of a scale order.
1292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1293pub struct PerpScaleLeg {
1294    pub price: Decimal,
1295    pub size: Decimal,
1296}
1297
1298/// Inputs of [`build_perp_scale_order_legs`].
1299#[derive(Debug, Clone, Copy)]
1300pub struct PerpScaleOrderSpec {
1301    pub start_price: Decimal,
1302    pub end_price: Decimal,
1303    pub total_size: Decimal,
1304    /// 2 to 100 legs.
1305    pub order_count: usize,
1306    /// Last leg's size divided by the first leg's (1 = equal sizes), up to 100.
1307    pub size_skew: Decimal,
1308    pub side: Side,
1309    /// Hyperliquid `szDecimals` of the market.
1310    pub size_decimals: u32,
1311}
1312
1313/// Split a scale order into evenly spaced limit legs, exactly as the
1314/// Hypercall order panel does: leg sizes follow `size_skew`, are floored to
1315/// the lot size with the remaining lots added to the last legs (so they sum
1316/// to `total_size`), and prices are rounded to a valid tick on the trader's
1317/// side.
1318pub fn build_perp_scale_order_legs(spec: PerpScaleOrderSpec) -> Result<Vec<PerpScaleLeg>> {
1319    let lot_decimals = validate_size_decimals(spec.size_decimals)?;
1320    if !(PERP_SCALE_MIN_ORDERS..=PERP_SCALE_MAX_ORDERS).contains(&spec.order_count) {
1321        return Err(ClientError::InvalidInput(format!(
1322            "scale orders need {PERP_SCALE_MIN_ORDERS} to {PERP_SCALE_MAX_ORDERS} legs"
1323        )));
1324    }
1325    let one = pow10(SCALE_WORKING_SCALE)?;
1326    let start = to_working_price_units(spec.start_price, "start price")?;
1327    let end = to_working_price_units(spec.end_price, "end price")?;
1328    let skew = to_working_units(spec.size_skew, SCALE_WORKING_SCALE, "size skew")?;
1329    if skew == 0 || skew > 100 * one {
1330        return Err(ClientError::InvalidInput(
1331            "size skew must be positive and at most 100".into(),
1332        ));
1333    }
1334    if start == 0 || end == 0 || start == end {
1335        return Err(ClientError::InvalidInput(
1336            "scale start and end prices must be positive and distinct".into(),
1337        ));
1338    }
1339    let (size_units, size_scale) = decimal_units(spec.total_size)?;
1340    if size_scale > lot_decimals {
1341        return Err(ClientError::InvalidInput(format!(
1342            "total size {} has more than {lot_decimals} decimals",
1343            spec.total_size
1344        )));
1345    }
1346    let size_lots = size_units * pow10(lot_decimals - size_scale)?;
1347    let count = spec.order_count as u128;
1348    if size_lots < count {
1349        return Err(ClientError::InvalidInput(
1350            "total size is too small for this many legs".into(),
1351        ));
1352    }
1353
1354    let overflow = || ClientError::ArithmeticOverflow {
1355        operation: "perp scale order",
1356    };
1357    let steps = count - 1;
1358    let weights: Vec<i128> = (0..count)
1359        .map(|index| {
1360            let base = i128::try_from(steps * one).map_err(|_| overflow())?;
1361            let delta = (i128::try_from(skew).map_err(|_| overflow())?
1362                - i128::try_from(one).map_err(|_| overflow())?)
1363                * i128::try_from(index).map_err(|_| overflow())?;
1364            Ok(base + delta)
1365        })
1366        .collect::<Result<_>>()?;
1367    let total_weight: i128 = weights.iter().sum();
1368    let size_lots_signed = i128::try_from(size_lots).map_err(|_| overflow())?;
1369    let mut sizes: Vec<i128> = weights
1370        .iter()
1371        .map(|weight| {
1372            size_lots_signed
1373                .checked_mul(*weight)
1374                .map(|product| product / total_weight)
1375                .ok_or_else(overflow)
1376        })
1377        .collect::<Result<_>>()?;
1378    let mut remainder = size_lots_signed - sizes.iter().sum::<i128>();
1379    let mut index = sizes.len() - 1;
1380    while remainder > 0 {
1381        sizes[index] += 1;
1382        remainder -= 1;
1383        index = (index + sizes.len() - 1) % sizes.len();
1384    }
1385    if sizes.iter().any(|size| *size <= 0) {
1386        return Err(ClientError::InvalidInput(
1387            "total size is too small for this size skew".into(),
1388        ));
1389    }
1390
1391    let start_signed = i128::try_from(start).map_err(|_| overflow())?;
1392    let end_signed = i128::try_from(end).map_err(|_| overflow())?;
1393    let steps_signed = i128::try_from(steps).map_err(|_| overflow())?;
1394    sizes
1395        .into_iter()
1396        .enumerate()
1397        .map(|(index, lots)| {
1398            let index = i128::try_from(index).map_err(|_| overflow())?;
1399            let price_units = start_signed + (end_signed - start_signed) * index / steps_signed;
1400            let price_units = u128::try_from(price_units).map_err(|_| overflow())?;
1401            let price = round_working_price_to_tick(price_units, spec.side, lot_decimals)?;
1402            let size =
1403                units_to_decimal(u128::try_from(lots).map_err(|_| overflow())?, lot_decimals)?;
1404            if price <= Decimal::ZERO {
1405                return Err(ClientError::InvalidInput(
1406                    "scale price range rounds to zero".into(),
1407                ));
1408            }
1409            Ok(PerpScaleLeg { price, size })
1410        })
1411        .collect()
1412}
1413
1414/// Child cloid of one signed batch: the nonce in the high bits and the
1415/// 1-based child index in the low byte. Distinct per child, never zero, and
1416/// reproducible from the signed nonce.
1417pub fn tee_perp_batch_cloid(nonce: u64, index: usize) -> Result<u128> {
1418    if nonce == 0 {
1419        return Err(ClientError::InvalidInput("nonce must be nonzero".into()));
1420    }
1421    if index >= MAX_BATCH_CLOID_INDEX {
1422        return Err(ClientError::InvalidInput(format!(
1423            "batch child index {index} exceeds {}",
1424            MAX_BATCH_CLOID_INDEX - 1
1425        )));
1426    }
1427    Ok((u128::from(nonce) << 8) + index as u128 + 1)
1428}
1429
1430fn nonzero_cloid(cloid: u128) -> Result<u128> {
1431    if cloid == 0 {
1432        return Err(ClientError::InvalidInput("cloid must not be zero".into()));
1433    }
1434    Ok(cloid)
1435}
1436
1437/// A plain limit child for an order batch.
1438pub fn tee_perp_limit_order_wire(
1439    asset: u32,
1440    side: Side,
1441    price: Decimal,
1442    size: Decimal,
1443    tif: PerpTimeInForce,
1444    reduce_only: bool,
1445    cloid: u128,
1446) -> Result<TeePerpOrderWire> {
1447    Ok(TeePerpOrderWire {
1448        asset,
1449        is_buy: matches!(side, Side::Buy),
1450        limit_px: to_perp_units(price, "limit price")?,
1451        sz: to_perp_units(size, "size")?,
1452        reduce_only,
1453        order_type: TeePerpOrderType::Limit(TeePerpLimitOrderType { tif }),
1454        cloid: nonzero_cloid(cloid)?,
1455    })
1456}
1457
1458/// One trigger exit or entry. `limit_price` is the signed execution bound:
1459/// the user's limit for a limit trigger, or the slippage-bounded worst price
1460/// from [`perp_market_limit_price`] for a market trigger.
1461#[expect(
1462    clippy::too_many_arguments,
1463    reason = "each argument is one independent order term, as in the HL order wire"
1464)]
1465pub fn tee_perp_trigger_order_wire(
1466    asset: u32,
1467    side: Side,
1468    trigger_price: Decimal,
1469    limit_price: Decimal,
1470    size: Decimal,
1471    is_market: bool,
1472    tpsl: TeePerpTpsl,
1473    reduce_only: bool,
1474    cloid: u128,
1475) -> Result<TeePerpOrderWire> {
1476    Ok(TeePerpOrderWire {
1477        asset,
1478        is_buy: matches!(side, Side::Buy),
1479        limit_px: to_perp_units(limit_price, "limit price")?,
1480        sz: to_perp_units(size, "size")?,
1481        reduce_only,
1482        order_type: TeePerpOrderType::Trigger(TeePerpTriggerOrderType {
1483            trigger_px: to_perp_units(trigger_price, "trigger price")?,
1484            is_market,
1485            tpsl,
1486        }),
1487        cloid: nonzero_cloid(cloid)?,
1488    })
1489}
1490
1491/// A take-profit or stop-loss exit executed as a market order once triggered.
1492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1493pub struct TeePerpExit {
1494    pub trigger_price: Decimal,
1495    /// Worst execution price once triggered.
1496    pub limit_price: Decimal,
1497}
1498
1499impl TeePerpExit {
1500    /// An exit whose execution bound is `trigger_price` moved `slippage_bps`
1501    /// against an exit on `exit_side`, as the Hypercall order panel signs it.
1502    pub fn market(
1503        trigger_price: Decimal,
1504        exit_side: Side,
1505        size_decimals: u32,
1506        slippage_bps: u32,
1507    ) -> Result<Self> {
1508        Ok(Self {
1509            trigger_price,
1510            limit_price: perp_market_limit_price(
1511                trigger_price,
1512                exit_side,
1513                size_decimals,
1514                slippage_bps,
1515            )?,
1516        })
1517    }
1518}
1519
1520fn opposite(side: Side) -> Side {
1521    match side {
1522        Side::Buy => Side::Sell,
1523        Side::Sell => Side::Buy,
1524    }
1525}
1526
1527fn exit_children(
1528    orders: &mut Vec<TeePerpOrderWire>,
1529    asset: u32,
1530    exit_side: Side,
1531    size: Decimal,
1532    take_profit: Option<TeePerpExit>,
1533    stop_loss: Option<TeePerpExit>,
1534    nonce: u64,
1535) -> Result<()> {
1536    if take_profit.is_none() && stop_loss.is_none() {
1537        return Err(ClientError::InvalidInput(
1538            "a TP/SL needs a take-profit or stop-loss price".into(),
1539        ));
1540    }
1541    for (tpsl, exit) in [(TeePerpTpsl::Tp, take_profit), (TeePerpTpsl::Sl, stop_loss)] {
1542        let Some(exit) = exit else { continue };
1543        let cloid = tee_perp_batch_cloid(nonce, orders.len())?;
1544        orders.push(tee_perp_trigger_order_wire(
1545            asset,
1546            exit_side,
1547            exit.trigger_price,
1548            exit.limit_price,
1549            size,
1550            true,
1551            tpsl,
1552            true,
1553            cloid,
1554        )?);
1555    }
1556    Ok(())
1557}
1558
1559/// The entry of a [`build_tee_perp_bracket_batch`].
1560#[derive(Debug, Clone, Copy)]
1561pub struct TeePerpBracketEntry {
1562    pub asset: u32,
1563    pub side: Side,
1564    pub price: Decimal,
1565    pub size: Decimal,
1566    pub tif: PerpTimeInForce,
1567    pub reduce_only: bool,
1568}
1569
1570/// An entry with attached TP/SL, grouped `normalTpsl` so Hyperliquid only
1571/// activates the exits once the entry fills. Exits are reduce-only market
1572/// triggers on the opposite side for the full entry size.
1573pub fn build_tee_perp_bracket_batch(
1574    entry: TeePerpBracketEntry,
1575    take_profit: Option<TeePerpExit>,
1576    stop_loss: Option<TeePerpExit>,
1577    nonce: u64,
1578) -> Result<TeePerpOrderBatchAction> {
1579    let mut orders = vec![tee_perp_limit_order_wire(
1580        entry.asset,
1581        entry.side,
1582        entry.price,
1583        entry.size,
1584        entry.tif,
1585        entry.reduce_only,
1586        tee_perp_batch_cloid(nonce, 0)?,
1587    )?];
1588    exit_children(
1589        &mut orders,
1590        entry.asset,
1591        opposite(entry.side),
1592        entry.size,
1593        take_profit,
1594        stop_loss,
1595        nonce,
1596    )?;
1597    Ok(TeePerpOrderBatchAction {
1598        orders,
1599        grouping: TeePerpOrderGrouping::NormalTpsl,
1600    })
1601}
1602
1603/// Reduce-only TP/SL exits on an existing position, grouped `positionTpsl`.
1604/// `position_side` is the position's direction (`Buy` = long); exits trade
1605/// the opposite side.
1606pub fn build_tee_perp_position_tpsl_batch(
1607    asset: u32,
1608    position_side: Side,
1609    size: Decimal,
1610    take_profit: Option<TeePerpExit>,
1611    stop_loss: Option<TeePerpExit>,
1612    nonce: u64,
1613) -> Result<TeePerpOrderBatchAction> {
1614    let mut orders = Vec::with_capacity(2);
1615    exit_children(
1616        &mut orders,
1617        asset,
1618        opposite(position_side),
1619        size,
1620        take_profit,
1621        stop_loss,
1622        nonce,
1623    )?;
1624    Ok(TeePerpOrderBatchAction {
1625        orders,
1626        grouping: TeePerpOrderGrouping::PositionTpsl,
1627    })
1628}
1629
1630/// Scale legs submitted together as one ungrouped batch.
1631pub fn build_tee_perp_scale_batch(
1632    asset: u32,
1633    side: Side,
1634    legs: &[PerpScaleLeg],
1635    tif: PerpTimeInForce,
1636    reduce_only: bool,
1637    nonce: u64,
1638) -> Result<TeePerpOrderBatchAction> {
1639    let orders = legs
1640        .iter()
1641        .enumerate()
1642        .map(|(index, leg)| {
1643            tee_perp_limit_order_wire(
1644                asset,
1645                side,
1646                leg.price,
1647                leg.size,
1648                tif,
1649                reduce_only,
1650                tee_perp_batch_cloid(nonce, index)?,
1651            )
1652        })
1653        .collect::<Result<Vec<_>>>()?;
1654    let batch = TeePerpOrderBatchAction {
1655        orders,
1656        grouping: TeePerpOrderGrouping::Na,
1657    };
1658    validate_batch(&batch)?;
1659    Ok(batch)
1660}
1661
1662fn validate_batch(batch: &TeePerpOrderBatchAction) -> Result<()> {
1663    if batch.orders.is_empty() || batch.orders.len() > MAX_TEE_PERP_ORDER_BATCH_CHILDREN {
1664        return Err(ClientError::InvalidInput(format!(
1665            "an order batch needs 1 to {MAX_TEE_PERP_ORDER_BATCH_CHILDREN} orders"
1666        )));
1667    }
1668    let mut cloids = std::collections::BTreeSet::new();
1669    for order in &batch.orders {
1670        nonzero_cloid(order.cloid)?;
1671        if !cloids.insert(order.cloid) {
1672            return Err(ClientError::InvalidInput(
1673                "every order in a batch must use a distinct cloid".into(),
1674            ));
1675        }
1676    }
1677    Ok(())
1678}
1679
1680// ---------------------------------------------------------------------------
1681// Modify and TWAP
1682// ---------------------------------------------------------------------------
1683
1684/// The new terms for one resting limit order, in human units.
1685///
1686/// The order is identified twice, and both must agree: by `target_directive_id`
1687/// (the `directiveId` its submit returned; for a batch child, that child's
1688/// `directiveId`) and by `cloid` (the order's client order ID, which the
1689/// modify preserves). Only limit orders (GTC, IOC, ALO) can be modified on
1690/// the TEE route; see the crate README for the Hyperliquid parity notes.
1691#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1692pub struct TeePerpOrderReplacement {
1693    pub asset: u32,
1694    pub target_directive_id: uuid::Uuid,
1695    pub cloid: u128,
1696    pub side: Side,
1697    /// New limit price. At most 8 decimal places.
1698    pub price: Decimal,
1699    /// New size in coins. At most 8 decimal places.
1700    pub size: Decimal,
1701    pub tif: PerpTimeInForce,
1702    pub reduce_only: bool,
1703}
1704
1705impl TeePerpOrderReplacement {
1706    /// The signed wire action, scaled to 1e8 units and validated as the
1707    /// server validates it.
1708    pub fn to_action(&self) -> Result<TeePerpModifyAction> {
1709        let action = TeePerpModifyAction {
1710            asset: self.asset,
1711            target_directive_id: self.target_directive_id,
1712            is_buy: matches!(self.side, Side::Buy),
1713            limit_px: to_perp_units(self.price, "limit price")?,
1714            sz: to_perp_units(self.size, "size")?,
1715            reduce_only: self.reduce_only,
1716            tif: self.tif,
1717            cloid: self.cloid,
1718        };
1719        validate_modify_action(&action)?;
1720        Ok(action)
1721    }
1722}
1723
1724/// One modify's terms, held to the server's rules: a non-nil target, a
1725/// non-zero cloid, and a positive price and size.
1726fn validate_modify_action(action: &TeePerpModifyAction) -> Result<()> {
1727    if action.target_directive_id.is_nil() {
1728        return Err(ClientError::InvalidInput(
1729            "target_directive_id must not be nil".into(),
1730        ));
1731    }
1732    nonzero_cloid(action.cloid)?;
1733    if action.limit_px == 0 || action.sz == 0 {
1734        return Err(ClientError::InvalidInput(
1735            "a modify needs a positive limit price and size".into(),
1736        ));
1737    }
1738    Ok(())
1739}
1740
1741/// A batch modify's shape: 1 to `max_children` children (never more than
1742/// [`MAX_TEE_PERP_BATCH_MODIFY_CHILDREN`]), each a valid single modify, with
1743/// distinct targets and distinct cloids.
1744fn validate_batch_modify(batch: &TeePerpBatchModifyAction, max_children: usize) -> Result<()> {
1745    let cap = max_children.min(MAX_TEE_PERP_BATCH_MODIFY_CHILDREN);
1746    if batch.modifies.is_empty() || batch.modifies.len() > cap {
1747        return Err(ClientError::InvalidInput(format!(
1748            "a batch modify needs 1 to {cap} orders, got {}",
1749            batch.modifies.len()
1750        )));
1751    }
1752    let mut targets = std::collections::BTreeSet::new();
1753    let mut cloids = std::collections::BTreeSet::new();
1754    for action in &batch.modifies {
1755        validate_modify_action(action)?;
1756        if !targets.insert(action.target_directive_id) {
1757            return Err(ClientError::InvalidInput(format!(
1758                "batch modify targets order {} twice",
1759                action.target_directive_id
1760            )));
1761        }
1762        if !cloids.insert(action.cloid) {
1763            return Err(ClientError::InvalidInput(
1764                "every order in a batch modify must use a distinct cloid".into(),
1765            ));
1766        }
1767    }
1768    Ok(())
1769}
1770
1771/// Build the signed action of a batch modify, refusing one the server would
1772/// refuse. `max_children` is the instance cap (`None` for
1773/// [`DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN`]); it can lower the cap but
1774/// never raise it past [`MAX_TEE_PERP_BATCH_MODIFY_CHILDREN`].
1775pub fn build_tee_perp_batch_modify(
1776    replacements: &[TeePerpOrderReplacement],
1777    max_children: Option<usize>,
1778) -> Result<TeePerpBatchModifyAction> {
1779    let max_children = max_children.unwrap_or(DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN);
1780    if max_children == 0 || max_children > MAX_TEE_PERP_BATCH_MODIFY_CHILDREN {
1781        return Err(ClientError::InvalidInput(format!(
1782            "max_children must be 1 to {MAX_TEE_PERP_BATCH_MODIFY_CHILDREN}"
1783        )));
1784    }
1785    let batch = TeePerpBatchModifyAction {
1786        modifies: replacements
1787            .iter()
1788            .map(TeePerpOrderReplacement::to_action)
1789            .collect::<Result<_>>()?,
1790    };
1791    validate_batch_modify(&batch, max_children)?;
1792    Ok(batch)
1793}
1794
1795fn validate_twap_action(action: &TeePerpTwapAction) -> Result<()> {
1796    if !(TEE_PERP_TWAP_MIN_MINUTES..=TEE_PERP_TWAP_MAX_MINUTES).contains(&action.minutes) {
1797        return Err(ClientError::InvalidInput(format!(
1798            "TWAP minutes must be {TEE_PERP_TWAP_MIN_MINUTES} to {TEE_PERP_TWAP_MAX_MINUTES}, got {}",
1799            action.minutes
1800        )));
1801    }
1802    if action.sz == 0 {
1803        return Err(ClientError::InvalidInput(
1804            "TWAP size must be positive".into(),
1805        ));
1806    }
1807    Ok(())
1808}
1809
1810/// A signed body whose nonce identifies it to the server.
1811trait SignedTeeSubmission: serde::Serialize {
1812    fn nonce(&self) -> u64;
1813}
1814
1815impl<A: serde::Serialize> SignedTeeSubmission for DirectiveSubmitRequest<A> {
1816    fn nonce(&self) -> u64 {
1817        self.nonce
1818    }
1819}
1820
1821impl SignedTeeSubmission for TeeApiWalletApprovalSubmitRequest {
1822    fn nonce(&self) -> u64 {
1823        self.nonce
1824    }
1825}
1826
1827/// Whether a failed submission may still have reached the server: any
1828/// transport or decode failure, a `408`, or a `5xx`. Other `4xx` answers
1829/// are definitive.
1830fn tee_submission_is_ambiguous(error: &ClientError) -> bool {
1831    matches!(
1832        error,
1833        ClientError::Http(_)
1834            | ClientError::Api {
1835                status: 408 | 500..=599,
1836                ..
1837            }
1838    )
1839}
1840
1841fn from_perp_units(units: u64) -> Decimal {
1842    Decimal::from_i128_with_scale(i128::from(units), 8).normalize()
1843}
1844
1845/// The preview form of a signed order wire (1e8 integers back to decimals),
1846/// so a preview describes exactly what will be signed.
1847pub fn perp_preview_order(order: &TeePerpOrderWire) -> PerpPreviewOrder {
1848    PerpPreviewOrder {
1849        asset: order.asset,
1850        is_buy: order.is_buy,
1851        limit_px: from_perp_units(order.limit_px),
1852        sz: from_perp_units(order.sz),
1853        reduce_only: order.reduce_only,
1854        order_type: match order.order_type {
1855            TeePerpOrderType::Limit(limit) => PerpPreviewOrderType::Limit(PerpPreviewLimit {
1856                tif: limit.tif.into(),
1857            }),
1858            TeePerpOrderType::Trigger(trigger) => {
1859                PerpPreviewOrderType::Trigger(PerpPreviewTrigger {
1860                    trigger_px: from_perp_units(trigger.trigger_px),
1861                    is_market: trigger.is_market,
1862                    tpsl: trigger.tpsl,
1863                })
1864            }
1865        },
1866    }
1867}
1868
1869/// The preview action of a signed order batch.
1870pub fn perp_preview_batch_action(batch: &TeePerpOrderBatchAction) -> PerpPreviewAction {
1871    PerpPreviewAction::OrderBatch {
1872        grouping: batch.grouping,
1873        orders: batch.orders.iter().map(perp_preview_order).collect(),
1874        leverage: None,
1875    }
1876}
1877
1878// ---------------------------------------------------------------------------
1879// Request parameters
1880// ---------------------------------------------------------------------------
1881
1882/// A market order: an IOC limit at `reference_price` moved `slippage_bps`
1883/// against the trader and rounded to a valid tick.
1884#[derive(Debug, Clone)]
1885pub struct TeePerpMarketOrderParams {
1886    pub account: AccountAddress,
1887    pub asset: u32,
1888    pub side: Side,
1889    pub size: Decimal,
1890    /// Best ask for a buy, best bid for a sell.
1891    pub reference_price: Decimal,
1892    /// Hyperliquid `szDecimals` of the market.
1893    pub size_decimals: u32,
1894    /// Defaults to [`PERP_MARKET_SLIPPAGE_BPS`].
1895    pub slippage_bps: Option<u32>,
1896    pub reduce_only: bool,
1897    pub client_order_id: Option<u128>,
1898    pub nonce: Option<u64>,
1899}
1900
1901/// How a trigger order executes once triggered.
1902#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1903pub enum TeePerpTriggerExecution {
1904    /// Market (IOC) bounded `slippage_bps` beyond the trigger price.
1905    Market {
1906        size_decimals: u32,
1907        /// Defaults to [`PERP_MARKET_SLIPPAGE_BPS`].
1908        slippage_bps: Option<u32>,
1909    },
1910    /// A limit order at `price`.
1911    Limit { price: Decimal },
1912}
1913
1914/// A native stop-loss or take-profit order (market or limit).
1915#[derive(Debug, Clone)]
1916pub struct TeePerpTriggerOrderParams {
1917    pub account: AccountAddress,
1918    pub asset: u32,
1919    pub side: Side,
1920    pub size: Decimal,
1921    pub trigger_price: Decimal,
1922    /// `Sl` for a stop, `Tp` for a take-profit.
1923    pub tpsl: TeePerpTpsl,
1924    pub execution: TeePerpTriggerExecution,
1925    pub reduce_only: bool,
1926    /// Defaults to `tee_perp_batch_cloid(nonce, 0)`.
1927    pub client_order_id: Option<u128>,
1928    pub nonce: Option<u64>,
1929}
1930
1931/// An entry with attached TP/SL exits (`normalTpsl`).
1932#[derive(Debug, Clone)]
1933pub struct TeePerpBracketOrderParams {
1934    pub account: AccountAddress,
1935    pub entry: TeePerpBracketEntry,
1936    pub take_profit: Option<TeePerpExit>,
1937    pub stop_loss: Option<TeePerpExit>,
1938    pub nonce: Option<u64>,
1939}
1940
1941/// TP/SL exits on an existing position (`positionTpsl`).
1942#[derive(Debug, Clone)]
1943pub struct TeePerpPositionTpslParams {
1944    pub account: AccountAddress,
1945    pub asset: u32,
1946    /// The position's direction (`Buy` = long).
1947    pub position_side: Side,
1948    pub size: Decimal,
1949    pub take_profit: Option<TeePerpExit>,
1950    pub stop_loss: Option<TeePerpExit>,
1951    pub nonce: Option<u64>,
1952}
1953
1954/// A scale order: limit legs submitted as one ungrouped batch.
1955#[derive(Debug, Clone)]
1956pub struct TeePerpScaleOrderParams {
1957    pub account: AccountAddress,
1958    pub asset: u32,
1959    pub side: Side,
1960    /// From [`build_perp_scale_order_legs`] or caller-chosen.
1961    pub legs: Vec<PerpScaleLeg>,
1962    pub tif: PerpTimeInForce,
1963    pub reduce_only: bool,
1964    pub nonce: Option<u64>,
1965}
1966
1967/// A caller-built order batch. Cloids must already be set; derive them from
1968/// the nonce with [`tee_perp_batch_cloid`] after reserving it with
1969/// [`HypercallClient::next_tee_perp_nonce`].
1970#[derive(Debug, Clone)]
1971pub struct TeePerpOrderBatchParams {
1972    pub account: AccountAddress,
1973    pub nonce: u64,
1974    pub batch: TeePerpOrderBatchAction,
1975}
1976
1977/// A leverage and margin-mode change.
1978#[derive(Debug, Clone, Copy)]
1979pub struct TeePerpLeverageParams {
1980    pub account: AccountAddress,
1981    pub asset: u32,
1982    /// `true` for cross margin, `false` for isolated.
1983    pub is_cross: bool,
1984    /// At least 1.
1985    pub leverage: u32,
1986    pub nonce: Option<u64>,
1987}
1988
1989/// One resting limit order's replacement
1990/// ([`HypercallClient::modify_tee_perp_order`]).
1991#[derive(Debug, Clone, Copy)]
1992pub struct TeePerpModifyParams {
1993    pub account: AccountAddress,
1994    pub replacement: TeePerpOrderReplacement,
1995    pub nonce: Option<u64>,
1996}
1997
1998/// Several resting limit orders' replacements under one signature
1999/// ([`HypercallClient::batch_modify_tee_perp_orders`]).
2000#[derive(Debug, Clone)]
2001pub struct TeePerpBatchModifyParams {
2002    pub account: AccountAddress,
2003    /// In the order the venue applies and answers them.
2004    pub replacements: Vec<TeePerpOrderReplacement>,
2005    /// The server instance's `api.tee_perp_batch_modify_max_children`, when
2006    /// it is not the default ([`DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN`]).
2007    /// At most [`MAX_TEE_PERP_BATCH_MODIFY_CHILDREN`].
2008    pub max_children: Option<usize>,
2009    pub nonce: Option<u64>,
2010}
2011
2012/// A native Hyperliquid TWAP ([`HypercallClient::place_tee_perp_twap_order`]).
2013#[derive(Debug, Clone, Copy)]
2014pub struct TeePerpTwapParams {
2015    pub account: AccountAddress,
2016    pub asset: u32,
2017    pub side: Side,
2018    /// Total size in coins. At most 8 decimal places.
2019    pub size: Decimal,
2020    pub reduce_only: bool,
2021    /// [`TEE_PERP_TWAP_MIN_MINUTES`] to [`TEE_PERP_TWAP_MAX_MINUTES`].
2022    pub minutes: u32,
2023    /// Vary slice timing.
2024    pub randomize: bool,
2025    pub nonce: Option<u64>,
2026}
2027
2028/// Cancel a running TWAP ([`HypercallClient::cancel_tee_perp_twap`]).
2029#[derive(Debug, Clone, Copy)]
2030pub struct TeePerpTwapCancelParams {
2031    pub account: AccountAddress,
2032    pub asset: u32,
2033    /// [`TeePerpTwapResponse::twap_id`] of the TWAP to cancel.
2034    pub twap_id: u64,
2035    pub nonce: Option<u64>,
2036}
2037
2038/// Parameters for [`HypercallClient::approve_hypercall_builder`].
2039#[derive(Debug, Clone)]
2040pub struct ApproveHypercallBuilderParams {
2041    /// HyperEVM JSON-RPC endpoint.
2042    pub rpc_url: String,
2043    /// The Account.sol (0.2.4 or newer) the manager controls.
2044    pub account: AccountAddress,
2045    /// Builder to approve. `None` reads `hl_builder_address` from `/exchange-info`.
2046    pub builder: Option<AccountAddress>,
2047}
2048
2049/// The manager-authenticated TEE API wallet approval challenge.
2050#[derive(Debug, Clone)]
2051pub struct TeeApiWalletApprovalChallenge {
2052    pub account: AccountAddress,
2053    pub manager: AccountAddress,
2054    /// Unix seconds signed in the authentication message.
2055    pub timestamp: i64,
2056    pub authentication_signature: String,
2057    pub package: TeeApiWalletApprovalPackage,
2058}
2059
2060/// Progress of a TEE API wallet approval directive.
2061#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2062pub enum TeeApiWalletApprovalProgress {
2063    Pending,
2064    Finalized,
2065    Failed,
2066}
2067
2068/// Classify a `/v1/directives/{id}` status of the approval directive.
2069pub fn tee_api_wallet_approval_progress(
2070    status: &DirectiveStatusResponse,
2071) -> TeeApiWalletApprovalProgress {
2072    if status.domain_status == DirectiveDomainStatus::Completed
2073        && status.delivery_status == DirectiveDeliveryStatus::Finalized
2074    {
2075        return TeeApiWalletApprovalProgress::Finalized;
2076    }
2077    if matches!(
2078        status.domain_status,
2079        DirectiveDomainStatus::Failed | DirectiveDomainStatus::Rejected
2080    ) || matches!(
2081        status.delivery_status,
2082        DirectiveDeliveryStatus::CoreRejected
2083            | DirectiveDeliveryStatus::Reverted
2084            | DirectiveDeliveryStatus::Expired
2085            | DirectiveDeliveryStatus::DeadLettered
2086    ) {
2087        return TeeApiWalletApprovalProgress::Failed;
2088    }
2089    TeeApiWalletApprovalProgress::Pending
2090}
2091
2092/// Result of [`HypercallClient::enroll_tee_api_wallet`].
2093#[derive(Debug, Clone)]
2094pub struct TeeApiWalletEnrollment {
2095    /// The TEE-controlled Hyperliquid API wallet now bound to the account.
2096    pub api_wallet: AccountAddress,
2097    pub api_wallet_name: String,
2098    /// `None` when Hyperliquid already had the wallet bound.
2099    pub directive_id: Option<String>,
2100}
2101
2102/// Polling of [`HypercallClient::enroll_tee_api_wallet`].
2103#[derive(Debug, Clone, Copy)]
2104pub struct TeeApiWalletEnrollmentPolling {
2105    pub interval: Duration,
2106    pub attempts: u32,
2107}
2108
2109impl Default for TeeApiWalletEnrollmentPolling {
2110    fn default() -> Self {
2111        Self {
2112            interval: Duration::from_secs(2),
2113            attempts: 60,
2114        }
2115    }
2116}
2117
2118/// Hypercall builder published by `/exchange-info`. Never guessed.
2119pub fn resolve_hypercall_builder_address(
2120    exchange_info: &ExchangeInfoResponse,
2121) -> Result<AccountAddress> {
2122    let configured = exchange_info.hl_builder_address.as_deref().ok_or_else(|| {
2123        ClientError::InvalidInput("exchange-info does not publish hl_builder_address".into())
2124    })?;
2125    let builder: AccountAddress = configured
2126        .parse()
2127        .map_err(|source| ClientError::invalid_input("hl_builder_address", source))?;
2128    if builder.as_wallet_address().inner() == Address::ZERO {
2129        return Err(ClientError::InvalidInput(
2130            "exchange-info publishes a zero hl_builder_address".into(),
2131        ));
2132    }
2133    Ok(builder)
2134}
2135
2136// ---------------------------------------------------------------------------
2137// Hyperliquid info reads
2138// ---------------------------------------------------------------------------
2139
2140/// Hyperliquid margin setting read back from the venue.
2141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2142pub struct HyperliquidLeverage {
2143    pub is_cross: bool,
2144    pub value: u32,
2145}
2146
2147#[derive(Debug, Deserialize)]
2148struct ActiveAssetData {
2149    user: String,
2150    coin: String,
2151    leverage: ActiveAssetLeverage,
2152}
2153
2154#[derive(Debug, Deserialize)]
2155struct ActiveAssetLeverage {
2156    #[serde(rename = "type")]
2157    kind: String,
2158    value: u32,
2159}
2160
2161/// Hyperliquid `userRole` response.
2162#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2163pub struct HyperliquidUserRole {
2164    pub role: String,
2165    #[serde(default)]
2166    pub data: Option<HyperliquidUserRoleData>,
2167}
2168
2169#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2170pub struct HyperliquidUserRoleData {
2171    #[serde(default)]
2172    pub user: Option<String>,
2173}
2174
2175impl HyperliquidUserRole {
2176    /// Whether this role is an API wallet (agent) bound to `account`.
2177    pub fn is_agent_for(&self, account: AccountAddress) -> bool {
2178        self.role == "agent"
2179            && self
2180                .data
2181                .as_ref()
2182                .and_then(|data| data.user.as_deref())
2183                .and_then(|user| user.parse::<AccountAddress>().ok())
2184                == Some(account)
2185    }
2186}
2187
2188/// Minimal Hyperliquid `/info` reader for TEE perp readbacks.
2189#[derive(Debug, Clone)]
2190pub struct HyperliquidInfoClient {
2191    client: reqwest::Client,
2192    url: String,
2193}
2194
2195impl HyperliquidInfoClient {
2196    pub fn new(url: impl Into<String>) -> Self {
2197        Self {
2198            client: reqwest::Client::builder()
2199                .timeout(Duration::from_secs(15))
2200                .build()
2201                .expect("failed to build reqwest client"),
2202            url: url.into(),
2203        }
2204    }
2205
2206    pub fn mainnet() -> Self {
2207        Self::new(HYPERLIQUID_MAINNET_INFO_URL)
2208    }
2209
2210    pub fn testnet() -> Self {
2211        Self::new(HYPERLIQUID_TESTNET_INFO_URL)
2212    }
2213
2214    /// The info client for a Hypercall directive chain id (999 or 998).
2215    pub fn for_chain_id(chain_id: u64) -> Result<Self> {
2216        match chain_id {
2217            999 => Ok(Self::mainnet()),
2218            998 => Ok(Self::testnet()),
2219            _ => Err(ClientError::InvalidInput(format!(
2220                "unsupported Hyperliquid chain id: {chain_id}"
2221            ))),
2222        }
2223    }
2224
2225    async fn post<T: serde::de::DeserializeOwned>(
2226        &self,
2227        body: serde_json::Value,
2228        action: &str,
2229    ) -> Result<T> {
2230        HypercallClient::send_reqwest_json(self.client.post(&self.url).json(&body), action).await
2231    }
2232
2233    /// Hyperliquid's role for `address`.
2234    pub async fn user_role(&self, address: AccountAddress) -> Result<HyperliquidUserRole> {
2235        self.post(
2236            serde_json::json!({"type": "userRole", "user": address.to_string()}),
2237            "read Hyperliquid user role",
2238        )
2239        .await
2240    }
2241
2242    /// Whether Hyperliquid has `api_wallet` bound as an agent of `account`:
2243    /// the TEE API wallet enrollment status.
2244    pub async fn is_tee_api_wallet_active(
2245        &self,
2246        account: AccountAddress,
2247        api_wallet: AccountAddress,
2248    ) -> Result<bool> {
2249        Ok(self.user_role(api_wallet).await?.is_agent_for(account))
2250    }
2251
2252    /// The account's leverage and margin mode for `coin` (e.g. `BTC` or
2253    /// `xyz:SNDK`), read back from Hyperliquid after a leverage change.
2254    pub async fn active_asset_leverage(
2255        &self,
2256        account: AccountAddress,
2257        coin: &str,
2258    ) -> Result<HyperliquidLeverage> {
2259        let data: ActiveAssetData = self
2260            .post(
2261                serde_json::json!({"type": "activeAssetData", "user": account.to_string(), "coin": coin}),
2262                "read Hyperliquid active asset data",
2263            )
2264            .await?;
2265        let echoed_user = data.user.parse::<AccountAddress>().ok();
2266        if echoed_user != Some(account) || data.coin != coin {
2267            return Err(ClientError::Api {
2268                status: 200,
2269                message: "Hyperliquid returned leverage for a different account or market".into(),
2270            });
2271        }
2272        let is_cross = match data.leverage.kind.as_str() {
2273            "cross" => true,
2274            "isolated" => false,
2275            _ => {
2276                return Err(ClientError::Api {
2277                    status: 200,
2278                    message: "Hyperliquid returned an invalid leverage setting".into(),
2279                })
2280            }
2281        };
2282        if data.leverage.value < 1 {
2283            return Err(ClientError::Api {
2284                status: 200,
2285                message: "Hyperliquid returned an invalid leverage setting".into(),
2286            });
2287        }
2288        Ok(HyperliquidLeverage {
2289            is_cross,
2290            value: data.leverage.value,
2291        })
2292    }
2293}
2294
2295// ---------------------------------------------------------------------------
2296// Client methods
2297// ---------------------------------------------------------------------------
2298
2299fn approval_typed_data_mismatch(field: &str) -> ClientError {
2300    ClientError::InvalidInput(format!(
2301        "TEE API wallet approval typed data does not match the package: {field}"
2302    ))
2303}
2304
2305fn validate_approval_typed_data(challenge: &TeeApiWalletApprovalChallenge) -> Result<()> {
2306    let typed = &challenge.package.typed_data;
2307    if typed["primaryType"] != "HLAddApiWallet" {
2308        return Err(approval_typed_data_mismatch("primaryType"));
2309    }
2310    if typed["domain"]["name"] != HYPERCALL_MANAGER_DOMAIN {
2311        return Err(approval_typed_data_mismatch("domain.name"));
2312    }
2313    let message = &typed["message"];
2314    let same_address = |value: &serde_json::Value, expected: WalletAddress| {
2315        value
2316            .as_str()
2317            .and_then(|text| text.parse::<WalletAddress>().ok())
2318            == Some(expected)
2319    };
2320    if !same_address(&message["account"], challenge.account.into_wallet_address()) {
2321        return Err(approval_typed_data_mismatch("message.account"));
2322    }
2323    let nonce = match &message["nonce"] {
2324        serde_json::Value::Number(number) => number.as_u64(),
2325        serde_json::Value::String(text) => text.parse().ok(),
2326        _ => None,
2327    };
2328    if nonce != Some(challenge.package.nonce) {
2329        return Err(approval_typed_data_mismatch("message.nonce"));
2330    }
2331    let action = &message["action"];
2332    if !same_address(
2333        &action["apiWalletAddress"],
2334        challenge.package.api_wallet_address,
2335    ) {
2336        return Err(approval_typed_data_mismatch(
2337            "message.action.apiWalletAddress",
2338        ));
2339    }
2340    if action["apiWalletName"] != challenge.package.api_wallet_name.as_str() {
2341        return Err(approval_typed_data_mismatch("message.action.apiWalletName"));
2342    }
2343    Ok(())
2344}
2345
2346fn onchain_error(
2347    operation: impl Into<String>,
2348    source: impl std::error::Error + Send + Sync + 'static,
2349) -> ClientError {
2350    ClientError::Onchain {
2351        operation: operation.into(),
2352        source: Box::new(source),
2353    }
2354}
2355
2356/// An Account implementation older than 0.2.4 has no `approveZeroFeeBuilder`
2357/// and reverts with no data.
2358fn is_missing_function_revert(error: &alloy::contract::Error) -> bool {
2359    match error.as_revert_data() {
2360        Some(data) => data.is_empty(),
2361        None => error
2362            .to_string()
2363            .to_ascii_lowercase()
2364            .contains("execution reverted"),
2365    }
2366}
2367
2368impl HypercallClient {
2369    /// The API server's current Unix millisecond, from the `/health` `Date`
2370    /// header (cached for a minute per client and its clones).
2371    pub async fn server_now_ms(&self) -> Result<u64> {
2372        let offset = match self.server_clock.cached_offset() {
2373            Some(offset) => offset,
2374            None => {
2375                let sent_ms = local_now_ms();
2376                let response = self.request(Method::GET, "/health").send().await?;
2377                let received_ms = local_now_ms();
2378                let date = response
2379                    .headers()
2380                    .get(reqwest::header::DATE)
2381                    .and_then(|value| value.to_str().ok())
2382                    .ok_or_else(|| ClientError::Api {
2383                        status: response.status().as_u16(),
2384                        message: "/health response carries no Date header to stamp TEE nonces"
2385                            .into(),
2386                    })?;
2387                let offset =
2388                    server_clock_offset_ms(date, sent_ms, received_ms).ok_or_else(|| {
2389                        ClientError::Api {
2390                            status: response.status().as_u16(),
2391                            message: format!("/health Date header is not an HTTP date: {date}"),
2392                        }
2393                    })?;
2394                self.server_clock.store(offset);
2395                offset
2396            }
2397        };
2398        u64::try_from(local_now_ms() + offset).map_err(|_| ClientError::ArithmeticOverflow {
2399            operation: "server clock",
2400        })
2401    }
2402
2403    /// Next TEE perp nonce for `signer`, stamped on the server clock and
2404    /// strictly increasing per signer within this process.
2405    pub async fn next_tee_perp_nonce(&self, signer: AccountAddress) -> Result<u64> {
2406        let now = self.server_now_ms().await?;
2407        Ok(next_nonce_at(signer.as_wallet_address().inner(), now))
2408    }
2409
2410    async fn resolve_tee_nonce(&self, signer: AccountAddress, nonce: Option<u64>) -> Result<u64> {
2411        match nonce {
2412            Some(nonce) => Ok(nonce),
2413            None => self.next_tee_perp_nonce(signer).await,
2414        }
2415    }
2416
2417    async fn post_tee<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2418    where
2419        T: serde::de::DeserializeOwned,
2420        B: serde::Serialize + ?Sized,
2421    {
2422        Self::send_json_body(self.request(Method::POST, route), body, action).await
2423    }
2424
2425    /// POST a signed, mutating submission. The body is serialized once and
2426    /// those exact bytes are sent, so an ambiguous failure can hand them back
2427    /// in [`ClientError::TeeSubmissionAmbiguous`] for an identical resend.
2428    async fn post_tee_signed<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2429    where
2430        T: serde::de::DeserializeOwned,
2431        B: SignedTeeSubmission,
2432    {
2433        let request_json = sonic_rs::to_string(body)
2434            .map_err(|source| ClientError::invalid_input("TEE request body", source))?;
2435        self.send_tee_submission(route, request_json, body.nonce(), action, false)
2436            .await
2437    }
2438
2439    async fn send_tee_submission<T>(
2440        &self,
2441        route: &str,
2442        request_json: String,
2443        nonce: u64,
2444        action: &str,
2445        resend: bool,
2446    ) -> Result<T>
2447    where
2448        T: serde::de::DeserializeOwned,
2449    {
2450        let request = self
2451            .request(Method::POST, route)
2452            .header(reqwest::header::CONTENT_TYPE, "application/json")
2453            .body(request_json.clone());
2454        match Self::send_reqwest_json(request, action).await {
2455            // A resend cannot settle the original's outcome: the signed action
2456            // can expire (and be refused before journal dedup) while the
2457            // original still executed, so every resend failure stays ambiguous.
2458            Err(error) if resend || tee_submission_is_ambiguous(&error) => {
2459                Err(ClientError::TeeSubmissionAmbiguous {
2460                    action: action.to_owned(),
2461                    route: route.to_owned(),
2462                    nonce,
2463                    request_json,
2464                    source: Box::new(error),
2465                })
2466            }
2467            result => result,
2468        }
2469    }
2470
2471    /// Resend the exact signed body of a [`ClientError::TeeSubmissionAmbiguous`].
2472    /// The server recognises the same signed action (same nonce, same terms)
2473    /// and does not submit it to the venue twice; a repeat comes back with
2474    /// `duplicate_directive` and stage `unknown`, meaning reconcile. Pass the
2475    /// error's `route` and `request_json` unchanged.
2476    ///
2477    /// Any failure of the resend, including a `4xx` such as an expired
2478    /// signature, is returned as [`ClientError::TeeSubmissionAmbiguous`]: the
2479    /// original request may still have executed, so reconcile before signing
2480    /// a fresh action.
2481    pub async fn resend_tee_submission<T>(&self, route: &str, request_json: &str) -> Result<T>
2482    where
2483        T: serde::de::DeserializeOwned,
2484    {
2485        let nonce = serde_json::from_str::<serde_json::Value>(request_json)
2486            .ok()
2487            .and_then(|body| match &body["nonce"] {
2488                serde_json::Value::Number(number) => number.as_u64(),
2489                serde_json::Value::String(text) => text.parse().ok(),
2490                _ => None,
2491            })
2492            .ok_or_else(|| {
2493                ClientError::InvalidInput("request_json carries no signed nonce".into())
2494            })?;
2495        self.send_tee_submission(
2496            route,
2497            request_json.to_owned(),
2498            nonce,
2499            "resend TEE submission",
2500            true,
2501        )
2502        .await
2503    }
2504
2505    /// Place one plain limit order (GTC, IOC, or ALO) on the TEE route.
2506    ///
2507    /// `client_order_id` defaults to the nonce.
2508    pub async fn place_tee_perp_limit_order<S>(
2509        &self,
2510        signer: &S,
2511        params: PerpLimitOrderParams,
2512    ) -> Result<TeePerpOrderResponse>
2513    where
2514        S: PerpDirectiveSigner + ?Sized,
2515    {
2516        let nonce = self
2517            .resolve_tee_nonce(signer.address(), params.nonce)
2518            .await?;
2519        let action = HlLimitOrderAction {
2520            asset: params.asset,
2521            is_buy: matches!(params.side, Side::Buy),
2522            limit_px: to_perp_units(params.price, "perp limit price")?,
2523            sz: to_perp_units(params.size, "perp size")?,
2524            reduce_only: params.reduce_only,
2525            tif: params.tif,
2526            cloid: nonzero_cloid(params.client_order_id.unwrap_or(u128::from(nonce)))?,
2527        };
2528        let signature = signer
2529            .sign_perp_limit_order_payload(PerpLimitOrderSignature {
2530                account: params.account,
2531                nonce,
2532                action,
2533            })
2534            .await?;
2535        let request = DirectiveSubmitRequest {
2536            account: params.account.into_wallet_address(),
2537            nonce,
2538            action,
2539            signature,
2540        };
2541        self.post_tee_signed(
2542            TEE_PERP_ORDER_SUBMIT_ROUTE,
2543            &request,
2544            "submit TEE perp order",
2545        )
2546        .await
2547    }
2548
2549    /// Place a market order: an IOC limit bounded by `slippage_bps`.
2550    pub async fn place_tee_perp_market_order<S>(
2551        &self,
2552        signer: &S,
2553        params: TeePerpMarketOrderParams,
2554    ) -> Result<TeePerpOrderResponse>
2555    where
2556        S: PerpDirectiveSigner + ?Sized,
2557    {
2558        let size_decimals = validate_size_decimals(params.size_decimals)?;
2559        if params.size.normalize().scale() > size_decimals {
2560            return Err(ClientError::InvalidInput(format!(
2561                "size {} has more than {size_decimals} decimals",
2562                params.size
2563            )));
2564        }
2565        let price = perp_market_limit_price(
2566            params.reference_price,
2567            params.side,
2568            size_decimals,
2569            params.slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2570        )?;
2571        self.place_tee_perp_limit_order(
2572            signer,
2573            PerpLimitOrderParams {
2574                account: params.account,
2575                asset: params.asset,
2576                side: params.side,
2577                price,
2578                size: params.size,
2579                tif: PerpTimeInForce::Ioc,
2580                reduce_only: params.reduce_only,
2581                client_order_id: params.client_order_id,
2582                nonce: params.nonce,
2583            },
2584        )
2585        .await
2586    }
2587
2588    /// Place one native stop-loss or take-profit order (market or limit).
2589    pub async fn place_tee_perp_trigger_order<S>(
2590        &self,
2591        signer: &S,
2592        params: TeePerpTriggerOrderParams,
2593    ) -> Result<TeePerpOrderBatchResponse>
2594    where
2595        S: TeePerpSigner + ?Sized,
2596    {
2597        let (limit_price, is_market) = match params.execution {
2598            TeePerpTriggerExecution::Market {
2599                size_decimals,
2600                slippage_bps,
2601            } => (
2602                perp_market_limit_price(
2603                    params.trigger_price,
2604                    params.side,
2605                    size_decimals,
2606                    slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2607                )?,
2608                true,
2609            ),
2610            TeePerpTriggerExecution::Limit { price } => (price, false),
2611        };
2612        let nonce = self
2613            .resolve_tee_nonce(signer.address(), params.nonce)
2614            .await?;
2615        let cloid = match params.client_order_id {
2616            Some(cloid) => cloid,
2617            None => tee_perp_batch_cloid(nonce, 0)?,
2618        };
2619        let order = tee_perp_trigger_order_wire(
2620            params.asset,
2621            params.side,
2622            params.trigger_price,
2623            limit_price,
2624            params.size,
2625            is_market,
2626            params.tpsl,
2627            params.reduce_only,
2628            cloid,
2629        )?;
2630        let signature = signer
2631            .sign_tee_perp_trigger_order_payload(TeePerpTriggerOrderSignature {
2632                account: params.account,
2633                nonce,
2634                order,
2635            })
2636            .await?;
2637        let request = DirectiveSubmitRequest {
2638            account: params.account.into_wallet_address(),
2639            nonce,
2640            action: order,
2641            signature,
2642        };
2643        self.post_tee_signed(
2644            TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE,
2645            &request,
2646            "submit TEE perp trigger order",
2647        )
2648        .await
2649    }
2650
2651    /// Submit a caller-built order batch (1 to 100 children).
2652    pub async fn place_tee_perp_order_batch<S>(
2653        &self,
2654        signer: &S,
2655        params: TeePerpOrderBatchParams,
2656    ) -> Result<TeePerpOrderBatchResponse>
2657    where
2658        S: TeePerpSigner + ?Sized,
2659    {
2660        validate_batch(&params.batch)?;
2661        let signature = signer
2662            .sign_tee_perp_order_batch_payload(TeePerpOrderBatchSignature {
2663                account: params.account,
2664                nonce: params.nonce,
2665                batch: &params.batch,
2666            })
2667            .await?;
2668        let request = DirectiveSubmitRequest {
2669            account: params.account.into_wallet_address(),
2670            nonce: params.nonce,
2671            action: params.batch,
2672            signature,
2673        };
2674        self.post_tee_signed(
2675            TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE,
2676            &request,
2677            "submit TEE perp order batch",
2678        )
2679        .await
2680    }
2681
2682    /// Place an entry with attached TP/SL exits (`normalTpsl`).
2683    pub async fn place_tee_perp_bracket_order<S>(
2684        &self,
2685        signer: &S,
2686        params: TeePerpBracketOrderParams,
2687    ) -> Result<TeePerpOrderBatchResponse>
2688    where
2689        S: TeePerpSigner + ?Sized,
2690    {
2691        let nonce = self
2692            .resolve_tee_nonce(signer.address(), params.nonce)
2693            .await?;
2694        let batch = build_tee_perp_bracket_batch(
2695            params.entry,
2696            params.take_profit,
2697            params.stop_loss,
2698            nonce,
2699        )?;
2700        self.place_tee_perp_order_batch(
2701            signer,
2702            TeePerpOrderBatchParams {
2703                account: params.account,
2704                nonce,
2705                batch,
2706            },
2707        )
2708        .await
2709    }
2710
2711    /// Place TP/SL exits on an existing position (`positionTpsl`).
2712    pub async fn place_tee_perp_position_tpsl<S>(
2713        &self,
2714        signer: &S,
2715        params: TeePerpPositionTpslParams,
2716    ) -> Result<TeePerpOrderBatchResponse>
2717    where
2718        S: TeePerpSigner + ?Sized,
2719    {
2720        let nonce = self
2721            .resolve_tee_nonce(signer.address(), params.nonce)
2722            .await?;
2723        let batch = build_tee_perp_position_tpsl_batch(
2724            params.asset,
2725            params.position_side,
2726            params.size,
2727            params.take_profit,
2728            params.stop_loss,
2729            nonce,
2730        )?;
2731        self.place_tee_perp_order_batch(
2732            signer,
2733            TeePerpOrderBatchParams {
2734                account: params.account,
2735                nonce,
2736                batch,
2737            },
2738        )
2739        .await
2740    }
2741
2742    /// Place a scale order: its legs as one ungrouped batch.
2743    pub async fn place_tee_perp_scale_order<S>(
2744        &self,
2745        signer: &S,
2746        params: TeePerpScaleOrderParams,
2747    ) -> Result<TeePerpOrderBatchResponse>
2748    where
2749        S: TeePerpSigner + ?Sized,
2750    {
2751        let nonce = self
2752            .resolve_tee_nonce(signer.address(), params.nonce)
2753            .await?;
2754        let batch = build_tee_perp_scale_batch(
2755            params.asset,
2756            params.side,
2757            &params.legs,
2758            params.tif,
2759            params.reduce_only,
2760            nonce,
2761        )?;
2762        self.place_tee_perp_order_batch(
2763            signer,
2764            TeePerpOrderBatchParams {
2765                account: params.account,
2766                nonce,
2767                batch,
2768            },
2769        )
2770        .await
2771    }
2772
2773    /// Cancel a resting order by Hyperliquid order ID.
2774    pub async fn cancel_tee_perp_order_by_oid<S>(
2775        &self,
2776        signer: &S,
2777        params: PerpCancelByOidParams,
2778    ) -> Result<TeePerpVenueActionResponse>
2779    where
2780        S: PerpDirectiveSigner + ?Sized,
2781    {
2782        if params.order_id == 0 {
2783            return Err(ClientError::InvalidInput("oid must not be zero".into()));
2784        }
2785        let nonce = self
2786            .resolve_tee_nonce(signer.address(), params.nonce)
2787            .await?;
2788        let action = HlCancelByOidAction {
2789            asset: params.asset,
2790            oid: params.order_id,
2791        };
2792        let signature = signer
2793            .sign_perp_cancel_by_oid_payload(PerpCancelByOidSignature {
2794                account: params.account,
2795                nonce,
2796                action,
2797            })
2798            .await?;
2799        let request = DirectiveSubmitRequest {
2800            account: params.account.into_wallet_address(),
2801            nonce,
2802            action,
2803            signature,
2804        };
2805        self.post_tee_signed(
2806            TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE,
2807            &request,
2808            "submit TEE perp cancel by oid",
2809        )
2810        .await
2811    }
2812
2813    /// Cancel a resting order by client order ID.
2814    pub async fn cancel_tee_perp_order_by_cloid<S>(
2815        &self,
2816        signer: &S,
2817        params: PerpCancelByCloidParams,
2818    ) -> Result<TeePerpCancelResponse>
2819    where
2820        S: PerpDirectiveSigner + ?Sized,
2821    {
2822        let nonce = self
2823            .resolve_tee_nonce(signer.address(), params.nonce)
2824            .await?;
2825        let action = HlCancelByCloidAction {
2826            asset: params.asset,
2827            cloid: nonzero_cloid(params.client_order_id)?,
2828        };
2829        let signature = signer
2830            .sign_perp_cancel_by_cloid_payload(PerpCancelByCloidSignature {
2831                account: params.account,
2832                nonce,
2833                action,
2834            })
2835            .await?;
2836        let request = DirectiveSubmitRequest {
2837            account: params.account.into_wallet_address(),
2838            nonce,
2839            action,
2840            signature,
2841        };
2842        self.post_tee_signed(
2843            TEE_PERP_CANCEL_SUBMIT_ROUTE,
2844            &request,
2845            "submit TEE perp cancel by cloid",
2846        )
2847        .await
2848    }
2849
2850    /// Change leverage and margin mode for one market. Read the venue's
2851    /// resulting setting back with [`HyperliquidInfoClient::active_asset_leverage`].
2852    pub async fn update_tee_perp_leverage<S>(
2853        &self,
2854        signer: &S,
2855        params: TeePerpLeverageParams,
2856    ) -> Result<TeePerpLeverageResponse>
2857    where
2858        S: TeePerpSigner + ?Sized,
2859    {
2860        if params.leverage == 0 {
2861            return Err(ClientError::InvalidInput(
2862                "leverage must be greater than zero".into(),
2863            ));
2864        }
2865        let nonce = self
2866            .resolve_tee_nonce(signer.address(), params.nonce)
2867            .await?;
2868        let action = TeePerpLeverageAction {
2869            asset: params.asset,
2870            is_cross: params.is_cross,
2871            leverage: params.leverage,
2872        };
2873        let signature = signer
2874            .sign_tee_perp_leverage_payload(TeePerpLeverageSignature {
2875                account: params.account,
2876                nonce,
2877                action,
2878            })
2879            .await?;
2880        let request = DirectiveSubmitRequest {
2881            account: params.account.into_wallet_address(),
2882            nonce,
2883            action,
2884            signature,
2885        };
2886        self.post_tee_signed(
2887            TEE_PERP_LEVERAGE_SUBMIT_ROUTE,
2888            &request,
2889            "submit TEE perp leverage",
2890        )
2891        .await
2892    }
2893
2894    /// Replace one resting limit order's price, size, side, TIF and
2895    /// reduce-only flag (Hyperliquid `modify`). The cloid is preserved.
2896    ///
2897    /// The engine reserves the larger of the old and new terms until the
2898    /// outcome is known: `rejected` or `not_submitted` restores the old terms
2899    /// (the original order still rests); `accepted` moves to the new terms.
2900    /// An `unknown` stage must be reconciled before modifying again.
2901    pub async fn modify_tee_perp_order<S>(
2902        &self,
2903        signer: &S,
2904        params: TeePerpModifyParams,
2905    ) -> Result<TeePerpModifyResponse>
2906    where
2907        S: TeePerpSigner + ?Sized,
2908    {
2909        let action = params.replacement.to_action()?;
2910        let nonce = self
2911            .resolve_tee_nonce(signer.address(), params.nonce)
2912            .await?;
2913        let signature = signer
2914            .sign_tee_perp_modify_payload(TeePerpModifySignature {
2915                account: params.account,
2916                nonce,
2917                action,
2918            })
2919            .await?;
2920        let request = DirectiveSubmitRequest {
2921            account: params.account.into_wallet_address(),
2922            nonce,
2923            action,
2924            signature,
2925        };
2926        self.post_tee_signed(
2927            TEE_PERP_ORDER_MODIFY_ROUTE,
2928            &request,
2929            "submit TEE perp modify",
2930        )
2931        .await
2932    }
2933
2934    /// Replace several resting limit orders in one signed Hyperliquid
2935    /// `batchModify` (one nonce, one venue call).
2936    ///
2937    /// The engine admits every child or none. After the venue answers, each
2938    /// child settles on its own: read
2939    /// [`TeePerpBatchModifyResponse::children`] (or
2940    /// [`TeePerpBatchModifyResponse::children_to_reconcile`]) rather than only
2941    /// the whole-action stage, which is `accepted` or `rejected` only when
2942    /// every child agrees. Charged as one order placement per child against
2943    /// the rate limit.
2944    ///
2945    /// Refused locally, before signing, when the batch is empty, exceeds
2946    /// `max_children` (50 by default), repeats a target or cloid, or carries an
2947    /// invalid child. A deployment whose enclave release does not enable batch
2948    /// modify answers `400 unsupported_action`
2949    /// ([`ClientError::is_unsupported_action`]).
2950    pub async fn batch_modify_tee_perp_orders<S>(
2951        &self,
2952        signer: &S,
2953        params: TeePerpBatchModifyParams,
2954    ) -> Result<TeePerpBatchModifyResponse>
2955    where
2956        S: TeePerpSigner + ?Sized,
2957    {
2958        let batch = build_tee_perp_batch_modify(&params.replacements, params.max_children)?;
2959        let nonce = self
2960            .resolve_tee_nonce(signer.address(), params.nonce)
2961            .await?;
2962        let signature = signer
2963            .sign_tee_perp_batch_modify_payload(TeePerpBatchModifySignature {
2964                account: params.account,
2965                nonce,
2966                batch: &batch,
2967            })
2968            .await?;
2969        let request = DirectiveSubmitRequest {
2970            account: params.account.into_wallet_address(),
2971            nonce,
2972            action: batch,
2973            signature,
2974        };
2975        self.post_tee_signed(
2976            TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
2977            &request,
2978            "submit TEE perp batch modify",
2979        )
2980        .await
2981    }
2982
2983    /// Start a native Hyperliquid TWAP (`twapOrder`). The engine reserves
2984    /// the full size at admission and releases it as fills arrive. Keep
2985    /// [`TeePerpTwapResponse::twap_id`] to cancel it.
2986    ///
2987    /// TWAP is disabled at runtime on deployments whose enclave release does
2988    /// not enable it; those answer `400 unsupported_action`
2989    /// ([`ClientError::is_unsupported_action`]).
2990    pub async fn place_tee_perp_twap_order<S>(
2991        &self,
2992        signer: &S,
2993        params: TeePerpTwapParams,
2994    ) -> Result<TeePerpTwapResponse>
2995    where
2996        S: TeePerpSigner + ?Sized,
2997    {
2998        let action = TeePerpTwapAction {
2999            asset: params.asset,
3000            is_buy: matches!(params.side, Side::Buy),
3001            sz: to_perp_units(params.size, "size")?,
3002            reduce_only: params.reduce_only,
3003            minutes: params.minutes,
3004            randomize: params.randomize,
3005        };
3006        validate_twap_action(&action)?;
3007        let nonce = self
3008            .resolve_tee_nonce(signer.address(), params.nonce)
3009            .await?;
3010        let signature = signer
3011            .sign_tee_perp_twap_payload(TeePerpTwapSignature {
3012                account: params.account,
3013                nonce,
3014                action,
3015            })
3016            .await?;
3017        let request = DirectiveSubmitRequest {
3018            account: params.account.into_wallet_address(),
3019            nonce,
3020            action,
3021            signature,
3022        };
3023        self.post_tee_signed(TEE_PERP_TWAP_SUBMIT_ROUTE, &request, "submit TEE perp TWAP")
3024            .await
3025    }
3026
3027    /// Cancel a running native TWAP (`twapCancel`). Like TWAP submit, this
3028    /// can answer `400 unsupported_action` where TWAP is disabled.
3029    pub async fn cancel_tee_perp_twap<S>(
3030        &self,
3031        signer: &S,
3032        params: TeePerpTwapCancelParams,
3033    ) -> Result<TeePerpVenueActionResponse>
3034    where
3035        S: TeePerpSigner + ?Sized,
3036    {
3037        if params.twap_id == 0 {
3038            return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
3039        }
3040        let nonce = self
3041            .resolve_tee_nonce(signer.address(), params.nonce)
3042            .await?;
3043        let action = TeePerpTwapCancelAction {
3044            asset: params.asset,
3045            twap_id: params.twap_id,
3046        };
3047        let signature = signer
3048            .sign_tee_perp_twap_cancel_payload(TeePerpTwapCancelSignature {
3049                account: params.account,
3050                nonce,
3051                action,
3052            })
3053            .await?;
3054        let request = DirectiveSubmitRequest {
3055            account: params.account.into_wallet_address(),
3056            nonce,
3057            action,
3058            signature,
3059        };
3060        self.post_tee_signed(
3061            TEE_PERP_TWAP_CANCEL_ROUTE,
3062            &request,
3063            "submit TEE perp TWAP cancel",
3064        )
3065        .await
3066    }
3067
3068    /// Preview an action's admission, margin, liquidation prices and max
3069    /// size without signing or reserving anything.
3070    pub async fn preview_tee_perp_action(
3071        &self,
3072        request: &PerpPreviewRequest,
3073    ) -> Result<PerpPreviewResponse> {
3074        let envelope: ApiResponse<PerpPreviewResponse> = self
3075            .post_tee(TEE_PERP_PREVIEW_ROUTE, request, "preview TEE perp action")
3076            .await?;
3077        if !envelope.success {
3078            return Err(ClientError::Api {
3079                status: 200,
3080                message: envelope
3081                    .error
3082                    .unwrap_or_else(|| "TEE perp preview failed".into()),
3083            });
3084        }
3085        envelope.data.ok_or_else(|| ClientError::Api {
3086            status: 200,
3087            message: "TEE perp preview returned no data".into(),
3088        })
3089    }
3090
3091    /// Configured TEE perp markets and whether each is supported.
3092    pub async fn get_tee_perp_markets(&self) -> Result<TeePerpMarketsResponse> {
3093        Self::send_reqwest_json(
3094            self.request(Method::GET, TEE_PERP_MARKETS_ROUTE),
3095            "get TEE perp markets",
3096        )
3097        .await
3098    }
3099
3100    /// Step 1 of enrollment: authenticate as the manager and fetch the
3101    /// account's TEE API wallet with its `HLAddApiWallet` approval payload.
3102    pub async fn request_tee_api_wallet_approval<S>(
3103        &self,
3104        manager: &S,
3105        account: AccountAddress,
3106    ) -> Result<TeeApiWalletApprovalChallenge>
3107    where
3108        S: TeeApiWalletManagerSigner + ?Sized,
3109    {
3110        let timestamp = i64::try_from(self.server_now_ms().await? / 1_000).map_err(|_| {
3111            ClientError::ArithmeticOverflow {
3112                operation: "authentication timestamp",
3113            }
3114        })?;
3115        let manager_address = manager.address();
3116        let authentication_signature = manager.sign_authentication_payload(timestamp).await?;
3117        let request = TeeApiWalletApprovalRequest {
3118            account: account.into_wallet_address(),
3119            manager: manager_address.into_wallet_address(),
3120            timestamp,
3121            signature: authentication_signature.clone(),
3122        };
3123        let package: TeeApiWalletApprovalPackage = self
3124            .post_tee(
3125                TEE_API_WALLET_APPROVAL_REQUEST_ROUTE,
3126                &request,
3127                "request TEE API wallet approval",
3128            )
3129            .await?;
3130        Ok(TeeApiWalletApprovalChallenge {
3131            account,
3132            manager: manager_address,
3133            timestamp,
3134            authentication_signature,
3135            package,
3136        })
3137    }
3138
3139    /// Step 2 of enrollment: sign the approval (after checking the returned
3140    /// typed data names exactly the packaged wallet) and submit it.
3141    pub async fn submit_tee_api_wallet_approval<S>(
3142        &self,
3143        manager: &S,
3144        challenge: &TeeApiWalletApprovalChallenge,
3145    ) -> Result<DirectiveSubmitResponse>
3146    where
3147        S: TeeApiWalletManagerSigner + ?Sized,
3148    {
3149        validate_approval_typed_data(challenge)?;
3150        let signature = manager
3151            .sign_tee_api_wallet_approval_payload(TeeApiWalletApprovalSignature {
3152                account: challenge.account,
3153                nonce: challenge.package.nonce,
3154                api_wallet_address: AccountAddress::from(
3155                    challenge.package.api_wallet_address.inner(),
3156                ),
3157                api_wallet_name: &challenge.package.api_wallet_name,
3158            })
3159            .await?;
3160        let request = TeeApiWalletApprovalSubmitRequest {
3161            account: challenge.account.into_wallet_address(),
3162            manager: challenge.manager.into_wallet_address(),
3163            timestamp: challenge.timestamp,
3164            authentication_signature: challenge.authentication_signature.clone(),
3165            tee_wallet_id: challenge.package.tee_wallet_id,
3166            nonce: challenge.package.nonce,
3167            signature,
3168        };
3169        self.post_tee_signed(
3170            TEE_API_WALLET_APPROVAL_ROUTE,
3171            &request,
3172            "submit TEE API wallet approval",
3173        )
3174        .await
3175    }
3176
3177    /// Enroll the account's TEE API wallet end to end, as the Hypercall
3178    /// order panel does: request it, skip the approval when Hyperliquid
3179    /// already binds it, otherwise submit the approval, poll the directive
3180    /// until it finalizes, and confirm the binding on Hyperliquid.
3181    pub async fn enroll_tee_api_wallet<S>(
3182        &self,
3183        manager: &S,
3184        account: AccountAddress,
3185        hyperliquid: &HyperliquidInfoClient,
3186        polling: TeeApiWalletEnrollmentPolling,
3187    ) -> Result<TeeApiWalletEnrollment>
3188    where
3189        S: TeeApiWalletManagerSigner + ?Sized,
3190    {
3191        let challenge = self
3192            .request_tee_api_wallet_approval(manager, account)
3193            .await?;
3194        let api_wallet = AccountAddress::from(challenge.package.api_wallet_address.inner());
3195        let api_wallet_name = challenge.package.api_wallet_name.clone();
3196        if hyperliquid
3197            .is_tee_api_wallet_active(account, api_wallet)
3198            .await?
3199        {
3200            return Ok(TeeApiWalletEnrollment {
3201                api_wallet,
3202                api_wallet_name,
3203                directive_id: None,
3204            });
3205        }
3206        let response = self
3207            .submit_tee_api_wallet_approval(manager, &challenge)
3208            .await?;
3209        if let Some(rejection) = &response.rejection {
3210            return Err(ClientError::Api {
3211                status: 200,
3212                message: format!(
3213                    "TEE API wallet approval rejected ({}): {}",
3214                    rejection.code, rejection.message
3215                ),
3216            });
3217        }
3218        let mut finalized = false;
3219        for _ in 0..polling.attempts {
3220            // The directive can briefly be absent before its row appears.
3221            if let Ok(status) = self.get_directive_status(&response.directive_id).await {
3222                match tee_api_wallet_approval_progress(&status) {
3223                    TeeApiWalletApprovalProgress::Finalized => {
3224                        finalized = true;
3225                        break;
3226                    }
3227                    TeeApiWalletApprovalProgress::Failed => {
3228                        return Err(ClientError::Api {
3229                            status: 200,
3230                            message: format!(
3231                                "TEE API wallet approval {} failed: domain {:?}, delivery {:?}",
3232                                response.directive_id, status.domain_status, status.delivery_status
3233                            ),
3234                        });
3235                    }
3236                    TeeApiWalletApprovalProgress::Pending => {}
3237                }
3238            }
3239            tokio::time::sleep(polling.interval).await;
3240        }
3241        if !finalized {
3242            return Err(ClientError::Api {
3243                status: 200,
3244                message: format!(
3245                    "TEE API wallet approval {} is still pending",
3246                    response.directive_id
3247                ),
3248            });
3249        }
3250        if !hyperliquid
3251            .is_tee_api_wallet_active(account, api_wallet)
3252            .await?
3253        {
3254            return Err(ClientError::Api {
3255                status: 200,
3256                message: "Hyperliquid did not bind the finalized TEE API wallet to this account"
3257                    .into(),
3258            });
3259        }
3260        Ok(TeeApiWalletEnrollment {
3261            api_wallet,
3262            api_wallet_name,
3263            directive_id: Some(response.directive_id),
3264        })
3265    }
3266
3267    /// Approve the zero-fee Hypercall builder for the account on Hyperliquid
3268    /// with one manager HyperEVM transaction calling
3269    /// `Account.approveZeroFeeBuilder(builder)`. Idempotent on the venue.
3270    ///
3271    /// Needed once per account before TEE perp orders are accepted (they are
3272    /// refused with `builder_not_approved` until then). Requires Account
3273    /// 0.2.4 or newer and a little HYPE on the manager for gas.
3274    pub async fn approve_hypercall_builder(
3275        &self,
3276        manager: &HypercallWallet,
3277        params: ApproveHypercallBuilderParams,
3278    ) -> Result<B256> {
3279        let builder = match params.builder {
3280            Some(builder) => builder,
3281            None => resolve_hypercall_builder_address(&self.get_exchange_info().await?)?,
3282        };
3283        let builder = builder.as_wallet_address().inner();
3284        if builder == Address::ZERO {
3285            return Err(ClientError::InvalidInput("builder must not be zero".into()));
3286        }
3287        let rpc_url = params
3288            .rpc_url
3289            .parse()
3290            .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
3291        let provider = ProviderBuilder::new()
3292            .wallet(manager.ethereum_wallet())
3293            .connect_http(rpc_url);
3294        let rpc_chain_id = provider
3295            .get_chain_id()
3296            .await
3297            .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
3298        if rpc_chain_id != manager.chain_id() {
3299            return Err(ClientError::InvalidInput(format!(
3300                "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {}",
3301                manager.chain_id()
3302            )));
3303        }
3304        let manager_address = manager.address.as_wallet_address().inner();
3305        let balance = provider
3306            .get_balance(manager_address)
3307            .await
3308            .map_err(|error| onchain_error("read manager HYPE balance", error))?;
3309        if balance.is_zero() {
3310            return Err(ClientError::InvalidInput(
3311                "the manager wallet needs a small amount of HYPE on HyperEVM to pay the network fee"
3312                    .into(),
3313            ));
3314        }
3315        let account = HypercallAccountBuilderApproval::new(
3316            params.account.as_wallet_address().inner(),
3317            &provider,
3318        );
3319        let call = account.approveZeroFeeBuilder(builder).from(manager_address);
3320        if let Err(error) = call.call().await {
3321            if is_missing_function_revert(&error) {
3322                return Err(ClientError::InvalidInput(
3323                    "this Account implementation predates approveZeroFeeBuilder (needs 0.2.4); trading cannot be enabled yet".into(),
3324                ));
3325            }
3326            return Err(onchain_error("simulate approveZeroFeeBuilder", error));
3327        }
3328        let submission_lock = evm_submission_lock(manager_address);
3329        let _guard = submission_lock.lock().await;
3330        let receipt = call
3331            .send()
3332            .await
3333            .map_err(|error| onchain_error("submit approveZeroFeeBuilder", error))?
3334            .with_timeout(Some(Duration::from_secs(60)))
3335            .get_receipt()
3336            .await
3337            .map_err(|error| onchain_error("confirm approveZeroFeeBuilder", error))?;
3338        if !receipt.status() {
3339            return Err(ClientError::TransactionReverted {
3340                operation: "approveZeroFeeBuilder",
3341                transaction_hash: Some(receipt.transaction_hash),
3342            });
3343        }
3344        Ok(receipt.transaction_hash)
3345    }
3346}
3347
3348#[cfg(test)]
3349#[path = "tee_perp_test.rs"]
3350mod tests;
3351
3352#[cfg(test)]
3353#[path = "tee_perp_modify_test.rs"]
3354mod modify_tests;