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;
476const 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
864fn 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
1473fn 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/// A signed body whose nonce identifies it to the server.
1854trait SignedTeeSubmission: serde::Serialize {
1855    fn nonce(&self) -> u64;
1856}
1857
1858impl<A: serde::Serialize> SignedTeeSubmission for DirectiveSubmitRequest<A> {
1859    fn nonce(&self) -> u64 {
1860        self.nonce
1861    }
1862}
1863
1864impl SignedTeeSubmission for TeeApiWalletApprovalSubmitRequest {
1865    fn nonce(&self) -> u64 {
1866        self.nonce
1867    }
1868}
1869
1870/// Whether a failed submission may still have reached the server: any
1871/// transport or decode failure, a `408`, or a `5xx`. Other `4xx` answers
1872/// are definitive.
1873fn tee_submission_is_ambiguous(error: &ClientError) -> bool {
1874    matches!(
1875        error,
1876        ClientError::Http(_)
1877            | ClientError::Api {
1878                status: 408 | 500..=599,
1879                ..
1880            }
1881    )
1882}
1883
1884#[path = "tee_perp_preview.rs"]
1885mod preview;
1886pub use preview::{perp_preview_batch_action, perp_preview_order};
1887
1888// ---------------------------------------------------------------------------
1889// Request parameters
1890// ---------------------------------------------------------------------------
1891
1892/// A market order: an IOC limit at `reference_price` moved `slippage_bps`
1893/// against the trader and rounded to a valid tick.
1894#[derive(Debug, Clone)]
1895pub struct TeePerpMarketOrderParams {
1896    pub account: AccountAddress,
1897    pub asset: u32,
1898    pub side: Side,
1899    pub size: Decimal,
1900    /// Best ask for a buy, best bid for a sell.
1901    pub reference_price: Decimal,
1902    /// Hyperliquid `szDecimals` of the market.
1903    pub size_decimals: u32,
1904    /// Defaults to [`PERP_MARKET_SLIPPAGE_BPS`].
1905    pub slippage_bps: Option<u32>,
1906    pub reduce_only: bool,
1907    pub client_order_id: Option<u128>,
1908    pub nonce: Option<u64>,
1909}
1910
1911/// How a trigger order executes once triggered.
1912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1913pub enum TeePerpTriggerExecution {
1914    /// Market (IOC) bounded `slippage_bps` beyond the trigger price.
1915    Market {
1916        size_decimals: u32,
1917        /// Defaults to [`PERP_MARKET_SLIPPAGE_BPS`].
1918        slippage_bps: Option<u32>,
1919    },
1920    /// A limit order at `price`.
1921    Limit { price: Decimal },
1922}
1923
1924/// A native stop-loss or take-profit order (market or limit).
1925#[derive(Debug, Clone)]
1926pub struct TeePerpTriggerOrderParams {
1927    pub account: AccountAddress,
1928    pub asset: u32,
1929    pub side: Side,
1930    pub size: Decimal,
1931    pub trigger_price: Decimal,
1932    /// `Sl` for a stop, `Tp` for a take-profit.
1933    pub tpsl: TeePerpTpsl,
1934    pub execution: TeePerpTriggerExecution,
1935    pub reduce_only: bool,
1936    /// Defaults to `tee_perp_batch_cloid(nonce, 0)`.
1937    pub client_order_id: Option<u128>,
1938    pub nonce: Option<u64>,
1939}
1940
1941/// An entry with attached TP/SL exits (`normalTpsl`).
1942#[derive(Debug, Clone)]
1943pub struct TeePerpBracketOrderParams {
1944    pub account: AccountAddress,
1945    pub entry: TeePerpBracketEntry,
1946    pub take_profit: Option<TeePerpExit>,
1947    pub stop_loss: Option<TeePerpExit>,
1948    pub nonce: Option<u64>,
1949}
1950
1951/// TP/SL exits on an existing position (`positionTpsl`).
1952#[derive(Debug, Clone)]
1953pub struct TeePerpPositionTpslParams {
1954    pub account: AccountAddress,
1955    pub asset: u32,
1956    /// The position's direction (`Buy` = long).
1957    pub position_side: Side,
1958    pub size: Decimal,
1959    pub take_profit: Option<TeePerpExit>,
1960    pub stop_loss: Option<TeePerpExit>,
1961    pub nonce: Option<u64>,
1962}
1963
1964/// A scale order: limit legs submitted as one ungrouped batch.
1965#[derive(Debug, Clone)]
1966pub struct TeePerpScaleOrderParams {
1967    pub account: AccountAddress,
1968    pub asset: u32,
1969    pub side: Side,
1970    /// From [`build_perp_scale_order_legs`] or caller-chosen.
1971    pub legs: Vec<PerpScaleLeg>,
1972    pub tif: PerpTimeInForce,
1973    pub reduce_only: bool,
1974    pub nonce: Option<u64>,
1975}
1976
1977/// A caller-built order batch. Cloids must already be set; derive them from
1978/// the nonce with [`tee_perp_batch_cloid`] after reserving it with
1979/// [`HypercallClient::next_tee_perp_nonce`].
1980#[derive(Debug, Clone)]
1981pub struct TeePerpOrderBatchParams {
1982    pub account: AccountAddress,
1983    pub nonce: u64,
1984    pub batch: TeePerpOrderBatchAction,
1985}
1986
1987/// A leverage and margin-mode change.
1988#[derive(Debug, Clone, Copy)]
1989pub struct TeePerpLeverageParams {
1990    pub account: AccountAddress,
1991    pub asset: u32,
1992    /// `true` for cross margin, `false` for isolated.
1993    pub is_cross: bool,
1994    /// At least 1.
1995    pub leverage: u32,
1996    pub nonce: Option<u64>,
1997}
1998
1999/// One resting limit order's replacement
2000/// ([`HypercallClient::modify_tee_perp_order`]).
2001#[derive(Debug, Clone, Copy)]
2002pub struct TeePerpModifyParams {
2003    pub account: AccountAddress,
2004    pub replacement: TeePerpOrderReplacement,
2005    pub nonce: Option<u64>,
2006}
2007
2008/// Several resting limit orders' replacements under one signature
2009/// ([`HypercallClient::batch_modify_tee_perp_orders`]).
2010#[derive(Debug, Clone)]
2011pub struct TeePerpBatchModifyParams {
2012    pub account: AccountAddress,
2013    /// In the order the venue applies and answers them.
2014    pub replacements: Vec<TeePerpOrderReplacement>,
2015    /// The server instance's `api.tee_perp_batch_modify_max_children`, when
2016    /// it is not the default ([`DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN`]).
2017    /// At most [`MAX_TEE_PERP_BATCH_MODIFY_CHILDREN`].
2018    pub max_children: Option<usize>,
2019    pub nonce: Option<u64>,
2020}
2021
2022/// A native Hyperliquid TWAP ([`HypercallClient::place_tee_perp_twap_order`]).
2023#[derive(Debug, Clone, Copy)]
2024pub struct TeePerpTwapParams {
2025    pub account: AccountAddress,
2026    pub asset: u32,
2027    pub side: Side,
2028    /// Total size in coins. At most 8 decimal places.
2029    pub size: Decimal,
2030    pub reduce_only: bool,
2031    /// [`TEE_PERP_TWAP_MIN_MINUTES`] to [`TEE_PERP_TWAP_MAX_MINUTES`].
2032    pub minutes: u32,
2033    /// Vary slice timing.
2034    pub randomize: bool,
2035    pub nonce: Option<u64>,
2036}
2037
2038/// Cancel a running TWAP ([`HypercallClient::cancel_tee_perp_twap`]).
2039#[derive(Debug, Clone, Copy)]
2040pub struct TeePerpTwapCancelParams {
2041    pub account: AccountAddress,
2042    pub asset: u32,
2043    /// [`TeePerpTwapResponse::twap_id`] of the TWAP to cancel.
2044    pub twap_id: u64,
2045    pub nonce: Option<u64>,
2046}
2047
2048/// Parameters for [`HypercallClient::approve_hypercall_builder`].
2049#[derive(Debug, Clone)]
2050pub struct ApproveHypercallBuilderParams {
2051    /// HyperEVM JSON-RPC endpoint.
2052    pub rpc_url: String,
2053    /// The Account.sol (0.2.4 or newer) the manager controls.
2054    pub account: AccountAddress,
2055    /// Builder to approve. `None` reads `hl_builder_address` from `/exchange-info`.
2056    pub builder: Option<AccountAddress>,
2057}
2058
2059/// The manager-authenticated TEE API wallet approval challenge.
2060#[derive(Debug, Clone)]
2061pub struct TeeApiWalletApprovalChallenge {
2062    pub account: AccountAddress,
2063    pub manager: AccountAddress,
2064    /// Unix seconds signed in the authentication message.
2065    pub timestamp: i64,
2066    pub authentication_signature: String,
2067    pub package: TeeApiWalletApprovalPackage,
2068}
2069
2070/// Progress of a TEE API wallet approval directive.
2071#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2072pub enum TeeApiWalletApprovalProgress {
2073    Pending,
2074    Finalized,
2075    Failed,
2076}
2077
2078/// Classify a `/v1/directives/{id}` status of the approval directive.
2079pub fn tee_api_wallet_approval_progress(
2080    status: &DirectiveStatusResponse,
2081) -> TeeApiWalletApprovalProgress {
2082    if status.domain_status == DirectiveDomainStatus::Completed
2083        && status.delivery_status == DirectiveDeliveryStatus::Finalized
2084    {
2085        return TeeApiWalletApprovalProgress::Finalized;
2086    }
2087    if matches!(
2088        status.domain_status,
2089        DirectiveDomainStatus::Failed | DirectiveDomainStatus::Rejected
2090    ) || matches!(
2091        status.delivery_status,
2092        DirectiveDeliveryStatus::CoreRejected
2093            | DirectiveDeliveryStatus::Reverted
2094            | DirectiveDeliveryStatus::Expired
2095            | DirectiveDeliveryStatus::DeadLettered
2096    ) {
2097        return TeeApiWalletApprovalProgress::Failed;
2098    }
2099    TeeApiWalletApprovalProgress::Pending
2100}
2101
2102/// Result of [`HypercallClient::enroll_tee_api_wallet`].
2103#[derive(Debug, Clone)]
2104pub struct TeeApiWalletEnrollment {
2105    /// The TEE-controlled Hyperliquid API wallet now bound to the account.
2106    pub api_wallet: AccountAddress,
2107    pub api_wallet_name: String,
2108    /// `None` when Hyperliquid already had the wallet bound.
2109    pub directive_id: Option<String>,
2110}
2111
2112/// Polling of [`HypercallClient::enroll_tee_api_wallet`].
2113#[derive(Debug, Clone, Copy)]
2114pub struct TeeApiWalletEnrollmentPolling {
2115    pub interval: Duration,
2116    pub attempts: u32,
2117}
2118
2119impl Default for TeeApiWalletEnrollmentPolling {
2120    fn default() -> Self {
2121        Self {
2122            interval: Duration::from_secs(2),
2123            attempts: 60,
2124        }
2125    }
2126}
2127
2128/// Hypercall builder published by `/exchange-info`. Never guessed.
2129pub fn resolve_hypercall_builder_address(
2130    exchange_info: &ExchangeInfoResponse,
2131) -> Result<AccountAddress> {
2132    let configured = exchange_info.hl_builder_address.as_deref().ok_or_else(|| {
2133        ClientError::InvalidInput("exchange-info does not publish hl_builder_address".into())
2134    })?;
2135    let builder: AccountAddress = configured
2136        .parse()
2137        .map_err(|source| ClientError::invalid_input("hl_builder_address", source))?;
2138    if builder.as_wallet_address().inner() == Address::ZERO {
2139        return Err(ClientError::InvalidInput(
2140            "exchange-info publishes a zero hl_builder_address".into(),
2141        ));
2142    }
2143    Ok(builder)
2144}
2145
2146// ---------------------------------------------------------------------------
2147// Hyperliquid info reads
2148// ---------------------------------------------------------------------------
2149
2150/// Hyperliquid margin setting read back from the venue.
2151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2152pub struct HyperliquidLeverage {
2153    pub is_cross: bool,
2154    pub value: u32,
2155}
2156
2157#[derive(Debug, Deserialize)]
2158struct ActiveAssetData {
2159    user: String,
2160    coin: String,
2161    leverage: ActiveAssetLeverage,
2162}
2163
2164#[derive(Debug, Deserialize)]
2165struct ActiveAssetLeverage {
2166    #[serde(rename = "type")]
2167    kind: String,
2168    value: u32,
2169}
2170
2171/// Hyperliquid `userRole` response.
2172#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2173pub struct HyperliquidUserRole {
2174    pub role: String,
2175    #[serde(default)]
2176    pub data: Option<HyperliquidUserRoleData>,
2177}
2178
2179#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2180pub struct HyperliquidUserRoleData {
2181    #[serde(default)]
2182    pub user: Option<String>,
2183}
2184
2185impl HyperliquidUserRole {
2186    /// Whether this role is an API wallet (agent) bound to `account`.
2187    pub fn is_agent_for(&self, account: AccountAddress) -> bool {
2188        self.role == "agent"
2189            && self
2190                .data
2191                .as_ref()
2192                .and_then(|data| data.user.as_deref())
2193                .and_then(|user| user.parse::<AccountAddress>().ok())
2194                == Some(account)
2195    }
2196}
2197
2198/// Minimal Hyperliquid `/info` reader for TEE perp readbacks.
2199#[derive(Debug, Clone)]
2200pub struct HyperliquidInfoClient {
2201    client: reqwest::Client,
2202    url: String,
2203}
2204
2205impl HyperliquidInfoClient {
2206    pub fn new(url: impl Into<String>) -> Self {
2207        Self {
2208            client: reqwest::Client::builder()
2209                .timeout(Duration::from_secs(15))
2210                .build()
2211                .expect("failed to build reqwest client"),
2212            url: url.into(),
2213        }
2214    }
2215
2216    pub fn mainnet() -> Self {
2217        Self::new(HYPERLIQUID_MAINNET_INFO_URL)
2218    }
2219
2220    pub fn testnet() -> Self {
2221        Self::new(HYPERLIQUID_TESTNET_INFO_URL)
2222    }
2223
2224    /// The info client for a Hypercall directive chain id (999 or 998).
2225    pub fn for_chain_id(chain_id: u64) -> Result<Self> {
2226        match chain_id {
2227            999 => Ok(Self::mainnet()),
2228            998 => Ok(Self::testnet()),
2229            _ => Err(ClientError::InvalidInput(format!(
2230                "unsupported Hyperliquid chain id: {chain_id}"
2231            ))),
2232        }
2233    }
2234
2235    async fn post<T: serde::de::DeserializeOwned>(
2236        &self,
2237        body: serde_json::Value,
2238        action: &str,
2239    ) -> Result<T> {
2240        HypercallClient::send_reqwest_json(self.client.post(&self.url).json(&body), action).await
2241    }
2242
2243    /// Hyperliquid's role for `address`.
2244    pub async fn user_role(&self, address: AccountAddress) -> Result<HyperliquidUserRole> {
2245        self.post(
2246            serde_json::json!({"type": "userRole", "user": address.to_string()}),
2247            "read Hyperliquid user role",
2248        )
2249        .await
2250    }
2251
2252    /// Whether Hyperliquid has `api_wallet` bound as an agent of `account`:
2253    /// the TEE API wallet enrollment status.
2254    pub async fn is_tee_api_wallet_active(
2255        &self,
2256        account: AccountAddress,
2257        api_wallet: AccountAddress,
2258    ) -> Result<bool> {
2259        Ok(self.user_role(api_wallet).await?.is_agent_for(account))
2260    }
2261
2262    /// The account's leverage and margin mode for `coin` (e.g. `BTC` or
2263    /// `xyz:SNDK`), read back from Hyperliquid after a leverage change.
2264    pub async fn active_asset_leverage(
2265        &self,
2266        account: AccountAddress,
2267        coin: &str,
2268    ) -> Result<HyperliquidLeverage> {
2269        let data: ActiveAssetData = self
2270            .post(
2271                serde_json::json!({"type": "activeAssetData", "user": account.to_string(), "coin": coin}),
2272                "read Hyperliquid active asset data",
2273            )
2274            .await?;
2275        let echoed_user = data.user.parse::<AccountAddress>().ok();
2276        if echoed_user != Some(account) || data.coin != coin {
2277            return Err(ClientError::Api {
2278                status: 200,
2279                message: "Hyperliquid returned leverage for a different account or market".into(),
2280            });
2281        }
2282        let is_cross = match data.leverage.kind.as_str() {
2283            "cross" => true,
2284            "isolated" => false,
2285            _ => {
2286                return Err(ClientError::Api {
2287                    status: 200,
2288                    message: "Hyperliquid returned an invalid leverage setting".into(),
2289                })
2290            }
2291        };
2292        if data.leverage.value < 1 {
2293            return Err(ClientError::Api {
2294                status: 200,
2295                message: "Hyperliquid returned an invalid leverage setting".into(),
2296            });
2297        }
2298        Ok(HyperliquidLeverage {
2299            is_cross,
2300            value: data.leverage.value,
2301        })
2302    }
2303}
2304
2305// ---------------------------------------------------------------------------
2306// Client methods
2307// ---------------------------------------------------------------------------
2308
2309fn approval_typed_data_mismatch(field: &str) -> ClientError {
2310    ClientError::InvalidInput(format!(
2311        "TEE API wallet approval typed data does not match the package: {field}"
2312    ))
2313}
2314
2315fn validate_approval_typed_data(challenge: &TeeApiWalletApprovalChallenge) -> Result<()> {
2316    let typed = &challenge.package.typed_data;
2317    if typed["primaryType"] != "HLAddApiWallet" {
2318        return Err(approval_typed_data_mismatch("primaryType"));
2319    }
2320    if typed["domain"]["name"] != HYPERCALL_MANAGER_DOMAIN {
2321        return Err(approval_typed_data_mismatch("domain.name"));
2322    }
2323    let message = &typed["message"];
2324    let same_address = |value: &serde_json::Value, expected: WalletAddress| {
2325        value
2326            .as_str()
2327            .and_then(|text| text.parse::<WalletAddress>().ok())
2328            == Some(expected)
2329    };
2330    if !same_address(&message["account"], challenge.account.into_wallet_address()) {
2331        return Err(approval_typed_data_mismatch("message.account"));
2332    }
2333    let nonce = match &message["nonce"] {
2334        serde_json::Value::Number(number) => number.as_u64(),
2335        serde_json::Value::String(text) => text.parse().ok(),
2336        _ => None,
2337    };
2338    if nonce != Some(challenge.package.nonce) {
2339        return Err(approval_typed_data_mismatch("message.nonce"));
2340    }
2341    let action = &message["action"];
2342    if !same_address(
2343        &action["apiWalletAddress"],
2344        challenge.package.api_wallet_address,
2345    ) {
2346        return Err(approval_typed_data_mismatch(
2347            "message.action.apiWalletAddress",
2348        ));
2349    }
2350    if action["apiWalletName"] != challenge.package.api_wallet_name.as_str() {
2351        return Err(approval_typed_data_mismatch("message.action.apiWalletName"));
2352    }
2353    Ok(())
2354}
2355
2356fn onchain_error(
2357    operation: impl Into<String>,
2358    source: impl std::error::Error + Send + Sync + 'static,
2359) -> ClientError {
2360    ClientError::Onchain {
2361        operation: operation.into(),
2362        source: Box::new(source),
2363    }
2364}
2365
2366/// An Account implementation older than 0.2.4 has no `approveZeroFeeBuilder`
2367/// and reverts with no data.
2368fn is_missing_function_revert(error: &alloy::contract::Error) -> bool {
2369    match error.as_revert_data() {
2370        Some(data) => data.is_empty(),
2371        None => error
2372            .to_string()
2373            .to_ascii_lowercase()
2374            .contains("execution reverted"),
2375    }
2376}
2377
2378impl HypercallClient {
2379    /// The API server's current Unix millisecond, from the `/health` `Date`
2380    /// header (cached for a minute per client and its clones).
2381    pub async fn server_now_ms(&self) -> Result<u64> {
2382        let offset = match self.server_clock.cached_offset() {
2383            Some(offset) => offset,
2384            None => {
2385                let sent_ms = local_now_ms();
2386                let response = self.request(Method::GET, "/health").send().await?;
2387                let received_ms = local_now_ms();
2388                let date = response
2389                    .headers()
2390                    .get(reqwest::header::DATE)
2391                    .and_then(|value| value.to_str().ok())
2392                    .ok_or_else(|| ClientError::Api {
2393                        status: response.status().as_u16(),
2394                        message: "/health response carries no Date header to stamp TEE nonces"
2395                            .into(),
2396                    })?;
2397                let offset =
2398                    server_clock_offset_ms(date, sent_ms, received_ms).ok_or_else(|| {
2399                        ClientError::Api {
2400                            status: response.status().as_u16(),
2401                            message: format!("/health Date header is not an HTTP date: {date}"),
2402                        }
2403                    })?;
2404                self.server_clock.store(offset);
2405                offset
2406            }
2407        };
2408        u64::try_from(local_now_ms() + offset).map_err(|_| ClientError::ArithmeticOverflow {
2409            operation: "server clock",
2410        })
2411    }
2412
2413    /// Next TEE perp nonce for `signer`, stamped on the server clock and
2414    /// strictly increasing per signer within this process.
2415    pub async fn next_tee_perp_nonce(&self, signer: AccountAddress) -> Result<u64> {
2416        let now = self.server_now_ms().await?;
2417        Ok(next_nonce_at(signer.as_wallet_address().inner(), now))
2418    }
2419
2420    async fn resolve_tee_nonce(&self, signer: AccountAddress, nonce: Option<u64>) -> Result<u64> {
2421        match nonce {
2422            Some(nonce) => Ok(nonce),
2423            None => self.next_tee_perp_nonce(signer).await,
2424        }
2425    }
2426
2427    async fn post_tee<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2428    where
2429        T: serde::de::DeserializeOwned,
2430        B: serde::Serialize + ?Sized,
2431    {
2432        Self::send_json_body(self.request(Method::POST, route), body, action).await
2433    }
2434
2435    /// POST a signed, mutating submission. The body is serialized once and
2436    /// those exact bytes are sent, so an ambiguous failure can hand them back
2437    /// in [`ClientError::TeeSubmissionAmbiguous`] for an identical resend.
2438    async fn post_tee_signed<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2439    where
2440        T: serde::de::DeserializeOwned,
2441        B: SignedTeeSubmission,
2442    {
2443        let request_json = sonic_rs::to_string(body)
2444            .map_err(|source| ClientError::invalid_input("TEE request body", source))?;
2445        self.send_tee_submission(route, request_json, body.nonce(), action, false)
2446            .await
2447    }
2448
2449    async fn send_tee_submission<T>(
2450        &self,
2451        route: &str,
2452        request_json: String,
2453        nonce: u64,
2454        action: &str,
2455        resend: bool,
2456    ) -> Result<T>
2457    where
2458        T: serde::de::DeserializeOwned,
2459    {
2460        let request = self
2461            .request(Method::POST, route)
2462            .header(reqwest::header::CONTENT_TYPE, "application/json")
2463            .body(request_json.clone());
2464        match Self::send_reqwest_json(request, action).await {
2465            // A resend cannot settle the original's outcome: the signed action
2466            // can expire (and be refused before journal dedup) while the
2467            // original still executed, so every resend failure stays ambiguous.
2468            Err(error) if resend || tee_submission_is_ambiguous(&error) => {
2469                Err(ClientError::TeeSubmissionAmbiguous {
2470                    action: action.to_owned(),
2471                    route: route.to_owned(),
2472                    nonce,
2473                    request_json,
2474                    source: Box::new(error),
2475                })
2476            }
2477            result => result,
2478        }
2479    }
2480
2481    /// Resend the exact signed body of a [`ClientError::TeeSubmissionAmbiguous`].
2482    /// The server recognises the same signed action (same nonce, same terms)
2483    /// and does not submit it to the venue twice; a repeat comes back with
2484    /// `duplicate_directive` and stage `unknown`, meaning reconcile. Pass the
2485    /// error's `route` and `request_json` unchanged.
2486    ///
2487    /// Any failure of the resend, including a `4xx` such as an expired
2488    /// signature, is returned as [`ClientError::TeeSubmissionAmbiguous`]: the
2489    /// original request may still have executed, so reconcile before signing
2490    /// a fresh action.
2491    pub async fn resend_tee_submission<T>(&self, route: &str, request_json: &str) -> Result<T>
2492    where
2493        T: serde::de::DeserializeOwned,
2494    {
2495        let nonce = serde_json::from_str::<serde_json::Value>(request_json)
2496            .ok()
2497            .and_then(|body| match &body["nonce"] {
2498                serde_json::Value::Number(number) => number.as_u64(),
2499                serde_json::Value::String(text) => text.parse().ok(),
2500                _ => None,
2501            })
2502            .ok_or_else(|| {
2503                ClientError::InvalidInput("request_json carries no signed nonce".into())
2504            })?;
2505        self.send_tee_submission(
2506            route,
2507            request_json.to_owned(),
2508            nonce,
2509            "resend TEE submission",
2510            true,
2511        )
2512        .await
2513    }
2514
2515    /// Place one plain limit order (GTC, IOC, or ALO) on the TEE route.
2516    ///
2517    /// `client_order_id` defaults to the nonce.
2518    pub async fn place_tee_perp_limit_order<S>(
2519        &self,
2520        signer: &S,
2521        params: PerpLimitOrderParams,
2522    ) -> Result<TeePerpOrderResponse>
2523    where
2524        S: PerpDirectiveSigner + ?Sized,
2525    {
2526        let nonce = self
2527            .resolve_tee_nonce(signer.address(), params.nonce)
2528            .await?;
2529        let action = HlLimitOrderAction {
2530            asset: params.asset,
2531            is_buy: matches!(params.side, Side::Buy),
2532            limit_px: to_perp_units(params.price, "perp limit price")?,
2533            sz: to_perp_units(params.size, "perp size")?,
2534            reduce_only: params.reduce_only,
2535            tif: params.tif,
2536            cloid: nonzero_cloid(params.client_order_id.unwrap_or(u128::from(nonce)))?,
2537        };
2538        let signature = signer
2539            .sign_perp_limit_order_payload(PerpLimitOrderSignature {
2540                account: params.account,
2541                nonce,
2542                action,
2543            })
2544            .await?;
2545        let request = DirectiveSubmitRequest {
2546            account: params.account.into_wallet_address(),
2547            nonce,
2548            action,
2549            signature,
2550        };
2551        self.post_tee_signed(
2552            TEE_PERP_ORDER_SUBMIT_ROUTE,
2553            &request,
2554            "submit TEE perp order",
2555        )
2556        .await
2557    }
2558
2559    /// Place a market order: an IOC limit bounded by `slippage_bps`.
2560    pub async fn place_tee_perp_market_order<S>(
2561        &self,
2562        signer: &S,
2563        params: TeePerpMarketOrderParams,
2564    ) -> Result<TeePerpOrderResponse>
2565    where
2566        S: PerpDirectiveSigner + ?Sized,
2567    {
2568        let size_decimals = validate_size_decimals(params.size_decimals)?;
2569        if params.size.normalize().scale() > size_decimals {
2570            return Err(ClientError::InvalidInput(format!(
2571                "size {} has more than {size_decimals} decimals",
2572                params.size
2573            )));
2574        }
2575        let price = perp_market_limit_price(
2576            params.reference_price,
2577            params.side,
2578            size_decimals,
2579            params.slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2580        )?;
2581        self.place_tee_perp_limit_order(
2582            signer,
2583            PerpLimitOrderParams {
2584                account: params.account,
2585                asset: params.asset,
2586                side: params.side,
2587                price,
2588                size: params.size,
2589                tif: PerpTimeInForce::Ioc,
2590                reduce_only: params.reduce_only,
2591                client_order_id: params.client_order_id,
2592                nonce: params.nonce,
2593            },
2594        )
2595        .await
2596    }
2597
2598    /// Place one native stop-loss or take-profit order (market or limit).
2599    pub async fn place_tee_perp_trigger_order<S>(
2600        &self,
2601        signer: &S,
2602        params: TeePerpTriggerOrderParams,
2603    ) -> Result<TeePerpOrderBatchResponse>
2604    where
2605        S: TeePerpSigner + ?Sized,
2606    {
2607        let (limit_price, is_market) = match params.execution {
2608            TeePerpTriggerExecution::Market {
2609                size_decimals,
2610                slippage_bps,
2611            } => (
2612                perp_market_limit_price(
2613                    params.trigger_price,
2614                    params.side,
2615                    size_decimals,
2616                    slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2617                )?,
2618                true,
2619            ),
2620            TeePerpTriggerExecution::Limit { price } => (price, false),
2621        };
2622        let nonce = self
2623            .resolve_tee_nonce(signer.address(), params.nonce)
2624            .await?;
2625        let cloid = match params.client_order_id {
2626            Some(cloid) => cloid,
2627            None => tee_perp_batch_cloid(nonce, 0)?,
2628        };
2629        let order = tee_perp_trigger_order_wire(
2630            params.asset,
2631            params.side,
2632            params.trigger_price,
2633            limit_price,
2634            params.size,
2635            is_market,
2636            params.tpsl,
2637            params.reduce_only,
2638            cloid,
2639        )?;
2640        let signature = signer
2641            .sign_tee_perp_trigger_order_payload(TeePerpTriggerOrderSignature {
2642                account: params.account,
2643                nonce,
2644                order,
2645            })
2646            .await?;
2647        let request = DirectiveSubmitRequest {
2648            account: params.account.into_wallet_address(),
2649            nonce,
2650            action: order,
2651            signature,
2652        };
2653        self.post_tee_signed(
2654            TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE,
2655            &request,
2656            "submit TEE perp trigger order",
2657        )
2658        .await
2659    }
2660
2661    /// Submit a caller-built order batch (1 to 100 children).
2662    pub async fn place_tee_perp_order_batch<S>(
2663        &self,
2664        signer: &S,
2665        params: TeePerpOrderBatchParams,
2666    ) -> Result<TeePerpOrderBatchResponse>
2667    where
2668        S: TeePerpSigner + ?Sized,
2669    {
2670        validate_batch(&params.batch)?;
2671        let signature = signer
2672            .sign_tee_perp_order_batch_payload(TeePerpOrderBatchSignature {
2673                account: params.account,
2674                nonce: params.nonce,
2675                batch: &params.batch,
2676            })
2677            .await?;
2678        let request = DirectiveSubmitRequest {
2679            account: params.account.into_wallet_address(),
2680            nonce: params.nonce,
2681            action: params.batch,
2682            signature,
2683        };
2684        self.post_tee_signed(
2685            TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE,
2686            &request,
2687            "submit TEE perp order batch",
2688        )
2689        .await
2690    }
2691
2692    /// Place an entry with attached TP/SL exits (`normalTpsl`).
2693    pub async fn place_tee_perp_bracket_order<S>(
2694        &self,
2695        signer: &S,
2696        params: TeePerpBracketOrderParams,
2697    ) -> Result<TeePerpOrderBatchResponse>
2698    where
2699        S: TeePerpSigner + ?Sized,
2700    {
2701        let nonce = self
2702            .resolve_tee_nonce(signer.address(), params.nonce)
2703            .await?;
2704        let batch = build_tee_perp_bracket_batch(
2705            params.entry,
2706            params.take_profit,
2707            params.stop_loss,
2708            nonce,
2709        )?;
2710        self.place_tee_perp_order_batch(
2711            signer,
2712            TeePerpOrderBatchParams {
2713                account: params.account,
2714                nonce,
2715                batch,
2716            },
2717        )
2718        .await
2719    }
2720
2721    /// Place TP/SL exits on an existing position (`positionTpsl`).
2722    pub async fn place_tee_perp_position_tpsl<S>(
2723        &self,
2724        signer: &S,
2725        params: TeePerpPositionTpslParams,
2726    ) -> Result<TeePerpOrderBatchResponse>
2727    where
2728        S: TeePerpSigner + ?Sized,
2729    {
2730        let nonce = self
2731            .resolve_tee_nonce(signer.address(), params.nonce)
2732            .await?;
2733        let batch = build_tee_perp_position_tpsl_batch(
2734            params.asset,
2735            params.position_side,
2736            params.size,
2737            params.take_profit,
2738            params.stop_loss,
2739            nonce,
2740        )?;
2741        self.place_tee_perp_order_batch(
2742            signer,
2743            TeePerpOrderBatchParams {
2744                account: params.account,
2745                nonce,
2746                batch,
2747            },
2748        )
2749        .await
2750    }
2751
2752    /// Place a scale order: its legs as one ungrouped batch.
2753    pub async fn place_tee_perp_scale_order<S>(
2754        &self,
2755        signer: &S,
2756        params: TeePerpScaleOrderParams,
2757    ) -> Result<TeePerpOrderBatchResponse>
2758    where
2759        S: TeePerpSigner + ?Sized,
2760    {
2761        let nonce = self
2762            .resolve_tee_nonce(signer.address(), params.nonce)
2763            .await?;
2764        let batch = build_tee_perp_scale_batch(
2765            params.asset,
2766            params.side,
2767            &params.legs,
2768            params.tif,
2769            params.reduce_only,
2770            nonce,
2771        )?;
2772        self.place_tee_perp_order_batch(
2773            signer,
2774            TeePerpOrderBatchParams {
2775                account: params.account,
2776                nonce,
2777                batch,
2778            },
2779        )
2780        .await
2781    }
2782
2783    /// Cancel a resting order by Hyperliquid order ID.
2784    pub async fn cancel_tee_perp_order_by_oid<S>(
2785        &self,
2786        signer: &S,
2787        params: PerpCancelByOidParams,
2788    ) -> Result<TeePerpVenueActionResponse>
2789    where
2790        S: PerpDirectiveSigner + ?Sized,
2791    {
2792        if params.order_id == 0 {
2793            return Err(ClientError::InvalidInput("oid must not be zero".into()));
2794        }
2795        let nonce = self
2796            .resolve_tee_nonce(signer.address(), params.nonce)
2797            .await?;
2798        let action = HlCancelByOidAction {
2799            asset: params.asset,
2800            oid: params.order_id,
2801        };
2802        let signature = signer
2803            .sign_perp_cancel_by_oid_payload(PerpCancelByOidSignature {
2804                account: params.account,
2805                nonce,
2806                action,
2807            })
2808            .await?;
2809        let request = DirectiveSubmitRequest {
2810            account: params.account.into_wallet_address(),
2811            nonce,
2812            action,
2813            signature,
2814        };
2815        self.post_tee_signed(
2816            TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE,
2817            &request,
2818            "submit TEE perp cancel by oid",
2819        )
2820        .await
2821    }
2822
2823    /// Cancel a resting order by client order ID.
2824    pub async fn cancel_tee_perp_order_by_cloid<S>(
2825        &self,
2826        signer: &S,
2827        params: PerpCancelByCloidParams,
2828    ) -> Result<TeePerpCancelResponse>
2829    where
2830        S: PerpDirectiveSigner + ?Sized,
2831    {
2832        let nonce = self
2833            .resolve_tee_nonce(signer.address(), params.nonce)
2834            .await?;
2835        let action = HlCancelByCloidAction {
2836            asset: params.asset,
2837            cloid: nonzero_cloid(params.client_order_id)?,
2838        };
2839        let signature = signer
2840            .sign_perp_cancel_by_cloid_payload(PerpCancelByCloidSignature {
2841                account: params.account,
2842                nonce,
2843                action,
2844            })
2845            .await?;
2846        let request = DirectiveSubmitRequest {
2847            account: params.account.into_wallet_address(),
2848            nonce,
2849            action,
2850            signature,
2851        };
2852        self.post_tee_signed(
2853            TEE_PERP_CANCEL_SUBMIT_ROUTE,
2854            &request,
2855            "submit TEE perp cancel by cloid",
2856        )
2857        .await
2858    }
2859
2860    /// Change leverage and margin mode for one market. Read the venue's
2861    /// resulting setting back with [`HyperliquidInfoClient::active_asset_leverage`].
2862    pub async fn update_tee_perp_leverage<S>(
2863        &self,
2864        signer: &S,
2865        params: TeePerpLeverageParams,
2866    ) -> Result<TeePerpLeverageResponse>
2867    where
2868        S: TeePerpSigner + ?Sized,
2869    {
2870        if params.leverage == 0 {
2871            return Err(ClientError::InvalidInput(
2872                "leverage must be greater than zero".into(),
2873            ));
2874        }
2875        let nonce = self
2876            .resolve_tee_nonce(signer.address(), params.nonce)
2877            .await?;
2878        let action = TeePerpLeverageAction {
2879            asset: params.asset,
2880            is_cross: params.is_cross,
2881            leverage: params.leverage,
2882        };
2883        let signature = signer
2884            .sign_tee_perp_leverage_payload(TeePerpLeverageSignature {
2885                account: params.account,
2886                nonce,
2887                action,
2888            })
2889            .await?;
2890        let request = DirectiveSubmitRequest {
2891            account: params.account.into_wallet_address(),
2892            nonce,
2893            action,
2894            signature,
2895        };
2896        self.post_tee_signed(
2897            TEE_PERP_LEVERAGE_SUBMIT_ROUTE,
2898            &request,
2899            "submit TEE perp leverage",
2900        )
2901        .await
2902    }
2903
2904    /// Replace one resting limit order's price, size, side, TIF and
2905    /// reduce-only flag (Hyperliquid `modify`). The cloid is preserved.
2906    ///
2907    /// The engine reserves the larger of the old and new terms until the
2908    /// outcome is known: `rejected` or `not_submitted` restores the old terms
2909    /// (the original order still rests); `accepted` moves to the new terms.
2910    /// An `unknown` stage must be reconciled before modifying again.
2911    pub async fn modify_tee_perp_order<S>(
2912        &self,
2913        signer: &S,
2914        params: TeePerpModifyParams,
2915    ) -> Result<TeePerpModifyResponse>
2916    where
2917        S: TeePerpSigner + ?Sized,
2918    {
2919        let action = params.replacement.to_action()?;
2920        let nonce = self
2921            .resolve_tee_nonce(signer.address(), params.nonce)
2922            .await?;
2923        let signature = signer
2924            .sign_tee_perp_modify_payload(TeePerpModifySignature {
2925                account: params.account,
2926                nonce,
2927                action,
2928            })
2929            .await?;
2930        let request = DirectiveSubmitRequest {
2931            account: params.account.into_wallet_address(),
2932            nonce,
2933            action,
2934            signature,
2935        };
2936        self.post_tee_signed(
2937            TEE_PERP_ORDER_MODIFY_ROUTE,
2938            &request,
2939            "submit TEE perp modify",
2940        )
2941        .await
2942    }
2943
2944    /// Replace several resting limit orders in one signed Hyperliquid
2945    /// `batchModify` (one nonce, one venue call).
2946    ///
2947    /// The engine admits every child or none. After the venue answers, each
2948    /// child settles on its own: read
2949    /// [`TeePerpBatchModifyResponse::children`] (or
2950    /// [`TeePerpBatchModifyResponse::children_to_reconcile`]) rather than only
2951    /// the whole-action stage, which is `accepted` or `rejected` only when
2952    /// every child agrees. Charged as one order placement per child against
2953    /// the rate limit.
2954    ///
2955    /// Refused locally, before signing, when the batch is empty, exceeds
2956    /// `max_children` (50 by default), repeats a target or cloid, or carries an
2957    /// invalid child. A deployment whose enclave release does not enable batch
2958    /// modify answers `400 unsupported_action`
2959    /// ([`ClientError::is_unsupported_action`]).
2960    pub async fn batch_modify_tee_perp_orders<S>(
2961        &self,
2962        signer: &S,
2963        params: TeePerpBatchModifyParams,
2964    ) -> Result<TeePerpBatchModifyResponse>
2965    where
2966        S: TeePerpSigner + ?Sized,
2967    {
2968        let batch = build_tee_perp_batch_modify(&params.replacements, params.max_children)?;
2969        let nonce = self
2970            .resolve_tee_nonce(signer.address(), params.nonce)
2971            .await?;
2972        let signature = signer
2973            .sign_tee_perp_batch_modify_payload(TeePerpBatchModifySignature {
2974                account: params.account,
2975                nonce,
2976                batch: &batch,
2977            })
2978            .await?;
2979        let request = DirectiveSubmitRequest {
2980            account: params.account.into_wallet_address(),
2981            nonce,
2982            action: batch,
2983            signature,
2984        };
2985        self.post_tee_signed(
2986            TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
2987            &request,
2988            "submit TEE perp batch modify",
2989        )
2990        .await
2991    }
2992
2993    /// Start a native Hyperliquid TWAP (`twapOrder`). The engine reserves
2994    /// the full size at admission and releases it as fills arrive. Keep
2995    /// [`TeePerpTwapResponse::twap_id`] to cancel it.
2996    ///
2997    /// TWAP is disabled at runtime on deployments whose enclave release does
2998    /// not enable it; those answer `400 unsupported_action`
2999    /// ([`ClientError::is_unsupported_action`]).
3000    pub async fn place_tee_perp_twap_order<S>(
3001        &self,
3002        signer: &S,
3003        params: TeePerpTwapParams,
3004    ) -> Result<TeePerpTwapResponse>
3005    where
3006        S: TeePerpSigner + ?Sized,
3007    {
3008        let action = TeePerpTwapAction {
3009            asset: params.asset,
3010            is_buy: matches!(params.side, Side::Buy),
3011            sz: to_perp_units(params.size, "size")?,
3012            reduce_only: params.reduce_only,
3013            minutes: params.minutes,
3014            randomize: params.randomize,
3015        };
3016        validate_twap_action(&action)?;
3017        let nonce = self
3018            .resolve_tee_nonce(signer.address(), params.nonce)
3019            .await?;
3020        let signature = signer
3021            .sign_tee_perp_twap_payload(TeePerpTwapSignature {
3022                account: params.account,
3023                nonce,
3024                action,
3025            })
3026            .await?;
3027        let request = DirectiveSubmitRequest {
3028            account: params.account.into_wallet_address(),
3029            nonce,
3030            action,
3031            signature,
3032        };
3033        self.post_tee_signed(TEE_PERP_TWAP_SUBMIT_ROUTE, &request, "submit TEE perp TWAP")
3034            .await
3035    }
3036
3037    /// Cancel a running native TWAP (`twapCancel`). Like TWAP submit, this
3038    /// can answer `400 unsupported_action` where TWAP is disabled.
3039    pub async fn cancel_tee_perp_twap<S>(
3040        &self,
3041        signer: &S,
3042        params: TeePerpTwapCancelParams,
3043    ) -> Result<TeePerpVenueActionResponse>
3044    where
3045        S: TeePerpSigner + ?Sized,
3046    {
3047        if params.twap_id == 0 {
3048            return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
3049        }
3050        let nonce = self
3051            .resolve_tee_nonce(signer.address(), params.nonce)
3052            .await?;
3053        let action = TeePerpTwapCancelAction {
3054            asset: params.asset,
3055            twap_id: params.twap_id,
3056        };
3057        let signature = signer
3058            .sign_tee_perp_twap_cancel_payload(TeePerpTwapCancelSignature {
3059                account: params.account,
3060                nonce,
3061                action,
3062            })
3063            .await?;
3064        let request = DirectiveSubmitRequest {
3065            account: params.account.into_wallet_address(),
3066            nonce,
3067            action,
3068            signature,
3069        };
3070        self.post_tee_signed(
3071            TEE_PERP_TWAP_CANCEL_ROUTE,
3072            &request,
3073            "submit TEE perp TWAP cancel",
3074        )
3075        .await
3076    }
3077
3078    /// Preview an action's admission, margin, liquidation prices and max
3079    /// size without signing or reserving anything.
3080    pub async fn preview_tee_perp_action(
3081        &self,
3082        request: &PerpPreviewRequest,
3083    ) -> Result<PerpPreviewResponse> {
3084        let envelope: ApiResponse<PerpPreviewResponse> = self
3085            .post_tee(TEE_PERP_PREVIEW_ROUTE, request, "preview TEE perp action")
3086            .await?;
3087        if !envelope.success {
3088            return Err(ClientError::Api {
3089                status: 200,
3090                message: envelope
3091                    .error
3092                    .unwrap_or_else(|| "TEE perp preview failed".into()),
3093            });
3094        }
3095        envelope.data.ok_or_else(|| ClientError::Api {
3096            status: 200,
3097            message: "TEE perp preview returned no data".into(),
3098        })
3099    }
3100
3101    /// Configured TEE perp markets and whether each is supported.
3102    pub async fn get_tee_perp_markets(&self) -> Result<TeePerpMarketsResponse> {
3103        Self::send_reqwest_json(
3104            self.request(Method::GET, TEE_PERP_MARKETS_ROUTE),
3105            "get TEE perp markets",
3106        )
3107        .await
3108    }
3109
3110    /// Step 1 of enrollment: authenticate as the manager and fetch the
3111    /// account's TEE API wallet with its `HLAddApiWallet` approval payload.
3112    pub async fn request_tee_api_wallet_approval<S>(
3113        &self,
3114        manager: &S,
3115        account: AccountAddress,
3116    ) -> Result<TeeApiWalletApprovalChallenge>
3117    where
3118        S: TeeApiWalletManagerSigner + ?Sized,
3119    {
3120        let timestamp = i64::try_from(self.server_now_ms().await? / 1_000).map_err(|_| {
3121            ClientError::ArithmeticOverflow {
3122                operation: "authentication timestamp",
3123            }
3124        })?;
3125        let manager_address = manager.address();
3126        let authentication_signature = manager.sign_authentication_payload(timestamp).await?;
3127        let request = TeeApiWalletApprovalRequest {
3128            account: account.into_wallet_address(),
3129            manager: manager_address.into_wallet_address(),
3130            timestamp,
3131            signature: authentication_signature.clone(),
3132        };
3133        let package: TeeApiWalletApprovalPackage = self
3134            .post_tee(
3135                TEE_API_WALLET_APPROVAL_REQUEST_ROUTE,
3136                &request,
3137                "request TEE API wallet approval",
3138            )
3139            .await?;
3140        Ok(TeeApiWalletApprovalChallenge {
3141            account,
3142            manager: manager_address,
3143            timestamp,
3144            authentication_signature,
3145            package,
3146        })
3147    }
3148
3149    /// Step 2 of enrollment: sign the approval (after checking the returned
3150    /// typed data names exactly the packaged wallet) and submit it.
3151    pub async fn submit_tee_api_wallet_approval<S>(
3152        &self,
3153        manager: &S,
3154        challenge: &TeeApiWalletApprovalChallenge,
3155    ) -> Result<DirectiveSubmitResponse>
3156    where
3157        S: TeeApiWalletManagerSigner + ?Sized,
3158    {
3159        validate_approval_typed_data(challenge)?;
3160        let signature = manager
3161            .sign_tee_api_wallet_approval_payload(TeeApiWalletApprovalSignature {
3162                account: challenge.account,
3163                nonce: challenge.package.nonce,
3164                api_wallet_address: AccountAddress::from(
3165                    challenge.package.api_wallet_address.inner(),
3166                ),
3167                api_wallet_name: &challenge.package.api_wallet_name,
3168            })
3169            .await?;
3170        let request = TeeApiWalletApprovalSubmitRequest {
3171            account: challenge.account.into_wallet_address(),
3172            manager: challenge.manager.into_wallet_address(),
3173            timestamp: challenge.timestamp,
3174            authentication_signature: challenge.authentication_signature.clone(),
3175            tee_wallet_id: challenge.package.tee_wallet_id,
3176            nonce: challenge.package.nonce,
3177            signature,
3178        };
3179        self.post_tee_signed(
3180            TEE_API_WALLET_APPROVAL_ROUTE,
3181            &request,
3182            "submit TEE API wallet approval",
3183        )
3184        .await
3185    }
3186
3187    /// Enroll the account's TEE API wallet end to end, as the Hypercall
3188    /// order panel does: request it, skip the approval when Hyperliquid
3189    /// already binds it, otherwise submit the approval, poll the directive
3190    /// until it finalizes, and confirm the binding on Hyperliquid.
3191    pub async fn enroll_tee_api_wallet<S>(
3192        &self,
3193        manager: &S,
3194        account: AccountAddress,
3195        hyperliquid: &HyperliquidInfoClient,
3196        polling: TeeApiWalletEnrollmentPolling,
3197    ) -> Result<TeeApiWalletEnrollment>
3198    where
3199        S: TeeApiWalletManagerSigner + ?Sized,
3200    {
3201        let challenge = self
3202            .request_tee_api_wallet_approval(manager, account)
3203            .await?;
3204        let api_wallet = AccountAddress::from(challenge.package.api_wallet_address.inner());
3205        let api_wallet_name = challenge.package.api_wallet_name.clone();
3206        if hyperliquid
3207            .is_tee_api_wallet_active(account, api_wallet)
3208            .await?
3209        {
3210            return Ok(TeeApiWalletEnrollment {
3211                api_wallet,
3212                api_wallet_name,
3213                directive_id: None,
3214            });
3215        }
3216        let response = self
3217            .submit_tee_api_wallet_approval(manager, &challenge)
3218            .await?;
3219        if let Some(rejection) = &response.rejection {
3220            return Err(ClientError::Api {
3221                status: 200,
3222                message: format!(
3223                    "TEE API wallet approval rejected ({}): {}",
3224                    rejection.code, rejection.message
3225                ),
3226            });
3227        }
3228        let mut finalized = false;
3229        for _ in 0..polling.attempts {
3230            // The directive can briefly be absent before its row appears.
3231            if let Ok(status) = self.get_directive_status(&response.directive_id).await {
3232                match tee_api_wallet_approval_progress(&status) {
3233                    TeeApiWalletApprovalProgress::Finalized => {
3234                        finalized = true;
3235                        break;
3236                    }
3237                    TeeApiWalletApprovalProgress::Failed => {
3238                        return Err(ClientError::Api {
3239                            status: 200,
3240                            message: format!(
3241                                "TEE API wallet approval {} failed: domain {:?}, delivery {:?}",
3242                                response.directive_id, status.domain_status, status.delivery_status
3243                            ),
3244                        });
3245                    }
3246                    TeeApiWalletApprovalProgress::Pending => {}
3247                }
3248            }
3249            tokio::time::sleep(polling.interval).await;
3250        }
3251        if !finalized {
3252            return Err(ClientError::Api {
3253                status: 200,
3254                message: format!(
3255                    "TEE API wallet approval {} is still pending",
3256                    response.directive_id
3257                ),
3258            });
3259        }
3260        if !hyperliquid
3261            .is_tee_api_wallet_active(account, api_wallet)
3262            .await?
3263        {
3264            return Err(ClientError::Api {
3265                status: 200,
3266                message: "Hyperliquid did not bind the finalized TEE API wallet to this account"
3267                    .into(),
3268            });
3269        }
3270        Ok(TeeApiWalletEnrollment {
3271            api_wallet,
3272            api_wallet_name,
3273            directive_id: Some(response.directive_id),
3274        })
3275    }
3276
3277    /// Approve the zero-fee Hypercall builder for the account on Hyperliquid
3278    /// with one manager HyperEVM transaction calling
3279    /// `Account.approveZeroFeeBuilder(builder)`. Idempotent on the venue.
3280    ///
3281    /// Needed once per account before TEE perp orders are accepted (they are
3282    /// refused with `builder_not_approved` until then). Requires Account
3283    /// 0.2.4 or newer and a little HYPE on the manager for gas.
3284    pub async fn approve_hypercall_builder(
3285        &self,
3286        manager: &HypercallWallet,
3287        params: ApproveHypercallBuilderParams,
3288    ) -> Result<B256> {
3289        let builder = match params.builder {
3290            Some(builder) => builder,
3291            None => resolve_hypercall_builder_address(&self.get_exchange_info().await?)?,
3292        };
3293        let builder = builder.as_wallet_address().inner();
3294        if builder == Address::ZERO {
3295            return Err(ClientError::InvalidInput("builder must not be zero".into()));
3296        }
3297        let rpc_url = params
3298            .rpc_url
3299            .parse()
3300            .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
3301        let provider = ProviderBuilder::new()
3302            .wallet(manager.ethereum_wallet())
3303            .connect_http(rpc_url);
3304        let rpc_chain_id = provider
3305            .get_chain_id()
3306            .await
3307            .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
3308        if rpc_chain_id != manager.chain_id() {
3309            return Err(ClientError::InvalidInput(format!(
3310                "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {}",
3311                manager.chain_id()
3312            )));
3313        }
3314        let manager_address = manager.address.as_wallet_address().inner();
3315        let balance = provider
3316            .get_balance(manager_address)
3317            .await
3318            .map_err(|error| onchain_error("read manager HYPE balance", error))?;
3319        if balance.is_zero() {
3320            return Err(ClientError::InvalidInput(
3321                "the manager wallet needs a small amount of HYPE on HyperEVM to pay the network fee"
3322                    .into(),
3323            ));
3324        }
3325        let account = HypercallAccountBuilderApproval::new(
3326            params.account.as_wallet_address().inner(),
3327            &provider,
3328        );
3329        let call = account.approveZeroFeeBuilder(builder).from(manager_address);
3330        if let Err(error) = call.call().await {
3331            if is_missing_function_revert(&error) {
3332                return Err(ClientError::InvalidInput(
3333                    "this Account implementation predates approveZeroFeeBuilder (needs 0.2.4); trading cannot be enabled yet".into(),
3334                ));
3335            }
3336            return Err(onchain_error("simulate approveZeroFeeBuilder", error));
3337        }
3338        let submission_lock = evm_submission_lock(manager_address);
3339        let _guard = submission_lock.lock().await;
3340        let receipt = call
3341            .send()
3342            .await
3343            .map_err(|error| onchain_error("submit approveZeroFeeBuilder", error))?
3344            .with_timeout(Some(Duration::from_secs(60)))
3345            .get_receipt()
3346            .await
3347            .map_err(|error| onchain_error("confirm approveZeroFeeBuilder", error))?;
3348        if !receipt.status() {
3349            return Err(ClientError::TransactionReverted {
3350                operation: "approveZeroFeeBuilder",
3351                transaction_hash: Some(receipt.transaction_hash),
3352            });
3353        }
3354        Ok(receipt.transaction_hash)
3355    }
3356}
3357
3358#[cfg(test)]
3359#[path = "tee_perp_test.rs"]
3360mod tests;
3361
3362#[cfg(test)]
3363#[path = "tee_perp_modify_test.rs"]
3364mod modify_tests;