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