Skip to main content

Module tee_perp

Module tee_perp 

Source
Expand description

TEE perp trading: Hyperliquid perp orders signed by the account’s app key (API wallet) and executed through Hypercall’s TEE-held Hyperliquid API wallet.

§Flow

  1. Register the app key once (manager wallet): HypercallClient::update_api_wallet adds it as an Account.sol API wallet. An options agent key (ApproveAgent, including keys made with “Create agent key” in account settings) is not enough on its own: TEE perp trades must be signed by an active on-chain API wallet, and anything else (including the manager itself) is rejected with invalid_signature. Wait for the registration directive to finalize before the app key signs.
  2. Enroll the TEE API wallet once (manager wallet): HypercallClient::enroll_tee_api_wallet requests the account’s TEE wallet, signs the HLAddApiWallet approval in the HypercallManagerSign domain, submits it, and waits until Hyperliquid binds the wallet.
  3. Approve the Hypercall builder once (manager wallet, HyperEVM transaction): HypercallClient::approve_hypercall_builder calls Account.approveZeroFeeBuilder(builder) (Account 0.2.4 or newer). Orders are refused with TeePerpErrorCode::BuilderNotApproved until then.
  4. Trade with the app key (an active Account API wallet). Every action is EIP-712 signed in the HypercallApiSign domain.

§Nonces

The nonce is a Unix millisecond on the API server’s clock. The server derives the venue expiry as nonce + 9000 and accepts it only when it falls in (server_now, server_now + 10000], so a nonce must lie in (server_now - 9000, server_now + 1000]. Methods that take nonce: Option<u64> stamp None from HypercallClient::next_tee_perp_nonce, which reads the server clock from the /health Date header (cached for a minute) and keeps nonces strictly increasing per signer.

§Outcomes

A 200 response carries a TeePerpOrderStage. unknown means the venue may have received the action: reconcile before acting again, and never resubmit the same intent through another route.

A signed submission that fails in transit (transport error, timeout, 5xx, or an undecodable 2xx) returns ClientError::TeeSubmissionAmbiguous with the exact signed body. Resend those bytes with HypercallClient::resend_tee_submission or reconcile; calling the placing method again would sign a new nonce (and, for batches, new nonce-derived cloids), which is a second order.

§Example

