hypercall-client
Rust API client for Hypercall.
Responsibilities
- HTTP and websocket clients for Hypercall API surfaces.
- EIP-712 wallet helpers for public options, RFQ, and quote-provider signing.
- TEE perp trading: enrollment, builder approval, orders, triggers, batches, cancels, leverage, preview, and markets.
- RFQ V2: EIP-712 signing for every action, the
/private/rfqs*transport, ambiguous-submission recovery, and the privaterfq_v2WebSocket channel. - Request and response convenience types re-exported from
hypercall-sdk-types.
Getting Started
Add the client from the public Git repository:
[]
= { = "https://github.com/hypercall-public/hypercall-rust" }
= "1"
= { = "1", = ["macros", "rt-multi-thread"] }
Create a production API client:
use HypercallClient;
async
WebSocket recovery
WsClient reconnects established /ws sessions with capped exponential
backoff and jitter. It identifies the wallet again, restores the exact desired
subscriptions and filters, and waits for subscription confirmations before
reporting that the transport is connected.
use ;
async
Replaceable public streams become ready after resubscription. Ordered public
and private streams enter RecoveryRequired because reconnecting cannot prove
that no events were missed. Callers must fetch the required order book snapshot,
portfolio snapshot, or durable REST state before calling mark_recovered().
Portfolio subscribers must do both because durable position-expiry events share
the portfolio channel.
Use connection_state_receiver() to watch transitions and
last_disconnect_reason() to inspect structured slow-consumer closes.
Batched indicative market data
subscribe_indicative_market_data(symbols) subscribes to
indicative_market_data_v2, which delivers one IndicativeMarketDataBatch
frame per batch window (25 ms by default). Rows arrive up to one window later,
in exchange for far fewer frames that compress much better when the connection
uses permessage-deflate. If the server confirms the channel without
"batch": true or rejects it as unknown_channel, the client moves the
subscription to indicative_market_data, one IndicativeMarketData frame per
row. Opt out with WsClient::new().with_batched_indicative(false). Read rows
through hypercall_client::indicative, which handles both:
use ;
async
Wallet Signing
HypercallWallet supports local private-key signing in every build:
use ;
Enable the kms feature to use AWS KMS-backed signing through the AWS SDK
default credential chain:
Private key export only works for local private-key wallets. KMS wallets never expose private key material.
Unified-account setup
Create and register the managed Account.sol before selecting portfolio
margin. The caller supplies the HyperEVM RPC URL and the Factory address for
the target deployment. The SDK reads the Factory's live minimum HYPE deposit
and applies the same 1% deposit and 20% gas-limit buffers as the Hypercall app.
use ;
use keccak256;
async
The manager and salt select a deterministic CREATE2 address. Account creation
is not idempotent: submitting again with an already-used manager/salt pair
reverts. salt: None uses salt zero to match the Hypercall app. Supply another
salt only when deliberately creating a distinct managed account.
API-wallet updates are manager-authorized directives. Reusing a name replaces its current API wallet. Passing the zero address removes that named wallet.
Account abstraction changes are manager-authorized. The SDK binds the signed action target to the supplied managed Account address.
use ;
use Duration;
async
Finalized confirms transaction delivery, not that HyperCore has exposed the
new account mode. After finalization, poll Hyperliquid's authoritative Info API
until userAbstraction is exactly unifiedAccount. Do not submit a
risk-increasing perp order before that read confirms the mode. The typed SDK
deliberately exposes only unified-account mode because the server and Account
contract reject all other hl_set_abstraction values.
Portfolio margin perp orders
Managed perp methods take an existing Account.sol address and the numeric
HyperCore asset ID. Creating or discovering the account and authorizing the API
wallet are separate setup steps. This example assumes the authoritative
Hyperliquid Info API already reports userAbstraction as unifiedAccount.
Prices and sizes must be positive and exactly representable with 8 decimal
places. The client rejects unsupported precision or overflow instead of
rounding.
use ;
use Decimal;
use Duration;
async
When client_order_id is omitted for placement, the selected nonce is used as
the u128 client order ID. An explicit nonce is available on every managed perp
request for deterministic orchestration. Allocate nonces durably and atomically
per signer. Never reuse a nonce, including when retrying a request. The response
always reports the server's actual stage, directive ID, recovered signer,
rejection, transaction hash, and any fills it knows about.
TEE perp trading
TEE perp methods submit Hyperliquid perp orders that Hypercall executes through
a TEE-held Hyperliquid API wallet, after Portfolio Margin admission. They are
separate from the managed /v1/actions/* directive methods above and use the
same app key (an active Account.sol API wallet) to sign.
An options agent key is not a perps app key. A key approved with
ApproveAgent (for example one made with "Create agent key" in account
settings) signs options and REST requests only. Perp trading directives and
TEE perp routes accept only a signer that is an active on-chain API wallet of
the Account (Account.isApiWalletActive). The manager signs setup actions such
as update_api_wallet but cannot sign trades itself, and cannot be an API
wallet. So the manager must register the key with update_api_wallet. Until then every TEE perp
request it signs is rejected with invalid_signature, and the message says the
key is an options/REST key that is not enabled for perps. The settings page can
do this step too: tick "Also enable for perps" when creating a key, or press
"Enable for perps" on an existing one.
Setup, once per account, with the manager wallet:
update_api_walletregisters the app key as an Account.sol API wallet (hc_update_api_wallet, domainHypercallManagerSign). Skip it when the app key is already active (Account.isApiWalletActive).enroll_tee_api_walletrequests the account's TEE API wallet, signs theHLAddApiWalletapproval (domainHypercallManagerSign), submits it, and waits until Hyperliquid binds the wallet.HyperliquidInfoClient::is_tee_api_wallet_activereads the enrollment status.approve_hypercall_buildersendsAccount.approveZeroFeeBuilder(builder)(Account 0.2.4 or newer) with the builder from/exchange-infohl_builder_address. Until then orders come back witherrorCode = builder_not_approved(requires_builder_approval()).
Trading, with the app key (domain HypercallApiSign):
| Method | Route | Signed type |
|---|---|---|
place_tee_perp_limit_order (GTC, IOC, ALO), place_tee_perp_market_order (bounded IOC) |
POST /v1/tee-perp/orders/submit |
HLOrder |
place_tee_perp_trigger_order (stop or take-profit, market or limit) |
POST /v1/tee-perp/orders/submit-trigger |
HCPerpTriggerOrder |
place_tee_perp_bracket_order (normalTpsl), place_tee_perp_position_tpsl (positionTpsl), place_tee_perp_scale_order and place_tee_perp_order_batch (na) |
POST /v1/tee-perp/orders/submit-batch |
HCPerpOrderBatch |
cancel_tee_perp_order_by_oid |
POST /v1/tee-perp/cancels/submit-by-oid |
HLCancel |
cancel_tee_perp_order_by_cloid |
POST /v1/tee-perp/cancels/submit |
HLCancelByCloid |
update_tee_perp_leverage |
POST /v1/tee-perp/leverage/submit |
HCPerpLeverageChange |
modify_tee_perp_order |
POST /v1/tee-perp/orders/modify |
HCPerpOrderModify |
batch_modify_tee_perp_orders |
POST /v1/tee-perp/orders/batch-modify |
HCPerpOrderBatchModify |
place_tee_perp_twap_order |
POST /v1/tee-perp/twap/submit |
HCPerpTwapOrder |
cancel_tee_perp_twap |
POST /v1/tee-perp/twap/cancel |
HCPerpTwapCancel |
preview_tee_perp_action |
POST /v1/tee-perp/preview |
none (read-only) |
get_tee_perp_markets |
GET /v1/tee-perp/markets |
none |
Nonces are Unix milliseconds on the API server's clock. The server derives the
venue expiry as nonce + 9000 and accepts it only within the next 10 seconds,
so a nonce must lie in (server_now - 9000, server_now + 1000]. Leave nonce
as None and the client stamps it from the /health Date header (cached for
a minute), strictly increasing per signer. Batch child cloids are
(nonce << 8) + index + 1 (tee_perp_batch_cloid).
Every submit returns a stage. unknown means the venue may have received the
action: reconcile before acting again, and never resubmit the same intent on
another route. A signed submission that fails in transit (transport error,
timeout, 5xx, or an undecodable 2xx) returns
ClientError::TeeSubmissionAmbiguous carrying the exact signed body; resend
those bytes with resend_tee_submission (the server deduplicates them) or
reconcile. Calling the placing method again signs a new nonce, and new
nonce-derived cloids, so it is a second order. Rejections carry a typed PerpRejectionReasonCode, the same
code the preview returns.
use ;
use keccak256;
use Decimal;
async
Market and market-trigger prices follow the Hypercall order panel: the
reference price moved slippage_bps against the trader (default
PERP_MARKET_SLIPPAGE_BPS, 2000 bps), rounded to a valid Hyperliquid tick
inside that bound, refused when no such tick still crosses. Scale legs come
from build_perp_scale_order_legs. Schedule-cancel and prepared cancels are not
part of the TEE perp SDK surface.
Modify, batch modify and TWAP
modify_tee_perp_order replaces one resting limit order's price, size, side,
TIF and reduce-only flag. batch_modify_tee_perp_orders replaces several under
one signature and one venue nonce (Hyperliquid batchModify). The engine
admits every child or none, then each child settles on its own, so read
children (each with its index, requestId, targetDirectiveId, cloid,
stage, message and venueOrder). Whenever Hyperliquid answered every child,
the whole-action stage is definite: accepted or rejected when every child
agrees, partial for a mix. It is unknown only when some child is genuinely
unknown (timeout, transport failure, unverifiable venue response).
children_to_reconcile() lists the children whose outcome is not definitive; a
stage this SDK does not know parses as Unrecognized and is treated as
unknown.
Hyperliquid applies a modify as a cancel of the original order followed by the
placement of the replacement. When the placement fails after the cancel (the
venue's Error placing new order during modify: ..., for example an ALO
replacement that would cross), the original order is gone too. The response
then reports stage: "rejected" with venueOrder: {"status": "cancelled", "reason": "modify rejected; venue cancelled original"}
(venue_cancelled_original()), and the engine treats the order as cancelled:
its reservation is released once a newer position snapshot has absorbed any
fill before the cancel. Any other rejected or not_submitted outcome leaves
the original order resting.
Modify and batch modify return only after Hyperliquid answered. An accepted
modify's venueOrder carries the replacement's NEW oid (resting or
filled); the old oid is cancelled. Trust the response over an immediate
orderStatus read: Hyperliquid's info endpoint can show the pre-modify order
for a few seconds after the exchange applied the modify.
The client refuses a batch before signing when it is empty, repeats a target or
cloid, or exceeds max_children (default 50, the server's default
api.tee_perp_batch_modify_max_children; never above 100).
TEE perp orders, modifies and batch modifies carry no Hypercall rate limit;
Hyperliquid's address-based request limit governs them. After Hyperliquid
refuses an Account's order action for that limit, the API answers that
Account's further order actions with 429 venue_rate_limited and
Retry-After for 10 seconds without sending them. Cancels are never held back.
TWAP (place_tee_perp_twap_order, cancel_tee_perp_twap) runs 5 to 1440
minutes, and the engine reserves the full size until fills arrive. TWAP and
batch modify are gated by the enclave release: a deployment that has not
enabled one answers 400 unsupported_action, which
ClientError::is_unsupported_action() detects. Nothing was reserved or sent to
the venue in that case.
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 ;
use Decimal;
async
Funding
Direct deposits are HyperEVM transactions. Withdrawals are signed Hypercall API requests. The methods are explicit about margin mode so a caller can never fall back to the wrong custody route.
The caller supplies the HyperEVM RPC URL and environment-specific USDC address.
The SDK fetches Exchange and Router from /exchange-info, verifies the API,
wallet, and RPC chain IDs match, and verifies the current account identity and
margin mode before approving funds.
Standard Margin
use ;
use dec;
async
Standard deposits approve the exact amount only when the existing allowance is
insufficient, then call Exchange.depositUsdcFor(account, amount) and wait for
both transactions to confirm successfully.
Portfolio Margin
Portfolio deposits must be funded by the manager of the canonical Account.sol.
The SDK resolves that identity through the portfolio API, requires Portfolio
Margin and an enabled Router, approves the exact amount only when needed, then
calls Router.deposit(account, usdc, amount, true).
use ;
use dec;
async
Deposit methods return only after the deposit receipt succeeds. A withdrawal
response means Hypercall accepted the request, not that delivery is final.
Poll get_directive_status with the returned directive ID. For durable
orchestration, allocate nonces atomically per signer and never use a nonce for a
different request. If a withdrawal uses an SDK-generated nonce and the HTTP
outcome is ambiguous, the error includes the selected nonce and canonical
request fields. Reconcile first. Any retry of that ambiguous request must reuse
the original nonce and every other canonical field exactly.
Portfolio Margin loan repayment
A Portfolio Margin account can repay its PM financing early from its HyperCore
USDC. The Account.sol manager signs a RepayPmLoan request; API wallets and
agents are refused. underlying names the loan exactly as get_pm_financing
lists it, and unpaid settlement obligations are always repaid first.
RepayAmount::All repays everything owed; RepayAmount::Usdc takes an exact
amount with at most six decimals.
use ;
use dec;
async
Acceptance reserves the USDC; the repayment lands once HyperCore confirms the
transfer. Poll get_pm_financing and follow repayment.requests by plan_id
until status.is_terminal(): Repaid, Canceled (nothing moved, sign a new
request) or EscalatedManual. An exact retry (same account, underlying,
amount and nonce) returns the original request, so pass nonce explicitly
when you may need to retry.
Rejections are ClientError::Api errors. PmRepayRejection::from_error reads
their stable code: the pm_voluntary_repayment_* codes, for example
InsufficientWithdrawable or RecoveryInProgress (409) and BelowMinimum
(400), plus NotManager (403, the signer is not the Account.sol manager),
InvalidNonce and SignatureVerificationFailed. repayment.blocked_reason
(RecoveryInProgress or AccountUnhealthy) predicts the matching rejection
through PmRepaymentBlockedReason::rejection, so a client can grey out the
action before signing. A server without voluntary repayment leaves
repayment as None.
Development
Run the focused client checks before changing this crate:
Feature Flags
| feature | used by | why |
|---|---|---|
| default | client users | Enables the Alloy rustls backend and rfq-v2. |
| alloy-rustls | live integrations | Enables rustls for the HTTP client, trusting the bundled webpki-roots set (1.0.10 or later), and Alloy's reqwest rustls backend. |
| alloy-native-tls | native TLS users | Enables native TLS (the platform trust store) for the HTTP client and Alloy's reqwest native TLS backend. |
| kms | AWS/client KMS users | Enables Alloy AWS signer support. |
| rfq-v2 (default) | RFQ V2 takers and makers | RFQ V2 client: rfq_v2, rfq_v2_recovery, rfq_v2_signing, signed read grants, and the private rfq_v2 WebSocket channel. |
RFQ V2 (rfq-v2)
RFQ V2 is a signed RFQ contract under /private/rfqs*: the taker signs the
RFQ, the maker signs the quote, and the taker signs the execution. It adds
anonymous takers, selected-maker routing, indicative quotes with firm-up,
repeated partial fills, atomic sweeps across up to 1,024 quotes, bulk quote
withdrawal, and a maker dead-man switch. V1 RFQ (/rfq/* and the rfq
channel) is unchanged.
The rfq-v2 feature is on by default since 0.3.0. It also enables rfq-v2 on
hypercall-sdk-types (the RFQ V2 DTOs and the AuthenticateRfqV2,
RfqV2Authenticated, and RfqV2Changed WebSocket messages) and on
hypercall-ws-protocol (the rfq_v2 channel). With
default-features = false, list it explicitly:
[]
= { = "https://github.com/hypercall-public/hypercall-rust", = "v0.5.0", = false, = ["alloy-rustls", "rfq-v2"] }
| Module | What it does |
|---|---|
rfq_v2_signing |
Builds and signs every RFQ V2 action with a HypercallWallet, and exposes the exact EIP-712 messages and digests for remote signers. |
rfq_v2 |
HTTP transport for create, quote, firm-up, decline, execute, sweep, cancel, withdraw, replace, the cancel schedule, and authorized reads. select_best_rfq_v2_quote picks the best executable firm quote locally. |
rfq_v2_recovery |
Exact-retry reconciliation of ambiguous executions and sweeps, the change-feed cursor, a private mirror, and maker hold tracking. |
WsClient::connect_rfq_v2 |
The private rfq_v2 change-hint channel, authenticated with a signed read grant and re-authenticated on reconnect. |
Take a quote as a taker:
use B256;
use ;
use RfqV2ActionAuth;
use ;
use ;
use Uuid;
async
Runnable versions, with deadline handling, ambiguous-submission
reconciliation, the maker dead-man switch, and quote pricing, are in
examples/rfq_v2_taker.rs and
examples/rfq_v2_maker.rs:
HYPERCALL_PRIVATE_KEY=0x... RFQ_INSTRUMENT=BTC-20261225-100000-C \
Rules the server enforces:
- Nonces are millisecond timestamps within two days before and one day
after server time, unique per signer.
HypercallClient::server_now_msreads the server clock. - Operation IDs on execution, sweep, cancel, withdrawal, bulk withdrawal,
the cancel schedule, and replacement must be UUIDv7s at most one hour old
and at most 30 seconds in the future by the server clock, or the server
answers 400
rfq_v2_invalid_operation_id.RfqV2ActionAuth::newmints a fresh one. Reuse an ID only to retry the identical signed request inside that window. - Selected makers are signed as a sorted, duplicate-free set. Build them
with
RfqV2Routing::selected_makers; the signer refuses an unsorted list. - Quote premiums must equal what the server derives from the leg prices.
rfq_v2_signing::rfq_v2_reference_premiumcomputes it. - Ambiguous submissions (transport error, timeout, 5xx) on a mutation
return
ClientError::RfqV2SubmissionAmbiguous. Do not sign a new request. Resend the original withreconcile_rfq_v2_executionorreconcile_rfq_v2_sweep, which resend the identical bytes under the original operation ID. - Availability: RFQ V2 is open to every account on
https://api.hypercall.xyz. A non-production environment can run it disabled, which answers every V2 route with 403rfq_v2_disabled(ClientError::RfqV2Api), or limited to an allowlist, which answers 403rfq_v2_not_allowlistedto accounts not on it.
WebSocket compression
WsClient offers RFC 7692 permessage-deflate on every connection and
reconnect. When the server accepts, compressed frames are inflated before they
reach get_messages() or wait_for_message(), so the JSON is identical either
way. When the server does not accept, the session runs uncompressed. An
inflated message larger than 64 MiB, the same limit as an uncompressed one,
fails the connection before more output is allocated. The client sends its own
messages uncompressed, which RFC 7692 allows.
use WsClient;
async
TLS uses the platform trust store through native-tls, for both compressed
and uncompressed sessions.