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
- Register the app key once (manager wallet):
HypercallClient::update_api_walletadds it as anAccount.solAPI 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 withinvalid_signature. Wait for the registration directive to finalize before the app key signs. - Enroll the TEE API wallet once (manager wallet):
HypercallClient::enroll_tee_api_walletrequests the account’s TEE wallet, signs theHLAddApiWalletapproval in theHypercallManagerSigndomain, submits it, and waits until Hyperliquid binds the wallet. - Approve the Hypercall builder once (manager wallet, HyperEVM
transaction):
HypercallClient::approve_hypercall_buildercallsAccount.approveZeroFeeBuilder(builder)(Account 0.2.4 or newer). Orders are refused withTeePerpErrorCode::BuilderNotApproveduntil then. - Trade with the app key (an active Account API wallet). Every action
is EIP-712 signed in the
HypercallApiSigndomain.
§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(®istration.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
modifycan 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 byoid, and the modify keeps the cloid. Hyperliquid also accepts anoidtarget 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,twapOrderortwapCancel.
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§
- Hypercall
Account Builder Approval - Module containing a contract’s types and functions.
Structs§
- AddApi
Wallet - Approve
Hypercall Builder Params - Parameters for
HypercallClient::approve_hypercall_builder. - HCPerp
Leverage Change - HCPerp
Order Batch - HCPerp
Order Batch Modify - Every child’s replacement terms, in request order.
- HCPerp
Order Modify - HCPerp
Trigger Order - HCPerp
Twap Cancel - HCPerp
Twap Order - HLAdd
ApiWallet - Hyperliquid
Info Client - Minimal Hyperliquid
/inforeader for TEE perp readbacks. - Hyperliquid
Leverage - Hyperliquid margin setting read back from the venue.
- Hyperliquid
User Role - Hyperliquid
userRoleresponse. - Hyperliquid
User Role Data - Perp
Leverage Change - Perp
Modify Terms - Replacement terms of one modify.
targetDirectiveIdis the UUID as a big-endian u128. Field names and order match the server’sPerpModifyTermsexactly; the digest depends on both. - Perp
Order Terms - One signed order. A limit child signs its TIF byte with
triggerPx = 0,isMarket = false,tpsl = 0. A trigger child signsencodedTif = 0, its trigger price, andtpsl1 (TP) or 2 (SL). - Perp
Scale Leg - One resting limit leg of a scale order.
- Perp
Scale Order Spec - Inputs of
build_perp_scale_order_legs. - Perp
Twap Cancel Terms - Perp
Twap Terms - TeeApi
Wallet Approval Challenge - The manager-authenticated TEE API wallet approval challenge.
- TeeApi
Wallet Approval Signature - Manager payload approving the account’s TEE API wallet on Hyperliquid.
- TeeApi
Wallet Enrollment - Result of
HypercallClient::enroll_tee_api_wallet. - TeeApi
Wallet Enrollment Polling - Polling of
HypercallClient::enroll_tee_api_wallet. - TeePerp
Batch Modify Params - Several resting limit orders’ replacements under one signature
(
HypercallClient::batch_modify_tee_perp_orders). - TeePerp
Batch Modify Signature - App-key payload for
POST /v1/tee-perp/orders/batch-modify(HCPerpOrderBatchModify). - TeePerp
Bracket Entry - The entry of a
build_tee_perp_bracket_batch. - TeePerp
Bracket Order Params - An entry with attached TP/SL exits (
normalTpsl). - TeePerp
Exit - A take-profit or stop-loss exit executed as a market order once triggered.
- TeePerp
Leverage Params - A leverage and margin-mode change.
- TeePerp
Leverage Signature - App-key payload for
POST /v1/tee-perp/leverage/submit. - TeePerp
Market Order Params - A market order: an IOC limit at
reference_pricemovedslippage_bpsagainst the trader and rounded to a valid tick. - TeePerp
Modify Params - One resting limit order’s replacement
(
HypercallClient::modify_tee_perp_order). - TeePerp
Modify Signature - App-key payload for
POST /v1/tee-perp/orders/modify(HCPerpOrderModify). - TeePerp
Order Batch Params - A caller-built order batch. Cloids must already be set; derive them from
the nonce with
tee_perp_batch_cloidafter reserving it withHypercallClient::next_tee_perp_nonce. - TeePerp
Order Batch Signature - App-key payload for
POST /v1/tee-perp/orders/submit-batch. - TeePerp
Order Replacement - The new terms for one resting limit order, in human units.
- TeePerp
Position Tpsl Params - TP/SL exits on an existing position (
positionTpsl). - TeePerp
Scale Order Params - A scale order: limit legs submitted as one ungrouped batch.
- TeePerp
Trigger Order Params - A native stop-loss or take-profit order (market or limit).
- TeePerp
Trigger Order Signature - App-key payload for
POST /v1/tee-perp/orders/submit-trigger. - TeePerp
Twap Cancel Params - Cancel a running TWAP (
HypercallClient::cancel_tee_perp_twap). - TeePerp
Twap Cancel Signature - App-key payload for
POST /v1/tee-perp/twap/cancel(HCPerpTwapCancel). - TeePerp
Twap Params - A native Hyperliquid TWAP (
HypercallClient::place_tee_perp_twap_order). - TeePerp
Twap Signature - App-key payload for
POST /v1/tee-perp/twap/submit(HCPerpTwapOrder).
Enums§
- TeeApi
Wallet Approval Progress - Progress of a TEE API wallet approval directive.
- TeePerp
Trigger Execution - 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 - szDecimalsdecimals. - 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§
- TeeApi
Wallet Manager Signer - Manager signer for TEE API wallet enrollment.
- TeePerp
Signer - App-key signer for TEE perp routes. Plain limit orders and cancels reuse
the
PerpDirectiveSignerschemas (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 tototal_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_childrenis the instance cap (NoneforDEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN); it can lower the cap but never raise it pastMAX_TEE_PERP_BATCH_MODIFY_CHILDREN. - build_
tee_ perp_ bracket_ batch - An entry with attached TP/SL, grouped
normalTpslso 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_sideis 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):
referencemovedslippage_bpsagainst the trader, rounded to a valid Hyperliquid tick inside that bound (buys round down, sells round up).referenceis 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
priceto Hyperliquid’s tick forside: buys round down and sells round up, so the result is never worse for the trader thanprice. - 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
nonceatserver_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_priceis the signed execution bound: the user’s limit for a limit trigger, or the slippage-bounded worst price fromperp_market_limit_pricefor 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
Nonewhen the nonce is zero or overflows.