use hypercall_client::{
    AccountAddress, ApproveHypercallBuilderParams, DirectiveDeliveryStatus, HypercallClient,
    HypercallWallet,
    HyperliquidInfoClient, PerpCancelByCloidParams, PerpLimitOrderParams, PerpPreviewAction,
    PerpPreviewRequest, PerpTimeInForce, Side, TeeApiWalletEnrollmentPolling, TeePerpBracketEntry,
    TeePerpBracketOrderParams, TeePerpExit, TeePerpLeverageParams, TeePerpMarketOrderParams,
    TeePerpTpsl, TeePerpTriggerExecution, TeePerpTriggerOrderParams, UpdateApiWalletParams,
    PERP_MARKET_SLIPPAGE_BPS,
};
use alloy::primitives::keccak256;
use rust_decimal::Decimal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = HypercallClient::new("https://api.hypercall.xyz");
    let manager = HypercallWallet::from_private_key("0xYOUR_MANAGER_KEY", 999)?;
    let app_key = HypercallWallet::from_private_key("0xYOUR_API_WALLET_KEY", 999)?;
    let account: AccountAddress = "0xYOUR_ACCOUNT_SOL_ADDRESS".parse()?;
    let hyperliquid = HyperliquidInfoClient::mainnet();

    // One-time setup with the manager wallet. An options agent key is not
    // enough: register the app key as an on-chain API wallet first.
    let registration = client
        .update_api_wallet(
            &manager,
            UpdateApiWalletParams {
                account,
                name: keccak256("tee-perps-app-key"),
                api_wallet: app_key.address,
                nonce: None,
            },
        )
        .await?;
    // Submission only enqueues the directive. Wait until it is final on
    // chain before the app key signs anything.
    loop {
        let status = client
            .get_directive_status(&registration.directive_id)
            .await?;
        match status.delivery_status {
            DirectiveDeliveryStatus::Finalized => break,
            DirectiveDeliveryStatus::CoreRejected
            | DirectiveDeliveryStatus::Reverted
            | DirectiveDeliveryStatus::Expired
            | DirectiveDeliveryStatus::DeadLettered => {
                return Err(format!("API wallet registration failed: {status:?}").into())
            }
            _ => tokio::time::sleep(std::time::Duration::from_secs(1)).await,
        }
    }
    let enrollment = client
        .enroll_tee_api_wallet(
            &manager,
            account,
            &hyperliquid,
            TeeApiWalletEnrollmentPolling::default(),
        )
        .await?;
    println!("TEE API wallet: {}", enrollment.api_wallet);
    client
        .approve_hypercall_builder(
            &manager,
            ApproveHypercallBuilderParams {
                rpc_url: "https://rpc.hyperliquid.xyz/evm".into(),
                account,
                builder: None, // read from /exchange-info hl_builder_address
            },
        )
        .await?;

    // Market metadata and a read-only preview.
    let markets = client.get_tee_perp_markets().await?;
    let btc = markets
        .by_hyperliquid_coin("BTC")
        .ok_or("BTC is not configured")?;
    let preview = client
        .preview_tee_perp_action(&PerpPreviewRequest {
            account: account.into_wallet_address(),
            action: PerpPreviewAction::Leverage {
                asset: btc.asset_id,
                is_cross: true,
                leverage: 5,
            },
        })
        .await?;
    println!(
        "{:?} {:?}, liquidation after {:?}",
        preview.decision, preview.reason_code, preview.liquidation_px_after
    );

    // Leverage, then read the venue's setting back.
    client
        .update_tee_perp_leverage(
            &app_key,
            TeePerpLeverageParams {
                account,
                asset: btc.asset_id,
                is_cross: true,
                leverage: 5,
                nonce: None,
            },
        )
        .await?;
    let venue = hyperliquid
        .active_asset_leverage(account, &btc.hyperliquid_coin)
        .await?;
    println!("venue leverage: {venue:?}");

    // Limit (GTC, IOC, or ALO) and market (bounded IOC) orders.
    let limit = client
        .place_tee_perp_limit_order(
            &app_key,
            PerpLimitOrderParams {
                account,
                asset: btc.asset_id,
                side: Side::Buy,
                price: Decimal::new(95_000, 0),
                size: Decimal::new(1, 3),
                tif: PerpTimeInForce::Alo,
                reduce_only: false,
                client_order_id: Some(42),
                nonce: None,
            },
        )
        .await?;
    if limit.requires_builder_approval() {
        return Err("approve the Hypercall builder first".into());
    }
    client
        .place_tee_perp_market_order(
            &app_key,
            TeePerpMarketOrderParams {
                account,
                asset: btc.asset_id,
                side: Side::Buy,
                size: Decimal::new(1, 3),
                reference_price: Decimal::new(100_000, 0), // best ask
                size_decimals: 5,
                slippage_bps: Some(50),
                reduce_only: false,
                client_order_id: None,
                nonce: None,
            },
        )
        .await?;

    // A stop-market order, and an entry with attached TP/SL.
    client
        .place_tee_perp_trigger_order(
            &app_key,
            TeePerpTriggerOrderParams {
                account,
                asset: btc.asset_id,
                side: Side::Sell,
                size: Decimal::new(1, 3),
                trigger_price: Decimal::new(90_000, 0),
                tpsl: TeePerpTpsl::Sl,
                execution: TeePerpTriggerExecution::Market {
                    size_decimals: 5,
                    slippage_bps: None,
                },
                reduce_only: true,
                client_order_id: None,
                nonce: None,
            },
        )
        .await?;
    let exit = |trigger: i64| {
        TeePerpExit::market(
            Decimal::new(trigger, 0),
            Side::Sell,
            5,
            PERP_MARKET_SLIPPAGE_BPS,
        )
    };
    let bracket = client
        .place_tee_perp_bracket_order(
            &app_key,
            TeePerpBracketOrderParams {
                account,
                entry: TeePerpBracketEntry {
                    asset: btc.asset_id,
                    side: Side::Buy,
                    price: Decimal::new(99_000, 0),
                    size: Decimal::new(1, 3),
                    tif: PerpTimeInForce::Gtc,
                    reduce_only: false,
                },
                take_profit: Some(exit(110_000)?),
                stop_loss: Some(exit(92_000)?),
                nonce: None,
            },
        )
        .await?;
    println!("bracket {:?}: {} children", bracket.stage, bracket.children.len());

    client
        .cancel_tee_perp_order_by_cloid(
            &app_key,
            PerpCancelByCloidParams {
                account,
                asset: btc.asset_id,
                client_order_id: 42,
                nonce: None,
            },
        )
        .await?;
    Ok(())
}

