Skip to main content

hypercall_client/
tee_spot.rs

1//! TEE user spot orders: HyperCore spot orders signed by the
2//! account's app key (an active Account API wallet) and placed through
3//! Hypercall's TEE-held Hyperliquid API wallet, on a portfolio-margin account.
4//!
5//! Setup is the TEE perp setup (register the app key, enroll the TEE API
6//! wallet, approve the Hypercall builder); see [`crate::tee_perp`]. Nonces
7//! follow the same server-clock window.
8//!
9//! A buy holds its whole cost at the limit back from PM cash until the order
10//! ends and a portfolio snapshot reflects it; a sell holds its coin. Proceeds
11//! and bought tokens count once a snapshot shows them.
12
13#![expect(
14    clippy::result_large_err,
15    reason = "these helpers preserve the established unboxed public ClientError contract"
16)]
17
18use alloy::primitives::B256;
19use alloy::sol;
20use alloy::sol_types::SolStruct;
21use hypercall_sdk_types::{
22    DirectiveSubmitRequest, PerpTimeInForce, TeeSpotCancelAction, TeeSpotOrderAction,
23    TeeSpotResponse, TEE_SPOT_ASSET_OFFSET, TEE_SPOT_CANCEL_SUBMIT_ROUTE,
24    TEE_SPOT_ORDER_SUBMIT_ROUTE,
25};
26use rust_decimal::Decimal;
27
28use crate::api::HypercallClient;
29use crate::error::{ClientError, Result};
30use crate::perp::to_perp_units;
31use crate::tee_perp::{nonzero_cloid, signing_domain, HYPERCALL_API_DOMAIN};
32use crate::wallet::{AccountAddress, HypercallSigner, HypercallWallet};
33use hypercall_sdk_types::Side;
34
35sol! {
36    struct SpotOrder {
37        uint32 asset;
38        bool isBuy;
39        uint64 limitPx;
40        uint64 sz;
41        uint8 encodedTif;
42        uint128 cloid;
43    }
44
45    struct HCSpotOrder {
46        address account;
47        uint64 nonce;
48        SpotOrder action;
49    }
50
51    struct SpotCancel {
52        uint32 asset;
53        uint128 cloid;
54    }
55
56    struct HCSpotCancel {
57        address account;
58        uint64 nonce;
59        SpotCancel action;
60    }
61}
62
63/// What the app key signs for one spot order.
64#[derive(Debug, Clone, Copy)]
65pub struct TeeSpotOrderSignature {
66    pub account: AccountAddress,
67    pub nonce: u64,
68    pub action: TeeSpotOrderAction,
69}
70
71/// What the app key signs for one spot cancel.
72#[derive(Debug, Clone, Copy)]
73pub struct TeeSpotCancelSignature {
74    pub account: AccountAddress,
75    pub nonce: u64,
76    pub action: TeeSpotCancelAction,
77}
78
79fn order_message(payload: &TeeSpotOrderSignature) -> Result<HCSpotOrder> {
80    let action = payload.action;
81    if action.asset < TEE_SPOT_ASSET_OFFSET {
82        return Err(ClientError::InvalidInput(
83            "spot asset must be 10000 + pair index".into(),
84        ));
85    }
86    let encoded_tif = match action.tif {
87        PerpTimeInForce::Gtc => 2,
88        PerpTimeInForce::Ioc => 3,
89        PerpTimeInForce::Alo => {
90            return Err(ClientError::InvalidInput(
91                "spot orders are GTC or IOC".into(),
92            ))
93        }
94    };
95    Ok(HCSpotOrder {
96        account: payload.account.as_wallet_address().inner(),
97        nonce: payload.nonce,
98        action: SpotOrder {
99            asset: action.asset,
100            isBuy: action.is_buy,
101            limitPx: action.limit_px,
102            sz: action.sz,
103            encodedTif: encoded_tif,
104            cloid: nonzero_cloid(action.cloid)?,
105        },
106    })
107}
108
109fn cancel_message(payload: &TeeSpotCancelSignature) -> Result<HCSpotCancel> {
110    Ok(HCSpotCancel {
111        account: payload.account.as_wallet_address().inner(),
112        nonce: payload.nonce,
113        action: SpotCancel {
114            asset: payload.action.asset,
115            cloid: nonzero_cloid(payload.action.cloid)?,
116        },
117    })
118}
119
120/// EIP-712 digest the app key signs for a TEE spot order.
121pub fn tee_spot_order_signing_hash(chain_id: u64, payload: &TeeSpotOrderSignature) -> Result<B256> {
122    Ok(order_message(payload)?
123        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
124}
125
126/// EIP-712 digest the app key signs for a TEE spot cancel.
127pub fn tee_spot_cancel_signing_hash(
128    chain_id: u64,
129    payload: &TeeSpotCancelSignature,
130) -> Result<B256> {
131    Ok(cancel_message(payload)?
132        .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
133}
134
135/// A key that signs TEE spot orders and cancels.
136#[expect(
137    async_fn_in_trait,
138    reason = "signers are used generically, never as Send-bound trait objects"
139)]
140pub trait TeeSpotSigner: HypercallSigner {
141    async fn sign_tee_spot_order_payload(&self, payload: TeeSpotOrderSignature) -> Result<String>;
142    async fn sign_tee_spot_cancel_payload(&self, payload: TeeSpotCancelSignature)
143        -> Result<String>;
144}
145
146impl TeeSpotSigner for HypercallWallet {
147    async fn sign_tee_spot_order_payload(&self, payload: TeeSpotOrderSignature) -> Result<String> {
148        let message = order_message(&payload)?;
149        self.sign_directive(&message, "HCSpotOrder", HYPERCALL_API_DOMAIN)
150            .await
151    }
152
153    async fn sign_tee_spot_cancel_payload(
154        &self,
155        payload: TeeSpotCancelSignature,
156    ) -> Result<String> {
157        let message = cancel_message(&payload)?;
158        self.sign_directive(&message, "HCSpotCancel", HYPERCALL_API_DOMAIN)
159            .await
160    }
161}
162
163/// One spot limit order. `price` is USDC per base token, `size` base tokens.
164#[derive(Debug, Clone)]
165pub struct TeeSpotOrderParams {
166    pub account: AccountAddress,
167    /// HyperCore spot pair index (the asset id is `10000 + pair_index`).
168    pub pair_index: u32,
169    pub side: Side,
170    pub price: Decimal,
171    pub size: Decimal,
172    /// GTC or IOC.
173    pub tif: PerpTimeInForce,
174    /// Defaults to the nonce.
175    pub client_order_id: Option<u128>,
176    /// Defaults to [`HypercallClient::next_tee_perp_nonce`].
177    pub nonce: Option<u64>,
178}
179
180/// Cancel one open spot order by its client order id.
181#[derive(Debug, Clone)]
182pub struct TeeSpotCancelParams {
183    pub account: AccountAddress,
184    pub pair_index: u32,
185    pub client_order_id: u128,
186    pub nonce: Option<u64>,
187}
188
189fn spot_asset(pair_index: u32) -> Result<u32> {
190    TEE_SPOT_ASSET_OFFSET
191        .checked_add(pair_index)
192        .ok_or_else(|| ClientError::InvalidInput("spot pair index overflows".into()))
193}
194
195impl HypercallClient {
196    /// Place one spot limit order through the TEE. Prices and sizes must
197    /// respect the pair's HyperCore tick and lot rules.
198    pub async fn place_tee_spot_order<S>(
199        &self,
200        signer: &S,
201        params: TeeSpotOrderParams,
202    ) -> Result<TeeSpotResponse>
203    where
204        S: TeeSpotSigner + ?Sized,
205    {
206        let nonce = self
207            .resolve_tee_nonce(signer.address(), params.nonce)
208            .await?;
209        let action = TeeSpotOrderAction {
210            asset: spot_asset(params.pair_index)?,
211            is_buy: matches!(params.side, Side::Buy),
212            limit_px: to_perp_units(params.price, "spot limit price")?,
213            sz: to_perp_units(params.size, "spot size")?,
214            tif: params.tif,
215            cloid: nonzero_cloid(params.client_order_id.unwrap_or(u128::from(nonce)))?,
216        };
217        let signature = signer
218            .sign_tee_spot_order_payload(TeeSpotOrderSignature {
219                account: params.account,
220                nonce,
221                action,
222            })
223            .await?;
224        let request = DirectiveSubmitRequest {
225            account: params.account.into_wallet_address(),
226            nonce,
227            action,
228            signature,
229        };
230        self.post_tee_signed(
231            TEE_SPOT_ORDER_SUBMIT_ROUTE,
232            &request,
233            "submit TEE spot order",
234        )
235        .await
236    }
237
238    /// Cancel one open spot order by client order id.
239    pub async fn cancel_tee_spot_order<S>(
240        &self,
241        signer: &S,
242        params: TeeSpotCancelParams,
243    ) -> Result<TeeSpotResponse>
244    where
245        S: TeeSpotSigner + ?Sized,
246    {
247        let nonce = self
248            .resolve_tee_nonce(signer.address(), params.nonce)
249            .await?;
250        let action = TeeSpotCancelAction {
251            asset: spot_asset(params.pair_index)?,
252            cloid: nonzero_cloid(params.client_order_id)?,
253        };
254        let signature = signer
255            .sign_tee_spot_cancel_payload(TeeSpotCancelSignature {
256                account: params.account,
257                nonce,
258                action,
259            })
260            .await?;
261        let request = DirectiveSubmitRequest {
262            account: params.account.into_wallet_address(),
263            nonce,
264            action,
265            signature,
266        };
267        self.post_tee_signed(
268            TEE_SPOT_CANCEL_SUBMIT_ROUTE,
269            &request,
270            "submit TEE spot cancel",
271        )
272        .await
273    }
274}
275
276#[cfg(test)]
277#[path = "tee_spot_test.rs"]
278mod tests;