§Modify, batch modify and TWAP

HypercallClient::modify_tee_perp_order and HypercallClient::batch_modify_tee_perp_orders replace resting limit orders; each batch child reports its own TeePerpOrderStage in TeePerpBatchModifyResponse::children. HypercallClient::place_tee_perp_twap_order and HypercallClient::cancel_tee_perp_twap drive native TWAPs. TWAP and batch modify are enabled per enclave release; a deployment without them answers 400 unsupported_action (ClientError::is_unsupported_action).

Hyperliquid parity. TWAP submit and cancel carry every twapOrder and twapCancel field (a, b, s, r, m, t; a, t). Modify and batch modify have these scope cuts:

  • Modify replaces limit orders only (GTC, IOC, ALO). Hyperliquid’s modify can also turn an order into a trigger order; the TEE route does not accept that, so a resting trigger order must be cancelled and re-placed.
  • The order is addressed by its cloid plus its engine directiveId, never by oid, and the modify keeps the cloid. Hyperliquid also accepts an oid target and a new cloid.
  • A batch modify carries at most the instance cap (50 by default, 100 at most), where Hyperliquid documents no per-call limit.
  • No builder field: Hyperliquid documents none on modify, batchModify, twapOrder or twapCancel.
use hypercall_client::{
    AccountAddress, HypercallClient, HypercallWallet, PerpTimeInForce, Side,
    TeePerpBatchModifyParams, TeePerpModifyParams, TeePerpOrderReplacement, TeePerpOrderStage,
    TeePerpTwapCancelParams, TeePerpTwapParams,
};
use rust_decimal::Decimal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = HypercallClient::new("https://api.hypercall.xyz");
    let app_key = HypercallWallet::from_private_key("0xYOUR_API_WALLET_KEY", 999)?;
    let account: AccountAddress = "0xYOUR_ACCOUNT_SOL_ADDRESS".parse()?;

    // `directiveId` and cloid returned when each order was placed.
    let bid = TeePerpOrderReplacement {
        asset: 0,
        target_directive_id: "01999b5a-7c1e-7000-8000-000000000042".parse()?,
        cloid: 42,
        side: Side::Buy,
        price: Decimal::new(99_500, 0),
        size: Decimal::new(2, 3),
        tif: PerpTimeInForce::Alo,
        reduce_only: false,
    };
    let ask = TeePerpOrderReplacement {
        target_directive_id: "01999b5a-7c1e-7000-8000-000000000043".parse()?,
        cloid: 43,
        side: Side::Sell,
        price: Decimal::new(100_500, 0),
        ..bid
    };

    // One order.
    let single = client
        .modify_tee_perp_order(
            &app_key,
            TeePerpModifyParams {
                account,
                replacement: bid,
                nonce: None,
            },
        )
        .await?;
    println!("modify {:?}", single.stage);

    // Both quotes in one signed batchModify; each child settles on its own.
    let batch = client
        .batch_modify_tee_perp_orders(
            &app_key,
            TeePerpBatchModifyParams {
                account,
                replacements: vec![bid, ask],
                max_children: None, // the server default, 50
                nonce: None,
            },
        )
        .await?;
    for child in &batch.children {
        match child.stage {
            TeePerpOrderStage::Accepted => println!("{} moved", child.cloid),
            // Hyperliquid cancelled the original before the replacement failed.
            _ if child.venue_cancelled_original() => {
                println!("{} cancelled: nothing rests any more", child.cloid)
            }
            TeePerpOrderStage::Rejected | TeePerpOrderStage::NotSubmitted => {
                println!("{} unchanged: the old order still rests", child.cloid)
            }
            _ => println!("{} unknown: reconcile before touching it", child.cloid),
        }
    }

    // A native TWAP. Deployments that have not enabled it answer
    // `400 unsupported_action`.
    match client
        .place_tee_perp_twap_order(
            &app_key,
            TeePerpTwapParams {
                account,
                asset: 0,
                side: Side::Sell,
                size: Decimal::new(5, 2),
                reduce_only: true,
                minutes: 30,
                randomize: true,
                nonce: None,
            },
        )
        .await
    {
        Ok(twap) => {
            if let Some(twap_id) = twap.twap_id {
                client
                    .cancel_tee_perp_twap(
                        &app_key,
                        TeePerpTwapCancelParams {
                            account,
                            asset: 0,
                            twap_id,
                            nonce: None,
                        },
                    )
                    .await?;
            }
        }
        Err(error) if error.is_unsupported_action() => println!("TWAP is not enabled here"),
        Err(error) => return Err(error.into()),
    }
    Ok(())
}

Modules§

HypercallAccountBuilderApproval
Module containing a contract’s types and functions.

Structs§

AddApiWallet
ApproveHypercallBuilderParams
Parameters for HypercallClient::approve_hypercall_builder.
HCPerpLeverageChange
HCPerpOrderBatch
HCPerpOrderBatchModify
Every child’s replacement terms, in request order.
HCPerpOrderModify
HCPerpTriggerOrder
HCPerpTwapCancel
HCPerpTwapOrder
HLAddApiWallet
HyperliquidInfoClient
Minimal Hyperliquid /info reader for TEE perp readbacks.
HyperliquidLeverage
Hyperliquid margin setting read back from the venue.
HyperliquidUserRole
Hyperliquid userRole response.
HyperliquidUserRoleData
PerpLeverageChange
PerpModifyTerms
Replacement terms of one modify. targetDirectiveId is the UUID as a big-endian u128. Field names and order match the server’s PerpModifyTerms exactly; the digest depends on both.
PerpOrderTerms
One signed order. A limit child signs its TIF byte with triggerPx = 0, isMarket = false, tpsl = 0. A trigger child signs encodedTif = 0, its trigger price, and tpsl 1 (TP) or 2 (SL).
PerpScaleLeg
One resting limit leg of a scale order.
PerpScaleOrderSpec
Inputs of build_perp_scale_order_legs.
PerpTwapCancelTerms
PerpTwapTerms
TeeApiWalletApprovalChallenge
The manager-authenticated TEE API wallet approval challenge.
TeeApiWalletApprovalSignature
Manager payload approving the account’s TEE API wallet on Hyperliquid.
TeeApiWalletEnrollment
Result of HypercallClient::enroll_tee_api_wallet.
TeeApiWalletEnrollmentPolling
Polling of HypercallClient::enroll_tee_api_wallet.
TeePerpBatchModifyParams
Several resting limit orders’ replacements under one signature (HypercallClient::batch_modify_tee_perp_orders).
TeePerpBatchModifySignature
App-key payload for POST /v1/tee-perp/orders/batch-modify (HCPerpOrderBatchModify).
TeePerpBracketEntry
The entry of a build_tee_perp_bracket_batch.
TeePerpBracketOrderParams
An entry with attached TP/SL exits (normalTpsl).
TeePerpExit
A take-profit or stop-loss exit executed as a market order once triggered.
TeePerpLeverageParams
A leverage and margin-mode change.
TeePerpLeverageSignature
App-key payload for POST /v1/tee-perp/leverage/submit.
TeePerpMarketOrderParams
A market order: an IOC limit at reference_price moved slippage_bps against the trader and rounded to a valid tick.
TeePerpModifyParams
One resting limit order’s replacement (HypercallClient::modify_tee_perp_order).
TeePerpModifySignature
App-key payload for POST /v1/tee-perp/orders/modify (HCPerpOrderModify).
TeePerpOrderBatchParams
A caller-built order batch. Cloids must already be set; derive them from the nonce with tee_perp_batch_cloid after reserving it with HypercallClient::next_tee_perp_nonce.
TeePerpOrderBatchSignature
App-key payload for POST /v1/tee-perp/orders/submit-batch.
TeePerpOrderReplacement
The new terms for one resting limit order, in human units.
TeePerpPositionTpslParams
TP/SL exits on an existing position (positionTpsl).
TeePerpScaleOrderParams
A scale order: limit legs submitted as one ungrouped batch.
TeePerpTriggerOrderParams
A native stop-loss or take-profit order (market or limit).
TeePerpTriggerOrderSignature
App-key payload for POST /v1/tee-perp/orders/submit-trigger.
TeePerpTwapCancelParams
Cancel a running TWAP (HypercallClient::cancel_tee_perp_twap).
TeePerpTwapCancelSignature
App-key payload for POST /v1/tee-perp/twap/cancel (HCPerpTwapCancel).
TeePerpTwapParams
A native Hyperliquid TWAP (HypercallClient::place_tee_perp_twap_order).
TeePerpTwapSignature
App-key payload for POST /v1/tee-perp/twap/submit (HCPerpTwapOrder).

Enums§

TeeApiWalletApprovalProgress
Progress of a TEE API wallet approval directive.
TeePerpTriggerExecution
How a trigger order executes once triggered.

Constants§

HYPERLIQUID_MAINNET_INFO_URL
Hyperliquid info endpoint on mainnet.
HYPERLIQUID_PERP_MAX_PRICE_DECIMALS
Hyperliquid perp prices carry at most 6 - szDecimals decimals.
HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES
Hyperliquid perp prices carry at most five significant figures.
HYPERLIQUID_TESTNET_INFO_URL
Hyperliquid info endpoint on testnet.
PERP_MARKET_SLIPPAGE_BPS
Default market-order slippage bound used by the Hypercall order panel: an IOC limit 2000 bps (20%) through the reference price, rounded to a valid tick inside that bound. Pass a tighter bound where it matters.
PERP_SCALE_MAX_ORDERS
Scale orders split into this many legs at most.
PERP_SCALE_MIN_ORDERS
Scale orders split into this many legs at least.

Traits§

TeeApiWalletManagerSigner
Manager signer for TEE API wallet enrollment.
TeePerpSigner
App-key signer for TEE perp routes. Plain limit orders and cancels reuse the PerpDirectiveSigner schemas (HLOrder, HLCancel, HLCancelByCloid); triggers, batches, leverage, modifies and TWAPs use these.

Functions§

build_perp_scale_order_legs
Split a scale order into evenly spaced limit legs, exactly as the Hypercall order panel does: leg sizes follow size_skew, are floored to the lot size with the remaining lots added to the last legs (so they sum to total_size), and prices are rounded to a valid tick on the trader’s side.
build_tee_perp_batch_modify
Build the signed action of a batch modify, refusing one the server would refuse. max_children is the instance cap (None for DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN); it can lower the cap but never raise it past MAX_TEE_PERP_BATCH_MODIFY_CHILDREN.
build_tee_perp_bracket_batch
An entry with attached TP/SL, grouped normalTpsl so Hyperliquid only activates the exits once the entry fills. Exits are reduce-only market triggers on the opposite side for the full entry size.
build_tee_perp_position_tpsl_batch
Reduce-only TP/SL exits on an existing position, grouped positionTpsl. position_side is the position’s direction (Buy = long); exits trade the opposite side.
build_tee_perp_scale_batch
Scale legs submitted together as one ungrouped batch.
perp_market_limit_price
The IOC limit price of a market order (or market trigger): reference moved slippage_bps against the trader, rounded to a valid Hyperliquid tick inside that bound (buys round down, sells round up). reference is the best ask for a buy and the best bid for a sell (or the trigger price).
perp_preview_batch_action
The preview action of a signed order batch.
perp_preview_order
The preview form of a signed order wire (1e8 integers back to decimals), so a preview describes exactly what will be signed.
resolve_hypercall_builder_address
Hypercall builder published by /exchange-info. Never guessed.
round_perp_price_to_tick
Round price to Hyperliquid’s tick for side: buys round down and sells round up, so the result is never worse for the trader than price.
tee_api_wallet_approval_progress
Classify a /v1/directives/{id} status of the approval directive.
tee_api_wallet_approval_signing_hash
EIP-712 digest the manager signs to approve the TEE API wallet.
tee_perp_batch_cloid
Child cloid of one signed batch: the nonce in the high bits and the 1-based child index in the low byte. Distinct per child, never zero, and reproducible from the signed nonce.
tee_perp_batch_modify_signing_hash
EIP-712 digest the app key signs for a TEE batch modify. Child order is signed.
tee_perp_leverage_signing_hash
EIP-712 digest the app key signs for a TEE leverage change.
tee_perp_limit_order_wire
A plain limit child for an order batch.
tee_perp_modify_signing_hash
EIP-712 digest the app key signs for a TEE single modify.
tee_perp_nonce_in_window
Whether the server would accept nonce at server_now_ms.
tee_perp_order_batch_signing_hash
EIP-712 digest the app key signs for a TEE order batch.
tee_perp_trigger_order_signing_hash
EIP-712 digest the app key signs for a TEE trigger order.
tee_perp_trigger_order_wire
One trigger exit or entry. limit_price is the signed execution bound: the user’s limit for a limit trigger, or the slippage-bounded worst price from perp_market_limit_price for a market trigger.
tee_perp_twap_cancel_signing_hash
EIP-712 digest the app key signs for a TEE TWAP cancel.
tee_perp_twap_signing_hash
EIP-712 digest the app key signs for a TEE TWAP.
tee_perp_venue_expires_after_ms
Venue expiry the server derives from a TEE perp nonce, or None when the nonce is zero or overflows.