From 0f14a65b8d61e40761b6d35bec6939d54da8fa2c Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Tue, 1 Dec 2026 11:42:09 +0100 Subject: [PATCH 1/3] feat(v1.1.0): support viem signers and address tracker fixes - Normalize viem accounts and wallet clients, preserve ethers signing, accept multisig inputs, and document browser/embedded wallets without adding dependencies (automation-tracker #128). - Accept native Gtc/Ioc helper aliases and validate known price precision without rounding (automation-tracker #130, #26). - Validate cloids, order-status IDs, transfer amounts/destinations, schedule-cancel timing, and empty base URLs (automation-tracker #107, #84, #72, #110). - Pass outcome coin names through metadata resolution and type outcome operations (automation-tracker #90, #91). - Lead streaming examples with merged fastAssetCtxs snapshots/diffs; clarify books and spot context channels (automation-tracker #117, #71, #95). - Expose copied active topics and document shared unsubscribe semantics; reference counting remains out of scope (automation-tracker #111). - Document nonce coordination, account modes, user signing, subaccount units, vault unlock times, and history rows (automation-tracker #70, #73, #80, #83). - Document metadata, outcome settlement, candle pagination, funding intervals, ledger variants, and thrown exchange errors (automation-tracker #93, #92, #98, #104, #106). - Attempt and revert lazy WebSocket dependencies after subscription-timing and test-runner regressions; bundle reduction remains unresolved (automation-tracker #112). - Bump only manifest versions to 1.1.0; adjust two existing invalid test inputs without adding cases; leave generated docs and workflows untouched. Validation: lint, typecheck, type tests, 189 unit tests, build, packed ESM/CJS/browser smoke, and Prettier pass. Throwaway viem 2.57.11 checks compile real inputs and match 40 offline signatures across mainnet/testnet and ESM/CJS. Public-only esbuild bundle: 298961/106079 bytes minified/gzip before, 301904/107064 after; no #112 optimization retained. --- README.md | 147 +++++++++++++++--- docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md | 180 ++++++++++++++--------- examples/Websocket/ws-public.ts | 13 +- package-lock.json | 4 +- package.json | 2 +- src/RestClient.ts | 145 ++++++++++++++---- src/WebsocketClient.ts | 18 ++- src/lib/action-builder.ts | 24 ++- src/lib/action-factory.ts | 12 +- src/lib/asset-resolver.ts | 3 +- src/lib/decimal.ts | 9 +- src/lib/request-utils.ts | 52 ++++++- src/lib/signing.ts | 95 +++++++++++- src/types/request/exchange.types.ts | 18 ++- src/types/request/info.types.ts | 2 + src/types/response/exchange.types.ts | 1 + src/types/response/info.types.ts | 60 +++++++- src/types/shared.types.ts | 45 +++++- src/types/websockets/ws-subscriptions.ts | 9 ++ test/unit/rest-exchange.test.ts | 5 +- test/unit/rest-info.test.ts | 17 ++- 21 files changed, 704 insertions(+), 157 deletions(-) diff --git a/README.md b/README.md index f6a701b..d58b341 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,8 @@ Take a look at our dedicated [HyperLiquid API quickstart guides for major framew - [REST API](#rest-api) - [Assets](#assets) -- [Custom Signer](#custom-signer) +- [Use a viem account, browser wallet or Privy/embedded wallet signer](#use-a-viem-account-browser-wallet-or-privyembedded-wallet-signer) +- [Nonces](#nonces) ## WebSocket Integration & Examples @@ -255,7 +256,7 @@ const postOnlyOrder = await client.submitLimitOrder({ `submitMarketOrder()` uses Hyperliquid's immediate-or-cancel market order mechanism. It loads the current midpoint, applies the requested maximum slippage, rounds the protection price to Hyperliquid's rules, rounds size down to the asset's supported precision, and submits an IOC order that cannot rest on the book. `maxSlippage` defaults to `0.05`, meaning 5%. Spot size is always the base asset quantity. -Both convenience methods support `clientOrderId` and `reduceOnly`. `submitMarketClose()` looks up the perpetual position, infers buy/sell from the signed size, and submits a reduce-only IOC order. Omit `size` to close the full position. `submitLimitOrder()` defaults to `timeInForce: 'GTC'`; use `'IOC'` for immediate-or-cancel or `postOnly: true` for add-liquidity-only behavior. Use `submitOrder()` when submitting batches, TP/SL orders, or other native wire shapes. +Both convenience methods support `clientOrderId` and `reduceOnly`. `submitMarketClose()` looks up the perpetual position, infers buy/sell from the signed size, and submits a reduce-only IOC order. Omit `size` to close the full position. `submitLimitOrder()` accepts `'GTC'`/`'Gtc'` (the default) and `'IOC'`/`'Ioc'` for immediate-or-cancel or `postOnly: true` for add-liquidity-only behavior. Use `submitOrder()` when submitting batches, TP/SL orders, or other native wire shapes. Prices, sizes, amounts, and trigger prices are exact decimal strings. JavaScript numbers are not accepted for decimal fields. @@ -320,27 +321,67 @@ Spot, HIP-3, and outcome asset IDs follow Hyperliquid's current offset rules. Th Balance responses keep Hyperliquid's token names. For example, SOL shown in the portfolio UI is currently returned as `USOL` by the API. -## Custom Signer +## Use a viem account, browser wallet or Privy/embedded wallet signer -You can provide an external signer instead of a private key: +Pass a viem local account or wallet client directly as `signer`; no adapter is needed. +Install viem in your application yourself. The SDK has no viem dependency. +Avoid viem **2.57.12–2.57.16**, which reject Hyperliquid's `HyperliquidTransaction:*` +EIP-712 type names; use 2.57.11 or 2.57.17 and later. + +For a server-side local account: ```ts -const client = new RestClient({ - signer: { - address: walletAddress, - signTypedData: (domain, types, value) => - walletClient.signTypedData({ - account: walletAddress, - domain, - types, - primaryType: Object.keys(types)[0], - message: value, - }), - }, +import { RestClient } from '@siebly/hyperliquid-api'; +import { privateKeyToAccount } from 'viem/accounts'; + +const key = process.env.HYPERLIQUID_PRIVATE_KEY; +if (!key) throw new Error('Set HYPERLIQUID_PRIVATE_KEY.'); +const account = privateKeyToAccount(key as `0x${string}`); +const client = new RestClient({ signer: account }); +``` + +For a browser wallet, create the wallet client with an account: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +// window.ethereum is supplied by the user's browser wallet. +const provider = window.ethereum; +if (!provider) throw new Error('Connect a browser wallet first.'); +const [address] = await provider.request({ method: 'eth_requestAccounts' }); +const walletClient = createWalletClient({ + account: address, + chain: arbitrum, + transport: custom(provider), }); +const client = new RestClient({ signer: walletClient }); ``` -The signer must expose `signTypedData`. It may also expose `address` or `getAddress()`. +For a Privy-style embedded wallet (using the wallet returned by your provider): + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +const provider = await embeddedWallet.getEthereumProvider(); +const walletClient = createWalletClient({ + account: embeddedWallet.address as `0x${string}`, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); +``` + +Wallet clients without an account fail at construction with a clear error. +Ethers wallets and custom signers using `signTypedData(domain, types, value)` +with `address` or `getAddress()` continue to work, as does `privateKey`. +The SDK selects the primary EIP-712 type for every action and normalizes viem inputs +once. The same inputs work in multisig `signers` arrays and `WebsocketAPIClient`. +Use `accountAddress` with an API wallet to identify the master account; transfers, +withdrawals, and other user-signed actions still require the account owner's signer. For an API wallet, pass the master account address to avoid an extra `userRole` lookup: @@ -359,7 +400,40 @@ const client = new RestClient({ If `accountAddress` is omitted, the first account getter or builder preflight resolves the API wallet's master address from `userRole`. Concurrent requests share the same lookup. -The nonce manager is shared by signer address across client instances. Supply `nonceProvider` when a process needs a different source of monotonic nonces. +## Nonces + +The default manager shares monotonic nonces by signer address across clients in the +same module instance. Each worker thread and process has its own manager. Workers +sharing a signer must coordinate through `nonceProvider`, or use a separate API +wallet per worker. See the [exchange nonce rules](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets). + +The SDK awaits `nonceProvider.nextNonce(lowerCaseSignerAddress)`. Return a non-negative +safe integer; otherwise it throws `RangeError` before sending. Your allocator must +allocate atomically across callers and keep nonces within the exchange's time window. +For example, delegate allocation to your own HTTP service: + +```ts +const client = new RestClient({ + signer: account, + nonceProvider: { + async nextNonce(signerAddress) { + const response = await fetch(process.env.NONCE_SERVICE_URL!, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ signerAddress }), + }); + if (!response.ok) throw new Error('Nonce allocation failed'); + const { nonce } = await response.json(); + return nonce; + }, + }, +}); +``` + +`L1ActionOptions.nonce` and `UserSignedActionOptions.nonce` override the provider for +one call; you must coordinate those values too. `invalidateNonce()` sends a signed +no-op to consume a nonce; it does not reset local allocation. A SharedArrayBuffer +manager is not included. ## WebSockets @@ -374,6 +448,35 @@ Connections open when first needed. Heartbeats, reconnection, resubscription, re ```ts import { WebsocketClient } from '@siebly/hyperliquid-api'; +const ws = new WebsocketClient(); +const prices: Record = {}; + +// A reconnect supplies a fresh snapshot; discard stale coins from the old cache. +ws.on('reconnected', () => { + for (const coin of Object.keys(prices)) delete prices[coin]; +}); +ws.on('message', (event) => { + if (event.channel !== 'fastAssetCtxs') return; + for (const [coin, ctx] of Object.entries(event.data)) { + prices[coin] = { ...prices[coin], ...ctx }; + } + console.log('BTC mark', prices.BTC?.markPx, 'mid', prices.BTC?.midPx); +}); +ws.on('exception', (error) => console.error(error)); +await ws.subscribe({ type: 'fastAssetCtxs' }); +``` + +The SDK decompresses `fastAssetCtxs` into `event.data`: the first message is a +snapshot, subsequent messages contain only changed coins and fields. Merge fields +per coin; `midPx: null` means no book mid. Reconnection supplies a fresh snapshot. +Hyperliquid recommends this feed instead of its deprecated upstream `allMids` +WebSocket feed; REST `getAllMids()` remains supported. + +For order books and account fills: + +```ts +import { WebsocketClient } from '@siebly/hyperliquid-api'; + const ws = new WebsocketClient(); ws.on('reconnected', ({ wsKey }) => { @@ -415,7 +518,11 @@ await ws.unsubscribe([book, fills]); ws.closeAll(); ``` -`subscribe()` and `unsubscribe()` manage topics independently of listeners and accept one topic or an array. The subscribe promise resolves after the socket opens and the request is sent; server acknowledgements emit through `response`. Incoming data emits once per wire message through `message`, preserving the upstream envelope and adding `wsKey`. +`subscribe()` and `unsubscribe()` manage topics independently of listeners and accept one topic or an array. Identical topics are merged; one unsubscribe removes the topic for all callers. `getActiveTopics(wsKey?)` returns a copy of cached topics (all connections when omitted). Reference counting is not provided. A rejected first subscribe leaves its topics cached for automatic retries. + +`l2Book` messages do not identify `nSigFigs` or `mantissa`; use separate clients for different groupings of one coin. `fast: true` sends 5 levels per side, compared with the default 20. Subscribe with `type: 'activeAssetCtx'` for both perps and spot, but listen for `channel: 'activeSpotAssetCtx'` for spot. There is no `activeSpotAssetCtx` subscription type. + +The subscribe promise resolves after the socket opens and the request is sent; server acknowledgements emit through `response`. Incoming data emits once per wire message through `message`, preserving the upstream envelope and adding `wsKey`. `fastAssetCtxs` payloads are decompressed inside the event's `data` field. User streams whose server events omit the user address use separate connections with a `user:
` key. Other streams share `public`. @@ -533,7 +640,7 @@ The npm package includes ES module and CommonJS builds. You do not need to build Use the [Vite guide](https://sieblyio.github.io/docs/hyperliquid/environments/vite.html) or [React guide](https://sieblyio.github.io/docs/hyperliquid/environments/react.html) for a complete public market-data project that imports `@siebly/hyperliquid-api` from npm. -The Vite example uses the package's browser entry points without extra bundler aliases or polyfills. These browser examples use public Hyperliquid REST data and WebSocket subscriptions. Keep private keys and API credentials in a secure server-side environment and make authenticated calls there. +The Vite example uses the package's browser entry points without extra bundler aliases or polyfills. These browser examples use public Hyperliquid REST data and WebSocket subscriptions. Keep raw private keys and API credentials server-side. Browser applications can sign through the connected wallet client shown above. Browser REST requests also depend on Hyperliquid's CORS policy. If a request is blocked, call the SDK through your application's server route instead. A development proxy does not solve CORS for a deployed application. diff --git a/docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md b/docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md index aa92bf5..77914c7 100644 --- a/docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md +++ b/docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md @@ -245,11 +245,11 @@ Hyperliquid uses one Info endpoint for market and account reads, one Exchange en `@siebly/hyperliquid-api` presents those surfaces through three clients: -| Client | Use it for | -| --- | --- | -| `RestClient` | Market data, account state, orders, transfers, staking, vaults, subaccounts, and other REST API operations | -| `WebsocketClient` | Public market-data and address-scoped account subscriptions | -| `WebsocketAPIClient` | The same awaitable Info and signed Exchange methods over Hyperliquid's WebSocket POST protocol | +| Client | Use it for | +| -------------------- | ---------------------------------------------------------------------------------------------------------- | +| `RestClient` | Market data, account state, orders, transfers, staking, vaults, subaccounts, and other REST API operations | +| `WebsocketClient` | Public market-data and address-scoped account subscriptions | +| `WebsocketAPIClient` | The same awaitable Info and signed Exchange methods over Hyperliquid's WebSocket POST protocol | `RestClient` also provides higher-level helpers such as `submitMarketOrder()`, `submitLimitOrder()`, `submitMarketClose()`, and `getBalances()`. Lower-level methods remain available for batching, TP/SL orders, transfers, vault operations, and other advanced workflows. @@ -290,19 +290,19 @@ Never put a private key in browser code, logs, or committed configuration. ## Hyperliquid products and request vocabulary -| Field or value | Example | Meaning | -| --- | --- | --- | -| Perpetual symbol | `BTC` | A perpetual market from `getPerpMetadata()` | -| Spot pair | `HYPE/USDC` | A readable Spot alias resolved from current metadata | -| Native Spot name | `PURR/USDC` or `@107` | The name used by HyperCore for a Spot pair | -| HIP-3 symbol | `dex:COIN` | A market on a HIP-3 perpetual DEX | -| Outcome asset | `#10` | An outcome-market identifier | -| `szDecimals` | `5` | The allowed number of decimal places in order size | -| `side` | `buy` or `sell` | The side accepted by the SDK's order helpers | -| `clientOrderId` | `0x` plus 32 hex characters | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id), called `cloid` by Hyperliquid | -| `accountAddress` | `HYPERLIQUID_ACCOUNT_ADDRESS` | The master account, subaccount, or vault whose state is queried | -| `vaultAddress` | `HYPERLIQUID_VAULT_ADDRESS` | Optional routing for actions signed on behalf of a vault or subaccount | -| `wsKey` | `public`, `api`, or `user:
` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) included with every emitted event | +| Field or value | Example | Meaning | +| ---------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------- | +| Perpetual symbol | `BTC` | A perpetual market from `getPerpMetadata()` | +| Spot pair | `HYPE/USDC` | A readable Spot alias resolved from current metadata | +| Native Spot name | `PURR/USDC` or `@107` | The name used by HyperCore for a Spot pair | +| HIP-3 symbol | `dex:COIN` | A market on a HIP-3 perpetual DEX | +| Outcome asset | `#10` | An outcome-market identifier | +| `szDecimals` | `5` | The allowed number of decimal places in order size | +| `side` | `buy` or `sell` | The side accepted by the SDK's order helpers | +| `clientOrderId` | `0x` plus 32 hex characters | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id), called `cloid` by Hyperliquid | +| `accountAddress` | `HYPERLIQUID_ACCOUNT_ADDRESS` | The master account, subaccount, or vault whose state is queried | +| `vaultAddress` | `HYPERLIQUID_VAULT_ADDRESS` | Optional routing for actions signed on behalf of a vault or subaccount | +| `wsKey` | `public`, `api`, or `user:
` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) included with every emitted event | Perpetual sizes are quantities of the underlying asset. Spot sizes are quantities of the base asset. Prices, sizes, transfer amounts, and trigger prices are exact decimal strings in SDK requests. @@ -519,6 +519,10 @@ Asset IDs differ across Mainnet and Testnet. Resolve them against the same netwo import { WebsocketClient } from '@siebly/hyperliquid-api'; const client = new WebsocketClient(); +const prices = {}; +client.on('reconnected', () => { + for (const coin of Object.keys(prices)) delete prices[coin]; +}); async function main() { client @@ -540,8 +544,11 @@ async function main() { client.on('message', ({ channel, data, wsKey }) => { switch (channel) { - case 'allMids': - console.log('BTC midpoint:', wsKey, data.mids.BTC); + case 'fastAssetCtxs': + for (const [coin, ctx] of Object.entries(data)) { + prices[coin] = { ...prices[coin], ...ctx }; + } + console.log('BTC midpoint:', wsKey, prices.BTC?.midPx); break; case 'l2Book': console.log('Best bid:', data.levels[0][0]); @@ -564,7 +571,7 @@ async function main() { try { await client.subscribe([ - { type: 'allMids' }, + { type: 'fastAssetCtxs' }, { type: 'l2Book', coin: 'BTC' }, { type: 'trades', coin: 'BTC' }, { type: 'candle', coin: 'BTC', interval: '1m' }, @@ -583,7 +590,7 @@ Register listeners before subscribing. Each incoming data message is emitted onc The promise returned by `subscribe()` resolves after the socket opens and the request is sent. It does not wait for the server acknowledgement, so do not use that promise alone as a stream-readiness signal. -Some channels send an initial snapshot before later updates. `l2Book` sends a current book, while `allMids`, trades, and candles continue with new values. The SDK sends regular heartbeat pings to check connection health. +Some channels send an initial snapshot before later updates. `fastAssetCtxs` sends a full snapshot, then only changed coins and fields: merge each coin into a cache. `midPx: null` means no book mid, and reconnects supply a fresh snapshot. `l2Book` sends a current book; trades and candles continue with new values. The upstream `allMids` WebSocket feed is deprecated; REST `getAllMids()` is unaffected. The SDK sends regular heartbeat pings to check connection health. `subscribe()` and `unsubscribe()` accept one topic or an array of topics. Equivalent topics are deduplicated by value. Listeners are independent of subscriptions: use `off('message', listener)` to remove a listener and `unsubscribe(topic)` to stop a stream. Call `client.closeAll()` when the application needs to close its WebSocket connections. @@ -1204,31 +1211,31 @@ An order-command response acknowledges the action and reports its immediate stat ### Market and account information -| Workflow | Representative methods | -| --- | --- | -| Perpetual markets | `getPerpMetadata()`, `getPerpAssetContexts()`, `getFundingHistory()`, `getPredictedFundingRates()` | -| Spot markets | `getSpotMetadata()`, `getSpotAssetContexts()`, `getTokenDetails()` | -| Books and trades | `getOrderBook()`, `getAllMids()`, `getCandles()`, `getRecentTrades()` | -| Orders and fills | `getOpenOrders()`, `getFrontendOpenOrders()`, `getOrderStatus()`, `getOrderHistory()`, `getUserFills()` | -| Account and risk | `getPerpAccountSummary()`, `getSpotBalances()`, `getPortfolio()`, `getUserFees()`, `getUserRateLimit()` | -| HIP-3 perpetual DEXs | `getPerpDexs()`, `getPerpDexStatus()`, `getPerpDexLimits()`, `getAllPerpMetadata()` | -| Outcome markets | `getOutcomeMetadata()`, `getSettledOutcome()` | -| Vaults and staking | `getVaultDetails()`, `getVaultSummaries()`, `getStakingSummary()`, `getStakingDelegations()` | -| Borrow and lend | `getAllBorrowLendReserveStates()`, `getBorrowLendReserveState()`, `getUserBorrowLendState()` | -| Subaccounts and signers | `getSubAccounts()`, `getExtraAgents()`, `getMultiSigSigners()`, `getUserRole()` | +| Workflow | Representative methods | +| ----------------------- | ------------------------------------------------------------------------------------------------------- | +| Perpetual markets | `getPerpMetadata()`, `getPerpAssetContexts()`, `getFundingHistory()`, `getPredictedFundingRates()` | +| Spot markets | `getSpotMetadata()`, `getSpotAssetContexts()`, `getTokenDetails()` | +| Books and trades | `getOrderBook()`, `getAllMids()`, `getCandles()`, `getRecentTrades()` | +| Orders and fills | `getOpenOrders()`, `getFrontendOpenOrders()`, `getOrderStatus()`, `getOrderHistory()`, `getUserFills()` | +| Account and risk | `getPerpAccountSummary()`, `getSpotBalances()`, `getPortfolio()`, `getUserFees()`, `getUserRateLimit()` | +| HIP-3 perpetual DEXs | `getPerpDexs()`, `getPerpDexStatus()`, `getPerpDexLimits()`, `getAllPerpMetadata()` | +| Outcome markets | `getOutcomeMetadata()`, `getSettledOutcome()`, `getOutcomeDeployerLimits()`, `submitUserOutcome()` | +| Vaults and staking | `getVaultDetails()`, `getVaultSummaries()`, `getStakingSummary()`, `getStakingDelegations()` | +| Borrow and lend | `getAllBorrowLendReserveStates()`, `getBorrowLendReserveState()`, `getUserBorrowLendState()` | +| Subaccounts and signers | `getSubAccounts()`, `getExtraAgents()`, `getMultiSigSigners()`, `getUserRole()` | ### Signed actions -| Workflow | Representative methods | -| --- | --- | -| Orders | `submitOrder()`, `submitMarketOrder()`, `submitLimitOrder()`, `modifyOrder()`, `cancelOrders()` | -| Position management | `submitMarketClose()`, `updateLeverage()`, `updateIsolatedMargin()`, `setIsolatedMarginLeverage()` | -| TWAP and safety | `submitTwapOrder()`, `cancelTwapOrder()`, `setCancelAllAfter()` | -| Transfers | `sendUsd()`, `sendSpotAsset()`, `sendAsset()`, `transferUsdBetweenSpotAndPerp()`, `withdrawUsd()` | -| Subaccounts and vaults | `createSubAccount()`, `transferUsdToOrFromSubAccount()`, `createVault()`, `transferVaultFunds()` | -| Staking | `depositIntoStaking()`, `withdrawFromStaking()`, `delegateOrUndelegateStake()`, `claimRewards()` | -| Account configuration | `approveApiWallet()`, `setUserPortfolioMargin()`, `setUserAbstraction()`, `setUserDexAbstraction()` | -| Advanced deployment | `deployPerp()`, `deploySpot()`, `submitUserOutcome()`, validator and multisig methods | +| Workflow | Representative methods | +| ---------------------- | --------------------------------------------------------------------------------------------------- | +| Orders | `submitOrder()`, `submitMarketOrder()`, `submitLimitOrder()`, `modifyOrder()`, `cancelOrders()` | +| Position management | `submitMarketClose()`, `updateLeverage()`, `updateIsolatedMargin()`, `setIsolatedMarginLeverage()` | +| TWAP and safety | `submitTwapOrder()`, `cancelTwapOrder()`, `setCancelAllAfter()` | +| Transfers | `sendUsd()`, `sendSpotAsset()`, `sendAsset()`, `transferUsdBetweenSpotAndPerp()`, `withdrawUsd()` | +| Subaccounts and vaults | `createSubAccount()`, `transferUsdToOrFromSubAccount()`, `createVault()`, `transferVaultFunds()` | +| Staking | `depositIntoStaking()`, `withdrawFromStaking()`, `delegateOrUndelegateStake()`, `claimRewards()` | +| Account configuration | `approveApiWallet()`, `setUserPortfolioMargin()`, `setUserAbstraction()`, `setUserDexAbstraction()` | +| Advanced deployment | `deployPerp()`, `deploySpot()`, `submitUserOutcome()`, validator and multisig methods | Use the focused [repository examples](../examples) and exported request types when moving beyond the workflows in this guide. Transfers, withdrawals, staking, account configuration, deployer operations, and multisig actions change funds or account settings, so confirm their current official requirements before using them. @@ -1266,32 +1273,67 @@ const client = new RestClient({ The signer still owns the nonce. A single API wallet used across several vaults or subaccounts shares one nonce set. Separate signers are easier to operate safely when those accounts trade concurrently. -### Custom signers +### Use a viem account, browser wallet or Privy/embedded wallet signer -`privateKey` is the simplest server-side option. Applications that keep keys in another wallet system can pass a signer with `signTypedData` instead: +Pass a viem local account or wallet client directly as `signer`; no adapter is needed. +Install viem in your application yourself. The SDK has no viem dependency. +Avoid viem **2.57.12–2.57.16**, which reject Hyperliquid's `HyperliquidTransaction:*` +EIP-712 type names; use 2.57.11 or 2.57.17 and later. -```javascript +For a server-side local account: + +```ts import { RestClient } from '@siebly/hyperliquid-api'; +import { privateKeyToAccount } from 'viem/accounts'; -export function createHyperliquidClient(walletClient, walletAddress) { - return new RestClient({ - accountAddress: walletAddress, - signer: { - address: walletAddress, - signTypedData: (domain, types, value) => - walletClient.signTypedData({ - account: walletAddress, - domain, - types, - primaryType: Object.keys(types)[0], - message: value, - }), - }, - }); -} +const key = process.env.HYPERLIQUID_PRIVATE_KEY; +if (!key) throw new Error('Set HYPERLIQUID_PRIVATE_KEY.'); +const account = privateKeyToAccount(key as `0x${string}`); +const client = new RestClient({ signer: account }); +``` + +For a browser wallet, create the wallet client with an account: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +// window.ethereum is supplied by the user's browser wallet. +const provider = window.ethereum; +if (!provider) throw new Error('Connect a browser wallet first.'); +const [address] = await provider.request({ method: 'eth_requestAccounts' }); +const walletClient = createWalletClient({ + account: address, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); +``` + +For a Privy-style embedded wallet (using the wallet returned by your provider): + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +const provider = await embeddedWallet.getEthereumProvider(); +const walletClient = createWalletClient({ + account: embeddedWallet.address as `0x${string}`, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); ``` -The signer may expose `address` or `getAddress()`. The SDK handles Hyperliquid's two signature schemes and required MessagePack field ordering. +Wallet clients without an account fail at construction with a clear error. +Ethers wallets and custom signers using `signTypedData(domain, types, value)` +with `address` or `getAddress()` continue to work, as does `privateKey`. +The SDK selects the primary EIP-712 type for every action and normalizes viem inputs +once. The same inputs work in multisig `signers` arrays and `WebsocketAPIClient`. +Use `accountAddress` with an API wallet to identify the master account; transfers, +withdrawals, and other user-signed actions still require the account owner's signer. ## Recover account state after a reconnect @@ -1406,9 +1448,9 @@ Here, `orderUpdates` uses `user:
` while `userFills` uses `public`, so e ## Choose Mainnet, Testnet, or custom API hosts -| Network | REST API host | WebSocket host | -| --- | --- | --- | -| Mainnet | `https://api.hyperliquid.xyz` | `wss://api.hyperliquid.xyz/ws` | +| Network | REST API host | WebSocket host | +| ------- | ------------------------------------- | -------------------------------------- | +| Mainnet | `https://api.hyperliquid.xyz` | `wss://api.hyperliquid.xyz/ws` | | Testnet | `https://api.hyperliquid-testnet.xyz` | `wss://api.hyperliquid-testnet.xyz/ws` | Mainnet is the default. Set `testnet: true` on every client that belongs to a Testnet workflow. @@ -1721,14 +1763,14 @@ Builder approval is optional. Call `approveBuilderFee()` only from a client conf - **Use a dead-man switch.** Refresh `setCancelAllAfter()` from a monitored process when unattended resting orders need automatic cancellation. - **Recover after gaps.** Rebuild the affected balances, positions, orders, and fills after a reconnect. - **Respect current limits.** Hyperliquid applies IP, address, open-order, connection, subscription, and in-flight request limits. Check the current [rate-limit documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits). -- **Keep keys server-side.** Browser use should be limited to public REST API calls and public-address WebSocket subscriptions. +- **Keep raw keys server-side.** Browser apps can use a connected browser or embedded wallet client as the signer; never bundle a raw private key. - **Monitor the route.** Track latency, reconnect frequency, and egress IP when using a proxy or custom endpoint. ## Frequently asked questions ### Can I use the SDK with plain JavaScript? -Yes. All examples in this guide are JavaScript. The package also includes TypeScript declarations. +Yes. Examples use JavaScript unless marked TypeScript. The package also includes TypeScript declarations. ### Which client should I start with? diff --git a/examples/Websocket/ws-public.ts b/examples/Websocket/ws-public.ts index 51f5cc4..99490c9 100644 --- a/examples/Websocket/ws-public.ts +++ b/examples/Websocket/ws-public.ts @@ -24,6 +24,8 @@ const wsClient = new WebsocketClient( logger, ); +const prices: Record = {}; + wsClient.on('open', (data) => { console.log('ws connection opened:', data.wsKey); }); @@ -33,6 +35,7 @@ wsClient.on('reconnecting', ({ wsKey }) => { }); wsClient.on('reconnected', (data) => { + for (const coin of Object.keys(prices)) delete prices[coin]; console.log('ws has reconnected ', data?.wsKey); }); @@ -50,8 +53,12 @@ wsClient.on('response', (event) => { wsClient.on('message', (event) => { switch (event.channel) { - case 'allMids': - console.log('allMids BTC:', event.data.mids.BTC); + case 'fastAssetCtxs': + // Snapshot first, then changed coins and fields only. null means no book mid. + for (const [coin, ctx] of Object.entries(event.data)) { + prices[coin] = { ...prices[coin], ...ctx }; + } + console.log('BTC:', prices.BTC); break; case 'l2Book': console.log( @@ -77,7 +84,7 @@ wsClient.on('message', (event) => { async function main() { try { await wsClient.subscribe([ - { type: 'allMids' }, + { type: 'fastAssetCtxs' }, { type: 'l2Book', coin: 'ETH' }, { type: 'trades', coin: 'BTC' }, { type: 'candle', coin: 'ETH', interval: '1m' }, diff --git a/package-lock.json b/package-lock.json index e074877..0ff9c1f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@siebly/hyperliquid-api", - "version": "1.0.5", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@siebly/hyperliquid-api", - "version": "1.0.5", + "version": "1.1.0", "license": "MIT", "dependencies": { "@msgpack/msgpack": "^3.1.2", diff --git a/package.json b/package.json index 840ab28..4a8a45e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@siebly/hyperliquid-api", - "version": "1.0.5", + "version": "1.1.0", "description": "Professional JavaScript & Node.js SDK for Hyperliquid's REST APIs and WebSockets, built in TypeScript with strong end to end tests.", "scripts": { "clean": "node scripts/clean.mjs", diff --git a/src/RestClient.ts b/src/RestClient.ts index 0bd6f41..8cb3926 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -10,6 +10,9 @@ import { marketLimitPrice, normalizeUserRequest, positiveDecimal, + validateCloid, + validateDestination, + validatePrice, } from './lib/request-utils.js'; import { USER_SIGNED_ACTIONS } from './lib/user-signed-actions.js'; import type { @@ -168,13 +171,14 @@ export class RestClient extends BaseRestClient { networkOptions: RestClientNetworkOptions = {}, ) { super( - options.baseUrl ?? + options.baseUrl?.trim() || (options.testnet === true ? TESTNET_API_URL : MAINNET_API_URL), options, networkOptions, ); } + /** Resolve metadata, including delisted markets; resolution does not imply tradability. */ resolveAsset(identifier: AssetIdentifier): Promise { return this.assetResolver.resolve(identifier); } @@ -195,7 +199,8 @@ export class RestClient extends BaseRestClient { * Mid prices for all coins (`allMids`). * * An empty book falls back to the last trade price. Spot mids are included - * only when `dex` is omitted or empty. + * only when `dex` is omitted or empty. HIP-3 mids require that DEX name in `dex`. + * Outcome sides appear under `#<10 * outcome + side>` coin names. */ getAllMids(params: { dex?: string } = {}): Promise { return this.info('allMids', params); @@ -224,7 +229,7 @@ export class RestClient extends BaseRestClient { * Metadata for every perp DEX (`allPerpMetas`). * * Each entry is one DEX: universe, margin tables, and collateral token. - * Index 0 is the default perp DEX. + * Index 0 is the default perp DEX. Entry i belongs to getPerpDexs()[i]. */ getAllPerpMetadata(): Promise { return this.info('allPerpMetas', {}); @@ -260,8 +265,10 @@ export class RestClient extends BaseRestClient { /** * Candle snapshot (`candleSnapshot`). * - * Only the most recent 5000 candles are available. HIP-3 coins use a - * `dex:COIN` name. + * Returns up to 5000 newest bars in the requested range, oldest first. + * Retention is roughly the latest 5000 bars per interval; an additional older + * page can be available. Page backwards with endTime = page[0].t - 1 until + * a short or empty page. HIP-3 coins use `dex:COIN`; outcomes use `#`. */ async getCandles(params: GetCandlesRequest): Promise { return this.info('candleSnapshot', { @@ -274,7 +281,8 @@ export class RestClient extends BaseRestClient { * * `assetPositions[].position.szi` is signed: positive is long, negative is short. * Under unified account or portfolio margin, use spot balances for the - * trading account balance across spot and perps. + * trading account balance across spot and perps. HIP-3 positions require + * the DEX name in `dex`; omitted means the default perp DEX. */ getPerpAccountSummary( params: AccountDexRequest = {}, @@ -329,6 +337,7 @@ export class RestClient extends BaseRestClient { /** * Open orders with trigger and reduce-only fields (`frontendOpenOrders`). * + * HIP-3 orders require that DEX name in `dex`; omitted means the default perp DEX. * Spot orders are included only for the first perp DEX. */ getFrontendOpenOrders( @@ -360,7 +369,10 @@ export class RestClient extends BaseRestClient { /** * Recent historical orders (`historicalOrders`). * - * Returns at most 2000 orders. `status` uses the same values as `getOrderStatus()`. + * Returns at most 2000 status-change rows, newest first. An order can appear + * several times; the first row for an oid is its latest status. There is no + * time-range option; retain your own history to extend this window. + * `status` uses the same values as `getOrderStatus()`. */ getOrderHistory(params: AccountRequest = {}): Promise { return this.accountInfo('historicalOrders', params); @@ -375,14 +387,17 @@ export class RestClient extends BaseRestClient { * * At most 20 levels per side. `nSigFigs` aggregates prices. `mantissa` is * only valid when `nSigFigs` is 5. + * @throws RangeError for unknown or incorrectly cased coins, or a missing book. */ - async getOrderBook( - params: GetOrderBookRequest, - ): Promise { - return this.info('l2Book', { + async getOrderBook(params: GetOrderBookRequest): Promise { + const book = await this.info('l2Book', { ...params, coin: await this.nameToCoin(params.coin), }); + if (book === null) { + throw new RangeError(`No order book exists for "${params.coin}".`); + } + return book; } getLeadingVaults(params: AccountRequest = {}): Promise { @@ -439,6 +454,7 @@ export class RestClient extends BaseRestClient { /** * Open orders (`openOrders`). * + * HIP-3 orders require that DEX name in `dex`; omitted means the default perp DEX. * Spot orders are included only for the first perp DEX. `side` `"B"` is bid * and `"A"` is ask. */ @@ -448,12 +464,26 @@ export class RestClient extends BaseRestClient { /** * Order status by order id or client order id (`orderStatus`). + * Decimal-digit strings are converted to safe integers; cloids use 0x plus + * 32 hex characters. Invalid or unsafe IDs throw RangeError before the request. * * `status: "unknownOid"` means the order was not found. Otherwise * `status` is `"order"` and `order.status` is the order state. */ getOrderStatus(params: GetOrderStatusRequest): Promise { - return this.accountInfo('orderStatus', params); + const oid = + typeof params.oid === 'string' && /^\d+$/.test(params.oid) + ? Number(params.oid) + : params.oid; + if ( + !(typeof oid === 'number' && Number.isSafeInteger(oid) && oid >= 0) && + !(typeof oid === 'string' && /^0x[0-9a-fA-F]{32}$/.test(oid)) + ) { + throw new RangeError( + 'oid must be a non-negative safe integer, a decimal-digit string representing one, or a 0x-prefixed 32-hex-character cloid.', + ); + } + return this.accountInfo('orderStatus', { ...params, oid }); } /** @@ -566,7 +596,7 @@ export class RestClient extends BaseRestClient { * * Only the first perp DEX is supported. Each entry is `[coin, venues]`, * and each venue is `[venue, quote]`. `quote` is `null` when that venue - * has no predicted rate. + * has no predicted rate. Delisted coins are included. */ getPredictedFundingRates(): Promise { return this.info('predictedFundings', {}); @@ -598,6 +628,11 @@ export class RestClient extends BaseRestClient { return this.info('settledOutcome', params); } + /** + * Returns perp and spot balances side by side, without querying the account mode. + * Under unified account or portfolio margin, spot holds the trading balance + * across both. Use getUserAbstraction() to interpret the account mode. + */ async getBalances( params: AccountDexRequest = {}, ): Promise { @@ -617,7 +652,7 @@ export class RestClient extends BaseRestClient { * Spot token balances (`spotClearinghouseState`). * * Under unified account or portfolio margin, this is the trading-account - * balance across spot and perps. + * balance across spot and perps. Portfolio margin can report negative total/hold. */ getSpotBalances(params: AccountRequest = {}): Promise { return this.accountInfo('spotClearinghouseState', params); @@ -644,6 +679,7 @@ export class RestClient extends BaseRestClient { * * The tuple is `[meta, contexts]`. Contexts include mark price, volume, * and supply. `midPx` is `null` when there is no mid. + * Outcome sides appear under `#<10 * outcome + side>` coin names. */ getSpotAssetContexts(): Promise { return this.info('spotMetaAndAssetCtxs', {}); @@ -749,6 +785,9 @@ export class RestClient extends BaseRestClient { * * `startTime` is inclusive, in milliseconds. `endTime` defaults to now. * Read `delta.type` to see which delta fields are set. + * Pages contain up to 2000 rows, oldest first from startTime. The exchange + * documents startTime as required. If omitted, observed responses contain + * the newest 2000 rows in reverse order; do not page by their last time. */ getUserNonFundingLedgerUpdates( params: GetUserNonFundingLedgerUpdatesRequest = {}, @@ -798,7 +837,9 @@ export class RestClient extends BaseRestClient { } /** - * Vault equity for this user (`userVaultEquities`). + * One row per vault for this user (`userVaultEquities`). Equity is a decimal + * string; lockedUntilTimestamp is the withdrawal unlock time in milliseconds + * (the same value as vaultDetails.followerState.lockupUntil). */ getUserVaultDeposits( params: AccountRequest = {}, @@ -845,7 +886,8 @@ export class RestClient extends BaseRestClient { * Place one or more orders (`order`). * * Each status is `resting`, `filled`, or `error`. The request can succeed - * while an individual order is rejected. + * while an individual order is rejected. Statuses usually has one entry per + * order; a pre-validation error can return a single entry for the entire batch. */ async submitOrder( params: SubmitOrderRequest, @@ -867,6 +909,8 @@ export class RestClient extends BaseRestClient { params: SubmitMarketOrderRequest, options: L1RequestOptions = {}, ): Promise> { + if (params.clientOrderId !== undefined) + validateCloid(params.clientOrderId, 'clientOrderId'); const maxSlippage = params.maxSlippage ?? DEFAULT_MARKET_ORDER_SLIPPAGE; if (!Number.isFinite(maxSlippage) || maxSlippage < 0 || maxSlippage >= 1) { throw new RangeError('maxSlippage must be at least 0 and less than 1.'); @@ -880,6 +924,7 @@ export class RestClient extends BaseRestClient { ); } + if (params.price !== undefined) validatePrice(params.price, 'price', asset); const dex = hip3Dex(asset.canonicalName); const mid = params.price ?? @@ -960,29 +1005,37 @@ export class RestClient extends BaseRestClient { /** * Place a limit order (`order`). * - * `postOnly` sends ALO. `timeInForce: "IOC"` sends IOC. Otherwise the order is GTC. + * `postOnly` sends ALO. `timeInForce: "IOC"` or "Ioc" sends IOC; "GTC" and + * "Gtc" send GTC. Prices violating known asset precision throw RangeError + * before signing; prices are never rounded. */ async submitLimitOrder( params: SubmitLimitOrderRequest, options: L1RequestOptions = {}, ): Promise> { + if (params.clientOrderId !== undefined) + validateCloid(params.clientOrderId, 'clientOrderId'); + positiveDecimal(params.price, 'price'); + positiveDecimal(params.size, 'size'); + const asset = await this.resolveAsset(params.symbol); + const price = validatePrice(params.price, 'price', asset); return this.submitOrder( { orders: [ { - a: params.symbol, + a: asset.assetId, b: params.side === 'buy', ...(params.clientOrderId === undefined ? {} : { c: params.clientOrderId }), - p: positiveDecimal(params.price, 'price'), + p: price, r: params.reduceOnly ?? false, s: positiveDecimal(params.size, 'size'), t: { limit: { tif: params.postOnly ? 'Alo' - : params.timeInForce === 'IOC' + : params.timeInForce?.toUpperCase() === 'IOC' ? 'Ioc' : 'Gtc', }, @@ -1018,7 +1071,8 @@ export class RestClient extends BaseRestClient { * Modify multiple resting orders (`batchModify`). * * Statuses match `submitOrder()`. `alwaysPlace` has the same meaning as - * on `modifyOrder()`. + * on `modifyOrder()`. A pre-validation error can return a single status for + * the entire batch, rather than one per order. oid is a number or a cloid. */ async modifyOrders( params: ModifyOrdersRequest, @@ -1164,6 +1218,11 @@ export class RestClient extends BaseRestClient { params: { time?: number } = {}, options: L1RequestOptions = {}, ): Promise { + if (params.time !== undefined && params.time < Date.now() + 5000) { + throw new RangeError( + 'time must be at least 5000 milliseconds in the future.', + ); + } return this.l1('scheduleCancel', params, options); } @@ -1184,6 +1243,7 @@ export class RestClient extends BaseRestClient { * Approve the configured builder fee (`approveBuilderFee`). * * `maxFeeRate` is a percent string such as `"0.001%"`. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ async approveBuilderFee( options: UserSignedRequestOptions = {}, @@ -1210,6 +1270,7 @@ export class RestClient extends BaseRestClient { * An account can have one unnamed agent and up to three named agents. * Append `valid_until {timestamp}` to the name to set an expiration, * at most 180 days ahead. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ approveApiWallet( params: ApproveApiWalletRequest, @@ -1230,14 +1291,17 @@ export class RestClient extends BaseRestClient { * Send USDC to another address on HyperCore (`usdSend`). * * This does not touch the EVM bridge. `expiresAfter` is not supported. + * Ledger rows can be internalTransfer or send with both DEX names empty. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendUsd( params: SendUsdRequest, options: UserSignedRequestOptions = {}, ): Promise { + validateDestination(params.destination); return this.userSigned( 'usdSend', - { ...params, amount: decimalToWire(params.amount), time: 0 }, + { ...params, amount: positiveDecimal(params.amount, 'amount'), time: 0 }, USER_SIGNED_ACTIONS.usdSend, options, ); @@ -1247,14 +1311,17 @@ export class RestClient extends BaseRestClient { * Send a spot token to another address on HyperCore (`spotSend`). * * This does not touch the EVM bridge. `token` is `name:tokenId`. + * Ledger rows can be spotTransfer or send with both DEX names "spot". + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendSpotAsset( params: SendSpotAssetRequest, options: UserSignedRequestOptions = {}, ): Promise { + validateDestination(params.destination); return this.userSigned( 'spotSend', - { ...params, amount: decimalToWire(params.amount), time: 0 }, + { ...params, amount: positiveDecimal(params.amount, 'amount'), time: 0 }, USER_SIGNED_ACTIONS.spotSend, options, ); @@ -1262,14 +1329,17 @@ export class RestClient extends BaseRestClient { /** * Start a USDC withdrawal to the bridge (`withdraw3`). + * The ledger row is withdraw and does not include the destination. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ withdrawUsd( params: WithdrawUsdRequest, options: UserSignedRequestOptions = {}, ): Promise { + validateDestination(params.destination); return this.userSigned( 'withdraw3', - { ...params, amount: decimalToWire(params.amount), time: 0 }, + { ...params, amount: positiveDecimal(params.amount, 'amount'), time: 0 }, USER_SIGNED_ACTIONS.withdraw, options, ); @@ -1278,7 +1348,8 @@ export class RestClient extends BaseRestClient { /** * Move USDC between spot and perp (`usdClassTransfer`). * - * `toPerp: true` sends spot to perp. + * `toPerp: true` sends spot to perp. For API wallets, use sendAssetFromApiWallet(). + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ transferUsdBetweenSpotAndPerp( params: TransferUsdBetweenSpotAndPerpRequest, @@ -1297,16 +1368,19 @@ export class RestClient extends BaseRestClient { * * Use `""` for the default USDC perp DEX and `"spot"` for spot. * Only the collateral token can move to or from a perp DEX. + * For API wallets, use sendAssetFromApiWallet(). + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendAsset( params: SendAssetRequest, options: UserSignedRequestOptions = {}, ): Promise { + validateDestination(params.destination); return this.userSigned( 'sendAsset', { ...params, - amount: decimalToWire(params.amount), + amount: positiveDecimal(params.amount, 'amount'), fromSubAccount: params.fromSubAccount ?? '', }, USER_SIGNED_ACTIONS.sendAsset, @@ -1318,6 +1392,7 @@ export class RestClient extends BaseRestClient { * Send tokens from Core to EVM with calldata (`sendToEvmWithData`). * * The linked contract must implement `coreReceiveWithData`. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendToEvmWithData( params: SendToEvmWithDataRequest, @@ -1356,6 +1431,7 @@ export class RestClient extends BaseRestClient { * Move native token from spot into staking (`cDeposit`). * * `wei` is the amount in wei. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ depositIntoStaking( params: { wei: number }, @@ -1373,6 +1449,7 @@ export class RestClient extends BaseRestClient { * Move native token from staking back to spot (`cWithdraw`). * * The transfer waits in a 7-day unstaking queue. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ withdrawFromStaking( params: { wei: number }, @@ -1390,6 +1467,7 @@ export class RestClient extends BaseRestClient { * Delegate or undelegate stake to a validator (`tokenDelegate`). * * A delegation to one validator locks for 1 day. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ delegateOrUndelegateStake( params: DelegateOrUndelegateStakeRequest, @@ -1403,6 +1481,9 @@ export class RestClient extends BaseRestClient { ); } + /** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ convertToMultiSigUser( params: ConvertToMultiSigUserRequest, options: UserSignedRequestOptions = {}, @@ -1426,6 +1507,9 @@ export class RestClient extends BaseRestClient { ); } + /** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ linkStakingAccount( params: LinkStakingAccountRequest, options: UserSignedRequestOptions = {}, @@ -1438,6 +1522,9 @@ export class RestClient extends BaseRestClient { ); } + /** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ disableStakingTradingLink( params: { tradingUser: string }, options: UserSignedRequestOptions = {}, @@ -1450,6 +1537,9 @@ export class RestClient extends BaseRestClient { ); } + /** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ setUserPortfolioMargin( params: UserToggleRequest, options: UserSignedRequestOptions = {}, @@ -1466,6 +1556,8 @@ export class RestClient extends BaseRestClient { * Set account abstraction (`userSetAbstraction`). * * `abstraction` is `"disabled"`, `"unifiedAccount"`, or `"portfolioMargin"`. + * `user` is required; it is not filled from the signer or accountAddress. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ setUserAbstraction( params: SetUserAbstractionRequest, @@ -1663,6 +1755,7 @@ export class RestClient extends BaseRestClient { ); } + /** Transfer USDC in integer micro-units: 1 USDC = 1_000_000 usd. */ transferUsdToOrFromSubAccount( params: TransferUsdToOrFromSubAccountRequest, options: L1RequestOptions = {}, diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index fb1f73a..60eeaae 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -163,6 +163,10 @@ export class WebsocketClient extends BaseWebsocketClient< * Topics are cached before connecting and restored automatically after reconnect. * The promise confirms local sending; server acknowledgements emit 'response'. * Resolve display aliases explicitly with nameToCoin() when needed. + * Identical topics are merged; one unsubscribe removes the topic for all callers. + * Subscribe to activeAssetCtx for both perps and spot; spot messages arrive + * on activeSpotAssetCtx (which is not a subscription type). + * A rejected first subscribe still leaves the topic cached for automatic retries. */ async subscribe( subscriptions: WebsocketSubscription | readonly WebsocketSubscription[], @@ -175,7 +179,10 @@ export class WebsocketClient extends BaseWebsocketClient< ); } - /** Remove cached topics independently of event listeners, including while disconnected. */ + /** + * Remove cached topics independently of event listeners, including while disconnected. + * Identical topics are merged; one unsubscribe removes the topic for all callers. + */ async unsubscribe( subscriptions: WebsocketSubscription | readonly WebsocketSubscription[], ): Promise { @@ -187,6 +194,15 @@ export class WebsocketClient extends BaseWebsocketClient< ); } + /** Copy of cached topics to restore on reconnect; omit wsKey to include every connection. */ + getActiveTopics(wsKey?: WsKey): readonly Readonly[] { + const store = this.getWsStore(); + const keys = wsKey === undefined ? store.getKeys() : [wsKey]; + return keys.flatMap((key) => + store.getTopics(key).map((topic) => ({ ...topic })), + ); + } + async sendWSAPIRequest( endpoint: 'action' | 'info', body: unknown, diff --git a/src/lib/action-builder.ts b/src/lib/action-builder.ts index d6446cc..15f3588 100644 --- a/src/lib/action-builder.ts +++ b/src/lib/action-builder.ts @@ -1,6 +1,7 @@ import type { ExchangeRequestEnvelope, HyperliquidSigner, + HyperliquidSignerInput, JsonObject, L1ActionOptions, NonceProvider, @@ -24,6 +25,7 @@ import { signMultiSigL1Action, signMultiSigUserSignedAction, signUserSignedAction, + toHyperliquidSigner, } from './signing.js'; import { sanitizeObjectForWire } from './wire.js'; @@ -55,7 +57,9 @@ export class ActionBuilder { this.signer = options.privateKey !== undefined ? createPrivateKeySigner(options.privateKey) - : options.signer; + : options.signer + ? toHyperliquidSigner(options.signer) + : undefined; this.configuredAccountAddress = options.accountAddress ? normalizeAddress(options.accountAddress) : undefined; @@ -158,11 +162,18 @@ export class ActionBuilder { async prepareMultiSigL1Action( action: JsonObject, - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]], + signerInputs: readonly [ + HyperliquidSignerInput, + ...HyperliquidSignerInput[], + ], multiSigUser: string, options: L1ActionOptions = {}, ): Promise> { this.partnerConfiguration(); + const signers = signerInputs.map(toHyperliquidSigner) as [ + HyperliquidSigner, + ...HyperliquidSigner[], + ]; const signerAddress = await getSignerAddress(signers[0]); const nonce = options.nonce ?? (await getNextNonce(this.nonceProvider, signerAddress)); @@ -198,11 +209,18 @@ export class ActionBuilder { async prepareMultiSigUserSignedAction( action: JsonObject, definition: UserSignedActionDefinition, - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]], + signerInputs: readonly [ + HyperliquidSignerInput, + ...HyperliquidSignerInput[], + ], multiSigUser: string, options: UserSignedActionOptions = {}, ): Promise> { this.partnerConfiguration(); + const signers = signerInputs.map(toHyperliquidSigner) as [ + HyperliquidSigner, + ...HyperliquidSigner[], + ]; const signerAddress = await getSignerAddress(signers[0]); const nonce = options.nonce ?? (await getNextNonce(this.nonceProvider, signerAddress)); diff --git a/src/lib/action-factory.ts b/src/lib/action-factory.ts index 4008562..1ff7175 100644 --- a/src/lib/action-factory.ts +++ b/src/lib/action-factory.ts @@ -2,6 +2,7 @@ import type { BuilderCode, JsonObject } from '../types/shared.types.js'; import type { AssetResolver } from './asset-resolver.js'; import { decimalToWire } from './decimal.js'; import { normalizeAddresses } from './normalize-addresses.js'; +import { validateCloid } from './request-utils.js'; import { sanitizeObjectForWire } from './wire.js'; export type AssetIdentifier = number | string; @@ -26,6 +27,7 @@ export type Grouping = 'na' | 'normalTpsl' | 'positionTpsl' | { p: number }; export interface OrderWireInput { a: AssetIdentifier; b: boolean; + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ c?: string; p: string; r: boolean; @@ -36,6 +38,7 @@ export interface OrderWireInput { export interface OrderWire { a: number; b: boolean; + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ c?: string; p: string; r: boolean; @@ -44,6 +47,7 @@ export interface OrderWire { } export interface ModifyWireInput { + /** Order ID (number) or client order ID (0x followed by 32 hex characters). */ oid: number | string; order: OrderWireInput; } @@ -55,6 +59,7 @@ export interface CancelWireInput { export interface CancelByCloidWireInput { asset: AssetIdentifier; + /** 0x followed by 32 hex characters (128 bits). */ cloid: string; } @@ -200,6 +205,7 @@ function normalizeExistingOrderWire(value: unknown): JsonObject { ); } + if (value.c !== undefined) validateCloid(value.c, 'c'); const normalized: JsonObject = { ...value, p: decimalToWire(value.p), @@ -488,7 +494,7 @@ export class ActionFactory { cancels: await Promise.all( cancels.map(async (cancel) => ({ asset: (await this.assetResolver.resolve(cancel.asset)).assetId, - cloid: cancel.cloid, + cloid: validateCloid(cancel.cloid, 'cloid'), })), ), ...(fastCancel ? { f: true } : {}), @@ -626,7 +632,7 @@ export class ActionFactory { return { asset: (await this.assetResolver.resolve(cancel.asset)).assetId, - cloid: cancel.cloid, + cloid: validateCloid(cancel.cloid, 'cloid'), }; }), ); @@ -692,7 +698,7 @@ export class ActionFactory { }; if (order.c !== undefined) { - wire.c = order.c; + wire.c = validateCloid(order.c, 'c'); } return wire; diff --git a/src/lib/asset-resolver.ts b/src/lib/asset-resolver.ts index 0f3072f..0f85435 100644 --- a/src/lib/asset-resolver.ts +++ b/src/lib/asset-resolver.ts @@ -155,11 +155,12 @@ export class AssetResolver { // Official Python Info.name_to_coin: exact dict lookup, no case folding. async nameToCoin(name: string): Promise { + if (/^#\d+$/.test(name)) return name; await this.ensureLoaded(); const resolved = this.aliases.get(name); if (!resolved) { throw new RangeError( - `Unknown Hyperliquid asset "${name}". Call refreshAssetMetadata() after a new listing.`, + `Unknown Hyperliquid asset "${name}". Coin names are case-sensitive; try the upper-case symbol. Call refreshAssetMetadata() after a new listing.`, ); } return resolved.canonicalName; diff --git a/src/lib/decimal.ts b/src/lib/decimal.ts index 9506630..e1a383e 100644 --- a/src/lib/decimal.ts +++ b/src/lib/decimal.ts @@ -35,15 +35,10 @@ export function decimalToScaledInteger( ); } - const scaled = - BigInt(integer) * 10n ** BigInt(decimalPlaces) + - BigInt(fraction.padEnd(decimalPlaces, '0') || '0'); + const scaled = Number(`${integer}${fraction.padEnd(decimalPlaces, '0')}`); const signed = negative ? -scaled : scaled; - if ( - signed > BigInt(Number.MAX_SAFE_INTEGER) || - signed < BigInt(Number.MIN_SAFE_INTEGER) - ) { + if (!Number.isSafeInteger(signed)) { throw new RangeError( `${value} cannot be represented safely as a scaled JavaScript integer.`, ); diff --git a/src/lib/request-utils.ts b/src/lib/request-utils.ts index f30ff0b..498d545 100644 --- a/src/lib/request-utils.ts +++ b/src/lib/request-utils.ts @@ -24,15 +24,21 @@ export function buildUserSignedAction( } export function decimalOrSubaccountAmount(value: string): string { + if (typeof value !== 'string') { + throw new TypeError('amount must be a string.'); + } const match = /^(.+?)\s+subaccount:(0x[0-9a-fA-F]{40})$/.exec(value); if (!match) { - return decimalToWire(value); + return positiveDecimal(value, 'amount'); } - return `${decimalToWire(match[1])} subaccount:${normalizeAddresses(match[2])}`; + return `${positiveDecimal(match[1], 'amount')} subaccount:${normalizeAddresses(match[2])}`; } export function positiveDecimal(value: string, field: string): string { + if (field === 'amount' && typeof value !== 'string') { + throw new TypeError(`${field} must be a string.`); + } const normalized = decimalToWire(value); if (normalized === '0' || normalized.startsWith('-')) { throw new RangeError(`${field} must be greater than zero.`); @@ -40,6 +46,48 @@ export function positiveDecimal(value: string, field: string): string { return normalized; } +export function validateDestination(value: string): string { + if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(value)) { + throw new TypeError( + 'destination must be 0x followed by 40 hex characters.', + ); + } + return value; +} + +export function validateCloid(value: unknown, field: string): string { + if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{32}$/.test(value)) { + throw new TypeError( + `${field} must be 0x followed by 32 hex characters (128 bits).`, + ); + } + return value; +} + +/** Validate without rounding. Numeric asset IDs may have no precision metadata. */ +export function validatePrice( + value: string, + field: string, + asset: ResolvedAsset, +): string { + const normalized = positiveDecimal(value, field); + if (asset.szDecimals === undefined) return normalized; + const [integer, fraction = ''] = normalized.split('.'); + const maxDecimals = + (asset.kind === 'spot' || asset.kind === 'outcome' ? 8 : 6) - + asset.szDecimals; + const significantFigures = `${integer}${fraction}`.replace(/^0+/, '').length; + if ( + fraction.length && + (fraction.length > maxDecimals || significantFigures > 5) + ) { + throw new RangeError( + `${field} "${value}" allows at most 5 significant figures and ${maxDecimals} decimal places; integer prices are always allowed.`, + ); + } + return normalized; +} + export function floorDecimalPlaces( value: string, decimalPlaces: number, diff --git a/src/lib/signing.ts b/src/lib/signing.ts index d0a403b..8ec36c8 100644 --- a/src/lib/signing.ts +++ b/src/lib/signing.ts @@ -14,10 +14,14 @@ import { } from '../constants.js'; import type { HyperliquidSigner, + HyperliquidSignerInput, JsonObject, Signature, + TypedDataDomain, TypedDataField, TypedDataTypes, + ViemLocalAccountLike, + ViemWalletClientLike, } from '../types/shared.types.js'; const AGENT_TYPES: TypedDataField[] = [ @@ -29,6 +33,81 @@ export function createPrivateKeySigner(privateKey: string): HyperliquidSigner { return new Wallet(privateKey); } +type SignWithPrimaryType = ( + domain: TypedDataDomain, + types: TypedDataTypes, + message: Record, + primaryType?: string, +) => Promise; + +const viemSigners = new WeakMap(); + +function signTypedData( + signer: HyperliquidSigner, + domain: TypedDataDomain, + types: TypedDataTypes, + value: Record, + primaryType: string, +): Promise { + const sign = viemSigners.get(signer); + return sign + ? sign(domain, types, value, primaryType) + : signer.signTypedData(domain, types, value); +} + +/** Normalize external inputs once; signing remains on the positional contract. */ +export function toHyperliquidSigner( + input: HyperliquidSignerInput, +): HyperliquidSigner { + if ( + !('type' in input) || + (input.type !== 'local' && input.type !== 'walletClient') + ) { + return input as HyperliquidSigner; + } + const local = + input.type === 'local' ? (input as ViemLocalAccountLike) : undefined; + const wallet = + input.type === 'walletClient' ? (input as ViemWalletClientLike) : undefined; + const account = wallet?.account; + if (wallet && !account) { + throw new TypeError( + 'Create the viem wallet client with an account before passing it as signer.', + ); + } + const sign: SignWithPrimaryType = async ( + domain, + types, + message, + primaryType, + ) => { + if (!primaryType) { + throw new TypeError('A viem signature requires an explicit primaryType.'); + } + const params = { + domain: { + ...domain, + chainId: Number(domain.chainId), + verifyingContract: domain.verifyingContract as `0x${string}`, + }, + types: Object.fromEntries( + Object.entries(types).filter(([name]) => name !== 'EIP712Domain'), + ), + primaryType, + message, + }; + return local + ? local.signTypedData(params) + : wallet!.signTypedData({ ...params, account: account! }); + }; + const signer: HyperliquidSigner = { + address: local ? local.address : account!.address, + signTypedData: sign, + }; + viemSigners.set(signer, sign); + return signer; +} + export function normalizeAddress(address: string): string { const normalizedPrefix = address.startsWith('0X') ? `0x${address.slice(2)}` @@ -60,7 +139,9 @@ function uint64ToBytes(value: number): Uint8Array { } const bytes = new Uint8Array(8); - new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false); + const view = new DataView(bytes.buffer); + view.setUint32(0, Math.floor(value / 0x100000000), false); + view.setUint32(4, value % 0x100000000, false); return bytes; } @@ -132,7 +213,8 @@ export async function signL1Action( isMainnet: boolean, ): Promise { const connectionId = actionHash(action, vaultAddress, nonce, expiresAfter); - const signature = await signer.signTypedData( + const signature = await signTypedData( + signer, { chainId: L1_SIGNATURE_CHAIN_ID, name: 'Exchange', @@ -144,6 +226,7 @@ export async function signL1Action( source: isMainnet ? 'a' : 'b', connectionId, }, + 'Agent', ); return splitSignature(signature); @@ -173,7 +256,8 @@ async function signMultiSigOuter( nonce, expiresAfter, ); - const signature = await leader.signTypedData( + const signature = await signTypedData( + leader, { chainId: Number.parseInt(USER_SIGNED_SIGNATURE_CHAIN_ID, 16), name: 'HyperliquidSignTransaction', @@ -192,6 +276,7 @@ async function signMultiSigOuter( multiSigActionHash, nonce, }, + 'HyperliquidTransaction:SendMultiSig', ); return splitSignature(signature); @@ -364,7 +449,8 @@ export async function signUserSignedAction( const types: TypedDataTypes = { [primaryType]: preparedTypes, }; - const signature = await signer.signTypedData( + const signature = await signTypedData( + signer, { chainId: Number.parseInt(USER_SIGNED_SIGNATURE_CHAIN_ID, 16), name: 'HyperliquidSignTransaction', @@ -373,6 +459,7 @@ export async function signUserSignedAction( }, types, preparedAction, + primaryType, ); return { diff --git a/src/types/request/exchange.types.ts b/src/types/request/exchange.types.ts index d5d1cb5..859c920 100644 --- a/src/types/request/exchange.types.ts +++ b/src/types/request/exchange.types.ts @@ -7,7 +7,7 @@ import type { OrderWireInput, } from '../../lib/action-factory.js'; import type { - HyperliquidSigner, + HyperliquidSignerInput, JsonObject, L1ActionOptions, UserSignedActionOptions, @@ -20,12 +20,12 @@ export type RawUserSignedRequestOptions = UserSignedActionOptions; export interface MultiSigL1RequestOptions extends RawL1RequestOptions { multiSigUser: string; - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]]; + signers: readonly [HyperliquidSignerInput, ...HyperliquidSignerInput[]]; } export interface MultiSigUserSignedRequestOptions extends RawUserSignedRequestOptions { multiSigUser: string; - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]]; + signers: readonly [HyperliquidSignerInput, ...HyperliquidSignerInput[]]; } export interface SubmitOrderRequest { @@ -36,6 +36,7 @@ export interface SubmitOrderRequest { export type OrderSide = 'buy' | 'sell'; export interface SubmitMarketOrderRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; maxSlippage?: number; price?: string; @@ -46,6 +47,7 @@ export interface SubmitMarketOrderRequest { } export interface SubmitMarketCloseRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; maxSlippage?: number; price?: string; @@ -54,6 +56,7 @@ export interface SubmitMarketCloseRequest { } export interface SubmitLimitOrderRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; postOnly?: boolean; price: string; @@ -61,7 +64,7 @@ export interface SubmitLimitOrderRequest { side: OrderSide; size: string; symbol: AssetIdentifier; - timeInForce?: 'GTC' | 'IOC'; + timeInForce?: 'GTC' | 'IOC' | 'Gtc' | 'Ioc'; } export interface ModifyOrderRequest extends ModifyWireInput { @@ -128,6 +131,7 @@ export interface SubmitTrailingStopRequest { export interface TransferUsdToOrFromSubAccountRequest { isDeposit: boolean; subAccountUser: string; + /** Integer micro-USDC: 1 USDC = 1_000_000. */ usd: number; } @@ -217,4 +221,8 @@ export interface SetUserAbstractionRequest { export type DeployPerpRequest = Omit; export type DeploySpotRequest = Omit; -export type SubmitUserOutcomeRequest = Omit; +export type SubmitUserOutcomeRequest = + | { splitOutcome: { outcome: number; amount: string } } + | { mergeOutcome: { outcome: number; amount: string | null } } + | { mergeQuestion: { question: number; amount: string | null } } + | { negateOutcome: { question: number; outcome: number; amount: string } }; diff --git a/src/types/request/info.types.ts b/src/types/request/info.types.ts index d239049..620e101 100644 --- a/src/types/request/info.types.ts +++ b/src/types/request/info.types.ts @@ -3,6 +3,7 @@ export interface AccountRequest { } export interface AccountDexRequest extends AccountRequest { + /** HIP-3 reads require the DEX name; omitted selects the default perp DEX. */ dex?: string; } @@ -69,6 +70,7 @@ export interface GetUserNonFundingLedgerUpdatesRequest extends AccountRequest { } export interface GetOrderStatusRequest extends AccountRequest { + /** Safe integer, decimal-digit string converted to one, or 0x plus 32 hex characters. */ oid: number | string; } diff --git a/src/types/response/exchange.types.ts b/src/types/response/exchange.types.ts index 1e1279f..056bfcf 100644 --- a/src/types/response/exchange.types.ts +++ b/src/types/response/exchange.types.ts @@ -7,6 +7,7 @@ export interface ExchangeErrorResponse { * Exchange result. Omit Data for acknowledgements, provide it for actions * returning data, or use unknown for raw actions with unknown results. */ +/** Wire response union. Clients throw HyperliquidApiError for status: 'err' instead of resolving it. */ export type ExchangeResponse = | ExchangeErrorResponse | { diff --git a/src/types/response/info.types.ts b/src/types/response/info.types.ts index 37a6d9f..020d3d1 100644 --- a/src/types/response/info.types.ts +++ b/src/types/response/info.types.ts @@ -83,6 +83,7 @@ export type UserRoleResponse = | { role: 'subAccount'; data: { master: string } }; export interface OrderBookLevel { + /** Number of orders at this price level. */ n: number; px: string; sz: string; @@ -92,6 +93,7 @@ export interface OrderBookResponse { coin: string; fast?: true; levels: [OrderBookLevel[], OrderBookLevel[]]; + /** Present only when nSigFigs is set; not necessarily the gap between grouped levels. */ spread?: string; time: number; } @@ -124,6 +126,7 @@ export interface Candle { } export interface OpenOrder { + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ cloid?: string | null; coin: string; limitPx: string; @@ -138,13 +141,16 @@ export interface OpenOrder { export interface SpotBalance { coin: string; entryNtl: string; + /** Decimal string; can be negative under portfolio margin. */ hold: string; token: number; + /** Decimal string; can be negative under portfolio margin. */ total: string; } export interface SpotBalancesResponse { balances: SpotBalance[]; + /** Available token amounts after maintenance requirements, keyed by spot token index. */ tokenToAvailableAfterMaintenance?: Array<[token: number, available: string]>; } @@ -230,6 +236,7 @@ export interface UserFill { export interface FrontendOpenOrder { children?: FrontendOpenOrder[]; + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ cloid?: string | null; coin: string; isPositionTpsl: boolean; @@ -248,39 +255,71 @@ export interface FrontendOpenOrder { } export type OrderState = + /** Rejected due to post-only immediate match */ | 'badAloPxRejected' + /** Rejected due to invalid TP/SL price */ | 'badTriggerPxRejected' + /** Canceled by user */ | 'canceled' + /** Canceled due to asset delisting */ | 'delistedCanceled' + /** Filled */ | 'filled' + /** Rejected due to insufficient spot balance */ | 'insufficientSpotBalanceRejected' - /** Returned by Hyperliquid, not yet in their docs. */ + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'insufficientWeiCanceled' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'internalCancel' + /** Rejected due to IOC not able to match */ | 'iocCancelRejected' + /** Canceled due to liquidation */ | 'liquidatedCanceled' + /** Canceled because insufficient margin to fill */ | 'marginCanceled' + /** Rejected due to lack of liquidity for market order */ | 'marketOrderNoLiquidityRejected' + /** Rejected due to order notional below minimum */ | 'minTradeNtlRejected' + /** Placed successfully */ | 'open' + /** Canceled due to order being too aggressive when open interest was at cap */ | 'openInterestCapCanceled' + /** Rejected due to open interest cap */ | 'openInterestIncreaseRejected' + /** Rejected due to price too far from oracle */ | 'oracleRejected' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'outcomeSettledCanceled' + /** Rejected due to insufficient margin */ | 'perpMarginRejected' + /** Rejected due to exceeding margin tier limit at current leverage */ | 'perpMaxPositionRejected' + /** Rejected due to open interest cap */ | 'positionFlipAtOpenInterestCapRejected' + /** Rejected due to open interest cap */ | 'positionIncreaseAtOpenInterestCapRejected' + /** Canceled reduced-only order that does not reduce position */ | 'reduceOnlyCanceled' + /** Rejected due to reduce only */ | 'reduceOnlyRejected' + /** Rejected at time of placement */ | 'rejected' + /** API only. Canceled due to exceeding scheduled cancel deadline (dead man's switch) */ | 'scheduledCancel' + /** Canceled due to self-trade prevention */ | 'selfTradeCanceled' + /** TP/SL only. Canceled due to sibling ordering being filled */ | 'siblingFilledCanceled' + /** Rejected due to invalid tick price */ | 'tickRejected' + /** Rejected due to price too aggressive at open interest cap */ | 'tooAggressiveAtOpenInterestCapRejected' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'tooManyOpenOrdersRejected' + /** Trigger order triggered */ | 'triggered' + /** Vaults only. Canceled due to a user's withdrawal from vault */ | 'vaultWithdrawalCanceled'; export interface OrderStatusDetails { @@ -429,7 +468,10 @@ export interface VaultSummary { } export interface UserVaultDeposit { + /** Vault equity in decimal units. */ equity: string; + /** Withdrawal unlock time in milliseconds; matches followerState.lockupUntil. */ + lockedUntilTimestamp: number; vaultAddress: string; } @@ -572,7 +614,9 @@ export interface StakingReward { } export type UserAbstraction = + /** Default mode for addresses that have not explicitly selected an abstraction. */ | 'default' + /** Discontinued DEX abstraction mode; prefer unifiedAccount or portfolioMargin. */ | 'dexAbstraction' | 'disabled' | 'portfolioMargin' @@ -620,6 +664,7 @@ export type BorrowLendReserveEntry = [ export interface PerpAsset { deployerFeeScale?: string; growthMode?: 'enabled'; + /** Delisted markets remain in universe and can still resolve; they have no mid or open interest. */ isDelisted?: boolean; lastFeeScaleChangeTime?: string; /** @@ -646,6 +691,7 @@ export interface PerpMarginTable { } export interface PerpMeta { + /** Spot token index of this DEX's collateral; look up in getSpotMetadata().tokens. */ collateralToken: number; marginTables: Array<[id: number, table: PerpMarginTable]>; universe: PerpAsset[]; @@ -770,6 +816,10 @@ export type UserNonFundingLedgerDelta = user: string; } | { amount: string; token: string; type: 'deployGasAuction' | 'spotGenesis' } + /** Observed in public non-funding ledgers. */ + | { type: 'gossipPriorityGasAuction'; token: string; amount: string } + /** Observed in public non-funding ledgers. */ + | { type: 'accountActivationGas'; token: string; amount: string } | { amount: string; isDeposit: boolean; @@ -797,8 +847,11 @@ export interface UserNonFundingLedgerUpdate { } export interface PredictedFundingQuote { + /** Venue funding interval in hours; can be absent, so do not assume 1. */ fundingIntervalHours?: number; + /** Decimal rate per venue interval, not necessarily hourly. Divide by the known interval to compare. */ fundingRate: string; + /** Milliseconds; observed HlPerp values mark the current hour boundary. Zero means none. */ nextFundingTime: number; } @@ -992,13 +1045,16 @@ export interface SettledOutcomeQuestion { description: string; name: string; question: { + /** Settled question identifier shared by its outcomes, not a settlement timestamp. */ settled: number; }; } export interface SettledOutcome { + /** Exchange-provided settlement details. */ details: string; question?: SettledOutcomeQuestion; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; spec: Outcome; } @@ -1058,6 +1114,7 @@ export type OutcomeGovernanceAction = settleOutcome: { details: string; outcome: number; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; }; } @@ -1076,6 +1133,7 @@ export type OutcomeGovernanceAction = details: string; nameAndDescription: [string, string]; outcome: number; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; sideNames: [string, string]; }>; diff --git a/src/types/shared.types.ts b/src/types/shared.types.ts index f1967ac..fa75a3f 100644 --- a/src/types/shared.types.ts +++ b/src/types/shared.types.ts @@ -20,7 +20,7 @@ export interface TypedDataField { } export interface TypedDataDomain { - chainId: bigint | number | string; + chainId: number | string; name: string; verifyingContract: string; version: string; @@ -43,6 +43,46 @@ export interface HyperliquidSigner { ) => Promise; } +/** Structural viem input; no viem installation is needed to use the SDK. */ +export interface ViemSignTypedDataParameters { + domain: { + chainId: number; + name: string; + verifyingContract: `0x${string}`; + version: string; + }; + types: TypedDataTypes; + primaryType: string; + message: Record; +} + +export interface ViemLocalAccountLike { + type: 'local'; + address: `0x${string}`; + signTypedData(params: ViemSignTypedDataParameters): Promise<`0x${string}`>; +} + +export interface ViemWalletClientLike { + /** viem publishes this as string; runtime detection requires 'walletClient'. */ + type: string; + account?: { address: `0x${string}` } | undefined; + signTypedData( + params: ViemSignTypedDataParameters & { + // Opaque viem Account: forward the original client.account without recreating it. + // Its local/smart account variants require methods outside this SDK's contract. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + account: any; + }, + ): Promise<`0x${string}`>; +} + +export type HyperliquidSignerInput = + HyperliquidSigner | ViemLocalAccountLike | ViemWalletClientLike; + +/** + * Awaited with a lower-case signer address; must return a non-negative safe integer. + * Invalid results throw RangeError before sending. Coordinate unique values across workers. + */ export interface NonceProvider { nextNonce(signerAddress: string): Promise | number; } @@ -63,9 +103,10 @@ export interface RestClientOptions { baseUrl?: string; keepAlive?: boolean; keepAliveMsecs?: number; + /** Coordinate across threads/processes; the default manager is local to this module instance. */ nonceProvider?: NonceProvider; privateKey?: string; - signer?: HyperliquidSigner; + signer?: HyperliquidSignerInput; testnet?: boolean; vaultAddress?: string; } diff --git a/src/types/websockets/ws-subscriptions.ts b/src/types/websockets/ws-subscriptions.ts index 3ffb97f..cf2e6d5 100644 --- a/src/types/websockets/ws-subscriptions.ts +++ b/src/types/websockets/ws-subscriptions.ts @@ -71,8 +71,10 @@ export interface SacSubscription { } export type WebsocketSubscription = + /** Deprecated upstream; use fastAssetCtxs for live prices. REST getAllMids remains supported. */ | { dex?: string; type: 'allMids' } | { dex?: string; type: 'assetCtxs' } + /** Spot messages arrive on activeSpotAssetCtx; perps arrive on activeAssetCtx. */ | { coin: string; type: 'activeAssetCtx' } | { coin: string; user: string; type: 'activeAssetData' } | { type: 'allDexsAssetCtxs' } @@ -84,9 +86,11 @@ export type WebsocketSubscription = | L2Subscription | { coin: string; + /** Lower latency, with 5 levels per side instead of the default 20. */ fast?: boolean; mantissa?: 1 | 2 | 5 | null; nSigFigs?: 2 | 3 | 4 | 5 | null; + /** Messages omit nSigFigs/mantissa; use separate clients for multiple groupings of one coin. */ type: 'l2Book'; } | { user: string; type: 'notification' } @@ -213,6 +217,11 @@ export interface OrderUpdateEvent { statusTimestamp: number; } +/** + * Decoded full snapshot first (also after resubscription), then changed coins/fields only. + * Merge each coin's fields into a cache. Either field can be omitted in a diff; + * midPx: null means the book has no mid. + */ export interface FastAssetCtxsEvent { [coin: string]: { markPx?: string; diff --git a/test/unit/rest-exchange.test.ts b/test/unit/rest-exchange.test.ts index bfb2094..fe309da 100644 --- a/test/unit/rest-exchange.test.ts +++ b/test/unit/rest-exchange.test.ts @@ -562,7 +562,8 @@ describe('RestClient Exchange requests', () => { t: true, }); await instance.cancelTwapOrder({ a: 0, t: 7 }); - await instance.setCancelAllAfter({ time: 4_000 }); + const cancelTime = Date.now() + 60_000; + await instance.setCancelAllAfter({ time: cancelTime }); expect(findAction(instance, 'updateLeverage')).toEqual({ type: 'updateLeverage', @@ -592,7 +593,7 @@ describe('RestClient Exchange requests', () => { }); expect(findAction(instance, 'scheduleCancel')).toEqual({ type: 'scheduleCancel', - time: 4_000, + time: cancelTime, }); }); diff --git a/test/unit/rest-info.test.ts b/test/unit/rest-info.test.ts index d6a5829..6534b5b 100644 --- a/test/unit/rest-info.test.ts +++ b/test/unit/rest-info.test.ts @@ -229,11 +229,18 @@ describe('RestClient Info requests', () => { user: LOWER_USER, dex: 'xyz', }); - await check(() => client.getOrderStatus({ user: USER, oid: '0x01' }), { - type: 'orderStatus', - user: LOWER_USER, - oid: '0x01', - }); + await check( + () => + client.getOrderStatus({ + user: USER, + oid: '0x00000000000000000000000000000001', + }), + { + type: 'orderStatus', + user: LOWER_USER, + oid: '0x00000000000000000000000000000001', + }, + ); await check(() => client.getPerpAnnotation({ coin: 'BTC' }), { type: 'perpAnnotation', coin: 'BTC', From 89c0b71210fe817e3ef206baa9abbc80b60c5037 Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Tue, 1 Dec 2026 11:54:58 +0100 Subject: [PATCH 2/3] feat(v1.1.0): optional customFetch transport (automation-tracker #124) - Restore decimalToScaledInteger, uint64ToBytes, and TypedDataDomain.chainId exactly from update30112026; retain Number() in the viem adapter (automation-tracker #128 follow-up). - Add the shared CustomFetch, CustomFetchRequestInit, and CustomFetchResponse structural types and opt-in REST transport; axios remains the unchanged default (automation-tracker #124). - Preserve HTTP/API error handling, propagate caller errors unchanged, apply supported timeout signals, and reject binary/multipart bodies before sending (automation-tracker #124). - Forward customFetch through existing WebSocket REST metadata options without changing WebSocket transport behavior (automation-tracker #124). - Document Edge runtimes / native fetch (optional); keep version 1.1.0 and dependencies unchanged (automation-tracker #124). Validation: npm ci, lint, tsc --noEmit, build, test:types, all 189 existing unit tests, test:packed, Prettier, and git diff --check pass. No tests or specs added. Throwaway verification confirms native-fetch type compatibility without DOM, local ESM/CJS transport/error parity, identical live public POST /info results and HTTP 422 errors, and 40 matching viem 2.57.11 signatures after the upstream restoration. Hyperliquid Info reads use POST rather than GET; no signed requests were sent. --- README.md | 49 +++++++++++++ src/WebsocketAPIClient.ts | 13 +++- src/WebsocketClient.ts | 3 + src/lib/BaseRestClient.ts | 107 ++++++++++++++++++++++++++++- src/lib/decimal.ts | 9 ++- src/lib/signing.ts | 4 +- src/types/shared.types.ts | 28 +++++++- src/types/websockets/ws-general.ts | 4 +- 8 files changed, 207 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index d58b341..28c0285 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ Take a look at our dedicated [HyperLiquid API quickstart guides for major framew ## REST API Examples - [REST API](#rest-api) +- [Edge runtimes / native fetch (optional)](#edge-runtimes--native-fetch-optional) - [Assets](#assets) - [Use a viem account, browser wallet or Privy/embedded wallet signer](#use-a-viem-account-browser-wallet-or-privyembedded-wallet-signer) - [Nonces](#nonces) @@ -292,6 +293,54 @@ Set `vaultAddress` on the client or per request when signing for a vault or suba Account getters such as `getBalances()`, `getSpotBalances()`, `getPerpAccountSummary()`, and `getPortfolio()` can omit `user` on an authenticated client. The SDK uses `vaultAddress` or `accountAddress` when configured. Otherwise it resolves an API wallet to its master account with one `userRole` request and caches the result for that client instance. Call `getAccountAddress()` to inspect the resolved address. Public clients without an account or signer must pass `user`. +## Edge runtimes / native fetch (optional) + +Axios remains the default REST transport. Opt in to the runtime's native fetch +on a client, without adding dependencies: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; + +const client = new RestClient({ customFetch: fetch }); +const metadata = await client.getPerpMetadata(); +``` + +For a Cloudflare Workers service binding or an egress fetcher: + +```ts +const client = new RestClient({ + customFetch: (url, init) => env.MY_FETCHER.fetch(url, init), +}); +``` + +Wrappers can add runtime-specific options such as `cache: 'no-store'` or their +own abort signal. The SDK calls the fetch function detached, passes the same +request URL and JSON body, and parses JSON or plain-text responses through its +existing response/error handling. HTTP errors remain `HyperliquidApiError`; +errors thrown by your fetcher (including network and abort errors) pass through +unchanged. + +Axios-only settings in the second constructor argument, including adapters, +agents, interceptors, headers, and transforms, are not applied in this mode. +The exception is `timeout` (including the SDK default), which becomes +`AbortSignal.timeout(timeout)` when supported; `timeout: 0` disables it. +Binary and multipart bodies are rejected locally; use the default axios +transport for those requests. Axios remains installed, so this option does not +remove it from the package or guarantee a smaller bundle. + +`CustomFetch`, `CustomFetchRequestInit`, and `CustomFetchResponse` are exported +structural types, requiring no DOM library. WebSocket metadata reads receive +the transport through the existing REST `requestOptions` object: + +```ts +import { WebsocketClient } from '@siebly/hyperliquid-api'; + +const ws = new WebsocketClient({ requestOptions: { customFetch: fetch } }); +``` + +`WebsocketAPIClient({ customFetch: fetch })` forwards it to its internal REST +metadata client; its WebSocket requests continue to use WebSockets. + ## Assets Trading actions accept official identifiers, numeric asset IDs, and aliases derived from live metadata: diff --git a/src/WebsocketAPIClient.ts b/src/WebsocketAPIClient.ts index 082cf51..78a9181 100644 --- a/src/WebsocketAPIClient.ts +++ b/src/WebsocketAPIClient.ts @@ -18,7 +18,18 @@ export class WebsocketAPIClient extends RestClient { logger: Logger = DefaultLogger, ) { super(options); - this.wsClient = new WebsocketClient(options, logger); + this.wsClient = new WebsocketClient( + options.customFetch === undefined + ? options + : { + ...options, + requestOptions: { + ...options.requestOptions, + customFetch: options.customFetch, + }, + }, + logger, + ); } getWSClient(): WebsocketClient { diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index 60eeaae..2dc8f27 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -126,6 +126,9 @@ export class WebsocketClient extends BaseWebsocketClient< : { assetCacheTtlMs: options.assetCacheTtlMs }), ...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }), ...(options.testnet === undefined ? {} : { testnet: options.testnet }), + ...(options.requestOptions?.customFetch === undefined + ? {} + : { customFetch: options.requestOptions.customFetch }), }, options.requestOptions, ); diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 115101c..f231852 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -1,6 +1,9 @@ import axios, { + AxiosError, + AxiosHeaders, type AxiosInstance, type AxiosRequestConfig, + type AxiosResponse, isAxiosError, } from 'axios'; @@ -19,6 +22,7 @@ import type { UserRoleResponse, } from '../types/response/info.types.js'; import type { + CustomFetch, JsonObject, RestClientNetworkOptions, RestClientOptions, @@ -89,6 +93,10 @@ export abstract class BaseRestClient { protected readonly axios: AxiosInstance; + private readonly customFetch: CustomFetch | undefined; + + private readonly fetchTimeout: number; + private builderApprovalPromise: Promise | undefined; private builderApprovalState: BuilderApprovalState = 'unchecked'; @@ -112,10 +120,12 @@ export abstract class BaseRestClient { timeout: networkOptions.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS, }; - if (options.keepAlive !== false) { + if (!options.customFetch && options.keepAlive !== false) { configureHttpsKeepAlive(requestConfig, options.keepAliveMsecs); } + this.customFetch = options.customFetch; + this.fetchTimeout = requestConfig.timeout!; this.axios = axios.create(requestConfig); this.assetResolver = new AssetResolver( (request) => this.submitRawInfoRequest(request), @@ -224,8 +234,25 @@ export abstract class BaseRestClient { } protected async post(path: string, body: unknown): Promise { + // Keep caller/network/abort errors outside the Axios error conversion below, + // including errors from a custom fetcher that happen to be AxiosErrors. + const fetchResponse = this.customFetch + ? await this.postWithCustomFetch(path, body) + : undefined; try { - const response = await this.axios.post(path, body); + const response = fetchResponse ?? (await this.axios.post(path, body)); + + if (fetchResponse && (response.status < 200 || response.status >= 300)) { + throw new AxiosError( + `Request failed with status code ${response.status}`, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][ + Math.floor(response.status / 100) - 4 + ], + response.config, + undefined, + response, + ); + } if (isHyperliquidErrorResponse(response.data)) { const message = @@ -268,6 +295,82 @@ export abstract class BaseRestClient { } } + private async postWithCustomFetch( + path: string, + body: unknown, + ): Promise> { + if ( + ArrayBuffer.isView(body) || + [ + '[object ArrayBuffer]', + '[object SharedArrayBuffer]', + '[object Blob]', + '[object File]', + '[object FormData]', + '[object ReadableStream]', + ].includes(Object.prototype.toString.call(body)) || + (body !== null && + typeof body === 'object' && + 'pipe' in body && + typeof body.pipe === 'function') + ) { + throw new Error( + 'customFetch does not support binary/multipart request bodies; use the default axios transport for this endpoint.', + ); + } + + const url = axios.getUri({ baseURL: this.baseUrl, url: path }); + const data = + typeof body === 'string' + ? body + : body == null + ? undefined + : JSON.stringify(body); + const headers: Record = { + Accept: 'application/json, text/plain, */*', + ...DEFAULT_REQUEST_HEADERS, + 'Content-Type': + body !== null && typeof body === 'object' + ? 'application/json' + : 'application/x-www-form-urlencoded', + }; + const fetchFn = this.customFetch!; + const result = await fetchFn(url, { + method: 'POST', + headers, + ...(data === undefined ? {} : { body: data }), + ...(this.fetchTimeout && + typeof AbortSignal !== 'undefined' && + typeof AbortSignal.timeout === 'function' + ? { signal: AbortSignal.timeout(this.fetchTimeout) } + : {}), + }); + const text = await result.text(); + let responseData: unknown = text; + try { + responseData = JSON.parse(text); + } catch { + // Match axios's default handling of text and empty response bodies. + } + const responseHeaders: Record = {}; + result.headers.forEach((value, key) => { + responseHeaders[key.toLowerCase()] = value; + }); + return { + data: responseData as T, + status: result.status, + statusText: result.statusText, + headers: responseHeaders, + config: { + url, + method: 'post', + data, + headers: new AxiosHeaders(headers), + timeout: this.fetchTimeout, + }, + }; + } + private async beforeActionSubmission( action: JsonObject, options: ActionSubmissionOptions, diff --git a/src/lib/decimal.ts b/src/lib/decimal.ts index e1a383e..9506630 100644 --- a/src/lib/decimal.ts +++ b/src/lib/decimal.ts @@ -35,10 +35,15 @@ export function decimalToScaledInteger( ); } - const scaled = Number(`${integer}${fraction.padEnd(decimalPlaces, '0')}`); + const scaled = + BigInt(integer) * 10n ** BigInt(decimalPlaces) + + BigInt(fraction.padEnd(decimalPlaces, '0') || '0'); const signed = negative ? -scaled : scaled; - if (!Number.isSafeInteger(signed)) { + if ( + signed > BigInt(Number.MAX_SAFE_INTEGER) || + signed < BigInt(Number.MIN_SAFE_INTEGER) + ) { throw new RangeError( `${value} cannot be represented safely as a scaled JavaScript integer.`, ); diff --git a/src/lib/signing.ts b/src/lib/signing.ts index 8ec36c8..3b0aeb0 100644 --- a/src/lib/signing.ts +++ b/src/lib/signing.ts @@ -139,9 +139,7 @@ function uint64ToBytes(value: number): Uint8Array { } const bytes = new Uint8Array(8); - const view = new DataView(bytes.buffer); - view.setUint32(0, Math.floor(value / 0x100000000), false); - view.setUint32(4, value % 0x100000000, false); + new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false); return bytes; } diff --git a/src/types/shared.types.ts b/src/types/shared.types.ts index fa75a3f..9b1ffad 100644 --- a/src/types/shared.types.ts +++ b/src/types/shared.types.ts @@ -20,7 +20,7 @@ export interface TypedDataField { } export interface TypedDataDomain { - chainId: number | string; + chainId: bigint | number | string; name: string; verifyingContract: string; version: string; @@ -97,10 +97,36 @@ export interface RequestOptions { timeout?: number; } +export interface CustomFetchRequestInit { + method: string; + headers: Record; + body?: string; + signal?: AbortSignal; +} + +export interface CustomFetchResponse { + status: number; + statusText: string; + headers: { forEach(callback: (value: string, key: string) => void): void }; + text(): Promise; +} + +export type CustomFetch = ( + url: string, + init: CustomFetchRequestInit, +) => Promise; + export interface RestClientOptions { accountAddress?: string; assetCacheTtlMs?: number; baseUrl?: string; + /** + * Optional fetch-compatible REST transport. Default: unset (axios). + * Pass native fetch or a wrapper such as (url, init) => env.FETCHER.fetch(url, init). + * Axios-only settings (network options, adapters, agents, interceptors) are ignored, + * except timeout, which uses AbortSignal.timeout() when available. + */ + customFetch?: CustomFetch; keepAlive?: boolean; keepAliveMsecs?: number; /** Coordinate across threads/processes; the default manager is local to this module instance. */ diff --git a/src/types/websockets/ws-general.ts b/src/types/websockets/ws-general.ts index bfcd13c..8a1045d 100644 --- a/src/types/websockets/ws-general.ts +++ b/src/types/websockets/ws-general.ts @@ -27,7 +27,9 @@ export interface WebsocketClientOptions { reconnectTimeout?: number; /** Maximum request duration in milliseconds, including connection setup. Default: 10,000. */ requestTimeoutMs?: number; - requestOptions?: RestClientNetworkOptions; + /** REST metadata options; customFetch is forwarded to the internal REST client. */ + requestOptions?: RestClientNetworkOptions & + Pick; testnet?: boolean; webSocketConstructor?: WebSocketConstructor; wsUrl?: string; From 713b0c11f4f66eb4a5bf825ca8596e41fbe3da47 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Tue, 1 Dec 2026 12:00:33 +0100 Subject: [PATCH 3/3] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 278 +- llms.txt | 5288 +++++++++++++++++++--------------- 2 files changed, 3087 insertions(+), 2479 deletions(-) diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index f6e7c64..44828a2 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -52,142 +52,142 @@ WebsocketAPIClient extends RestClient and exposes the same methods over Hyperliq | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getAllMids()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L200) | | POST | `/info (allMids)` | -| [getActiveAssetData()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L208) | :closed_lock_with_key: | POST | `/info (activeAssetData)` | -| [getAllBorrowLendReserveStates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L219) | | POST | `/info (allBorrowLendReserveStates)` | -| [getAllPerpMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L229) | | POST | `/info (allPerpMetas)` | -| [getApprovedBuilders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L236) | :closed_lock_with_key: | POST | `/info (approvedBuilders)` | -| [getBorrowLendReserveState()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L243) | | POST | `/info (borrowLendReserveState)` | -| [getUserBorrowLendState()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L254) | :closed_lock_with_key: | POST | `/info (borrowLendUserState)` | -| [getCandles()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L266) | | POST | `/info (candleSnapshot)` | -| [getPerpAccountSummary()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L279) | :closed_lock_with_key: | POST | `/info (clearinghouseState)` | -| [getStakingDelegations()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L288) | :closed_lock_with_key: | POST | `/info (delegations)` | -| [getStakingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L299) | :closed_lock_with_key: | POST | `/info (delegatorHistory)` | -| [getStakingRewards()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L310) | :closed_lock_with_key: | POST | `/info (delegatorRewards)` | -| [getStakingSummary()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L317) | :closed_lock_with_key: | POST | `/info (delegatorSummary)` | -| [getExchangeStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L321) | | POST | `/info (exchangeStatus)` | -| [getExtraAgents()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L325) | :closed_lock_with_key: | POST | `/info (extraAgents)` | -| [getFrontendOpenOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L334) | :closed_lock_with_key: | POST | `/info (frontendOpenOrders)` | -| [getFundingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L343) | | POST | `/info (fundingHistory)` | -| [getGossipPriorityAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L352) | | POST | `/info (gossipPriorityAuctionStatus)` | -| [getGossipRootIps()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L356) | | POST | `/info (gossipRootIps)` | -| [getOrderHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L365) | :closed_lock_with_key: | POST | `/info (historicalOrders)` | -| [getVipStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L369) | :closed_lock_with_key: | POST | `/info (isVip)` | -| [getOrderBook()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L379) | | POST | `/info (l2Book)` | -| [getLeadingVaults()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L388) | :closed_lock_with_key: | POST | `/info (leadingVaults)` | -| [getLegalStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L392) | :closed_lock_with_key: | POST | `/info (legalCheck)` | -| [getLiquidatablePositions()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L396) | | POST | `/info (liquidatable)` | -| [getMarginTable()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L400) | | POST | `/info (marginTable)` | -| [getMaxBuilderFee()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L409) | :closed_lock_with_key: | POST | `/info (maxBuilderFee)` | -| [getMaxMarketOrderNotionals()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L413) | | POST | `/info (maxMarketOrderNtls)` | -| [getPerpMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L422) | | POST | `/info (meta)` | -| [getPerpAssetContexts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L433) | | POST | `/info (metaAndAssetCtxs)` | -| [getOpenOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L445) | :closed_lock_with_key: | POST | `/info (openOrders)` | -| [getOrderStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L455) | :closed_lock_with_key: | POST | `/info (orderStatus)` | -| [getOutcomeMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L462) | | POST | `/info (outcomeMeta)` | -| [getOutcomeDeployerLimits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L471) | | POST | `/info (outcomeDeployerLimits)` | -| [getPerpAnnotation()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L482) | | POST | `/info (perpAnnotation)` | -| [getPerpCategories()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L491) | | POST | `/info (perpCategories)` | -| [getConcisePerpAnnotations()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L500) | | POST | `/info (perpConciseAnnotations)` | -| [getPerpDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L507) | | POST | `/info (perpDeployAuctionStatus)` | -| [getPerpDexLimits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L516) | | POST | `/info (perpDexLimits)` | -| [getPerpDexStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L525) | | POST | `/info (perpDexStatus)` | -| [getPerpDexs()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L535) | | POST | `/info (perpDexs)` | -| [getPerpsAtOpenInterestCap()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L544) | | POST | `/info (perpsAtOpenInterestCap)` | -| [getPortfolio()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L554) | :closed_lock_with_key: | POST | `/info (portfolio)` | -| [getPreTransferCheck()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L558) | | POST | `/info (preTransferCheck)` | -| [getPredictedFundingRates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L571) | | POST | `/info (predictedFundings)` | -| [getRecentTrades()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L575) | | POST | `/info (recentTrades)` | -| [getReferralInfo()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L586) | :closed_lock_with_key: | POST | `/info (referral)` | -| [getSettledOutcome()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L595) | | POST | `/info (settledOutcome)` | -| [getBalances()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L601) | :closed_lock_with_key: | POST | `/info (clearinghouseState, spotClearinghouseState)` | -| [getSpotBalances()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L622) | :closed_lock_with_key: | POST | `/info (spotClearinghouseState)` | -| [getSpotDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L629) | :closed_lock_with_key: | POST | `/info (spotDeployState)` | -| [getSpotMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L638) | | POST | `/info (spotMeta)` | -| [getSpotAssetContexts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L648) | | POST | `/info (spotMetaAndAssetCtxs)` | -| [getSpotPairDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L655) | | POST | `/info (spotPairDeployAuctionStatus)` | -| [getSubAccounts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L664) | :closed_lock_with_key: | POST | `/info (subAccounts)` | -| [getSubAccountsWithAllDexStates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L668) | :closed_lock_with_key: | POST | `/info (subAccounts2)` | -| [getTokenDetails()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L680) | | POST | `/info (tokenDetails)` | -| [getTwapHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L684) | :closed_lock_with_key: | POST | `/info (twapHistory)` | -| [getUserAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L691) | :closed_lock_with_key: | POST | `/info (userAbstraction)` | -| [getUserBorrowLendInterest()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L695) | :closed_lock_with_key: | POST | `/info (userBorrowLendInterest)` | -| [getUserDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L704) | :closed_lock_with_key: | POST | `/info (userDexAbstraction)` | -| [getUserFees()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L711) | :closed_lock_with_key: | POST | `/info (userFees)` | -| [getUserFills()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L721) | :closed_lock_with_key: | POST | `/info (userFills)` | -| [getUserFillsByTime()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L731) | :closed_lock_with_key: | POST | `/info (userFillsByTime)` | -| [getUserFundingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L740) | :closed_lock_with_key: | POST | `/info (userFunding)` | -| [getUserNonFundingLedgerUpdates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L753) | :closed_lock_with_key: | POST | `/info (userNonFundingLedgerUpdates)` | -| [getUserRateLimit()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L765) | :closed_lock_with_key: | POST | `/info (userRateLimit)` | -| [getUserRole()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L775) | | POST | `/info (userRole)` | -| [getMultiSigSigners()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L779) | :closed_lock_with_key: | POST | `/info (userToMultiSigSigners)` | -| [getUserTwapSliceFills()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L790) | :closed_lock_with_key: | POST | `/info (userTwapSliceFills)` | -| [getUserTwapSliceFillsByTime()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L794) | :closed_lock_with_key: | POST | `/info (userTwapSliceFillsByTime)` | -| [getUserVaultDeposits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L803) | :closed_lock_with_key: | POST | `/info (userVaultEquities)` | -| [getValidatorL1Votes()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L809) | | POST | `/info (validatorL1Votes)` | -| [getValidatorSummaries()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L813) | | POST | `/info (validatorSummaries)` | -| [getVaultDetails()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L823) | | POST | `/info (vaultDetails)` | -| [getVaultSummaries()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L829) | | POST | `/info (vaultSummaries)` | -| [getWebData2()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L833) | :closed_lock_with_key: | POST | `/info (webData2)` | -| [getAlignedQuoteTokenStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L838) | | POST | `/info (alignedQuoteTokenInfo)` | -| [submitOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L850) | :closed_lock_with_key: | POST | `/exchange (order)` | -| [submitMarketOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L866) | :closed_lock_with_key: | POST | `/exchange (order)` | -| [submitMarketClose()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L921) | :closed_lock_with_key: | POST | `/exchange (order)` | -| [submitLimitOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L965) | :closed_lock_with_key: | POST | `/exchange (order)` | -| [modifyOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1007) | :closed_lock_with_key: | POST | `/exchange (modify)` | -| [modifyOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1023) | :closed_lock_with_key: | POST | `/exchange (batchModify)` | -| [cancelOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1042) | :closed_lock_with_key: | POST | `/exchange (cancel)` | -| [cancelOrdersByClientOrderId()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1060) | :closed_lock_with_key: | POST | `/exchange (cancelByCloid)` | -| [updateLeverage()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1076) | :closed_lock_with_key: | POST | `/exchange (updateLeverage)` | -| [updateIsolatedMargin()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1096) | :closed_lock_with_key: | POST | `/exchange (updateIsolatedMargin)` | -| [setIsolatedMarginLeverage()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1108) | :closed_lock_with_key: | POST | `/exchange (topUpIsolatedOnlyMargin)` | -| [submitTwapOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1124) | :closed_lock_with_key: | POST | `/exchange (twapOrder)` | -| [cancelTwapOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1136) | :closed_lock_with_key: | POST | `/exchange (twapCancel)` | -| [submitTrailingStop()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1150) | :closed_lock_with_key: | POST | `/exchange (trailingStop)` | -| [setCancelAllAfter()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1163) | :closed_lock_with_key: | POST | `/exchange (scheduleCancel)` | -| [setReferrer()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1170) | :closed_lock_with_key: | POST | `/exchange (setReferrer)` | -| [registerReferrer()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1176) | :closed_lock_with_key: | POST | `/exchange (registerReferrer)` | -| [approveApiWallet()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1214) | :closed_lock_with_key: | POST | `/exchange (approveAgent)` | -| [sendUsd()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1234) | :closed_lock_with_key: | POST | `/exchange (usdSend)` | -| [sendSpotAsset()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1251) | :closed_lock_with_key: | POST | `/exchange (spotSend)` | -| [withdrawUsd()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1266) | :closed_lock_with_key: | POST | `/exchange (withdraw3)` | -| [transferUsdBetweenSpotAndPerp()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1283) | :closed_lock_with_key: | POST | `/exchange (usdClassTransfer)` | -| [sendAsset()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1301) | :closed_lock_with_key: | POST | `/exchange (sendAsset)` | -| [sendToEvmWithData()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1322) | :closed_lock_with_key: | POST | `/exchange (sendToEvmWithData)` | -| [sendAssetFromApiWallet()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1339) | :closed_lock_with_key: | POST | `/exchange (agentSendAsset)` | -| [depositIntoStaking()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1360) | :closed_lock_with_key: | POST | `/exchange (cDeposit)` | -| [withdrawFromStaking()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1377) | :closed_lock_with_key: | POST | `/exchange (cWithdraw)` | -| [delegateOrUndelegateStake()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1394) | :closed_lock_with_key: | POST | `/exchange (tokenDelegate)` | -| [convertToMultiSigUser()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1406) | :closed_lock_with_key: | POST | `/exchange (convertToMultiSigUser)` | -| [linkStakingAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1429) | :closed_lock_with_key: | POST | `/exchange (linkStakingUser)` | -| [disableStakingTradingLink()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1441) | :closed_lock_with_key: | POST | `/exchange (stakingLinkDisableTradingUser)` | -| [setUserPortfolioMargin()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1453) | :closed_lock_with_key: | POST | `/exchange (userPortfolioMargin)` | -| [setUserAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1470) | :closed_lock_with_key: | POST | `/exchange (userSetAbstraction)` | -| [setUserDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1487) | :closed_lock_with_key: | POST | `/exchange (userDexAbstraction)` | -| [enableApiWalletDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1504) | :closed_lock_with_key: | POST | `/exchange (agentEnableDexAbstraction)` | -| [setApiWalletAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1515) | :closed_lock_with_key: | POST | `/exchange (agentSetAbstraction)` | -| [executeBorrowLendOperation()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1522) | :closed_lock_with_key: | POST | `/exchange (borrowLend)` | -| [claimRewards()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1543) | :closed_lock_with_key: | POST | `/exchange (claimRewards)` | -| [createSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1547) | :closed_lock_with_key: | POST | `/exchange (createSubAccount)` | -| [createVault()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1554) | :closed_lock_with_key: | POST | `/exchange (createVault)` | -| [setEvmBigBlocks()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1561) | :closed_lock_with_key: | POST | `/exchange (evmUserModify)` | -| [finalizeEvmContract()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1568) | :closed_lock_with_key: | POST | `/exchange (finalizeEvmContract)` | -| [submitGossipPriorityBid()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1581) | :closed_lock_with_key: | POST | `/exchange (gossipPriorityBid)` | -| [transferHip3LiquidatorFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1594) | :closed_lock_with_key: | POST | `/exchange (hip3LiquidatorTransfer)` | -| [invalidateNonce()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1604) | :closed_lock_with_key: | POST | `/exchange (noop)` | -| [deployPerp()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1608) | :closed_lock_with_key: | POST | `/exchange (perpDeploy)` | -| [deploySpot()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1615) | :closed_lock_with_key: | POST | `/exchange (spotDeploy)` | -| [reserveAdditionalActions()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1627) | :closed_lock_with_key: | POST | `/exchange (reserveRequestWeight)` | -| [setDisplayName()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1634) | :closed_lock_with_key: | POST | `/exchange (setDisplayName)` | -| [setSpotDusting()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1641) | :closed_lock_with_key: | POST | `/exchange (spotUser)` | -| [renameSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1648) | :closed_lock_with_key: | POST | `/exchange (subAccountModify)` | -| [transferSpotToOrFromSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1655) | :closed_lock_with_key: | POST | `/exchange (subAccountSpotTransfer)` | -| [transferUsdToOrFromSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1666) | :closed_lock_with_key: | POST | `/exchange (subAccountTransfer)` | -| [transferVaultFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1676) | :closed_lock_with_key: | POST | `/exchange (vaultTransfer)` | -| [distributeVaultFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1683) | :closed_lock_with_key: | POST | `/exchange (vaultDistribute)` | -| [modifyVault()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1690) | :closed_lock_with_key: | POST | `/exchange (vaultModify)` | -| [updateValidatorL1Stream()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1714) | :closed_lock_with_key: | POST | `/exchange (validatorL1Stream)` | -| [submitSignerAction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1725) | :closed_lock_with_key: | POST | `/exchange (CSignerAction)` | -| [submitValidatorAction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1732) | :closed_lock_with_key: | POST | `/exchange (CValidatorAction)` | -| [authorizeAqav2Role()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1745) | :closed_lock_with_key: | POST | `/exchange (authorizeAqav2Role)` | -| [submitUserOutcome()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1760) | :closed_lock_with_key: | POST | `/exchange (userOutcome)` | \ No newline at end of file +| [getAllMids()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L205) | | POST | `/info (allMids)` | +| [getActiveAssetData()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L213) | :closed_lock_with_key: | POST | `/info (activeAssetData)` | +| [getAllBorrowLendReserveStates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L224) | | POST | `/info (allBorrowLendReserveStates)` | +| [getAllPerpMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L234) | | POST | `/info (allPerpMetas)` | +| [getApprovedBuilders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L241) | :closed_lock_with_key: | POST | `/info (approvedBuilders)` | +| [getBorrowLendReserveState()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L248) | | POST | `/info (borrowLendReserveState)` | +| [getUserBorrowLendState()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L259) | :closed_lock_with_key: | POST | `/info (borrowLendUserState)` | +| [getCandles()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L273) | | POST | `/info (candleSnapshot)` | +| [getPerpAccountSummary()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L287) | :closed_lock_with_key: | POST | `/info (clearinghouseState)` | +| [getStakingDelegations()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L296) | :closed_lock_with_key: | POST | `/info (delegations)` | +| [getStakingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L307) | :closed_lock_with_key: | POST | `/info (delegatorHistory)` | +| [getStakingRewards()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L318) | :closed_lock_with_key: | POST | `/info (delegatorRewards)` | +| [getStakingSummary()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L325) | :closed_lock_with_key: | POST | `/info (delegatorSummary)` | +| [getExchangeStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L329) | | POST | `/info (exchangeStatus)` | +| [getExtraAgents()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L333) | :closed_lock_with_key: | POST | `/info (extraAgents)` | +| [getFrontendOpenOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L343) | :closed_lock_with_key: | POST | `/info (frontendOpenOrders)` | +| [getFundingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L352) | | POST | `/info (fundingHistory)` | +| [getGossipPriorityAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L361) | | POST | `/info (gossipPriorityAuctionStatus)` | +| [getGossipRootIps()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L365) | | POST | `/info (gossipRootIps)` | +| [getOrderHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L377) | :closed_lock_with_key: | POST | `/info (historicalOrders)` | +| [getVipStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L381) | :closed_lock_with_key: | POST | `/info (isVip)` | +| [getOrderBook()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L392) | | POST | `/info (l2Book)` | +| [getLeadingVaults()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L403) | :closed_lock_with_key: | POST | `/info (leadingVaults)` | +| [getLegalStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L407) | :closed_lock_with_key: | POST | `/info (legalCheck)` | +| [getLiquidatablePositions()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L411) | | POST | `/info (liquidatable)` | +| [getMarginTable()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L415) | | POST | `/info (marginTable)` | +| [getMaxBuilderFee()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L424) | :closed_lock_with_key: | POST | `/info (maxBuilderFee)` | +| [getMaxMarketOrderNotionals()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L428) | | POST | `/info (maxMarketOrderNtls)` | +| [getPerpMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L437) | | POST | `/info (meta)` | +| [getPerpAssetContexts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L448) | | POST | `/info (metaAndAssetCtxs)` | +| [getOpenOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L461) | :closed_lock_with_key: | POST | `/info (openOrders)` | +| [getOrderStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L473) | :closed_lock_with_key: | POST | `/info (orderStatus)` | +| [getOutcomeMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L492) | | POST | `/info (outcomeMeta)` | +| [getOutcomeDeployerLimits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L501) | | POST | `/info (outcomeDeployerLimits)` | +| [getPerpAnnotation()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L512) | | POST | `/info (perpAnnotation)` | +| [getPerpCategories()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L521) | | POST | `/info (perpCategories)` | +| [getConcisePerpAnnotations()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L530) | | POST | `/info (perpConciseAnnotations)` | +| [getPerpDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L537) | | POST | `/info (perpDeployAuctionStatus)` | +| [getPerpDexLimits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L546) | | POST | `/info (perpDexLimits)` | +| [getPerpDexStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L555) | | POST | `/info (perpDexStatus)` | +| [getPerpDexs()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L565) | | POST | `/info (perpDexs)` | +| [getPerpsAtOpenInterestCap()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L574) | | POST | `/info (perpsAtOpenInterestCap)` | +| [getPortfolio()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L584) | :closed_lock_with_key: | POST | `/info (portfolio)` | +| [getPreTransferCheck()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L588) | | POST | `/info (preTransferCheck)` | +| [getPredictedFundingRates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L601) | | POST | `/info (predictedFundings)` | +| [getRecentTrades()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L605) | | POST | `/info (recentTrades)` | +| [getReferralInfo()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L616) | :closed_lock_with_key: | POST | `/info (referral)` | +| [getSettledOutcome()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L625) | | POST | `/info (settledOutcome)` | +| [getBalances()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L636) | :closed_lock_with_key: | POST | `/info (clearinghouseState, spotClearinghouseState)` | +| [getSpotBalances()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L657) | :closed_lock_with_key: | POST | `/info (spotClearinghouseState)` | +| [getSpotDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L664) | :closed_lock_with_key: | POST | `/info (spotDeployState)` | +| [getSpotMetadata()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L673) | | POST | `/info (spotMeta)` | +| [getSpotAssetContexts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L684) | | POST | `/info (spotMetaAndAssetCtxs)` | +| [getSpotPairDeployAuctionStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L691) | | POST | `/info (spotPairDeployAuctionStatus)` | +| [getSubAccounts()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L700) | :closed_lock_with_key: | POST | `/info (subAccounts)` | +| [getSubAccountsWithAllDexStates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L704) | :closed_lock_with_key: | POST | `/info (subAccounts2)` | +| [getTokenDetails()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L716) | | POST | `/info (tokenDetails)` | +| [getTwapHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L720) | :closed_lock_with_key: | POST | `/info (twapHistory)` | +| [getUserAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L727) | :closed_lock_with_key: | POST | `/info (userAbstraction)` | +| [getUserBorrowLendInterest()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L731) | :closed_lock_with_key: | POST | `/info (userBorrowLendInterest)` | +| [getUserDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L740) | :closed_lock_with_key: | POST | `/info (userDexAbstraction)` | +| [getUserFees()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L747) | :closed_lock_with_key: | POST | `/info (userFees)` | +| [getUserFills()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L757) | :closed_lock_with_key: | POST | `/info (userFills)` | +| [getUserFillsByTime()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L767) | :closed_lock_with_key: | POST | `/info (userFillsByTime)` | +| [getUserFundingHistory()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L776) | :closed_lock_with_key: | POST | `/info (userFunding)` | +| [getUserNonFundingLedgerUpdates()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L792) | :closed_lock_with_key: | POST | `/info (userNonFundingLedgerUpdates)` | +| [getUserRateLimit()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L804) | :closed_lock_with_key: | POST | `/info (userRateLimit)` | +| [getUserRole()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L814) | | POST | `/info (userRole)` | +| [getMultiSigSigners()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L818) | :closed_lock_with_key: | POST | `/info (userToMultiSigSigners)` | +| [getUserTwapSliceFills()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L829) | :closed_lock_with_key: | POST | `/info (userTwapSliceFills)` | +| [getUserTwapSliceFillsByTime()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L833) | :closed_lock_with_key: | POST | `/info (userTwapSliceFillsByTime)` | +| [getUserVaultDeposits()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L844) | :closed_lock_with_key: | POST | `/info (userVaultEquities)` | +| [getValidatorL1Votes()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L850) | | POST | `/info (validatorL1Votes)` | +| [getValidatorSummaries()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L854) | | POST | `/info (validatorSummaries)` | +| [getVaultDetails()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L864) | | POST | `/info (vaultDetails)` | +| [getVaultSummaries()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L870) | | POST | `/info (vaultSummaries)` | +| [getWebData2()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L874) | :closed_lock_with_key: | POST | `/info (webData2)` | +| [getAlignedQuoteTokenStatus()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L879) | | POST | `/info (alignedQuoteTokenInfo)` | +| [submitOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L892) | :closed_lock_with_key: | POST | `/exchange (order)` | +| [submitMarketOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L908) | :closed_lock_with_key: | POST | `/exchange (order)` | +| [submitMarketClose()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L966) | :closed_lock_with_key: | POST | `/exchange (order)` | +| [submitLimitOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1012) | :closed_lock_with_key: | POST | `/exchange (order)` | +| [modifyOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1060) | :closed_lock_with_key: | POST | `/exchange (modify)` | +| [modifyOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1077) | :closed_lock_with_key: | POST | `/exchange (batchModify)` | +| [cancelOrders()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1096) | :closed_lock_with_key: | POST | `/exchange (cancel)` | +| [cancelOrdersByClientOrderId()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1114) | :closed_lock_with_key: | POST | `/exchange (cancelByCloid)` | +| [updateLeverage()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1130) | :closed_lock_with_key: | POST | `/exchange (updateLeverage)` | +| [updateIsolatedMargin()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1150) | :closed_lock_with_key: | POST | `/exchange (updateIsolatedMargin)` | +| [setIsolatedMarginLeverage()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1162) | :closed_lock_with_key: | POST | `/exchange (topUpIsolatedOnlyMargin)` | +| [submitTwapOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1178) | :closed_lock_with_key: | POST | `/exchange (twapOrder)` | +| [cancelTwapOrder()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1190) | :closed_lock_with_key: | POST | `/exchange (twapCancel)` | +| [submitTrailingStop()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1204) | :closed_lock_with_key: | POST | `/exchange (trailingStop)` | +| [setCancelAllAfter()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1217) | :closed_lock_with_key: | POST | `/exchange (scheduleCancel)` | +| [setReferrer()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1229) | :closed_lock_with_key: | POST | `/exchange (setReferrer)` | +| [registerReferrer()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1235) | :closed_lock_with_key: | POST | `/exchange (registerReferrer)` | +| [approveApiWallet()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1275) | :closed_lock_with_key: | POST | `/exchange (approveAgent)` | +| [sendUsd()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1297) | :closed_lock_with_key: | POST | `/exchange (usdSend)` | +| [sendSpotAsset()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1317) | :closed_lock_with_key: | POST | `/exchange (spotSend)` | +| [withdrawUsd()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1335) | :closed_lock_with_key: | POST | `/exchange (withdraw3)` | +| [transferUsdBetweenSpotAndPerp()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1354) | :closed_lock_with_key: | POST | `/exchange (usdClassTransfer)` | +| [sendAsset()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1374) | :closed_lock_with_key: | POST | `/exchange (sendAsset)` | +| [sendToEvmWithData()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1397) | :closed_lock_with_key: | POST | `/exchange (sendToEvmWithData)` | +| [sendAssetFromApiWallet()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1414) | :closed_lock_with_key: | POST | `/exchange (agentSendAsset)` | +| [depositIntoStaking()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1436) | :closed_lock_with_key: | POST | `/exchange (cDeposit)` | +| [withdrawFromStaking()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1454) | :closed_lock_with_key: | POST | `/exchange (cWithdraw)` | +| [delegateOrUndelegateStake()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1472) | :closed_lock_with_key: | POST | `/exchange (tokenDelegate)` | +| [convertToMultiSigUser()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1487) | :closed_lock_with_key: | POST | `/exchange (convertToMultiSigUser)` | +| [linkStakingAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1513) | :closed_lock_with_key: | POST | `/exchange (linkStakingUser)` | +| [disableStakingTradingLink()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1528) | :closed_lock_with_key: | POST | `/exchange (stakingLinkDisableTradingUser)` | +| [setUserPortfolioMargin()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1543) | :closed_lock_with_key: | POST | `/exchange (userPortfolioMargin)` | +| [setUserAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1562) | :closed_lock_with_key: | POST | `/exchange (userSetAbstraction)` | +| [setUserDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1579) | :closed_lock_with_key: | POST | `/exchange (userDexAbstraction)` | +| [enableApiWalletDexAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1596) | :closed_lock_with_key: | POST | `/exchange (agentEnableDexAbstraction)` | +| [setApiWalletAbstraction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1607) | :closed_lock_with_key: | POST | `/exchange (agentSetAbstraction)` | +| [executeBorrowLendOperation()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1614) | :closed_lock_with_key: | POST | `/exchange (borrowLend)` | +| [claimRewards()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1635) | :closed_lock_with_key: | POST | `/exchange (claimRewards)` | +| [createSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1639) | :closed_lock_with_key: | POST | `/exchange (createSubAccount)` | +| [createVault()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1646) | :closed_lock_with_key: | POST | `/exchange (createVault)` | +| [setEvmBigBlocks()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1653) | :closed_lock_with_key: | POST | `/exchange (evmUserModify)` | +| [finalizeEvmContract()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1660) | :closed_lock_with_key: | POST | `/exchange (finalizeEvmContract)` | +| [submitGossipPriorityBid()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1673) | :closed_lock_with_key: | POST | `/exchange (gossipPriorityBid)` | +| [transferHip3LiquidatorFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1686) | :closed_lock_with_key: | POST | `/exchange (hip3LiquidatorTransfer)` | +| [invalidateNonce()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1696) | :closed_lock_with_key: | POST | `/exchange (noop)` | +| [deployPerp()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1700) | :closed_lock_with_key: | POST | `/exchange (perpDeploy)` | +| [deploySpot()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1707) | :closed_lock_with_key: | POST | `/exchange (spotDeploy)` | +| [reserveAdditionalActions()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1719) | :closed_lock_with_key: | POST | `/exchange (reserveRequestWeight)` | +| [setDisplayName()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1726) | :closed_lock_with_key: | POST | `/exchange (setDisplayName)` | +| [setSpotDusting()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1733) | :closed_lock_with_key: | POST | `/exchange (spotUser)` | +| [renameSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1740) | :closed_lock_with_key: | POST | `/exchange (subAccountModify)` | +| [transferSpotToOrFromSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1747) | :closed_lock_with_key: | POST | `/exchange (subAccountSpotTransfer)` | +| [transferUsdToOrFromSubAccount()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1759) | :closed_lock_with_key: | POST | `/exchange (subAccountTransfer)` | +| [transferVaultFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1769) | :closed_lock_with_key: | POST | `/exchange (vaultTransfer)` | +| [distributeVaultFunds()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1776) | :closed_lock_with_key: | POST | `/exchange (vaultDistribute)` | +| [modifyVault()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1783) | :closed_lock_with_key: | POST | `/exchange (vaultModify)` | +| [updateValidatorL1Stream()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1807) | :closed_lock_with_key: | POST | `/exchange (validatorL1Stream)` | +| [submitSignerAction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1818) | :closed_lock_with_key: | POST | `/exchange (CSignerAction)` | +| [submitValidatorAction()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1825) | :closed_lock_with_key: | POST | `/exchange (CValidatorAction)` | +| [authorizeAqav2Role()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1838) | :closed_lock_with_key: | POST | `/exchange (authorizeAqav2Role)` | +| [submitUserOutcome()](https://github.com/sieblyio/hyperliquid-api/blob/main/src/RestClient.ts#L1853) | :closed_lock_with_key: | POST | `/exchange (userOutcome)` | \ No newline at end of file diff --git a/llms.txt b/llms.txt index 5be9c87..b0d8812 100644 --- a/llms.txt +++ b/llms.txt @@ -135,106 +135,6 @@ File: scripts/clean.mjs ================ -================ -File: src/types/request/info.types.ts -================ -export interface AccountRequest { - user?: string; -} -⋮---- -export interface AccountDexRequest extends AccountRequest { - dex?: string; -} -⋮---- -export interface UserRequest { - user: string; -} -⋮---- -export interface TimeRangeRequest extends AccountRequest { - endTime?: number; - startTime?: number; -} -⋮---- -export interface GetCandlesRequest { - coin: string; - endTime?: number; - interval: - | '1d' - | '12h' - | '15m' - | '1h' - | '1m' - | '2h' - | '30m' - | '3d' - | '3m' - | '4h' - | '5m' - | '8h' - | '1w' - | '1M'; - startTime: number; -} -⋮---- -export interface GetOrderBookRequest { - coin: string; - mantissa?: 1 | 2 | 5 | null; - nSigFigs?: 2 | 3 | 4 | 5 | null; -} -⋮---- -export interface GetUserFillsRequest extends AccountRequest { - aggregateByTime?: boolean; -} -⋮---- -export interface GetUserFillsByTimeRequest extends TimeRangeRequest { - aggregateByTime?: boolean; - reversed?: boolean; - startTime: number; -} -⋮---- -export interface GetUserFundingHistoryRequest extends AccountRequest { - endTime?: number; - startTime?: number; -} -⋮---- -export interface GetFundingHistoryRequest { - coin: string; - endTime?: number; - startTime: number; -} -⋮---- -export interface GetUserNonFundingLedgerUpdatesRequest extends AccountRequest { - endTime?: number; - startTime?: number; -} -⋮---- -export interface GetOrderStatusRequest extends AccountRequest { - oid: number | string; -} -⋮---- -export interface GetUserTwapSliceFillsByTimeRequest extends AccountRequest { - endTime?: number; - startTime: number; -} -⋮---- -export interface GetUserBorrowLendInterestRequest extends AccountRequest { - endTime?: number; - startTime: number; -} -⋮---- -export interface GetMaxBuilderFeeRequest extends AccountRequest { - builder: string; -} -⋮---- -export interface GetPreTransferCheckRequest extends UserRequest { - source: string; -} -⋮---- -export interface GetVaultDetailsRequest { - user?: string; - vaultAddress: string; -} - ================ File: src/constants.ts ================ @@ -675,6 +575,112 @@ File: scripts/postbuild.mjs ================ async function copySourceDeclarations(directory) +================ +File: src/types/request/info.types.ts +================ +export interface AccountRequest { + user?: string; +} +⋮---- +export interface AccountDexRequest extends AccountRequest { + /** HIP-3 reads require the DEX name; omitted selects the default perp DEX. */ + dex?: string; +} +⋮---- +/** HIP-3 reads require the DEX name; omitted selects the default perp DEX. */ +⋮---- +export interface UserRequest { + user: string; +} +⋮---- +export interface TimeRangeRequest extends AccountRequest { + endTime?: number; + startTime?: number; +} +⋮---- +export interface GetCandlesRequest { + coin: string; + endTime?: number; + interval: + | '1d' + | '12h' + | '15m' + | '1h' + | '1m' + | '2h' + | '30m' + | '3d' + | '3m' + | '4h' + | '5m' + | '8h' + | '1w' + | '1M'; + startTime: number; +} +⋮---- +export interface GetOrderBookRequest { + coin: string; + mantissa?: 1 | 2 | 5 | null; + nSigFigs?: 2 | 3 | 4 | 5 | null; +} +⋮---- +export interface GetUserFillsRequest extends AccountRequest { + aggregateByTime?: boolean; +} +⋮---- +export interface GetUserFillsByTimeRequest extends TimeRangeRequest { + aggregateByTime?: boolean; + reversed?: boolean; + startTime: number; +} +⋮---- +export interface GetUserFundingHistoryRequest extends AccountRequest { + endTime?: number; + startTime?: number; +} +⋮---- +export interface GetFundingHistoryRequest { + coin: string; + endTime?: number; + startTime: number; +} +⋮---- +export interface GetUserNonFundingLedgerUpdatesRequest extends AccountRequest { + endTime?: number; + startTime?: number; +} +⋮---- +export interface GetOrderStatusRequest extends AccountRequest { + /** Safe integer, decimal-digit string converted to one, or 0x plus 32 hex characters. */ + oid: number | string; +} +⋮---- +/** Safe integer, decimal-digit string converted to one, or 0x plus 32 hex characters. */ +⋮---- +export interface GetUserTwapSliceFillsByTimeRequest extends AccountRequest { + endTime?: number; + startTime: number; +} +⋮---- +export interface GetUserBorrowLendInterestRequest extends AccountRequest { + endTime?: number; + startTime: number; +} +⋮---- +export interface GetMaxBuilderFeeRequest extends AccountRequest { + builder: string; +} +⋮---- +export interface GetPreTransferCheckRequest extends UserRequest { + source: string; +} +⋮---- +export interface GetVaultDetailsRequest { + user?: string; + vaultAddress: string; +} + ================ File: src/types/websockets/ws-events.ts ================ @@ -873,42 +879,145 @@ export interface WebSocketConstructor { } ================ -File: src/types/shared.types.ts +File: .nvmrc ================ -import type { AxiosRequestConfig } from 'axios'; -⋮---- -export type HyperliquidNetwork = 'mainnet' | 'testnet'; -export type HyperliquidChain = 'Mainnet' | 'Testnet'; -⋮---- -export type JsonPrimitive = boolean | number | string | null; -export type JsonValue = - JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; -export type JsonObject = Record; -⋮---- -export interface Signature { - r: string; - s: string; - v: number; -} -⋮---- -export interface TypedDataField { - name: string; - type: string; -} -⋮---- -export interface TypedDataDomain { - chainId: bigint | number | string; - name: string; - verifyingContract: string; - version: string; +v24.22.3 + +================ +File: tsconfig.extensions.json +================ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "declaration": false, + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmit": true + }, + "include": ["src/**/*.*", "examples/**/*.ts"], + "exclude": ["node_modules", "dist", "examples/apidoc", "examples/tstests"] } + +================ +File: examples/Rest/rest-leverage.ts +================ +import { RestClient } from '../../src/index.js'; ⋮---- -export type TypedDataTypes = Record; +// or +// import { RestClient } from '@siebly/hyperliquid-api'; ⋮---- /** - * Portable signer contract used by the SDK. + * Read ETH leverage, then set cross and isolated leverage. * - * ethers Wallet and most browser wallet adapters already satisfy this shape. + * Unix: + * HYPERLIQUID_PRIVATE_KEY='0xabc' npx tsx examples/Rest/rest-leverage.ts + */ +⋮---- +// testnet: true, +⋮---- +async function main() + +================ +File: examples/Websocket/WS-API/ws-api-client.ts +================ +import { + DefaultLogger, + type ExchangeResponse, + type OrderResponseData, + WebsocketAPIClient, +} from '../../../src/index.js'; +⋮---- +// or +// import { DefaultLogger, WebsocketAPIClient } from '@siebly/hyperliquid-api'; +⋮---- +/** + * WebsocketAPIClient has the same Info and Exchange methods as RestClient, but + * sends them over Hyperliquid's correlated WebSocket POST protocol. + * + * Public example: + * npx tsx examples/Websocket/WS-API/ws-api-client.ts + * + * Private example: + * HYPERLIQUID_PRIVATE_KEY='0xabc' npx tsx examples/Websocket/WS-API/ws-api-client.ts + */ +⋮---- +// trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params), +⋮---- +// testnet: true, +⋮---- +function firstRestingOid( + result: ExchangeResponse, +): number | undefined +⋮---- +async function main() +⋮---- +// Optional: open the WS API connection early so the first call is not a +// cold start. connect() happens automatically on the first request. +// await wsClient.connect(); + +================ +File: examples/Websocket/ws-private.ts +================ +import { DefaultLogger, WebsocketClient } from '../../src/index.js'; +⋮---- +// or +// import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api'; +⋮---- +/** + * Account streams. These need a wallet address, not a private key. The SDK + * isolates user streams whose server events omit the user onto per-user + * connections. + * + * Data emits through on('message'), with the original channel and wsKey. + * Subscription acknowledgements emit through on('response'). + * + * Unix: + * HYPERLIQUID_ADDRESS='0xabc' npx tsx examples/Websocket/ws-private.ts + */ +⋮---- +// trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params), +⋮---- +// testnet: true, +⋮---- +async function main() + +================ +File: src/types/shared.types.ts +================ +import type { AxiosRequestConfig } from 'axios'; +⋮---- +export type HyperliquidNetwork = 'mainnet' | 'testnet'; +export type HyperliquidChain = 'Mainnet' | 'Testnet'; +⋮---- +export type JsonPrimitive = boolean | number | string | null; +export type JsonValue = + JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; +export type JsonObject = Record; +⋮---- +export interface Signature { + r: string; + s: string; + v: number; +} +⋮---- +export interface TypedDataField { + name: string; + type: string; +} +⋮---- +export interface TypedDataDomain { + chainId: bigint | number | string; + name: string; + verifyingContract: string; + version: string; +} +⋮---- +export type TypedDataTypes = Record; +⋮---- +/** + * Portable signer contract used by the SDK. + * + * ethers Wallet and most browser wallet adapters already satisfy this shape. */ export interface HyperliquidSigner { address?: string; @@ -920,6 +1029,63 @@ export interface HyperliquidSigner { ) => Promise; } ⋮---- +/** Structural viem input; no viem installation is needed to use the SDK. */ +export interface ViemSignTypedDataParameters { + domain: { + chainId: number; + name: string; + verifyingContract: `0x${string}`; + version: string; + }; + types: TypedDataTypes; + primaryType: string; + message: Record; +} +⋮---- +export interface ViemLocalAccountLike { + type: 'local'; + address: `0x${string}`; + signTypedData(params: ViemSignTypedDataParameters): Promise<`0x${string}`>; +} +⋮---- +signTypedData(params: ViemSignTypedDataParameters): Promise<`0x$ +⋮---- +export interface ViemWalletClientLike { + /** viem publishes this as string; runtime detection requires 'walletClient'. */ + type: string; + account?: { address: `0x${string}` } | undefined; + signTypedData( + params: ViemSignTypedDataParameters & { + // Opaque viem Account: forward the original client.account without recreating it. + // Its local/smart account variants require methods outside this SDK's contract. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + account: any; + }, + ): Promise<`0x${string}`>; +} +⋮---- +/** viem publishes this as string; runtime detection requires 'walletClient'. */ +⋮---- +signTypedData( + params: ViemSignTypedDataParameters & { + // Opaque viem Account: forward the original client.account without recreating it. + // Its local/smart account variants require methods outside this SDK's contract. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + account: any; + }, +): Promise<`0x$ +⋮---- +// Opaque viem Account: forward the original client.account without recreating it. +// Its local/smart account variants require methods outside this SDK's contract. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export type HyperliquidSignerInput = + HyperliquidSigner | ViemLocalAccountLike | ViemWalletClientLike; +⋮---- +/** + * Awaited with a lower-case signer address; must return a non-negative safe integer. + * Invalid results throw RangeError before sending. Coordinate unique values across workers. + */ export interface NonceProvider { nextNonce(signerAddress: string): Promise | number; } @@ -936,19 +1102,58 @@ export interface RequestOptions { timeout?: number; } ⋮---- +export interface CustomFetchRequestInit { + method: string; + headers: Record; + body?: string; + signal?: AbortSignal; +} +⋮---- +export interface CustomFetchResponse { + status: number; + statusText: string; + headers: { forEach(callback: (value: string, key: string) => void): void }; + text(): Promise; +} +⋮---- +headers: +text(): Promise; +⋮---- +export type CustomFetch = ( + url: string, + init: CustomFetchRequestInit, +) => Promise; +⋮---- export interface RestClientOptions { accountAddress?: string; assetCacheTtlMs?: number; baseUrl?: string; + /** + * Optional fetch-compatible REST transport. Default: unset (axios). + * Pass native fetch or a wrapper such as (url, init) => env.FETCHER.fetch(url, init). + * Axios-only settings (network options, adapters, agents, interceptors) are ignored, + * except timeout, which uses AbortSignal.timeout() when available. + */ + customFetch?: CustomFetch; keepAlive?: boolean; keepAliveMsecs?: number; + /** Coordinate across threads/processes; the default manager is local to this module instance. */ nonceProvider?: NonceProvider; privateKey?: string; - signer?: HyperliquidSigner; + signer?: HyperliquidSignerInput; testnet?: boolean; vaultAddress?: string; } ⋮---- +/** + * Optional fetch-compatible REST transport. Default: unset (axios). + * Pass native fetch or a wrapper such as (url, init) => env.FETCHER.fetch(url, init). + * Axios-only settings (network options, adapters, agents, interceptors) are ignored, + * except timeout, which uses AbortSignal.timeout() when available. + */ +⋮---- +/** Coordinate across threads/processes; the default manager is local to this module instance. */ +⋮---- export interface ExchangeRequestEnvelope { action: Action; expiresAfter: number | null; @@ -985,107 +1190,9 @@ export interface L1ActionOptions { } ================ -File: .nvmrc -================ -v24.22.3 - -================ -File: tsconfig.extensions.json -================ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "declaration": false, - "module": "NodeNext", - "moduleResolution": "NodeNext", - "noEmit": true - }, - "include": ["src/**/*.*", "examples/**/*.ts"], - "exclude": ["node_modules", "dist", "examples/apidoc", "examples/tstests"] -} - -================ -File: examples/Rest/rest-leverage.ts -================ -import { RestClient } from '../../src/index.js'; -⋮---- -// or -// import { RestClient } from '@siebly/hyperliquid-api'; -⋮---- -/** - * Read ETH leverage, then set cross and isolated leverage. - * - * Unix: - * HYPERLIQUID_PRIVATE_KEY='0xabc' npx tsx examples/Rest/rest-leverage.ts - */ -⋮---- -// testnet: true, -⋮---- -async function main() - -================ -File: examples/Websocket/WS-API/ws-api-client.ts +File: src/index.ts ================ -import { - DefaultLogger, - type ExchangeResponse, - type OrderResponseData, - WebsocketAPIClient, -} from '../../../src/index.js'; -⋮---- -// or -// import { DefaultLogger, WebsocketAPIClient } from '@siebly/hyperliquid-api'; -⋮---- -/** - * WebsocketAPIClient has the same Info and Exchange methods as RestClient, but - * sends them over Hyperliquid's correlated WebSocket POST protocol. - * - * Public example: - * npx tsx examples/Websocket/WS-API/ws-api-client.ts - * - * Private example: - * HYPERLIQUID_PRIVATE_KEY='0xabc' npx tsx examples/Websocket/WS-API/ws-api-client.ts - */ -⋮---- -// trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params), -⋮---- -// testnet: true, -⋮---- -function firstRestingOid( - result: ExchangeResponse, -): number | undefined -⋮---- -async function main() -⋮---- -// Optional: open the WS API connection early so the first call is not a -// cold start. connect() happens automatically on the first request. -// await wsClient.connect(); -================ -File: examples/Websocket/ws-private.ts -================ -import { DefaultLogger, WebsocketClient } from '../../src/index.js'; -⋮---- -// or -// import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api'; -⋮---- -/** - * Account streams. These need a wallet address, not a private key. The SDK - * isolates user streams whose server events omit the user onto per-user - * connections. - * - * Data emits through on('message'), with the original channel and wsKey. - * Subscription acknowledgements emit through on('response'). - * - * Unix: - * HYPERLIQUID_ADDRESS='0xabc' npx tsx examples/Websocket/ws-private.ts - */ -⋮---- -// trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params), -⋮---- -// testnet: true, -⋮---- -async function main() ================ File: examples/Websocket/ws-public.ts @@ -1108,6 +1215,8 @@ import { DefaultLogger, WebsocketClient } from '../../src/index.js'; ⋮---- // testnet: true, ⋮---- +// Snapshot first, then changed coins and fields only. null means no book mid. +⋮---- async function main() ⋮---- // Native Spot universe names pass through without metadata requests. @@ -1128,7 +1237,7 @@ import type { OrderWireInput, } from '../../lib/action-factory.js'; import type { - HyperliquidSigner, + HyperliquidSignerInput, JsonObject, L1ActionOptions, UserSignedActionOptions, @@ -1141,12 +1250,12 @@ export type RawUserSignedRequestOptions = UserSignedActionOptions; ⋮---- export interface MultiSigL1RequestOptions extends RawL1RequestOptions { multiSigUser: string; - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]]; + signers: readonly [HyperliquidSignerInput, ...HyperliquidSignerInput[]]; } ⋮---- export interface MultiSigUserSignedRequestOptions extends RawUserSignedRequestOptions { multiSigUser: string; - signers: readonly [HyperliquidSigner, ...HyperliquidSigner[]]; + signers: readonly [HyperliquidSignerInput, ...HyperliquidSignerInput[]]; } ⋮---- export interface SubmitOrderRequest { @@ -1157,6 +1266,7 @@ export interface SubmitOrderRequest { export type OrderSide = 'buy' | 'sell'; ⋮---- export interface SubmitMarketOrderRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; maxSlippage?: number; price?: string; @@ -1166,7 +1276,10 @@ export interface SubmitMarketOrderRequest { symbol: AssetIdentifier; } ⋮---- +/** 0x followed by 32 hex characters (128 bits). */ +⋮---- export interface SubmitMarketCloseRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; maxSlippage?: number; price?: string; @@ -1174,7 +1287,10 @@ export interface SubmitMarketCloseRequest { symbol: AssetIdentifier; } ⋮---- +/** 0x followed by 32 hex characters (128 bits). */ +⋮---- export interface SubmitLimitOrderRequest { + /** 0x followed by 32 hex characters (128 bits). */ clientOrderId?: string; postOnly?: boolean; price: string; @@ -1182,9 +1298,11 @@ export interface SubmitLimitOrderRequest { side: OrderSide; size: string; symbol: AssetIdentifier; - timeInForce?: 'GTC' | 'IOC'; + timeInForce?: 'GTC' | 'IOC' | 'Gtc' | 'Ioc'; } ⋮---- +/** 0x followed by 32 hex characters (128 bits). */ +⋮---- export interface ModifyOrderRequest extends ModifyWireInput { alwaysPlace?: true; } @@ -1253,9 +1371,12 @@ export interface SubmitTrailingStopRequest { export interface TransferUsdToOrFromSubAccountRequest { isDeposit: boolean; subAccountUser: string; + /** Integer micro-USDC: 1 USDC = 1_000_000. */ usd: number; } ⋮---- +/** Integer micro-USDC: 1 USDC = 1_000_000. */ +⋮---- export interface TransferSpotToOrFromSubAccountRequest { amount: string; isDeposit: boolean; @@ -1342,7 +1463,11 @@ export interface SetUserAbstractionRequest { ⋮---- export type DeployPerpRequest = Omit; export type DeploySpotRequest = Omit; -export type SubmitUserOutcomeRequest = Omit; +export type SubmitUserOutcomeRequest = + | { splitOutcome: { outcome: number; amount: string } } + | { mergeOutcome: { outcome: number; amount: string | null } } + | { mergeQuestion: { question: number; amount: string | null } } + | { negateOutcome: { question: number; outcome: number; amount: string } }; ================ File: src/types/response/exchange.types.ts @@ -1356,6 +1481,7 @@ export interface ExchangeErrorResponse { * Exchange result. Omit Data for acknowledgements, provide it for actions * returning data, or use unknown for raw actions with unknown results. */ +/** Wire response union. Clients throw HyperliquidApiError for status: 'err' instead of resolving it. */ export type ExchangeResponse = | ExchangeErrorResponse | { @@ -1425,12 +1551,84 @@ export interface TrailingStopResponseData { } ================ -File: src/types/websockets/ws-general.ts +File: src/WebsocketAPIClient.ts ================ +import { HyperliquidWebSocketError } from './lib/websocket/errors.js'; +import { + DefaultLogger, + type DefaultLogger as Logger, +} from './lib/websocket/logger.js'; +import { RestClient } from './RestClient.js'; import type { - RestClientNetworkOptions, - RestClientOptions, -} from '../shared.types.js'; + WebsocketAPIClientOptions, + WebsocketClientEventMap, +} from './types/websockets/ws-general.js'; +import { WebsocketClient } from './WebsocketClient.js'; +⋮---- +export class WebsocketAPIClient extends RestClient +⋮---- +constructor( + options: WebsocketAPIClientOptions = {}, + logger: Logger = DefaultLogger, + ) +⋮---- +getWSClient(): WebsocketClient +⋮---- +connect(): Promise +⋮---- +on( + event: K, + listener: (...args: WebsocketClientEventMap[K]) => void, + ): this +⋮---- +once( + event: K, + listener: (...args: WebsocketClientEventMap[K]) => void, + ): this +⋮---- +off( + event: K, + listener: (...args: WebsocketClientEventMap[K]) => void, + ): this +⋮---- +isConnected(): boolean +⋮---- +close(): void +⋮---- +closeAll(): void +⋮---- +protected override post(path: string, body: unknown): Promise + +================ +File: .gitignore +================ +hyperliquidref +!.gitkeep +.DS_Store +*.log +*.tgz +.env +.env.test +localtest.sh +.eslintcache +.npm +.tmp-packed* +coverage +dist +node_modules +README_BEFORE_RELEASE.md +examples/tstests +/tmp/ +localtest.sh +rest-ts.ts + +================ +File: src/types/websockets/ws-general.ts +================ +import type { + RestClientNetworkOptions, + RestClientOptions, +} from '../shared.types.js'; import type { WebsocketMessageEvent, WebsocketResponseEvent, @@ -1456,7 +1654,9 @@ export interface WebsocketClientOptions { reconnectTimeout?: number; /** Maximum request duration in milliseconds, including connection setup. Default: 10,000. */ requestTimeoutMs?: number; - requestOptions?: RestClientNetworkOptions; + /** REST metadata options; customFetch is forwarded to the internal REST client. */ + requestOptions?: RestClientNetworkOptions & + Pick; testnet?: boolean; webSocketConstructor?: WebSocketConstructor; wsUrl?: string; @@ -1476,6 +1676,8 @@ export interface WebsocketClientOptions { ⋮---- /** Maximum request duration in milliseconds, including connection setup. Default: 10,000. */ ⋮---- +/** REST metadata options; customFetch is forwarded to the internal REST client. */ +⋮---- export type WebsocketAPIClientOptions = RestClientOptions & Omit; ⋮---- @@ -1517,2297 +1719,2279 @@ export type WebsocketLifecycleCallback = ( ) => void; ================ -File: src/index.ts -================ - - -================ -File: src/WebsocketAPIClient.ts +File: src/types/websockets/ws-subscriptions.ts ================ -import { HyperliquidWebSocketError } from './lib/websocket/errors.js'; -import { - DefaultLogger, - type DefaultLogger as Logger, -} from './lib/websocket/logger.js'; -import { RestClient } from './RestClient.js'; import type { - WebsocketAPIClientOptions, - WebsocketClientEventMap, -} from './types/websockets/ws-general.js'; -import { WebsocketClient } from './WebsocketClient.js'; + ActiveAssetData, + Candle, + HistoricalOrder, + LeadingVault, + OpenOrder, + OrderBookResponse, + OrderState, + PerpAccountSummaryResponse, + PerpAssetContext, + SpotAssetContext, + SpotBalancesResponse, + Trade, + TwapHistoryEntry, + TwapSliceFill, + TwapState, + UserFill, + UserNonFundingLedgerUpdate, +} from '../response/info.types.js'; ⋮---- -export class WebsocketAPIClient extends RestClient +export type CandleInterval = + | '1d' + | '12h' + | '15m' + | '1h' + | '1m' + | '1M' + | '2h' + | '30m' + | '3d' + | '3m' + | '4h' + | '5m' + | '8h' + | '1w'; ⋮---- -constructor( - options: WebsocketAPIClientOptions = {}, - logger: Logger = DefaultLogger, - ) +export type UserSubscriptionType = + | 'activeAssetData' + | 'allDexsClearinghouseState' + | 'clearinghouseState' + | 'notification' + | 'openOrders' + | 'orderUpdates' + | 'spotState' + | 'twapStates' + | 'userEvents' + | 'userFills' + | 'userFundings' + | 'userHistoricalOrders' + | 'userNonFundingLedgerUpdates' + | 'userTwapHistory' + | 'userTwapSliceFills' + | 'webData3'; ⋮---- -getWSClient(): WebsocketClient +/** Incremental order book feed. s and m work like l2Book's nSigFigs and mantissa. + * https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions + */ +export interface L2Subscription { + c: string; + s?: number; + m?: number; + type: 'l2'; +} ⋮---- -connect(): Promise +export interface PacSubscription { + type: 'pac'; +} ⋮---- -on( - event: K, - listener: (...args: WebsocketClientEventMap[K]) => void, - ): this +export interface SacSubscription { + type: 'sac'; +} ⋮---- -once( - event: K, - listener: (...args: WebsocketClientEventMap[K]) => void, - ): this +export type WebsocketSubscription = + /** Deprecated upstream; use fastAssetCtxs for live prices. REST getAllMids remains supported. */ + | { dex?: string; type: 'allMids' } + | { dex?: string; type: 'assetCtxs' } + /** Spot messages arrive on activeSpotAssetCtx; perps arrive on activeAssetCtx. */ + | { coin: string; type: 'activeAssetCtx' } + | { coin: string; user: string; type: 'activeAssetData' } + | { type: 'allDexsAssetCtxs' } + | { user: string; type: 'allDexsClearinghouseState' } + | { coin: string; type: 'bbo' } + | { coin: string; interval: CandleInterval; type: 'candle' } + | { dex?: string; user: string; type: 'clearinghouseState' } + | { type: 'fastAssetCtxs' } + | L2Subscription + | { + coin: string; + /** Lower latency, with 5 levels per side instead of the default 20. */ + fast?: boolean; + mantissa?: 1 | 2 | 5 | null; + nSigFigs?: 2 | 3 | 4 | 5 | null; + /** Messages omit nSigFigs/mantissa; use separate clients for multiple groupings of one coin. */ + type: 'l2Book'; + } + | { user: string; type: 'notification' } + | { dex?: string; user: string; type: 'openOrders' } + | { user: string; type: 'orderUpdates' } + | { type: 'outcomeMetaUpdates' } + | PacSubscription + | SacSubscription + | { type: 'spotAssetCtxs' } + | { + ignorePortfolioMargin?: boolean; + isPortfolioMargin?: never; + user: string; + type: 'spotState'; + } + | { + ignorePortfolioMargin?: never; + isPortfolioMargin?: boolean; + user: string; + type: 'spotState'; + } + | { coin: string; type: 'trades' } + | { dex?: string; user: string; type: 'twapStates' } + | { user: string; type: 'userEvents' } + | { aggregateByTime?: boolean; user: string; type: 'userFills' } + | { user: string; type: 'userFundings' } + | { user: string; type: 'userHistoricalOrders' } + | { user: string; type: 'userNonFundingLedgerUpdates' } + | { user: string; type: 'userTwapHistory' } + | { user: string; type: 'userTwapSliceFills' } + | { user: string; type: 'webData3' }; ⋮---- -off( - event: K, - listener: (...args: WebsocketClientEventMap[K]) => void, - ): this +/** Deprecated upstream; use fastAssetCtxs for live prices. REST getAllMids remains supported. */ ⋮---- -isConnected(): boolean +/** Spot messages arrive on activeSpotAssetCtx; perps arrive on activeAssetCtx. */ ⋮---- -close(): void +/** Lower latency, with 5 levels per side instead of the default 20. */ ⋮---- -closeAll(): void +/** Messages omit nSigFigs/mantissa; use separate clients for multiple groupings of one coin. */ ⋮---- -protected override post(path: string, body: unknown): Promise - -================ -File: docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md -================ - - -# Hyperliquid API JavaScript Tutorial for Node.js - - - -> [!TIP] -> Read this guide in tutorial format on the Siebly website: [Hyperliquid JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/hyperliquid/javascript/tutorial) - - - -This tutorial uses [`@siebly/hyperliquid-api`](https://www.npmjs.com/package/@siebly/hyperliquid-api), Siebly's Node.js and JavaScript SDK for Hyperliquid. It covers public market data, account state, perpetual and Spot orders, public and account WebSocket streams, WebSocket API requests, Testnet, network routing, and proxies. - -The SDK handles asset resolution, action signing, exact wire formatting, nonce allocation, WebSocket heartbeats, reconnects, resubscriptions, and WebSocket request matching. TypeScript declarations are included for projects that use them. - -**Key links** - -- Hyperliquid JavaScript SDK by Siebly: [`@siebly/hyperliquid-api`](https://siebly.io/sdk/hyperliquid/javascript) -- npm package: [`@siebly/hyperliquid-api`](https://www.npmjs.com/package/@siebly/hyperliquid-api) -- GitHub repository: [`sieblyio/hyperliquid-api`](https://github.com/sieblyio/hyperliquid-api) -- SDK examples: [Hyperliquid SDK examples](https://siebly.io/examples/Hyperliquid) -- Repository examples: [JavaScript and TypeScript examples](../examples) -- Hyperliquid API documentation: [Official API docs](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) -- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) -- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) - -## Why use `@siebly/hyperliquid-api`? - -Hyperliquid uses one Info endpoint for market and account reads, one Exchange endpoint for signed actions, and one WebSocket endpoint for both subscriptions and request-response traffic. Asset identifiers and signing formats also vary by operation. - -`@siebly/hyperliquid-api` presents those surfaces through three clients: - -| Client | Use it for | -| --- | --- | -| `RestClient` | Market data, account state, orders, transfers, staking, vaults, subaccounts, and other REST API operations | -| `WebsocketClient` | Public market-data and address-scoped account subscriptions | -| `WebsocketAPIClient` | The same awaitable Info and signed Exchange methods over Hyperliquid's WebSocket POST protocol | - -`RestClient` also provides higher-level helpers such as `submitMarketOrder()`, `submitLimitOrder()`, `submitMarketClose()`, and `getBalances()`. Lower-level methods remain available for batching, TP/SL orders, transfers, vault operations, and other advanced workflows. - -## Install the SDK - -```bash -npm install @siebly/hyperliquid-api -``` - -Node.js 22 or newer is supported. Every example below is plain JavaScript. - -## Set up a wallet and API wallet - -Public market data and account-state reads do not require a private key. Hyperliquid account state is queried by public address. - -Orders and other Exchange actions require a signer. For an automated process, create and approve an API wallet from the [Hyperliquid API page](https://app.hyperliquid.xyz/API). Hyperliquid also calls these agent wallets. - -Keep two values separate: - -- The API wallet private key signs actions. -- The master account, subaccount, or vault address identifies the account being managed. - -Store them in a server-side environment or secret manager: - -- `HYPERLIQUID_API_WALLET_KEY` -- `HYPERLIQUID_ACCOUNT_ADDRESS` - -For Testnet examples, use separate values: - -- `HYPERLIQUID_TESTNET_API_WALLET_KEY` -- `HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS` - -An API wallet address is not the account address. Passing the API wallet address to account queries usually returns empty state. See Hyperliquid's [nonces and API wallets](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets) documentation for the full model. - -Use one API wallet per trading process. If several processes or subaccounts share a signer, they also share its nonce set. Separate API wallets avoid nonce collisions and make process ownership clearer. - -Never put a private key in browser code, logs, or committed configuration. - -## Hyperliquid products and request vocabulary - -| Field or value | Example | Meaning | -| --- | --- | --- | -| Perpetual symbol | `BTC` | A perpetual market from `getPerpMetadata()` | -| Spot pair | `HYPE/USDC` | A readable Spot alias resolved from current metadata | -| Native Spot name | `PURR/USDC` or `@107` | The name used by HyperCore for a Spot pair | -| HIP-3 symbol | `dex:COIN` | A market on a HIP-3 perpetual DEX | -| Outcome asset | `#10` | An outcome-market identifier | -| `szDecimals` | `5` | The allowed number of decimal places in order size | -| `side` | `buy` or `sell` | The side accepted by the SDK's order helpers | -| `clientOrderId` | `0x` plus 32 hex characters | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id), called `cloid` by Hyperliquid | -| `accountAddress` | `HYPERLIQUID_ACCOUNT_ADDRESS` | The master account, subaccount, or vault whose state is queried | -| `vaultAddress` | `HYPERLIQUID_VAULT_ADDRESS` | Optional routing for actions signed on behalf of a vault or subaccount | -| `wsKey` | `public`, `api`, or `user:
` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) included with every emitted event | - -Perpetual sizes are quantities of the underlying asset. Spot sizes are quantities of the base asset. Prices, sizes, transfer amounts, and trigger prices are exact decimal strings in SDK requests. - -Hyperliquid prices may use up to five significant figures, subject to the asset's decimal limit. Order sizes use the asset's `szDecimals`. Read the current [tick and lot-size rules](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size) before constructing values yourself. - -Info responses are endpoint-specific. Some methods return objects, some return arrays, and `getOrderBook()` may return `null` for an unavailable book. There is no shared success envelope for Info responses. - - - -## Start building: first REST API calls - -Run each example on its own. Start with public market data, then read account state and inspect asset metadata. - -### 1. Make public REST API calls - -Public Info calls need no wallet or API key. - - - -```javascript -import { RestClient } from '@siebly/hyperliquid-api'; - -const client = new RestClient(); - -async function main() { - try { - const status = await client.getExchangeStatus(); - console.log('Exchange status:', status); - } catch (error) { - console.error('Exchange-status request failed:', error); - } - - try { - const mids = await client.getAllMids(); - console.log('BTC midpoint:', mids.BTC); - } catch (error) { - console.error('Midpoint request failed:', error); - } - - try { - const metadata = await client.getPerpMetadata(); - const btc = metadata.universe.find((asset) => asset.name === 'BTC'); - console.log('BTC perpetual metadata:', btc); - } catch (error) { - console.error('Perpetual metadata request failed:', error); - } - - try { - const orderBook = await client.getOrderBook({ - coin: 'BTC', - }); - console.log('Best bid:', orderBook?.levels[0][0]); - console.log('Best ask:', orderBook?.levels[1][0]); - } catch (error) { - console.error('Order-book request failed:', error); - } - - try { - const candles = await client.getCandles({ - coin: 'BTC', - interval: '1h', - startTime: Date.now() - 24 * 60 * 60 * 1000, - }); - console.log('Latest hourly candle:', candles.at(-1)); - } catch (error) { - console.error('Candle request failed:', error); - } - - try { - const trades = await client.getRecentTrades({ - coin: 'BTC', - }); - console.log('Most recent trade:', trades[0]); - } catch (error) { - console.error('Recent-trade request failed:', error); - } -} - -main(); -``` - -The response shapes reflect the requested data: - -- `getExchangeStatus()` returns an object with `time` and `specialStatuses`. -- `getAllMids()` returns an object whose keys are asset names and whose values are decimal strings. -- `getPerpMetadata()` returns an object with `universe`, `marginTables`, and `collateralToken`. -- `getOrderBook()` returns `coin`, `time`, and two arrays under `levels`. Index `0` contains bids and index `1` contains asks. Each level has `px`, `sz`, and `n`. -- `getCandles()` returns candle objects with fields such as `t`, `T`, `o`, `c`, `h`, `l`, `v`, and `n`. -- `getRecentTrades()` returns an array. `side: 'B'` is a buy and `side: 'A'` is a sell. - -### 2. Read account state by address - -Balances, positions, orders, and fills are Info queries keyed by a public address. No signer is needed for these reads. - - - -```javascript -import { RestClient } from '@siebly/hyperliquid-api'; - -const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; - -if (!accountAddress) { - throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); -} - -const client = new RestClient({ accountAddress }); - -async function main() { - try { - const balances = await client.getBalances(); - console.log('Account:', balances.user); - console.log('Spot balances:', balances.spot.balances); - console.log('Perpetual positions:', balances.perp.assetPositions); - } catch (error) { - console.error('Balance request failed:', error); - } - - try { - const openOrders = await client.getOpenOrders(); - console.log('Open orders:', openOrders); - } catch (error) { - console.error('Open-order request failed:', error); - } - - try { - const fills = await client.getUserFills({ - aggregateByTime: true, - }); - console.log('Recent fills:', fills); - } catch (error) { - console.error('Fill request failed:', error); - } - - try { - const funding = await client.getUserFundingHistory({ - startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, - }); - console.log('Recent funding payments:', funding); - } catch (error) { - console.error('Funding-history request failed:', error); - } -} - -main(); -``` - -`getBalances()` combines the Spot clearinghouse state and the default perpetual clearinghouse state. The perpetual response includes margin summaries, `withdrawable`, and `assetPositions`. A signed position size is available as `position.szi`: positive is long, negative is short, and zero is flat. Under unified account or portfolio margin, Spot state is the relevant balance view. This helper does not aggregate every HIP-3 DEX. - -A client configured with `accountAddress` may omit `user` from account getters. A public client can instead pass `{ user: accountAddress }` to each account method. - -Time-ranged Info methods have response limits. Paginate long histories by moving `startTime` to the last returned timestamp. See the official [Info endpoint documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint) for each method's current limit. - -### 3. Resolve perpetual, Spot, HIP-3, and outcome assets - -The SDK loads current Mainnet or Testnet metadata when an operation needs an asset ID. The cache lasts five minutes by default. - - - -```javascript -import { RestClient } from '@siebly/hyperliquid-api'; - -const client = new RestClient(); - -async function main() { - try { - const btcPerpetual = await client.resolveAsset('BTC'); - console.log('BTC perpetual:', btcPerpetual); - } catch (error) { - console.error('Perpetual resolution failed:', error); - } - - try { - const hypeSpot = await client.resolveAsset('HYPE/USDC'); - console.log('HYPE/USDC Spot:', hypeSpot); - } catch (error) { - console.error('Spot resolution failed:', error); - } - - try { - const nativeSpotName = await client.nameToCoin('HYPE/USDC'); - console.log('Native Spot name:', nativeSpotName); - } catch (error) { - console.error('Spot-name lookup failed:', error); - } - - try { - await client.refreshAssetMetadata(); - console.log('Asset metadata refreshed.'); - } catch (error) { - console.error('Metadata refresh failed:', error); - } -} - -main(); -``` - -`resolveAsset()` returns the numeric `assetId`, canonical name, asset kind, and `szDecimals` where available. It accepts current metadata names, readable Spot aliases, numeric IDs, HIP-3 names such as `dex:COIN`, and outcome identifiers such as `#10`. - -Asset IDs differ across Mainnet and Testnet. Resolve them against the same network that will receive the request. Do not add `-PERP` or `-SPOT` suffixes. - -`getOrderBook()`, `getCandles()`, and `getFundingHistory()` apply Hyperliquid's native name mapping where required. For example, a readable Spot alias such as `HYPE/USDC` resolves to its current `@` name, while `PURR/USDC` is already a native universe name. Streaming subscriptions, `getRecentTrades()`, and `getActiveAssetData()` expect an official coin name. Call `nameToCoin()` explicitly when starting with a readable Spot alias, then pass the result as `coin`. Subscribing with a native coin name does not make a REST API metadata request. - - - -## Build with Hyperliquid WebSocket streams - -`WebsocketClient` manages connections, JSON parsing, heartbeats, reconnects, and resubscriptions. Subscriptions are objects that match Hyperliquid's documented channel types. - -### 4. Subscribe to public market data - - - -```javascript -import { WebsocketClient } from '@siebly/hyperliquid-api'; - -const client = new WebsocketClient(); - -async function main() { - client - .on('open', ({ wsKey }) => { - console.log('WebSocket opened:', wsKey); - }) - .on('reconnecting', ({ wsKey, event }) => { - console.log('WebSocket reconnecting:', wsKey, event); - }) - .on('reconnected', ({ wsKey }) => { - console.log('WebSocket reconnected:', wsKey); - }) - .on('close', ({ wsKey }) => { - console.log('WebSocket closed:', wsKey); - }) - .on('exception', ({ wsKey, event, data }) => { - console.error('WebSocket exception:', wsKey, event ?? data); - }); - - client.on('message', ({ channel, data, wsKey }) => { - switch (channel) { - case 'allMids': - console.log('BTC midpoint:', wsKey, data.mids.BTC); - break; - case 'l2Book': - console.log('Best bid:', data.levels[0][0]); - console.log('Best ask:', data.levels[1][0]); - break; - case 'trades': - console.log('Trades:', data); - break; - case 'candle': - console.log('One-minute candle:', data); - break; - } - }); - - client.on('response', ({ channel, data, wsKey }) => { - if (channel === 'subscriptionResponse') { - console.log('Subscription acknowledgement:', wsKey, data); - } - }); - - try { - await client.subscribe([ - { type: 'allMids' }, - { type: 'l2Book', coin: 'BTC' }, - { type: 'trades', coin: 'BTC' }, - { type: 'candle', coin: 'BTC', interval: '1m' }, - ]); - } catch (error) { - console.error('Market subscription failed:', error); - } -} - -main(); -``` - -Hyperliquid sends a [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) when the subscription is registered. The SDK emits that protocol message through `response`. Market and account updates arrive through `message`, preserving the full `{ channel, data, wsKey }` envelope. - -Register listeners before subscribing. Each incoming data message is emitted once, and every registered `message` listener receives it. Filter by `channel` and the payload's coin or user when consuming several feeds. - -The promise returned by `subscribe()` resolves after the socket opens and the request is sent. It does not wait for the server acknowledgement, so do not use that promise alone as a stream-readiness signal. - -Some channels send an initial snapshot before later updates. `l2Book` sends a current book, while `allMids`, trades, and candles continue with new values. The SDK sends regular heartbeat pings to check connection health. - -`subscribe()` and `unsubscribe()` accept one topic or an array of topics. Equivalent topics are deduplicated by value. Listeners are independent of subscriptions: use `off('message', listener)` to remove a listener and `unsubscribe(topic)` to stop a stream. Call `client.closeAll()` when the application needs to close its WebSocket connections. - -`connectionTimeout` defaults to 10,000 ms. Heartbeats use a 10,000 ms ping interval and a 1,000 ms pong deadline. Increase `connectionTimeout` or `pongTimeout` for a higher-latency connection. Reconnect delays start at 500 ms and double up to 10,000 ms. - -#### Subscribe to a Spot market - -Resolve a readable Spot pair once, then subscribe with its native coin name. The lookup uses the REST API; `subscribe()` itself only sends WebSocket messages. - -```javascript -import { WebsocketClient } from '@siebly/hyperliquid-api'; - -const client = new WebsocketClient(); - -client.on('message', ({ channel, data }) => { - if (channel === 'l2Book') { - console.log('Spot book:', data.coin, data.levels); - } -}); - -client.on('exception', ({ wsKey, event, data }) => { - console.error('WebSocket exception:', wsKey, event ?? data); -}); - -async function main() { - let coin; - - try { - coin = await client.nameToCoin('HYPE/USDC'); - } catch (error) { - console.error('Spot-name lookup failed:', error); - return; - } - - try { - await client.subscribe({ type: 'l2Book', coin }); - } catch (error) { - console.error('Spot subscription failed:', error); - } -} - -main(); -``` - -### 5. Subscribe to account updates - -Account subscriptions use the account's public address. They do not need a signer. - - - -```javascript -import { WebsocketClient } from '@siebly/hyperliquid-api'; - -const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; - -if (!user) { - throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); -} - -const client = new WebsocketClient(); - -async function main() { - client - .on('open', ({ wsKey }) => { - console.log('WebSocket opened:', wsKey); - }) - .on('reconnected', ({ wsKey }) => { - console.log('WebSocket reconnected:', wsKey); - }) - .on('exception', ({ wsKey, event, data }) => { - console.error('WebSocket exception:', wsKey, event ?? data); - }); - - client.on('message', ({ channel, data, wsKey }) => { - switch (channel) { - case 'orderUpdates': - console.log('Order updates:', wsKey, data); - break; - case 'userFills': - console.log('Fill snapshot:', data.isSnapshot === true); - console.log('Fills:', data.fills); - break; - case 'clearinghouseState': - console.log('Perpetual state:', data.clearinghouseState); - break; - case 'spotState': - console.log('Spot state:', data.spotState); - break; - } - }); - - try { - await client.subscribe([ - { type: 'orderUpdates', user }, - { type: 'userFills', user, aggregateByTime: true }, - { type: 'clearinghouseState', user }, - { type: 'spotState', user }, - ]); - } catch (error) { - console.error('Account subscription failed:', error); - } -} - -main(); -``` - -`userFills`, `userFundings`, and similar time-series streams tag their initial payload with `isSnapshot: true`. Use the snapshot to initialize state, then process later payloads as changes. Avoid applying the same snapshot twice after a reconnect. - -The `orderUpdates` stream reports order transitions. Use it with a REST API query when reconciling [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation) after an uncertain order or cancellation response. - -Every lifecycle, message, response, and exception event includes `wsKey`. Most subscriptions share `public`. `orderUpdates`, `notification`, and `userEvents` use `user:` connections because their server messages omit the address. Use that key to identify the account. The `userEvents` subscription emits messages on Hyperliquid's `user` channel. - - - -## Place and manage Testnet orders - -Use Hyperliquid Testnet to run the following workflows. Create and approve an API wallet from the [Testnet API page](https://app.hyperliquid-testnet.xyz/API), fund the account from the [Testnet faucet](https://app.hyperliquid-testnet.xyz/drip), then set `HYPERLIQUID_TESTNET_API_WALLET_KEY` and `HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS`. The faucet currently requires the same address to have deposited on Mainnet. - -The SDK signs Exchange actions with the API wallet and sends account queries for the configured account address. It lowercases EVM addresses and formats action fields in the order required by Hyperliquid's signing rules. - -Order responses need two checks: - -1. `status` must be `ok`. -2. Each entry under `response.data.statuses` must be inspected. - -An order status entry may contain `resting`, `filled`, or `error`. A successful request can still contain an order-specific error. - -The SDK makes a passive, one-time attempt to apply the `SIEBLY` referral code around the first trading action from a client instance when the account has no existing referrer. It does not replace an existing referrer, delay the order, or retry the referral request. Hyperliquid's current [referral terms](https://hyperliquid.gitbook.io/hyperliquid-docs/referrals) describe any user discount. - -### 6. Run a perpetual REST API order lifecycle - -This example reads current BTC metadata and book data, places a post-only Testnet order, queries it, cancels it by client order ID, and queries it again. - - - -```javascript -import { randomBytes } from 'node:crypto'; -import { RestClient } from '@siebly/hyperliquid-api'; - -const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; -const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; - -if (!privateKey || !accountAddress) { - throw new Error( - 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', - ); -} - -const client = new RestClient({ - privateKey, - accountAddress, - testnet: true, -}); - -function trimDecimal(value) { - if (!value.includes('.')) { - return value; - } - return value.replace(/0+$/, '').replace(/\.$/, ''); -} - -function sizeForNotional(price, szDecimals, targetNotional) { - const factor = 10 ** szDecimals; - const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; - return trimDecimal(size.toFixed(szDecimals)); -} - -async function main() { - let btc; - let orderBook; - - try { - const metadata = await client.getPerpMetadata(); - btc = metadata.universe.find((asset) => asset.name === 'BTC'); - console.log('BTC metadata:', btc); - } catch (error) { - console.error('Perpetual metadata request failed:', error); - return; - } - - if (!btc) { - console.error('BTC was not returned by the Testnet perpetual metadata.'); - return; - } - - try { - orderBook = await client.getOrderBook({ coin: 'BTC' }); - console.log('BTC order book received at:', orderBook?.time); - } catch (error) { - console.error('Order-book request failed:', error); - return; - } - - const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; - - if (!bid) { - console.error('The BTC order book did not contain a bid.'); - return; - } - - const clientOrderId = `0x${randomBytes(16).toString('hex')}`; - const size = sizeForNotional(bid.px, btc.szDecimals, 12); - let orderId; - - try { - const result = await client.submitLimitOrder({ - symbol: 'BTC', - side: 'buy', - price: bid.px, - size, - postOnly: true, - clientOrderId, - }); - console.log('Order response:', result); - - if (result.status !== 'ok') { - console.error('Hyperliquid rejected the order request:', result.response); - return; - } - - const orderStatus = result.response.data?.statuses[0]; - - if (!orderStatus) { - console.error('The order response did not contain an order status.'); - return; - } - - if ('error' in orderStatus) { - console.error('The order was rejected:', orderStatus.error); - return; - } - - if ('filled' in orderStatus) { - console.log('The order filled immediately:', orderStatus.filled); - return; - } - - orderId = orderStatus.resting.oid; - console.log('Resting order ID:', orderId); - } catch (error) { - console.error('Order submission failed:', error); - return; - } - - try { - const currentOrder = await client.getOrderStatus({ oid: orderId }); - console.log('Order before cancellation:', currentOrder); - } catch (error) { - console.error('Order-status request failed:', error); - } - - try { - const cancellation = await client.cancelOrdersByClientOrderId({ - cancels: [{ asset: 'BTC', cloid: clientOrderId }], - }); - console.log('Cancellation response:', cancellation); - } catch (error) { - console.error('Cancellation failed:', error); - return; - } - - try { - const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); - console.log('Final order state:', finalOrder); - } catch (error) { - console.error('Final order-status request failed:', error); - } +export interface AllMidsEvent { + dex?: string; + mids: Record; } - -main(); -``` - -The fifth bid is already a valid Hyperliquid price and normally remains below the best ask, which makes it suitable for an add-liquidity-only order. The size targets at least 12 USDC of notional and rounds up to the asset's `szDecimals`, keeping it above Hyperliquid's current 10 USDC minimum order value. - -`postOnly: true` maps to Hyperliquid's `Alo` time in force. Without `postOnly`, `submitLimitOrder()` defaults to good-till-cancelled. Set `timeInForce: 'IOC'` for immediate-or-cancel. - -The `clientOrderId` is 16 random bytes encoded as a 32-character hexadecimal string. Keep it with the local order record. It can be used with `getOrderStatus()` and `cancelOrdersByClientOrderId()` when the numeric exchange order ID is not yet known. - -### 7. Run a Spot REST API order lifecycle - -Spot orders use the same helper, but the symbol resolves to a Spot asset ID and size means base-asset quantity. This example places a post-only PURR/USDC buy on Testnet. - - - -```javascript -import { randomBytes } from 'node:crypto'; -import { RestClient } from '@siebly/hyperliquid-api'; - -const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; -const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; - -if (!privateKey || !accountAddress) { - throw new Error( - 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', - ); +⋮---- +export interface AssetContextEvent { + coin: string; + ctx: PerpAssetContext | SpotAssetContext; } - -const client = new RestClient({ - privateKey, - accountAddress, - testnet: true, -}); - -function trimDecimal(value) { - if (!value.includes('.')) { - return value; - } - return value.replace(/0+$/, '').replace(/\.$/, ''); +⋮---- +export interface ActivePerpAssetContextEvent extends AssetContextEvent { + ctx: PerpAssetContext; } - -function sizeForNotional(price, szDecimals, targetNotional) { - const factor = 10 ** szDecimals; - const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; - return trimDecimal(size.toFixed(szDecimals)); +⋮---- +export interface ActiveSpotAssetContextEvent extends AssetContextEvent { + ctx: SpotAssetContext; } - -async function main() { - let asset; - let orderBook; - - try { - asset = await client.resolveAsset('PURR/USDC'); - console.log('PURR/USDC asset:', asset); - } catch (error) { - console.error('Spot asset resolution failed:', error); - return; - } - - if (asset.szDecimals === undefined) { - console.error('PURR/USDC size metadata was not available.'); - return; - } - - try { - orderBook = await client.getOrderBook({ coin: 'PURR/USDC' }); - console.log('PURR/USDC order book received at:', orderBook?.time); - } catch (error) { - console.error('Spot order-book request failed:', error); - return; - } - - const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; - - if (!bid) { - console.error('The PURR/USDC order book did not contain a bid.'); - return; - } - - const clientOrderId = `0x${randomBytes(16).toString('hex')}`; - const size = sizeForNotional(bid.px, asset.szDecimals, 12); - let orderId; - - try { - const result = await client.submitLimitOrder({ - symbol: 'PURR/USDC', - side: 'buy', - price: bid.px, - size, - postOnly: true, - clientOrderId, - }); - console.log('Spot order response:', result); - - if (result.status !== 'ok') { - console.error('Hyperliquid rejected the order request:', result.response); - return; - } - - const orderStatus = result.response.data?.statuses[0]; - - if (!orderStatus) { - console.error('The order response did not contain an order status.'); - return; - } - - if ('error' in orderStatus) { - console.error('The order was rejected:', orderStatus.error); - return; - } - - if ('filled' in orderStatus) { - console.log('The order filled immediately:', orderStatus.filled); - return; - } - - orderId = orderStatus.resting.oid; - console.log('Resting Spot order ID:', orderId); - } catch (error) { - console.error('Spot order submission failed:', error); - return; - } - - try { - const currentOrder = await client.getOrderStatus({ oid: orderId }); - console.log('Spot order before cancellation:', currentOrder); - } catch (error) { - console.error('Spot order-status request failed:', error); - } - - try { - const cancellation = await client.cancelOrdersByClientOrderId({ - cancels: [{ asset: 'PURR/USDC', cloid: clientOrderId }], - }); - console.log('Spot cancellation response:', cancellation); - } catch (error) { - console.error('Spot cancellation failed:', error); - return; - } - - try { - const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); - console.log('Final Spot order state:', finalOrder); - } catch (error) { - console.error('Final Spot order-status request failed:', error); - } +⋮---- +export interface AssetCtxsEvent { + ctxs: PerpAssetContext[]; + dex: string; +} +⋮---- +export interface AllDexsAssetCtxsEvent { + ctxs: Array<[dex: string, contexts: PerpAssetContext[]]>; +} +⋮---- +export type WsBook = Pick; +⋮---- +/** Snapshot, uncompressed diff, or base64 raw-DEFLATE compressed WsL2Diff. */ +export type WsL2 = { s: WsBook } | { u: WsL2Diff } | { c: string }; +⋮---- +export interface WsL2Diff { + /** Coin. */ + c: string; + /** Time. */ + t: number; + /** [bids, asks] levels to add or replace by price after removals. */ + l: [WsL2LevelUpdate[], WsL2LevelUpdate[]]; + /** [bids, asks] indexes to remove from the previous book. */ + r: [number[], number[]]; +} +⋮---- +/** Coin. */ +⋮---- +/** Time. */ +⋮---- +/** [bids, asks] levels to add or replace by price after removals. */ +⋮---- +/** [bids, asks] indexes to remove from the previous book. */ +⋮---- +export interface WsL2LevelUpdate { + /** Price. */ + p: string; + /** Size. Diffs do not include the number of orders. */ + s: string; +} +⋮---- +/** Price. */ +⋮---- +/** Size. Diffs do not include the number of orders. */ +⋮---- +/** Decoded perp contexts by dex, positional over each dex's universe. The first dex is ''. + * After the initial snapshot, contexts contain only changed fields, or {}. + */ +export type WsPac = Array< + [dex: string, contexts: Array>] +>; +⋮---- +/** Decoded spot contexts by coin. After the snapshot, only changed coins/fields appear. */ +export type WsSac = Record>; +⋮---- +export interface ClearinghouseStateEvent { + clearinghouseState: PerpAccountSummaryResponse; + dex: string; + user: string; +} +⋮---- +export interface AllDexsClearinghouseStateEvent { + clearinghouseStates: Array<[dex: string, state: PerpAccountSummaryResponse]>; + user: string; +} +⋮---- +export type ActiveAssetDataEvent = ActiveAssetData; +⋮---- +export interface BboEvent { + bbo: [ + bid: { n: number; px: string; sz: string } | null, + offer: { n: number; px: string; sz: string } | null, + ]; + coin: string; + time: number; +} +⋮---- +export type TradeEvent = Trade; +⋮---- +export interface NotificationEvent { + notification: string; +} +⋮---- +export interface OrderUpdateEvent { + order: OpenOrder; + status: OrderState; + statusTimestamp: number; +} +⋮---- +/** + * Decoded full snapshot first (also after resubscription), then changed coins/fields only. + * Merge each coin's fields into a cache. Either field can be omitted in a diff; + * midPx: null means the book has no mid. + */ +export interface FastAssetCtxsEvent { + [coin: string]: { + markPx?: string; + midPx?: string | null; + }; +} +⋮---- +export type SpotAssetCtxsEvent = SpotAssetContext[]; +⋮---- +export interface OutcomeMetaUpdatesEvent { + updates: Array< + | { + outcomeCreated: { + description: string; + name: string; + outcome: number; + quoteToken: string; + sideSpecs: Array<{ name: string; token?: number }>; + }; + } + | { outcomeSettled: { outcome: number } } + | { + questionUpdated: { + description: string; + fallbackOutcome: number; + name: string; + namedOutcomes: number[]; + question: number; + settledNamedOutcomes: number[]; + }; + } + | { questionSettled: { question: number } } + >; } - -main(); -``` - -The account needs enough Testnet USDC to reserve the order. A Spot sell needs the corresponding base asset. Hyperliquid may return internal token names in balances, so use the names returned by the API when reconciling funds. - -### Market orders, closing positions, and leverage - -`submitMarketOrder()` is an immediate-or-cancel limit order with a protection price. When `price` is omitted, the SDK loads the current midpoint, applies `maxSlippage`, rounds the protection price to Hyperliquid's rules, and rounds size down to `szDecimals`. - -Call `submitMarketOrder()` with `symbol`, `side`, `size`, and an optional `maxSlippage`. For example, a BTC buy can use `{ symbol: 'BTC', side: 'buy', size: '0.001', maxSlippage: 0.01 }`. - -`submitMarketClose()` reads the current perpetual position, chooses the closing side, and submits a reduce-only immediate-or-cancel order. Omit `size` to close the full position. - -Call `submitMarketClose()` with the perpetual symbol and an optional `maxSlippage`. Add `size` when only part of the position should be closed. - -Call `updateLeverage()` with `{ asset: 'BTC', isCross: true, leverage: 3 }` to select three-times cross leverage for BTC. Use the current asset metadata and account limits when choosing leverage. - -These are signed production actions on Mainnet and signed test actions on Testnet. Read current account and market state before calling them. - - - -## Send Info and Exchange requests with the WebSocket API - -`WebsocketAPIClient` exposes the same promise-based methods as `RestClient`, but sends supported Info and Exchange requests through Hyperliquid's WebSocket POST protocol. - -The SDK opens the connection when needed, assigns a unique request ID, matches the response to the promise, and rejects protocol errors. The raw `id` and response wrapper do not need to be managed by application code. - -This example reads market data, submits a post-only BTC Testnet order, and cancels it through the WebSocket API. - - - -```javascript -import { randomBytes } from 'node:crypto'; -import { WebsocketAPIClient } from '@siebly/hyperliquid-api'; - -const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; -const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; - -if (!privateKey || !accountAddress) { - throw new Error( - 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', - ); +⋮---- +export interface UserFillsEvent { + fills: UserFill[]; + isSnapshot?: boolean; + user: string; } - -const client = new WebsocketAPIClient({ - privateKey, - accountAddress, - testnet: true, -}); - -function trimDecimal(value) { - if (!value.includes('.')) { - return value; - } - return value.replace(/0+$/, '').replace(/\.$/, ''); +⋮---- +export interface OpenOrdersEvent { + dex: string; + orders: OpenOrder[]; + user: string; } - -function sizeForNotional(price, szDecimals, targetNotional) { - const factor = 10 ** szDecimals; - const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; - return trimDecimal(size.toFixed(szDecimals)); +⋮---- +export interface UserFundingsEvent { + fundings: Array<{ + coin: string; + fundingRate: string; + nSamples: number | null; + szi: string; + time: number; + usdc: string; + }>; + isSnapshot?: boolean; + user: string; } - -async function main() { - client - .on('open', ({ wsKey }) => { - console.log('WebSocket API opened:', wsKey); - }) - .on('reconnected', ({ wsKey }) => { - console.log('WebSocket API reconnected:', wsKey); - }) - .on('exception', ({ wsKey, event, data }) => { - console.error('WebSocket API exception:', wsKey, event ?? data); - }); - - let btc; - let orderBook; - - try { - const metadata = await client.getPerpMetadata(); - btc = metadata.universe.find((asset) => asset.name === 'BTC'); - console.log('BTC metadata:', btc); - } catch (error) { - console.error('WebSocket metadata request failed:', error); - client.closeAll(); - return; - } - - if (!btc) { - console.error('BTC was not returned by the Testnet perpetual metadata.'); - client.closeAll(); - return; - } - - try { - orderBook = await client.getOrderBook({ coin: 'BTC' }); - console.log('BTC order book received at:', orderBook?.time); - } catch (error) { - console.error('WebSocket order-book request failed:', error); - client.closeAll(); - return; - } - - const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; - - if (!bid) { - console.error('The BTC order book did not contain a bid.'); - client.closeAll(); - return; - } - - const clientOrderId = `0x${randomBytes(16).toString('hex')}`; - const size = sizeForNotional(bid.px, btc.szDecimals, 12); - let orderId; - - try { - const result = await client.submitLimitOrder({ - symbol: 'BTC', - side: 'buy', - price: bid.px, - size, - postOnly: true, - clientOrderId, - }); - console.log('WebSocket order response:', result); - - if (result.status !== 'ok') { - console.error('Hyperliquid rejected the order request:', result.response); - client.closeAll(); - return; +⋮---- +export interface UserHistoricalOrdersEvent { + isSnapshot?: boolean; + orderHistory: HistoricalOrder[]; + user: string; +} +⋮---- +export interface UserNonFundingLedgerUpdatesEvent { + isSnapshot?: boolean; + nonFundingLedgerUpdates: UserNonFundingLedgerUpdate[]; + user: string; +} +⋮---- +export interface UserTwapHistoryEvent { + history: TwapHistoryEntry[]; + isSnapshot?: boolean; + user: string; +} +⋮---- +export interface UserTwapSliceFillsEvent { + isSnapshot?: boolean; + twapSliceFills: TwapSliceFill[]; + user: string; +} +⋮---- +export interface SpotStateEvent { + spotState: SpotBalancesResponse; + user: string; +} +⋮---- +export interface TwapStatesEvent { + dex: string; + states: Array<[twapId: number, state: TwapState]>; + user: string; +} +⋮---- +export type UserEvent = + | { fills: UserFill[] } + | { + funding: { + coin: string; + fundingRate: string; + nSamples: number | null; + szi: string; + time: number; + usdc: string; + }; } + | { + liquidation: { + lid: number; + liquidated_account_value: string; + liquidated_ntl_pos: string; + liquidated_user: string; + liquidator: string; + }; + } + | { nonUserCancel: Array<{ coin: string; oid: number }> } + | { twapHistory: TwapHistoryEntry[] } + | { twapSliceFills: TwapSliceFill[] }; +⋮---- +export interface WebData3PerpDexState { + leadingVaults?: LeadingVault[]; + perpsAtOpenInterestCap?: string[]; + totalVaultEquity: string; +} +⋮---- +export interface WebData3Event { + perpDexStates: WebData3PerpDexState[]; + userState: { + abstraction?: 'disabled' | 'portfolioMargin' | 'unifiedAccount'; + agentAddress: string | null; + agentValidUntil: number | null; + cumLedger: string; + dexAbstractionEnabled?: boolean; + isVault: boolean; + optOutOfSpotDusting?: true; + serverTime: number; + user: string; + }; +} +⋮---- +export type GenericWebsocketEvent = + Record | unknown[] | string | number | boolean | null; +⋮---- +/** Payload types keyed by subscription type. Wire envelopes are defined in ws-events. */ +export interface WebsocketSubscriptionData { + activeAssetCtx: AssetContextEvent; + activeAssetData: ActiveAssetDataEvent; + allDexsAssetCtxs: AllDexsAssetCtxsEvent; + allDexsClearinghouseState: AllDexsClearinghouseStateEvent; + allMids: AllMidsEvent; + assetCtxs: AssetCtxsEvent; + bbo: BboEvent; + candle: Candle; + clearinghouseState: ClearinghouseStateEvent; + fastAssetCtxs: FastAssetCtxsEvent; + l2: WsL2; + l2Book: OrderBookResponse; + notification: NotificationEvent; + openOrders: OpenOrdersEvent; + orderUpdates: OrderUpdateEvent[]; + outcomeMetaUpdates: OutcomeMetaUpdatesEvent; + pac: WsPac; + sac: WsSac; + spotAssetCtxs: SpotAssetCtxsEvent; + spotState: SpotStateEvent; + trades: TradeEvent[]; + twapStates: TwapStatesEvent; + userEvents: UserEvent; + userFills: UserFillsEvent; + userFundings: UserFundingsEvent; + userHistoricalOrders: UserHistoricalOrdersEvent; + userNonFundingLedgerUpdates: UserNonFundingLedgerUpdatesEvent; + userTwapHistory: UserTwapHistoryEvent; + userTwapSliceFills: UserTwapSliceFillsEvent; + webData3: WebData3Event; +} +⋮---- +export type WebsocketEventFor = + WebsocketSubscriptionData[S['type']]; - const orderStatus = result.response.data?.statuses[0]; - - if (!orderStatus) { - console.error('The order response did not contain an order status.'); - client.closeAll(); - return; - } +================ +File: docs/HYPERLIQUID_SDK_QUICKSTART_GUIDE.md +================ + - if ('error' in orderStatus) { - console.error('The order was rejected:', orderStatus.error); - client.closeAll(); - return; - } +# Hyperliquid API JavaScript Tutorial for Node.js - if ('filled' in orderStatus) { - console.log('The order filled immediately:', orderStatus.filled); - client.closeAll(); - return; - } + - orderId = orderStatus.resting.oid; - console.log('Resting order ID:', orderId); - } catch (error) { - console.error('WebSocket order submission failed:', error); - client.closeAll(); - return; - } +> [!TIP] +> Read this guide in tutorial format on the Siebly website: [Hyperliquid JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/hyperliquid/javascript/tutorial) - try { - const currentOrder = await client.getOrderStatus({ oid: orderId }); - console.log('Order before cancellation:', currentOrder); - } catch (error) { - console.error('WebSocket order-status request failed:', error); - } + - try { - const cancellation = await client.cancelOrdersByClientOrderId({ - cancels: [{ asset: 'BTC', cloid: clientOrderId }], - }); - console.log('WebSocket cancellation response:', cancellation); - } catch (error) { - console.error('WebSocket cancellation failed:', error); - } +This tutorial uses [`@siebly/hyperliquid-api`](https://www.npmjs.com/package/@siebly/hyperliquid-api), Siebly's Node.js and JavaScript SDK for Hyperliquid. It covers public market data, account state, perpetual and Spot orders, public and account WebSocket streams, WebSocket API requests, Testnet, network routing, and proxies. - try { - const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); - console.log('Final WebSocket order state:', finalOrder); - } catch (error) { - console.error('Final WebSocket order-status request failed:', error); - } +The SDK handles asset resolution, action signing, exact wire formatting, nonce allocation, WebSocket heartbeats, reconnects, resubscriptions, and WebSocket request matching. TypeScript declarations are included for projects that use them. - client.closeAll(); -} +**Key links** -main(); -``` +- Hyperliquid JavaScript SDK by Siebly: [`@siebly/hyperliquid-api`](https://siebly.io/sdk/hyperliquid/javascript) +- npm package: [`@siebly/hyperliquid-api`](https://www.npmjs.com/package/@siebly/hyperliquid-api) +- GitHub repository: [`sieblyio/hyperliquid-api`](https://github.com/sieblyio/hyperliquid-api) +- SDK examples: [Hyperliquid SDK examples](https://siebly.io/examples/Hyperliquid) +- Repository examples: [JavaScript and TypeScript examples](../examples) +- Hyperliquid API documentation: [Official API docs](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) +- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) +- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) -WebSocket POST supports Info requests and signed Exchange actions. Explorer requests are not supported. Use `WebsocketClient` for subscriptions and `WebsocketAPIClient` for awaitable request-response calls. +## Why use `@siebly/hyperliquid-api`? -Successful POST replies also emit `response` events with `channel: 'post'` and `wsKey: 'api'`. Protocol errors and top-level Exchange rejections emit `exception` and reject the matching promise. An accepted action can still contain individual order errors, so inspect its status entries. Use `try`/`catch` for each command; event listeners provide additional connection and protocol diagnostics. +Hyperliquid uses one Info endpoint for market and account reads, one Exchange endpoint for signed actions, and one WebSocket endpoint for both subscriptions and request-response traffic. Asset identifiers and signing formats also vary by operation. -`requestTimeoutMs` defaults to 10,000 ms and includes connection setup. Requests interrupted by a disconnect are rejected, not replayed after reconnection. Query the order's status before retrying a command whose outcome is uncertain. +`@siebly/hyperliquid-api` presents those surfaces through three clients: -An order-command response acknowledges the action and reports its immediate status. Confirm later changes through `orderUpdates` or `getOrderStatus()`. That distinction is important when an order fills or is cancelled immediately after its first response. +| Client | Use it for | +| -------------------- | ---------------------------------------------------------------------------------------------------------- | +| `RestClient` | Market data, account state, orders, transfers, staking, vaults, subaccounts, and other REST API operations | +| `WebsocketClient` | Public market-data and address-scoped account subscriptions | +| `WebsocketAPIClient` | The same awaitable Info and signed Exchange methods over Hyperliquid's WebSocket POST protocol | -## Explore more REST API methods +`RestClient` also provides higher-level helpers such as `submitMarketOrder()`, `submitLimitOrder()`, `submitMarketClose()`, and `getBalances()`. Lower-level methods remain available for batching, TP/SL orders, transfers, vault operations, and other advanced workflows. -`RestClient` covers Hyperliquid's wider Info and Exchange surfaces. The following groups are a starting map rather than a complete list. +## Install the SDK -### Market and account information +```bash +npm install @siebly/hyperliquid-api +``` -| Workflow | Representative methods | -| --- | --- | -| Perpetual markets | `getPerpMetadata()`, `getPerpAssetContexts()`, `getFundingHistory()`, `getPredictedFundingRates()` | -| Spot markets | `getSpotMetadata()`, `getSpotAssetContexts()`, `getTokenDetails()` | -| Books and trades | `getOrderBook()`, `getAllMids()`, `getCandles()`, `getRecentTrades()` | -| Orders and fills | `getOpenOrders()`, `getFrontendOpenOrders()`, `getOrderStatus()`, `getOrderHistory()`, `getUserFills()` | -| Account and risk | `getPerpAccountSummary()`, `getSpotBalances()`, `getPortfolio()`, `getUserFees()`, `getUserRateLimit()` | -| HIP-3 perpetual DEXs | `getPerpDexs()`, `getPerpDexStatus()`, `getPerpDexLimits()`, `getAllPerpMetadata()` | -| Outcome markets | `getOutcomeMetadata()`, `getSettledOutcome()` | -| Vaults and staking | `getVaultDetails()`, `getVaultSummaries()`, `getStakingSummary()`, `getStakingDelegations()` | -| Borrow and lend | `getAllBorrowLendReserveStates()`, `getBorrowLendReserveState()`, `getUserBorrowLendState()` | -| Subaccounts and signers | `getSubAccounts()`, `getExtraAgents()`, `getMultiSigSigners()`, `getUserRole()` | +Node.js 22 or newer is supported. Every example below is plain JavaScript. -### Signed actions +## Set up a wallet and API wallet -| Workflow | Representative methods | -| --- | --- | -| Orders | `submitOrder()`, `submitMarketOrder()`, `submitLimitOrder()`, `modifyOrder()`, `cancelOrders()` | -| Position management | `submitMarketClose()`, `updateLeverage()`, `updateIsolatedMargin()`, `setIsolatedMarginLeverage()` | -| TWAP and safety | `submitTwapOrder()`, `cancelTwapOrder()`, `setCancelAllAfter()` | -| Transfers | `sendUsd()`, `sendSpotAsset()`, `sendAsset()`, `transferUsdBetweenSpotAndPerp()`, `withdrawUsd()` | -| Subaccounts and vaults | `createSubAccount()`, `transferUsdToOrFromSubAccount()`, `createVault()`, `transferVaultFunds()` | -| Staking | `depositIntoStaking()`, `withdrawFromStaking()`, `delegateOrUndelegateStake()`, `claimRewards()` | -| Account configuration | `approveApiWallet()`, `setUserPortfolioMargin()`, `setUserAbstraction()`, `setUserDexAbstraction()` | -| Advanced deployment | `deployPerp()`, `deploySpot()`, `submitUserOutcome()`, validator and multisig methods | +Public market data and account-state reads do not require a private key. Hyperliquid account state is queried by public address. -Use the focused [repository examples](../examples) and exported request types when moving beyond the workflows in this guide. Transfers, withdrawals, staking, account configuration, deployer operations, and multisig actions change funds or account settings, so confirm their current official requirements before using them. +Orders and other Exchange actions require a signer. For an automated process, create and approve an API wallet from the [Hyperliquid API page](https://app.hyperliquid.xyz/API). Hyperliquid also calls these agent wallets. -### Batch orders, TP/SL, and dead-man switches +Keep two values separate: -Use `submitOrder()` when sending native wire-shaped batches or TP/SL orders. A batch is one request for IP limits but each order still counts toward address-based limits. Inspect every returned status, because errors usually align with individual batch entries. +- The API wallet private key signs actions. +- The master account, subaccount, or vault address identifies the account being managed. -`setCancelAllAfter()` schedules cancellation of open orders if the account stops refreshing the deadline. Hyperliquid currently requires the trigger to be at least five seconds in the future and limits each account to ten scheduled-cancel triggers per UTC day. Refresh it from a monitored process, and call the method without `time` to remove the schedule when the strategy stops normally. +Store them in a server-side environment or secret manager: -Set `expiresAfter: Date.now() + 10_000` in the second argument of a signed method when an action should expire after ten seconds. This adds an action deadline. It does not replace order time in force or a dead-man switch. +- `HYPERLIQUID_API_WALLET_KEY` +- `HYPERLIQUID_ACCOUNT_ADDRESS` -### Vaults and subaccounts +For Testnet examples, use separate values: -Set `vaultAddress` on the client when all signed actions belong to one vault or subaccount: +- `HYPERLIQUID_TESTNET_API_WALLET_KEY` +- `HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS` -```javascript -import { RestClient } from '@siebly/hyperliquid-api'; +An API wallet address is not the account address. Passing the API wallet address to account queries usually returns empty state. See Hyperliquid's [nonces and API wallets](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets) documentation for the full model. -const privateKey = process.env.HYPERLIQUID_API_WALLET_KEY; -const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; -const vaultAddress = process.env.HYPERLIQUID_VAULT_ADDRESS; +Use one API wallet per trading process. If several processes or subaccounts share a signer, they also share its nonce set. Separate API wallets avoid nonce collisions and make process ownership clearer. -if (!privateKey || !accountAddress || !vaultAddress) { - throw new Error( - 'Set HYPERLIQUID_API_WALLET_KEY, HYPERLIQUID_ACCOUNT_ADDRESS, and HYPERLIQUID_VAULT_ADDRESS before starting.', - ); -} +Never put a private key in browser code, logs, or committed configuration. -const client = new RestClient({ - privateKey, - accountAddress, - vaultAddress, -}); -``` +## Hyperliquid products and request vocabulary -The signer still owns the nonce. A single API wallet used across several vaults or subaccounts shares one nonce set. Separate signers are easier to operate safely when those accounts trade concurrently. +| Field or value | Example | Meaning | +| ---------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------- | +| Perpetual symbol | `BTC` | A perpetual market from `getPerpMetadata()` | +| Spot pair | `HYPE/USDC` | A readable Spot alias resolved from current metadata | +| Native Spot name | `PURR/USDC` or `@107` | The name used by HyperCore for a Spot pair | +| HIP-3 symbol | `dex:COIN` | A market on a HIP-3 perpetual DEX | +| Outcome asset | `#10` | An outcome-market identifier | +| `szDecimals` | `5` | The allowed number of decimal places in order size | +| `side` | `buy` or `sell` | The side accepted by the SDK's order helpers | +| `clientOrderId` | `0x` plus 32 hex characters | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id), called `cloid` by Hyperliquid | +| `accountAddress` | `HYPERLIQUID_ACCOUNT_ADDRESS` | The master account, subaccount, or vault whose state is queried | +| `vaultAddress` | `HYPERLIQUID_VAULT_ADDRESS` | Optional routing for actions signed on behalf of a vault or subaccount | +| `wsKey` | `public`, `api`, or `user:
` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) included with every emitted event | -### Custom signers +Perpetual sizes are quantities of the underlying asset. Spot sizes are quantities of the base asset. Prices, sizes, transfer amounts, and trigger prices are exact decimal strings in SDK requests. -`privateKey` is the simplest server-side option. Applications that keep keys in another wallet system can pass a signer with `signTypedData` instead: +Hyperliquid prices may use up to five significant figures, subject to the asset's decimal limit. Order sizes use the asset's `szDecimals`. Read the current [tick and lot-size rules](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size) before constructing values yourself. -```javascript -import { RestClient } from '@siebly/hyperliquid-api'; +Info responses are endpoint-specific. Some methods return objects, some return arrays, and `getOrderBook()` may return `null` for an unavailable book. There is no shared success envelope for Info responses. -export function createHyperliquidClient(walletClient, walletAddress) { - return new RestClient({ - accountAddress: walletAddress, - signer: { - address: walletAddress, - signTypedData: (domain, types, value) => - walletClient.signTypedData({ - account: walletAddress, - domain, - types, - primaryType: Object.keys(types)[0], - message: value, - }), - }, - }); -} -``` + -The signer may expose `address` or `getAddress()`. The SDK handles Hyperliquid's two signature schemes and required MessagePack field ordering. +## Start building: first REST API calls -## Recover account state after a reconnect +Run each example on its own. Start with public market data, then read account state and inspect asset metadata. -Subscriptions are restored after a reconnect, but updates that occurred during the gap still need to be reconciled. Reload the account state required by the process, build a replacement snapshot, then publish it only after every required read succeeds. +### 1. Make public REST API calls -This example refreshes balances, open orders, and recent fills when an account-stream connection returns. +Public Info calls need no wallet or API key. - + ```javascript -import { RestClient, WebsocketClient } from '@siebly/hyperliquid-api'; - -const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; - -if (!accountAddress) { - throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); -} - -const restClient = new RestClient({ accountAddress }); -const websocketClient = new WebsocketClient(); - -let accountState = { - balances: undefined, - openOrders: [], - recentFills: [], -}; -let recoveryVersion = 0; +import { RestClient } from '@siebly/hyperliquid-api'; -async function reloadAccountState() { - const version = ++recoveryVersion; - let balances; - let openOrders; - let recentFills; +const client = new RestClient(); +async function main() { try { - balances = await restClient.getBalances(); + const status = await client.getExchangeStatus(); + console.log('Exchange status:', status); } catch (error) { - console.error('Balance recovery failed:', error); - return; + console.error('Exchange-status request failed:', error); } try { - openOrders = await restClient.getOpenOrders(); + const mids = await client.getAllMids(); + console.log('BTC midpoint:', mids.BTC); } catch (error) { - console.error('Open-order recovery failed:', error); - return; + console.error('Midpoint request failed:', error); } try { - recentFills = await restClient.getUserFills({ - aggregateByTime: true, - }); + const metadata = await client.getPerpMetadata(); + const btc = metadata.universe.find((asset) => asset.name === 'BTC'); + console.log('BTC perpetual metadata:', btc); } catch (error) { - console.error('Fill recovery failed:', error); - return; + console.error('Perpetual metadata request failed:', error); } - // A newer recovery must not be overwritten by an older request sequence. - if (version !== recoveryVersion) { - return; + try { + const orderBook = await client.getOrderBook({ + coin: 'BTC', + }); + console.log('Best bid:', orderBook?.levels[0][0]); + console.log('Best ask:', orderBook?.levels[1][0]); + } catch (error) { + console.error('Order-book request failed:', error); } - accountState = { - balances, - openOrders, - recentFills, - }; - - console.log('Recovered account state:', accountState); -} - -async function main() { - websocketClient - .on('reconnected', async ({ wsKey }) => { - console.log('WebSocket reconnected:', wsKey); - await reloadAccountState(); - }) - .on('exception', ({ wsKey, event, data }) => { - console.error('WebSocket exception:', wsKey, event ?? data); + try { + const candles = await client.getCandles({ + coin: 'BTC', + interval: '1h', + startTime: Date.now() - 24 * 60 * 60 * 1000, }); - - websocketClient.on('message', ({ channel, data, wsKey }) => { - if (channel === 'orderUpdates') { - console.log('Order updates:', wsKey, data); - } else if (channel === 'userFills') { - console.log('Fill update:', data); - } - }); + console.log('Latest hourly candle:', candles.at(-1)); + } catch (error) { + console.error('Candle request failed:', error); + } try { - await websocketClient.subscribe([ - { type: 'orderUpdates', user: accountAddress }, - { type: 'userFills', user: accountAddress, aggregateByTime: true }, - ]); + const trades = await client.getRecentTrades({ + coin: 'BTC', + }); + console.log('Most recent trade:', trades[0]); } catch (error) { - console.error('Account subscription failed:', error); + console.error('Recent-trade request failed:', error); } - - await reloadAccountState(); } main(); ``` -This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration): rebuilding trusted [account state](https://siebly.io/reference/glossary#accountstate) from current REST API reads after a stream gap. Use [Scoped Recovery](https://siebly.io/reference/glossary#scoped-recovery) to reload only the state owned by the affected connection, and see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows) for wider state-management patterns. - -If the process stores a durable fill cursor, reload by time and deduplicate by trade ID before replacing state. The initial `userFills` snapshot after resubscription may overlap with the REST API result. - -Here, `orderUpdates` uses `user:
` while `userFills` uses `public`, so either connection can trigger recovery. The version counter prevents overlapping recoveries from publishing out of order. This example logs stream events separately; a live state cache also needs to reconcile events received while its REST API reads are in flight. - - +The response shapes reflect the requested data: -## Choose Mainnet, Testnet, or custom API hosts +- `getExchangeStatus()` returns an object with `time` and `specialStatuses`. +- `getAllMids()` returns an object whose keys are asset names and whose values are decimal strings. +- `getPerpMetadata()` returns an object with `universe`, `marginTables`, and `collateralToken`. +- `getOrderBook()` returns `coin`, `time`, and two arrays under `levels`. Index `0` contains bids and index `1` contains asks. Each level has `px`, `sz`, and `n`. +- `getCandles()` returns candle objects with fields such as `t`, `T`, `o`, `c`, `h`, `l`, `v`, and `n`. +- `getRecentTrades()` returns an array. `side: 'B'` is a buy and `side: 'A'` is a sell. -| Network | REST API host | WebSocket host | -| --- | --- | --- | -| Mainnet | `https://api.hyperliquid.xyz` | `wss://api.hyperliquid.xyz/ws` | -| Testnet | `https://api.hyperliquid-testnet.xyz` | `wss://api.hyperliquid-testnet.xyz/ws` | +### 2. Read account state by address -Mainnet is the default. Set `testnet: true` on every client that belongs to a Testnet workflow. +Balances, positions, orders, and fills are Info queries keyed by a public address. No signer is needed for these reads. - + ```javascript -import { - RestClient, - WebsocketAPIClient, - WebsocketClient, -} from '@siebly/hyperliquid-api'; - -const mainnetRest = new RestClient(); -const mainnetStreams = new WebsocketClient(); -const mainnetWebsocketApi = new WebsocketAPIClient(); - -const testnetRest = new RestClient({ testnet: true }); -const testnetStreams = new WebsocketClient({ testnet: true }); -const testnetWebsocketApi = new WebsocketAPIClient({ testnet: true }); +import { RestClient } from '@siebly/hyperliquid-api'; -const restApiUrl = process.env.HYPERLIQUID_REST_API_URL; -const websocketUrl = process.env.HYPERLIQUID_WEBSOCKET_URL; +const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; -if (!restApiUrl || !websocketUrl) { - throw new Error( - 'Set HYPERLIQUID_REST_API_URL and HYPERLIQUID_WEBSOCKET_URL before using custom hosts.', - ); +if (!accountAddress) { + throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); } -const customRest = new RestClient({ - baseUrl: restApiUrl, -}); - -const customStreams = new WebsocketClient({ - baseUrl: restApiUrl, - wsUrl: websocketUrl, -}); - -console.log({ - mainnetRest, - mainnetStreams, - mainnetWebsocketApi, - testnetRest, - testnetStreams, - testnetWebsocketApi, - customRest, - customStreams, -}); -``` +const client = new RestClient({ accountAddress }); -`baseUrl` changes REST API routing. `wsUrl` changes WebSocket routing. The explicit `WebsocketClient.nameToCoin()` and `resolveAsset()` helpers use REST API metadata, so set both values if those helpers also need custom routing. Native streaming subscriptions use only `wsUrl`. +async function main() { + try { + const balances = await client.getBalances(); + console.log('Account:', balances.user); + console.log('Spot balances:', balances.spot.balances); + console.log('Perpetual positions:', balances.perp.assetPositions); + } catch (error) { + console.error('Balance request failed:', error); + } -Keep Mainnet and Testnet private keys, account addresses, client order IDs, and persistent state in separate configuration. Asset IDs and available markets can differ between the two networks. + try { + const openOrders = await client.getOpenOrders(); + console.log('Open orders:', openOrders); + } catch (error) { + console.error('Open-order request failed:', error); + } -## Use a proxy with the REST API and WebSockets + try { + const fills = await client.getUserFills({ + aggregateByTime: true, + }); + console.log('Recent fills:', fills); + } catch (error) { + console.error('Fill request failed:', error); + } -Install the proxy agent needed by your network: + try { + const funding = await client.getUserFundingHistory({ + startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, + }); + console.log('Recent funding payments:', funding); + } catch (error) { + console.error('Funding-history request failed:', error); + } +} -```bash -npm install https-proxy-agent socks-proxy-agent ws +main(); ``` -The REST API client accepts Axios network options as its second constructor argument. WebSocket clients accept a custom WebSocket constructor. These are separate routes, so configure and test each one. - -See [Using a Proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. - -### HTTP or HTTPS proxy +`getBalances()` combines the Spot clearinghouse state and the default perpetual clearinghouse state. The perpetual response includes margin summaries, `withdrawable`, and `assetPositions`. A signed position size is available as `position.szi`: positive is long, negative is short, and zero is flat. Under unified account or portfolio margin, Spot state is the relevant balance view. This helper does not aggregate every HIP-3 DEX. -`HttpsProxyAgent` supports both HTTP and HTTPS proxy URLs. +A client configured with `accountAddress` may omit `user` from account getters. A public client can instead pass `{ user: accountAddress }` to each account method. - +Time-ranged Info methods have response limits. Paginate long histories by moving `startTime` to the last returned timestamp. See the official [Info endpoint documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint) for each method's current limit. -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import WebSocket from 'ws'; -import { - RestClient, - WebsocketAPIClient, - WebsocketClient, -} from '@siebly/hyperliquid-api'; +### 3. Resolve perpetual, Spot, HIP-3, and outcome assets -const proxyUrl = process.env.HYPERLIQUID_PROXY_URL; +The SDK loads current Mainnet or Testnet metadata when an operation needs an asset ID. The cache lasts five minutes by default. -if (!proxyUrl) { - throw new Error('Set HYPERLIQUID_PROXY_URL before starting.'); -} + -const agent = new HttpsProxyAgent(proxyUrl); -const parsedProxy = new URL(proxyUrl); -const axiosProxy = { - protocol: parsedProxy.protocol.slice(0, -1), - host: parsedProxy.hostname, - port: Number( - parsedProxy.port || (parsedProxy.protocol === 'https:' ? 443 : 80), - ), - ...(parsedProxy.username - ? { - auth: { - username: decodeURIComponent(parsedProxy.username), - password: decodeURIComponent(parsedProxy.password), - }, - } - : {}), -}; +```javascript +import { RestClient } from '@siebly/hyperliquid-api'; -class ProxyWebSocket { - constructor(url) { - this.socket = Reflect.construct(WebSocket, [url, { agent }]); - this.onopen = null; - this.onmessage = null; - this.onerror = null; - this.onclose = null; +const client = new RestClient(); - this.socket.onopen = () => this.onopen?.(); - this.socket.onmessage = (event) => this.onmessage?.({ data: event.data }); - this.socket.onerror = (event) => this.onerror?.(event); - this.socket.onclose = (event) => - this.onclose?.({ code: event.code, reason: String(event.reason) }); +async function main() { + try { + const btcPerpetual = await client.resolveAsset('BTC'); + console.log('BTC perpetual:', btcPerpetual); + } catch (error) { + console.error('Perpetual resolution failed:', error); } - get readyState() { - return this.socket.readyState; + try { + const hypeSpot = await client.resolveAsset('HYPE/USDC'); + console.log('HYPE/USDC Spot:', hypeSpot); + } catch (error) { + console.error('Spot resolution failed:', error); } - send(data) { - this.socket.send(data); + try { + const nativeSpotName = await client.nameToCoin('HYPE/USDC'); + console.log('Native Spot name:', nativeSpotName); + } catch (error) { + console.error('Spot-name lookup failed:', error); } - close(code, reason) { - this.socket.close(code, reason); + try { + await client.refreshAssetMetadata(); + console.log('Asset metadata refreshed.'); + } catch (error) { + console.error('Metadata refresh failed:', error); } } -const restClient = new RestClient( - { keepAlive: false }, - { - httpsAgent: agent, - proxy: false, - }, -); +main(); +``` -const websocketClient = new WebsocketClient({ - requestOptions: { - proxy: axiosProxy, - }, - webSocketConstructor: ProxyWebSocket, -}); +`resolveAsset()` returns the numeric `assetId`, canonical name, asset kind, and `szDecimals` where available. It accepts current metadata names, readable Spot aliases, numeric IDs, HIP-3 names such as `dex:COIN`, and outcome identifiers such as `#10`. -const websocketApiClient = new WebsocketAPIClient({ - webSocketConstructor: ProxyWebSocket, +Asset IDs differ across Mainnet and Testnet. Resolve them against the same network that will receive the request. Do not add `-PERP` or `-SPOT` suffixes. + +`getOrderBook()`, `getCandles()`, and `getFundingHistory()` apply Hyperliquid's native name mapping where required. For example, a readable Spot alias such as `HYPE/USDC` resolves to its current `@` name, while `PURR/USDC` is already a native universe name. Streaming subscriptions, `getRecentTrades()`, and `getActiveAssetData()` expect an official coin name. Call `nameToCoin()` explicitly when starting with a readable Spot alias, then pass the result as `coin`. Subscribing with a native coin name does not make a REST API metadata request. + + + +## Build with Hyperliquid WebSocket streams + +`WebsocketClient` manages connections, JSON parsing, heartbeats, reconnects, and resubscriptions. Subscriptions are objects that match Hyperliquid's documented channel types. + +### 4. Subscribe to public market data + + + +```javascript +import { WebsocketClient } from '@siebly/hyperliquid-api'; + +const client = new WebsocketClient(); +const prices = {}; +client.on('reconnected', () => { + for (const coin of Object.keys(prices)) delete prices[coin]; }); async function main() { - try { - const status = await restClient.getExchangeStatus(); - console.log('REST API through proxy:', status); - } catch (error) { - console.error('Proxied REST API request failed:', error); - } + client + .on('open', ({ wsKey }) => { + console.log('WebSocket opened:', wsKey); + }) + .on('reconnecting', ({ wsKey, event }) => { + console.log('WebSocket reconnecting:', wsKey, event); + }) + .on('reconnected', ({ wsKey }) => { + console.log('WebSocket reconnected:', wsKey); + }) + .on('close', ({ wsKey }) => { + console.log('WebSocket closed:', wsKey); + }) + .on('exception', ({ wsKey, event, data }) => { + console.error('WebSocket exception:', wsKey, event ?? data); + }); - websocketClient.on('message', ({ channel, data }) => { - if (channel === 'allMids') { - console.log('Stream through proxy:', data.mids.BTC); + client.on('message', ({ channel, data, wsKey }) => { + switch (channel) { + case 'fastAssetCtxs': + for (const [coin, ctx] of Object.entries(data)) { + prices[coin] = { ...prices[coin], ...ctx }; + } + console.log('BTC midpoint:', wsKey, prices.BTC?.midPx); + break; + case 'l2Book': + console.log('Best bid:', data.levels[0][0]); + console.log('Best ask:', data.levels[1][0]); + break; + case 'trades': + console.log('Trades:', data); + break; + case 'candle': + console.log('One-minute candle:', data); + break; + } + }); + + client.on('response', ({ channel, data, wsKey }) => { + if (channel === 'subscriptionResponse') { + console.log('Subscription acknowledgement:', wsKey, data); } }); try { - await websocketClient.subscribe({ type: 'allMids' }); - } catch (error) { - console.error('Proxied stream subscription failed:', error); - } - - try { - const mids = await websocketApiClient.getAllMids(); - console.log('WebSocket API through proxy:', mids.BTC); + await client.subscribe([ + { type: 'fastAssetCtxs' }, + { type: 'l2Book', coin: 'BTC' }, + { type: 'trades', coin: 'BTC' }, + { type: 'candle', coin: 'BTC', interval: '1m' }, + ]); } catch (error) { - console.error('Proxied WebSocket API request failed:', error); + console.error('Market subscription failed:', error); } } main(); ``` -Set `keepAlive: false` so the SDK preserves the custom agent, and set `proxy: false` so Axios does not apply separate environment-proxy handling on top of it. - -`webSocketConstructor` routes the socket itself. Streaming subscriptions send native topics without REST API metadata requests. `requestOptions.proxy` routes REST API metadata requests if you explicitly call `nameToCoin()` or `resolveAsset()` on the streaming client. - -### SOCKS5 proxy +Hyperliquid sends a [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) when the subscription is registered. The SDK emits that protocol message through `response`. Market and account updates arrive through `message`, preserving the full `{ channel, data, wsKey }` envelope. - +Register listeners before subscribing. Each incoming data message is emitted once, and every registered `message` listener receives it. Filter by `channel` and the payload's coin or user when consuming several feeds. -```javascript -import { SocksProxyAgent } from 'socks-proxy-agent'; -import WebSocket from 'ws'; -import { - RestClient, - WebsocketAPIClient, - WebsocketClient, -} from '@siebly/hyperliquid-api'; +The promise returned by `subscribe()` resolves after the socket opens and the request is sent. It does not wait for the server acknowledgement, so do not use that promise alone as a stream-readiness signal. -const proxyUrl = process.env.HYPERLIQUID_SOCKS_PROXY_URL; +Some channels send an initial snapshot before later updates. `fastAssetCtxs` sends a full snapshot, then only changed coins and fields: merge each coin into a cache. `midPx: null` means no book mid, and reconnects supply a fresh snapshot. `l2Book` sends a current book; trades and candles continue with new values. The upstream `allMids` WebSocket feed is deprecated; REST `getAllMids()` is unaffected. The SDK sends regular heartbeat pings to check connection health. -if (!proxyUrl) { - throw new Error('Set HYPERLIQUID_SOCKS_PROXY_URL before starting.'); -} +`subscribe()` and `unsubscribe()` accept one topic or an array of topics. Equivalent topics are deduplicated by value. Listeners are independent of subscriptions: use `off('message', listener)` to remove a listener and `unsubscribe(topic)` to stop a stream. Call `client.closeAll()` when the application needs to close its WebSocket connections. -const agent = new SocksProxyAgent(proxyUrl); +`connectionTimeout` defaults to 10,000 ms. Heartbeats use a 10,000 ms ping interval and a 1,000 ms pong deadline. Increase `connectionTimeout` or `pongTimeout` for a higher-latency connection. Reconnect delays start at 500 ms and double up to 10,000 ms. -class ProxyWebSocket { - constructor(url) { - this.socket = Reflect.construct(WebSocket, [url, { agent }]); - this.onopen = null; - this.onmessage = null; - this.onerror = null; - this.onclose = null; +#### Subscribe to a Spot market - this.socket.onopen = () => this.onopen?.(); - this.socket.onmessage = (event) => this.onmessage?.({ data: event.data }); - this.socket.onerror = (event) => this.onerror?.(event); - this.socket.onclose = (event) => - this.onclose?.({ code: event.code, reason: String(event.reason) }); - } +Resolve a readable Spot pair once, then subscribe with its native coin name. The lookup uses the REST API; `subscribe()` itself only sends WebSocket messages. - get readyState() { - return this.socket.readyState; - } +```javascript +import { WebsocketClient } from '@siebly/hyperliquid-api'; - send(data) { - this.socket.send(data); - } +const client = new WebsocketClient(); - close(code, reason) { - this.socket.close(code, reason); +client.on('message', ({ channel, data }) => { + if (channel === 'l2Book') { + console.log('Spot book:', data.coin, data.levels); } -} - -const restClient = new RestClient( - { keepAlive: false }, - { - httpsAgent: agent, - proxy: false, - }, -); - -const websocketClient = new WebsocketClient({ - webSocketConstructor: ProxyWebSocket, }); -const websocketApiClient = new WebsocketAPIClient({ - webSocketConstructor: ProxyWebSocket, +client.on('exception', ({ wsKey, event, data }) => { + console.error('WebSocket exception:', wsKey, event ?? data); }); async function main() { - try { - const status = await restClient.getExchangeStatus(); - console.log('REST API through SOCKS5:', status); - } catch (error) { - console.error('SOCKS5 REST API request failed:', error); - } - - websocketClient.on('message', ({ channel, data }) => { - if (channel === 'allMids') { - console.log('WebSocket through SOCKS5:', data.mids.BTC); - } - }); + let coin; try { - await websocketClient.subscribe({ type: 'allMids' }); + coin = await client.nameToCoin('HYPE/USDC'); } catch (error) { - console.error('SOCKS5 stream subscription failed:', error); + console.error('Spot-name lookup failed:', error); + return; } try { - const mids = await websocketApiClient.getAllMids(); - console.log('WebSocket API through SOCKS5:', mids.BTC); + await client.subscribe({ type: 'l2Book', coin }); } catch (error) { - console.error('SOCKS5 WebSocket API request failed:', error); + console.error('Spot subscription failed:', error); } } main(); ``` -Set `keepAlive: false` so the REST API client preserves the SOCKS agent. Streaming subscriptions do not trigger REST API metadata lookups. Resolve readable aliases with the configured `restClient.nameToCoin()` first, then pass the result to `websocketClient.subscribe()`, so alias resolution also follows the SOCKS route. +### 5. Subscribe to account updates -A proxy changes the network route, not the account, network, or available products. Monitor latency, disconnects, and the proxy's egress IP. +Account subscriptions use the account's public address. They do not need a signer. -## Understand Siebly referral and builder settings + -The SDK includes two separate Hyperliquid features: +```javascript +import { WebsocketClient } from '@siebly/hyperliquid-api'; -- Referral code: around the first supported trading action from a client instance, the SDK makes one passive attempt to apply `SIEBLY`. Hyperliquid leaves an existing referrer unchanged. Trading continues if the referral request fails. -- Builder code: after the account has approved Siebly's builder fee, the SDK can include the builder code on eligible orders. The configured maximum is 0.1%. Approval must be signed by the main wallet, not an API wallet. If a main-wallet private key is configured and approval is missing, the SDK may attempt that approval in the background. An API wallet cannot grant it. +const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; -Builder approval is optional. Call `approveBuilderFee()` only from a client configured with the main wallet signer and only after reviewing Hyperliquid's current [builder-code documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/builder-codes). The approval sets a maximum and can be revoked through Hyperliquid. +if (!user) { + throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); +} -## Production checklist +const client = new WebsocketClient(); -- **Keep signers isolated.** Use a separate approved API wallet per trading process and, where practical, per subaccount. -- **Query the correct address.** Account reads use the master account, subaccount, or vault address rather than the API wallet address. -- **Keep time synchronized.** Signed nonces are millisecond timestamps and must remain inside Hyperliquid's accepted time window. -- **Use exact decimal strings.** Avoid JavaScript floating-point arithmetic for stored financial values. Trim trailing decimal zeroes before native wire-shaped actions. -- **Read current metadata.** Resolve assets and use the latest `szDecimals`, universe names, margin tables, and market status. -- **Meet minimum notional.** Hyperliquid currently requires at least 10 units of the quote asset for an order. -- **Check every action status.** A top-level `ok` response may contain an order-specific `error` entry. -- **Reconcile uncertain writes.** Query by [custom order ID](https://siebly.io/reference/glossary#custom-order-id) before retrying a timed-out submission. -- **Confirm final order state.** Treat the first response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then use `getOrderStatus()` or `orderUpdates`. -- **Use action deadlines where useful.** `expiresAfter` limits how long a signed action remains valid. A stale deadline rejection currently consumes extra address-based rate-limit allowance. -- **Use a dead-man switch.** Refresh `setCancelAllAfter()` from a monitored process when unattended resting orders need automatic cancellation. -- **Recover after gaps.** Rebuild the affected balances, positions, orders, and fills after a reconnect. -- **Respect current limits.** Hyperliquid applies IP, address, open-order, connection, subscription, and in-flight request limits. Check the current [rate-limit documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits). -- **Keep keys server-side.** Browser use should be limited to public REST API calls and public-address WebSocket subscriptions. -- **Monitor the route.** Track latency, reconnect frequency, and egress IP when using a proxy or custom endpoint. +async function main() { + client + .on('open', ({ wsKey }) => { + console.log('WebSocket opened:', wsKey); + }) + .on('reconnected', ({ wsKey }) => { + console.log('WebSocket reconnected:', wsKey); + }) + .on('exception', ({ wsKey, event, data }) => { + console.error('WebSocket exception:', wsKey, event ?? data); + }); -## Frequently asked questions + client.on('message', ({ channel, data, wsKey }) => { + switch (channel) { + case 'orderUpdates': + console.log('Order updates:', wsKey, data); + break; + case 'userFills': + console.log('Fill snapshot:', data.isSnapshot === true); + console.log('Fills:', data.fills); + break; + case 'clearinghouseState': + console.log('Perpetual state:', data.clearinghouseState); + break; + case 'spotState': + console.log('Spot state:', data.spotState); + break; + } + }); -### Can I use the SDK with plain JavaScript? + try { + await client.subscribe([ + { type: 'orderUpdates', user }, + { type: 'userFills', user, aggregateByTime: true }, + { type: 'clearinghouseState', user }, + { type: 'spotState', user }, + ]); + } catch (error) { + console.error('Account subscription failed:', error); + } +} -Yes. All examples in this guide are JavaScript. The package also includes TypeScript declarations. +main(); +``` -### Which client should I start with? +`userFills`, `userFundings`, and similar time-series streams tag their initial payload with `isSnapshot: true`. Use the snapshot to initialize state, then process later payloads as changes. Avoid applying the same snapshot twice after a reconnect. -Start with `RestClient` for public market data and account state. Add `WebsocketClient` for live subscriptions. Use `WebsocketAPIClient` when you need awaitable Info or Exchange requests over WebSocket. +The `orderUpdates` stream reports order transitions. Use it with a REST API query when reconciling [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation) after an uncertain order or cancellation response. -### Why do account reads work without a private key? +Every lifecycle, message, response, and exception event includes `wsKey`. Most subscriptions share `public`. `orderUpdates`, `notification`, and `userEvents` use `user:` connections because their server messages omit the address. Use that key to identify the account. The `userEvents` subscription emits messages on Hyperliquid's `user` channel. -Hyperliquid Info queries use a public account address. A signer is needed for Exchange actions that change orders, funds, leverage, or account settings. + -### Why are my balances empty when I use an API wallet? +## Place and manage Testnet orders -Account queries need the master account, subaccount, or vault address. The API wallet address identifies the signer, not the account whose state is being queried. Set `accountAddress` on the client. +Use Hyperliquid Testnet to run the following workflows. Create and approve an API wallet from the [Testnet API page](https://app.hyperliquid-testnet.xyz/API), fund the account from the [Testnet faucet](https://app.hyperliquid-testnet.xyz/drip), then set `HYPERLIQUID_TESTNET_API_WALLET_KEY` and `HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS`. The faucet currently requires the same address to have deposited on Mainnet. -### What is the difference between a wallet and an API wallet? +The SDK signs Exchange actions with the API wallet and sends account queries for the configured account address. It lowercases EVM addresses and formats action fields in the order required by Hyperliquid's signing rules. -The main wallet owns the account. An approved API wallet signs actions on its behalf. Use an API wallet for an automated process and keep the main wallet key outside that process. +Order responses need two checks: -### Why are REST API response shapes different? +1. `status` must be `ok`. +2. Each entry under `response.data.statuses` must be inspected. -Hyperliquid's Info endpoint selects an operation through the request body, and each operation has its own response schema. The SDK returns that response directly. +An order status entry may contain `resting`, `filled`, or `error`. A successful request can still contain an order-specific error. -### Why did an order fail when the response status was `ok`? +The SDK makes a passive, one-time attempt to apply the `SIEBLY` referral code around the first trading action from a client instance when the account has no existing referrer. It does not replace an existing referrer, delay the order, or retry the referral request. Hyperliquid's current [referral terms](https://hyperliquid.gitbook.io/hyperliquid-docs/referrals) describe any user discount. -The top-level status describes the action request. Each order has its own entry under `response.data.statuses`, which may contain `resting`, `filled`, or `error`. +### 6. Run a perpetual REST API order lifecycle -### Does `submitMarketOrder()` send a native market order? +This example reads current BTC metadata and book data, places a post-only Testnet order, queries it, cancels it by client order ID, and queries it again. -It sends an immediate-or-cancel limit order with a protection price. The SDK derives and rounds that price from the midpoint when one is not supplied. + -### How do I tell perpetual and Spot assets apart? +```javascript +import { randomBytes } from 'node:crypto'; +import { RestClient } from '@siebly/hyperliquid-api'; -Perpetuals commonly use names such as `BTC`. Spot markets use native universe names such as `PURR/USDC` or `@107`. REST API helpers can resolve readable metadata-derived aliases such as `HYPE/USDC`. For streaming subscriptions, call `nameToCoin()` explicitly to resolve an alias, then subscribe with the returned native coin name. +const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; +const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; -### Do account WebSocket streams require authentication? +if (!privateKey || !accountAddress) { + throw new Error( + 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', + ); +} -They use the public account address. The SDK isolates user-scoped channels when needed and resubscribes after reconnecting. +const client = new RestClient({ + privateKey, + accountAddress, + testnet: true, +}); -### How do subscription acknowledgements appear? +function trimDecimal(value) { + if (!value.includes('.')) { + return value; + } + return value.replace(/0+$/, '').replace(/\.$/, ''); +} + +function sizeForNotional(price, szDecimals, targetNotional) { + const factor = 10 ** szDecimals; + const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; + return trimDecimal(size.toFixed(szDecimals)); +} + +async function main() { + let btc; + let orderBook; + + try { + const metadata = await client.getPerpMetadata(); + btc = metadata.universe.find((asset) => asset.name === 'BTC'); + console.log('BTC metadata:', btc); + } catch (error) { + console.error('Perpetual metadata request failed:', error); + return; + } -Listen for `response` events with `channel === 'subscriptionResponse'`. Snapshot and update envelopes arrive through `message`. Both events include `wsKey`, and the promise returned by `subscribe()` only confirms that the subscription request was sent. + if (!btc) { + console.error('BTC was not returned by the Testnet perpetual metadata.'); + return; + } -### What is the difference between `WebsocketClient` and `WebsocketAPIClient`? + try { + orderBook = await client.getOrderBook({ coin: 'BTC' }); + console.log('BTC order book received at:', orderBook?.time); + } catch (error) { + console.error('Order-book request failed:', error); + return; + } -`WebsocketClient` consumes ongoing subscriptions. `WebsocketAPIClient` sends one Info or Exchange request and resolves the matching response as a promise. + const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; -### Should I retry a timed-out order submission? + if (!bid) { + console.error('The BTC order book did not contain a bid.'); + return; + } -Not immediately. Query `getOrderStatus()` with the client order ID first. A request can reach Hyperliquid even when the response does not reach your process. + const clientOrderId = `0x${randomBytes(16).toString('hex')}`; + const size = sizeForNotional(bid.px, btc.szDecimals, 12); + let orderId; -### How do I use a vault or subaccount? + try { + const result = await client.submitLimitOrder({ + symbol: 'BTC', + side: 'buy', + price: bid.px, + size, + postOnly: true, + clientOrderId, + }); + console.log('Order response:', result); -Set its address as `vaultAddress` for signed actions and use the same address for its account-state queries. The API wallet must be approved to act for the relevant account. + if (result.status !== 'ok') { + console.error('Hyperliquid rejected the order request:', result.response); + return; + } -### Can I use Mainnet credentials on Testnet? + const orderStatus = result.response.data?.statuses[0]; -Keep the networks separate. Approval state, account balances, assets, and API-wallet registration differ between Mainnet and Testnet. + if (!orderStatus) { + console.error('The order response did not contain an order status.'); + return; + } -### Does a proxy change which network I use? + if ('error' in orderStatus) { + console.error('The order was rejected:', orderStatus.error); + return; + } -No. `testnet`, `baseUrl`, and `wsUrl` select the destination. A proxy only changes the network path used to reach it. + if ('filled' in orderStatus) { + console.log('The order filled immediately:', orderStatus.filled); + return; + } -## Next steps + orderId = orderStatus.resting.oid; + console.log('Resting order ID:', orderId); + } catch (error) { + console.error('Order submission failed:', error); + return; + } -1. Run the public REST API example and inspect the current BTC metadata and order book. -2. Set a public account address and load balances, positions, open orders, and fills. -3. Add public and account WebSocket subscriptions, including reconnect handling. -4. Approve a Testnet API wallet and run the perpetual order lifecycle. -5. Add client order IDs, action deadlines, dead-man-switch refresh, and scoped recovery before moving a strategy to Mainnet. + try { + const currentOrder = await client.getOrderStatus({ oid: orderId }); + console.log('Order before cancellation:', currentOrder); + } catch (error) { + console.error('Order-status request failed:', error); + } -Continue with the [Hyperliquid SDK examples](https://siebly.io/examples/Hyperliquid), browse the [source repository](https://github.com/sieblyio/hyperliquid-api), and check the [official Hyperliquid API documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) for current exchange behavior. + try { + const cancellation = await client.cancelOrdersByClientOrderId({ + cancels: [{ asset: 'BTC', cloid: clientOrderId }], + }); + console.log('Cancellation response:', cancellation); + } catch (error) { + console.error('Cancellation failed:', error); + return; + } -================ -File: src/types/websockets/ws-subscriptions.ts -================ -import type { - ActiveAssetData, - Candle, - HistoricalOrder, - LeadingVault, - OpenOrder, - OrderBookResponse, - OrderState, - PerpAccountSummaryResponse, - PerpAssetContext, - SpotAssetContext, - SpotBalancesResponse, - Trade, - TwapHistoryEntry, - TwapSliceFill, - TwapState, - UserFill, - UserNonFundingLedgerUpdate, -} from '../response/info.types.js'; -⋮---- -export type CandleInterval = - | '1d' - | '12h' - | '15m' - | '1h' - | '1m' - | '1M' - | '2h' - | '30m' - | '3d' - | '3m' - | '4h' - | '5m' - | '8h' - | '1w'; -⋮---- -export type UserSubscriptionType = - | 'activeAssetData' - | 'allDexsClearinghouseState' - | 'clearinghouseState' - | 'notification' - | 'openOrders' - | 'orderUpdates' - | 'spotState' - | 'twapStates' - | 'userEvents' - | 'userFills' - | 'userFundings' - | 'userHistoricalOrders' - | 'userNonFundingLedgerUpdates' - | 'userTwapHistory' - | 'userTwapSliceFills' - | 'webData3'; -⋮---- -/** Incremental order book feed. s and m work like l2Book's nSigFigs and mantissa. - * https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions - */ -export interface L2Subscription { - c: string; - s?: number; - m?: number; - type: 'l2'; -} -⋮---- -export interface PacSubscription { - type: 'pac'; -} -⋮---- -export interface SacSubscription { - type: 'sac'; -} -⋮---- -export type WebsocketSubscription = - | { dex?: string; type: 'allMids' } - | { dex?: string; type: 'assetCtxs' } - | { coin: string; type: 'activeAssetCtx' } - | { coin: string; user: string; type: 'activeAssetData' } - | { type: 'allDexsAssetCtxs' } - | { user: string; type: 'allDexsClearinghouseState' } - | { coin: string; type: 'bbo' } - | { coin: string; interval: CandleInterval; type: 'candle' } - | { dex?: string; user: string; type: 'clearinghouseState' } - | { type: 'fastAssetCtxs' } - | L2Subscription - | { - coin: string; - fast?: boolean; - mantissa?: 1 | 2 | 5 | null; - nSigFigs?: 2 | 3 | 4 | 5 | null; - type: 'l2Book'; - } - | { user: string; type: 'notification' } - | { dex?: string; user: string; type: 'openOrders' } - | { user: string; type: 'orderUpdates' } - | { type: 'outcomeMetaUpdates' } - | PacSubscription - | SacSubscription - | { type: 'spotAssetCtxs' } - | { - ignorePortfolioMargin?: boolean; - isPortfolioMargin?: never; - user: string; - type: 'spotState'; - } - | { - ignorePortfolioMargin?: never; - isPortfolioMargin?: boolean; - user: string; - type: 'spotState'; - } - | { coin: string; type: 'trades' } - | { dex?: string; user: string; type: 'twapStates' } - | { user: string; type: 'userEvents' } - | { aggregateByTime?: boolean; user: string; type: 'userFills' } - | { user: string; type: 'userFundings' } - | { user: string; type: 'userHistoricalOrders' } - | { user: string; type: 'userNonFundingLedgerUpdates' } - | { user: string; type: 'userTwapHistory' } - | { user: string; type: 'userTwapSliceFills' } - | { user: string; type: 'webData3' }; -⋮---- -export interface AllMidsEvent { - dex?: string; - mids: Record; -} -⋮---- -export interface AssetContextEvent { - coin: string; - ctx: PerpAssetContext | SpotAssetContext; -} -⋮---- -export interface ActivePerpAssetContextEvent extends AssetContextEvent { - ctx: PerpAssetContext; -} -⋮---- -export interface ActiveSpotAssetContextEvent extends AssetContextEvent { - ctx: SpotAssetContext; -} -⋮---- -export interface AssetCtxsEvent { - ctxs: PerpAssetContext[]; - dex: string; -} -⋮---- -export interface AllDexsAssetCtxsEvent { - ctxs: Array<[dex: string, contexts: PerpAssetContext[]]>; + try { + const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); + console.log('Final order state:', finalOrder); + } catch (error) { + console.error('Final order-status request failed:', error); + } } -⋮---- -export type WsBook = Pick; -⋮---- -/** Snapshot, uncompressed diff, or base64 raw-DEFLATE compressed WsL2Diff. */ -export type WsL2 = { s: WsBook } | { u: WsL2Diff } | { c: string }; -⋮---- -export interface WsL2Diff { - /** Coin. */ - c: string; - /** Time. */ - t: number; - /** [bids, asks] levels to add or replace by price after removals. */ - l: [WsL2LevelUpdate[], WsL2LevelUpdate[]]; - /** [bids, asks] indexes to remove from the previous book. */ - r: [number[], number[]]; + +main(); +``` + +The fifth bid is already a valid Hyperliquid price and normally remains below the best ask, which makes it suitable for an add-liquidity-only order. The size targets at least 12 USDC of notional and rounds up to the asset's `szDecimals`, keeping it above Hyperliquid's current 10 USDC minimum order value. + +`postOnly: true` maps to Hyperliquid's `Alo` time in force. Without `postOnly`, `submitLimitOrder()` defaults to good-till-cancelled. Set `timeInForce: 'IOC'` for immediate-or-cancel. + +The `clientOrderId` is 16 random bytes encoded as a 32-character hexadecimal string. Keep it with the local order record. It can be used with `getOrderStatus()` and `cancelOrdersByClientOrderId()` when the numeric exchange order ID is not yet known. + +### 7. Run a Spot REST API order lifecycle + +Spot orders use the same helper, but the symbol resolves to a Spot asset ID and size means base-asset quantity. This example places a post-only PURR/USDC buy on Testnet. + + + +```javascript +import { randomBytes } from 'node:crypto'; +import { RestClient } from '@siebly/hyperliquid-api'; + +const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; +const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; + +if (!privateKey || !accountAddress) { + throw new Error( + 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', + ); } -⋮---- -/** Coin. */ -⋮---- -/** Time. */ -⋮---- -/** [bids, asks] levels to add or replace by price after removals. */ -⋮---- -/** [bids, asks] indexes to remove from the previous book. */ -⋮---- -export interface WsL2LevelUpdate { - /** Price. */ - p: string; - /** Size. Diffs do not include the number of orders. */ - s: string; + +const client = new RestClient({ + privateKey, + accountAddress, + testnet: true, +}); + +function trimDecimal(value) { + if (!value.includes('.')) { + return value; + } + return value.replace(/0+$/, '').replace(/\.$/, ''); } -⋮---- -/** Price. */ -⋮---- -/** Size. Diffs do not include the number of orders. */ -⋮---- -/** Decoded perp contexts by dex, positional over each dex's universe. The first dex is ''. - * After the initial snapshot, contexts contain only changed fields, or {}. - */ -export type WsPac = Array< - [dex: string, contexts: Array>] ->; -⋮---- -/** Decoded spot contexts by coin. After the snapshot, only changed coins/fields appear. */ -export type WsSac = Record>; -⋮---- -export interface ClearinghouseStateEvent { - clearinghouseState: PerpAccountSummaryResponse; - dex: string; - user: string; + +function sizeForNotional(price, szDecimals, targetNotional) { + const factor = 10 ** szDecimals; + const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; + return trimDecimal(size.toFixed(szDecimals)); } -⋮---- -export interface AllDexsClearinghouseStateEvent { - clearinghouseStates: Array<[dex: string, state: PerpAccountSummaryResponse]>; - user: string; + +async function main() { + let asset; + let orderBook; + + try { + asset = await client.resolveAsset('PURR/USDC'); + console.log('PURR/USDC asset:', asset); + } catch (error) { + console.error('Spot asset resolution failed:', error); + return; + } + + if (asset.szDecimals === undefined) { + console.error('PURR/USDC size metadata was not available.'); + return; + } + + try { + orderBook = await client.getOrderBook({ coin: 'PURR/USDC' }); + console.log('PURR/USDC order book received at:', orderBook?.time); + } catch (error) { + console.error('Spot order-book request failed:', error); + return; + } + + const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; + + if (!bid) { + console.error('The PURR/USDC order book did not contain a bid.'); + return; + } + + const clientOrderId = `0x${randomBytes(16).toString('hex')}`; + const size = sizeForNotional(bid.px, asset.szDecimals, 12); + let orderId; + + try { + const result = await client.submitLimitOrder({ + symbol: 'PURR/USDC', + side: 'buy', + price: bid.px, + size, + postOnly: true, + clientOrderId, + }); + console.log('Spot order response:', result); + + if (result.status !== 'ok') { + console.error('Hyperliquid rejected the order request:', result.response); + return; + } + + const orderStatus = result.response.data?.statuses[0]; + + if (!orderStatus) { + console.error('The order response did not contain an order status.'); + return; + } + + if ('error' in orderStatus) { + console.error('The order was rejected:', orderStatus.error); + return; + } + + if ('filled' in orderStatus) { + console.log('The order filled immediately:', orderStatus.filled); + return; + } + + orderId = orderStatus.resting.oid; + console.log('Resting Spot order ID:', orderId); + } catch (error) { + console.error('Spot order submission failed:', error); + return; + } + + try { + const currentOrder = await client.getOrderStatus({ oid: orderId }); + console.log('Spot order before cancellation:', currentOrder); + } catch (error) { + console.error('Spot order-status request failed:', error); + } + + try { + const cancellation = await client.cancelOrdersByClientOrderId({ + cancels: [{ asset: 'PURR/USDC', cloid: clientOrderId }], + }); + console.log('Spot cancellation response:', cancellation); + } catch (error) { + console.error('Spot cancellation failed:', error); + return; + } + + try { + const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); + console.log('Final Spot order state:', finalOrder); + } catch (error) { + console.error('Final Spot order-status request failed:', error); + } } -⋮---- -export type ActiveAssetDataEvent = ActiveAssetData; -⋮---- -export interface BboEvent { - bbo: [ - bid: { n: number; px: string; sz: string } | null, - offer: { n: number; px: string; sz: string } | null, - ]; - coin: string; - time: number; + +main(); +``` + +The account needs enough Testnet USDC to reserve the order. A Spot sell needs the corresponding base asset. Hyperliquid may return internal token names in balances, so use the names returned by the API when reconciling funds. + +### Market orders, closing positions, and leverage + +`submitMarketOrder()` is an immediate-or-cancel limit order with a protection price. When `price` is omitted, the SDK loads the current midpoint, applies `maxSlippage`, rounds the protection price to Hyperliquid's rules, and rounds size down to `szDecimals`. + +Call `submitMarketOrder()` with `symbol`, `side`, `size`, and an optional `maxSlippage`. For example, a BTC buy can use `{ symbol: 'BTC', side: 'buy', size: '0.001', maxSlippage: 0.01 }`. + +`submitMarketClose()` reads the current perpetual position, chooses the closing side, and submits a reduce-only immediate-or-cancel order. Omit `size` to close the full position. + +Call `submitMarketClose()` with the perpetual symbol and an optional `maxSlippage`. Add `size` when only part of the position should be closed. + +Call `updateLeverage()` with `{ asset: 'BTC', isCross: true, leverage: 3 }` to select three-times cross leverage for BTC. Use the current asset metadata and account limits when choosing leverage. + +These are signed production actions on Mainnet and signed test actions on Testnet. Read current account and market state before calling them. + + + +## Send Info and Exchange requests with the WebSocket API + +`WebsocketAPIClient` exposes the same promise-based methods as `RestClient`, but sends supported Info and Exchange requests through Hyperliquid's WebSocket POST protocol. + +The SDK opens the connection when needed, assigns a unique request ID, matches the response to the promise, and rejects protocol errors. The raw `id` and response wrapper do not need to be managed by application code. + +This example reads market data, submits a post-only BTC Testnet order, and cancels it through the WebSocket API. + + + +```javascript +import { randomBytes } from 'node:crypto'; +import { WebsocketAPIClient } from '@siebly/hyperliquid-api'; + +const privateKey = process.env.HYPERLIQUID_TESTNET_API_WALLET_KEY; +const accountAddress = process.env.HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS; + +if (!privateKey || !accountAddress) { + throw new Error( + 'Set HYPERLIQUID_TESTNET_API_WALLET_KEY and HYPERLIQUID_TESTNET_ACCOUNT_ADDRESS before starting.', + ); } -⋮---- -export type TradeEvent = Trade; -⋮---- -export interface NotificationEvent { - notification: string; + +const client = new WebsocketAPIClient({ + privateKey, + accountAddress, + testnet: true, +}); + +function trimDecimal(value) { + if (!value.includes('.')) { + return value; + } + return value.replace(/0+$/, '').replace(/\.$/, ''); } -⋮---- -export interface OrderUpdateEvent { - order: OpenOrder; - status: OrderState; - statusTimestamp: number; + +function sizeForNotional(price, szDecimals, targetNotional) { + const factor = 10 ** szDecimals; + const size = Math.ceil((targetNotional / Number(price)) * factor) / factor; + return trimDecimal(size.toFixed(szDecimals)); } -⋮---- -export interface FastAssetCtxsEvent { - [coin: string]: { - markPx?: string; - midPx?: string | null; - }; + +async function main() { + client + .on('open', ({ wsKey }) => { + console.log('WebSocket API opened:', wsKey); + }) + .on('reconnected', ({ wsKey }) => { + console.log('WebSocket API reconnected:', wsKey); + }) + .on('exception', ({ wsKey, event, data }) => { + console.error('WebSocket API exception:', wsKey, event ?? data); + }); + + let btc; + let orderBook; + + try { + const metadata = await client.getPerpMetadata(); + btc = metadata.universe.find((asset) => asset.name === 'BTC'); + console.log('BTC metadata:', btc); + } catch (error) { + console.error('WebSocket metadata request failed:', error); + client.closeAll(); + return; + } + + if (!btc) { + console.error('BTC was not returned by the Testnet perpetual metadata.'); + client.closeAll(); + return; + } + + try { + orderBook = await client.getOrderBook({ coin: 'BTC' }); + console.log('BTC order book received at:', orderBook?.time); + } catch (error) { + console.error('WebSocket order-book request failed:', error); + client.closeAll(); + return; + } + + const bid = orderBook?.levels[0][4] ?? orderBook?.levels[0][0]; + + if (!bid) { + console.error('The BTC order book did not contain a bid.'); + client.closeAll(); + return; + } + + const clientOrderId = `0x${randomBytes(16).toString('hex')}`; + const size = sizeForNotional(bid.px, btc.szDecimals, 12); + let orderId; + + try { + const result = await client.submitLimitOrder({ + symbol: 'BTC', + side: 'buy', + price: bid.px, + size, + postOnly: true, + clientOrderId, + }); + console.log('WebSocket order response:', result); + + if (result.status !== 'ok') { + console.error('Hyperliquid rejected the order request:', result.response); + client.closeAll(); + return; + } + + const orderStatus = result.response.data?.statuses[0]; + + if (!orderStatus) { + console.error('The order response did not contain an order status.'); + client.closeAll(); + return; + } + + if ('error' in orderStatus) { + console.error('The order was rejected:', orderStatus.error); + client.closeAll(); + return; + } + + if ('filled' in orderStatus) { + console.log('The order filled immediately:', orderStatus.filled); + client.closeAll(); + return; + } + + orderId = orderStatus.resting.oid; + console.log('Resting order ID:', orderId); + } catch (error) { + console.error('WebSocket order submission failed:', error); + client.closeAll(); + return; + } + + try { + const currentOrder = await client.getOrderStatus({ oid: orderId }); + console.log('Order before cancellation:', currentOrder); + } catch (error) { + console.error('WebSocket order-status request failed:', error); + } + + try { + const cancellation = await client.cancelOrdersByClientOrderId({ + cancels: [{ asset: 'BTC', cloid: clientOrderId }], + }); + console.log('WebSocket cancellation response:', cancellation); + } catch (error) { + console.error('WebSocket cancellation failed:', error); + } + + try { + const finalOrder = await client.getOrderStatus({ oid: clientOrderId }); + console.log('Final WebSocket order state:', finalOrder); + } catch (error) { + console.error('Final WebSocket order-status request failed:', error); + } + + client.closeAll(); } -⋮---- -export type SpotAssetCtxsEvent = SpotAssetContext[]; -⋮---- -export interface OutcomeMetaUpdatesEvent { - updates: Array< - | { - outcomeCreated: { - description: string; - name: string; - outcome: number; - quoteToken: string; - sideSpecs: Array<{ name: string; token?: number }>; - }; - } - | { outcomeSettled: { outcome: number } } - | { - questionUpdated: { - description: string; - fallbackOutcome: number; - name: string; - namedOutcomes: number[]; - question: number; - settledNamedOutcomes: number[]; - }; - } - | { questionSettled: { question: number } } - >; + +main(); +``` + +WebSocket POST supports Info requests and signed Exchange actions. Explorer requests are not supported. Use `WebsocketClient` for subscriptions and `WebsocketAPIClient` for awaitable request-response calls. + +Successful POST replies also emit `response` events with `channel: 'post'` and `wsKey: 'api'`. Protocol errors and top-level Exchange rejections emit `exception` and reject the matching promise. An accepted action can still contain individual order errors, so inspect its status entries. Use `try`/`catch` for each command; event listeners provide additional connection and protocol diagnostics. + +`requestTimeoutMs` defaults to 10,000 ms and includes connection setup. Requests interrupted by a disconnect are rejected, not replayed after reconnection. Query the order's status before retrying a command whose outcome is uncertain. + +An order-command response acknowledges the action and reports its immediate status. Confirm later changes through `orderUpdates` or `getOrderStatus()`. That distinction is important when an order fills or is cancelled immediately after its first response. + +## Explore more REST API methods + +`RestClient` covers Hyperliquid's wider Info and Exchange surfaces. The following groups are a starting map rather than a complete list. + +### Market and account information + +| Workflow | Representative methods | +| ----------------------- | ------------------------------------------------------------------------------------------------------- | +| Perpetual markets | `getPerpMetadata()`, `getPerpAssetContexts()`, `getFundingHistory()`, `getPredictedFundingRates()` | +| Spot markets | `getSpotMetadata()`, `getSpotAssetContexts()`, `getTokenDetails()` | +| Books and trades | `getOrderBook()`, `getAllMids()`, `getCandles()`, `getRecentTrades()` | +| Orders and fills | `getOpenOrders()`, `getFrontendOpenOrders()`, `getOrderStatus()`, `getOrderHistory()`, `getUserFills()` | +| Account and risk | `getPerpAccountSummary()`, `getSpotBalances()`, `getPortfolio()`, `getUserFees()`, `getUserRateLimit()` | +| HIP-3 perpetual DEXs | `getPerpDexs()`, `getPerpDexStatus()`, `getPerpDexLimits()`, `getAllPerpMetadata()` | +| Outcome markets | `getOutcomeMetadata()`, `getSettledOutcome()`, `getOutcomeDeployerLimits()`, `submitUserOutcome()` | +| Vaults and staking | `getVaultDetails()`, `getVaultSummaries()`, `getStakingSummary()`, `getStakingDelegations()` | +| Borrow and lend | `getAllBorrowLendReserveStates()`, `getBorrowLendReserveState()`, `getUserBorrowLendState()` | +| Subaccounts and signers | `getSubAccounts()`, `getExtraAgents()`, `getMultiSigSigners()`, `getUserRole()` | + +### Signed actions + +| Workflow | Representative methods | +| ---------------------- | --------------------------------------------------------------------------------------------------- | +| Orders | `submitOrder()`, `submitMarketOrder()`, `submitLimitOrder()`, `modifyOrder()`, `cancelOrders()` | +| Position management | `submitMarketClose()`, `updateLeverage()`, `updateIsolatedMargin()`, `setIsolatedMarginLeverage()` | +| TWAP and safety | `submitTwapOrder()`, `cancelTwapOrder()`, `setCancelAllAfter()` | +| Transfers | `sendUsd()`, `sendSpotAsset()`, `sendAsset()`, `transferUsdBetweenSpotAndPerp()`, `withdrawUsd()` | +| Subaccounts and vaults | `createSubAccount()`, `transferUsdToOrFromSubAccount()`, `createVault()`, `transferVaultFunds()` | +| Staking | `depositIntoStaking()`, `withdrawFromStaking()`, `delegateOrUndelegateStake()`, `claimRewards()` | +| Account configuration | `approveApiWallet()`, `setUserPortfolioMargin()`, `setUserAbstraction()`, `setUserDexAbstraction()` | +| Advanced deployment | `deployPerp()`, `deploySpot()`, `submitUserOutcome()`, validator and multisig methods | + +Use the focused [repository examples](../examples) and exported request types when moving beyond the workflows in this guide. Transfers, withdrawals, staking, account configuration, deployer operations, and multisig actions change funds or account settings, so confirm their current official requirements before using them. + +### Batch orders, TP/SL, and dead-man switches + +Use `submitOrder()` when sending native wire-shaped batches or TP/SL orders. A batch is one request for IP limits but each order still counts toward address-based limits. Inspect every returned status, because errors usually align with individual batch entries. + +`setCancelAllAfter()` schedules cancellation of open orders if the account stops refreshing the deadline. Hyperliquid currently requires the trigger to be at least five seconds in the future and limits each account to ten scheduled-cancel triggers per UTC day. Refresh it from a monitored process, and call the method without `time` to remove the schedule when the strategy stops normally. + +Set `expiresAfter: Date.now() + 10_000` in the second argument of a signed method when an action should expire after ten seconds. This adds an action deadline. It does not replace order time in force or a dead-man switch. + +### Vaults and subaccounts + +Set `vaultAddress` on the client when all signed actions belong to one vault or subaccount: + +```javascript +import { RestClient } from '@siebly/hyperliquid-api'; + +const privateKey = process.env.HYPERLIQUID_API_WALLET_KEY; +const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; +const vaultAddress = process.env.HYPERLIQUID_VAULT_ADDRESS; + +if (!privateKey || !accountAddress || !vaultAddress) { + throw new Error( + 'Set HYPERLIQUID_API_WALLET_KEY, HYPERLIQUID_ACCOUNT_ADDRESS, and HYPERLIQUID_VAULT_ADDRESS before starting.', + ); } -⋮---- -export interface UserFillsEvent { - fills: UserFill[]; - isSnapshot?: boolean; - user: string; + +const client = new RestClient({ + privateKey, + accountAddress, + vaultAddress, +}); +``` + +The signer still owns the nonce. A single API wallet used across several vaults or subaccounts shares one nonce set. Separate signers are easier to operate safely when those accounts trade concurrently. + +### Use a viem account, browser wallet or Privy/embedded wallet signer + +Pass a viem local account or wallet client directly as `signer`; no adapter is needed. +Install viem in your application yourself. The SDK has no viem dependency. +Avoid viem **2.57.12–2.57.16**, which reject Hyperliquid's `HyperliquidTransaction:*` +EIP-712 type names; use 2.57.11 or 2.57.17 and later. + +For a server-side local account: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { privateKeyToAccount } from 'viem/accounts'; + +const key = process.env.HYPERLIQUID_PRIVATE_KEY; +if (!key) throw new Error('Set HYPERLIQUID_PRIVATE_KEY.'); +const account = privateKeyToAccount(key as `0x${string}`); +const client = new RestClient({ signer: account }); +``` + +For a browser wallet, create the wallet client with an account: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +// window.ethereum is supplied by the user's browser wallet. +const provider = window.ethereum; +if (!provider) throw new Error('Connect a browser wallet first.'); +const [address] = await provider.request({ method: 'eth_requestAccounts' }); +const walletClient = createWalletClient({ + account: address, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); +``` + +For a Privy-style embedded wallet (using the wallet returned by your provider): + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +const provider = await embeddedWallet.getEthereumProvider(); +const walletClient = createWalletClient({ + account: embeddedWallet.address as `0x${string}`, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); +``` + +Wallet clients without an account fail at construction with a clear error. +Ethers wallets and custom signers using `signTypedData(domain, types, value)` +with `address` or `getAddress()` continue to work, as does `privateKey`. +The SDK selects the primary EIP-712 type for every action and normalizes viem inputs +once. The same inputs work in multisig `signers` arrays and `WebsocketAPIClient`. +Use `accountAddress` with an API wallet to identify the master account; transfers, +withdrawals, and other user-signed actions still require the account owner's signer. + +## Recover account state after a reconnect + +Subscriptions are restored after a reconnect, but updates that occurred during the gap still need to be reconciled. Reload the account state required by the process, build a replacement snapshot, then publish it only after every required read succeeds. + +This example refreshes balances, open orders, and recent fills when an account-stream connection returns. + + + +```javascript +import { RestClient, WebsocketClient } from '@siebly/hyperliquid-api'; + +const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; + +if (!accountAddress) { + throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS before starting.'); } -⋮---- -export interface OpenOrdersEvent { - dex: string; - orders: OpenOrder[]; - user: string; + +const restClient = new RestClient({ accountAddress }); +const websocketClient = new WebsocketClient(); + +let accountState = { + balances: undefined, + openOrders: [], + recentFills: [], +}; +let recoveryVersion = 0; + +async function reloadAccountState() { + const version = ++recoveryVersion; + let balances; + let openOrders; + let recentFills; + + try { + balances = await restClient.getBalances(); + } catch (error) { + console.error('Balance recovery failed:', error); + return; + } + + try { + openOrders = await restClient.getOpenOrders(); + } catch (error) { + console.error('Open-order recovery failed:', error); + return; + } + + try { + recentFills = await restClient.getUserFills({ + aggregateByTime: true, + }); + } catch (error) { + console.error('Fill recovery failed:', error); + return; + } + + // A newer recovery must not be overwritten by an older request sequence. + if (version !== recoveryVersion) { + return; + } + + accountState = { + balances, + openOrders, + recentFills, + }; + + console.log('Recovered account state:', accountState); } -⋮---- -export interface UserFundingsEvent { - fundings: Array<{ - coin: string; - fundingRate: string; - nSamples: number | null; - szi: string; - time: number; - usdc: string; - }>; - isSnapshot?: boolean; - user: string; + +async function main() { + websocketClient + .on('reconnected', async ({ wsKey }) => { + console.log('WebSocket reconnected:', wsKey); + await reloadAccountState(); + }) + .on('exception', ({ wsKey, event, data }) => { + console.error('WebSocket exception:', wsKey, event ?? data); + }); + + websocketClient.on('message', ({ channel, data, wsKey }) => { + if (channel === 'orderUpdates') { + console.log('Order updates:', wsKey, data); + } else if (channel === 'userFills') { + console.log('Fill update:', data); + } + }); + + try { + await websocketClient.subscribe([ + { type: 'orderUpdates', user: accountAddress }, + { type: 'userFills', user: accountAddress, aggregateByTime: true }, + ]); + } catch (error) { + console.error('Account subscription failed:', error); + } + + await reloadAccountState(); } -⋮---- -export interface UserHistoricalOrdersEvent { - isSnapshot?: boolean; - orderHistory: HistoricalOrder[]; - user: string; + +main(); +``` + +This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration): rebuilding trusted [account state](https://siebly.io/reference/glossary#accountstate) from current REST API reads after a stream gap. Use [Scoped Recovery](https://siebly.io/reference/glossary#scoped-recovery) to reload only the state owned by the affected connection, and see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows) for wider state-management patterns. + +If the process stores a durable fill cursor, reload by time and deduplicate by trade ID before replacing state. The initial `userFills` snapshot after resubscription may overlap with the REST API result. + +Here, `orderUpdates` uses `user:
` while `userFills` uses `public`, so either connection can trigger recovery. The version counter prevents overlapping recoveries from publishing out of order. This example logs stream events separately; a live state cache also needs to reconcile events received while its REST API reads are in flight. + + + +## Choose Mainnet, Testnet, or custom API hosts + +| Network | REST API host | WebSocket host | +| ------- | ------------------------------------- | -------------------------------------- | +| Mainnet | `https://api.hyperliquid.xyz` | `wss://api.hyperliquid.xyz/ws` | +| Testnet | `https://api.hyperliquid-testnet.xyz` | `wss://api.hyperliquid-testnet.xyz/ws` | + +Mainnet is the default. Set `testnet: true` on every client that belongs to a Testnet workflow. + + + +```javascript +import { + RestClient, + WebsocketAPIClient, + WebsocketClient, +} from '@siebly/hyperliquid-api'; + +const mainnetRest = new RestClient(); +const mainnetStreams = new WebsocketClient(); +const mainnetWebsocketApi = new WebsocketAPIClient(); + +const testnetRest = new RestClient({ testnet: true }); +const testnetStreams = new WebsocketClient({ testnet: true }); +const testnetWebsocketApi = new WebsocketAPIClient({ testnet: true }); + +const restApiUrl = process.env.HYPERLIQUID_REST_API_URL; +const websocketUrl = process.env.HYPERLIQUID_WEBSOCKET_URL; + +if (!restApiUrl || !websocketUrl) { + throw new Error( + 'Set HYPERLIQUID_REST_API_URL and HYPERLIQUID_WEBSOCKET_URL before using custom hosts.', + ); } -⋮---- -export interface UserNonFundingLedgerUpdatesEvent { - isSnapshot?: boolean; - nonFundingLedgerUpdates: UserNonFundingLedgerUpdate[]; - user: string; + +const customRest = new RestClient({ + baseUrl: restApiUrl, +}); + +const customStreams = new WebsocketClient({ + baseUrl: restApiUrl, + wsUrl: websocketUrl, +}); + +console.log({ + mainnetRest, + mainnetStreams, + mainnetWebsocketApi, + testnetRest, + testnetStreams, + testnetWebsocketApi, + customRest, + customStreams, +}); +``` + +`baseUrl` changes REST API routing. `wsUrl` changes WebSocket routing. The explicit `WebsocketClient.nameToCoin()` and `resolveAsset()` helpers use REST API metadata, so set both values if those helpers also need custom routing. Native streaming subscriptions use only `wsUrl`. + +Keep Mainnet and Testnet private keys, account addresses, client order IDs, and persistent state in separate configuration. Asset IDs and available markets can differ between the two networks. + +## Use a proxy with the REST API and WebSockets + +Install the proxy agent needed by your network: + +```bash +npm install https-proxy-agent socks-proxy-agent ws +``` + +The REST API client accepts Axios network options as its second constructor argument. WebSocket clients accept a custom WebSocket constructor. These are separate routes, so configure and test each one. + +See [Using a Proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. + +### HTTP or HTTPS proxy + +`HttpsProxyAgent` supports both HTTP and HTTPS proxy URLs. + + + +```javascript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import WebSocket from 'ws'; +import { + RestClient, + WebsocketAPIClient, + WebsocketClient, +} from '@siebly/hyperliquid-api'; + +const proxyUrl = process.env.HYPERLIQUID_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set HYPERLIQUID_PROXY_URL before starting.'); } -⋮---- -export interface UserTwapHistoryEvent { - history: TwapHistoryEntry[]; - isSnapshot?: boolean; - user: string; + +const agent = new HttpsProxyAgent(proxyUrl); +const parsedProxy = new URL(proxyUrl); +const axiosProxy = { + protocol: parsedProxy.protocol.slice(0, -1), + host: parsedProxy.hostname, + port: Number( + parsedProxy.port || (parsedProxy.protocol === 'https:' ? 443 : 80), + ), + ...(parsedProxy.username + ? { + auth: { + username: decodeURIComponent(parsedProxy.username), + password: decodeURIComponent(parsedProxy.password), + }, + } + : {}), +}; + +class ProxyWebSocket { + constructor(url) { + this.socket = Reflect.construct(WebSocket, [url, { agent }]); + this.onopen = null; + this.onmessage = null; + this.onerror = null; + this.onclose = null; + + this.socket.onopen = () => this.onopen?.(); + this.socket.onmessage = (event) => this.onmessage?.({ data: event.data }); + this.socket.onerror = (event) => this.onerror?.(event); + this.socket.onclose = (event) => + this.onclose?.({ code: event.code, reason: String(event.reason) }); + } + + get readyState() { + return this.socket.readyState; + } + + send(data) { + this.socket.send(data); + } + + close(code, reason) { + this.socket.close(code, reason); + } } -⋮---- -export interface UserTwapSliceFillsEvent { - isSnapshot?: boolean; - twapSliceFills: TwapSliceFill[]; - user: string; + +const restClient = new RestClient( + { keepAlive: false }, + { + httpsAgent: agent, + proxy: false, + }, +); + +const websocketClient = new WebsocketClient({ + requestOptions: { + proxy: axiosProxy, + }, + webSocketConstructor: ProxyWebSocket, +}); + +const websocketApiClient = new WebsocketAPIClient({ + webSocketConstructor: ProxyWebSocket, +}); + +async function main() { + try { + const status = await restClient.getExchangeStatus(); + console.log('REST API through proxy:', status); + } catch (error) { + console.error('Proxied REST API request failed:', error); + } + + websocketClient.on('message', ({ channel, data }) => { + if (channel === 'allMids') { + console.log('Stream through proxy:', data.mids.BTC); + } + }); + + try { + await websocketClient.subscribe({ type: 'allMids' }); + } catch (error) { + console.error('Proxied stream subscription failed:', error); + } + + try { + const mids = await websocketApiClient.getAllMids(); + console.log('WebSocket API through proxy:', mids.BTC); + } catch (error) { + console.error('Proxied WebSocket API request failed:', error); + } } -⋮---- -export interface SpotStateEvent { - spotState: SpotBalancesResponse; - user: string; + +main(); +``` + +Set `keepAlive: false` so the SDK preserves the custom agent, and set `proxy: false` so Axios does not apply separate environment-proxy handling on top of it. + +`webSocketConstructor` routes the socket itself. Streaming subscriptions send native topics without REST API metadata requests. `requestOptions.proxy` routes REST API metadata requests if you explicitly call `nameToCoin()` or `resolveAsset()` on the streaming client. + +### SOCKS5 proxy + + + +```javascript +import { SocksProxyAgent } from 'socks-proxy-agent'; +import WebSocket from 'ws'; +import { + RestClient, + WebsocketAPIClient, + WebsocketClient, +} from '@siebly/hyperliquid-api'; + +const proxyUrl = process.env.HYPERLIQUID_SOCKS_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set HYPERLIQUID_SOCKS_PROXY_URL before starting.'); } -⋮---- -export interface TwapStatesEvent { - dex: string; - states: Array<[twapId: number, state: TwapState]>; - user: string; + +const agent = new SocksProxyAgent(proxyUrl); + +class ProxyWebSocket { + constructor(url) { + this.socket = Reflect.construct(WebSocket, [url, { agent }]); + this.onopen = null; + this.onmessage = null; + this.onerror = null; + this.onclose = null; + + this.socket.onopen = () => this.onopen?.(); + this.socket.onmessage = (event) => this.onmessage?.({ data: event.data }); + this.socket.onerror = (event) => this.onerror?.(event); + this.socket.onclose = (event) => + this.onclose?.({ code: event.code, reason: String(event.reason) }); + } + + get readyState() { + return this.socket.readyState; + } + + send(data) { + this.socket.send(data); + } + + close(code, reason) { + this.socket.close(code, reason); + } } -⋮---- -export type UserEvent = - | { fills: UserFill[] } - | { - funding: { - coin: string; - fundingRate: string; - nSamples: number | null; - szi: string; - time: number; - usdc: string; - }; - } - | { - liquidation: { - lid: number; - liquidated_account_value: string; - liquidated_ntl_pos: string; - liquidated_user: string; - liquidator: string; - }; + +const restClient = new RestClient( + { keepAlive: false }, + { + httpsAgent: agent, + proxy: false, + }, +); + +const websocketClient = new WebsocketClient({ + webSocketConstructor: ProxyWebSocket, +}); + +const websocketApiClient = new WebsocketAPIClient({ + webSocketConstructor: ProxyWebSocket, +}); + +async function main() { + try { + const status = await restClient.getExchangeStatus(); + console.log('REST API through SOCKS5:', status); + } catch (error) { + console.error('SOCKS5 REST API request failed:', error); + } + + websocketClient.on('message', ({ channel, data }) => { + if (channel === 'allMids') { + console.log('WebSocket through SOCKS5:', data.mids.BTC); } - | { nonUserCancel: Array<{ coin: string; oid: number }> } - | { twapHistory: TwapHistoryEntry[] } - | { twapSliceFills: TwapSliceFill[] }; -⋮---- -export interface WebData3PerpDexState { - leadingVaults?: LeadingVault[]; - perpsAtOpenInterestCap?: string[]; - totalVaultEquity: string; -} -⋮---- -export interface WebData3Event { - perpDexStates: WebData3PerpDexState[]; - userState: { - abstraction?: 'disabled' | 'portfolioMargin' | 'unifiedAccount'; - agentAddress: string | null; - agentValidUntil: number | null; - cumLedger: string; - dexAbstractionEnabled?: boolean; - isVault: boolean; - optOutOfSpotDusting?: true; - serverTime: number; - user: string; - }; -} -⋮---- -export type GenericWebsocketEvent = - Record | unknown[] | string | number | boolean | null; -⋮---- -/** Payload types keyed by subscription type. Wire envelopes are defined in ws-events. */ -export interface WebsocketSubscriptionData { - activeAssetCtx: AssetContextEvent; - activeAssetData: ActiveAssetDataEvent; - allDexsAssetCtxs: AllDexsAssetCtxsEvent; - allDexsClearinghouseState: AllDexsClearinghouseStateEvent; - allMids: AllMidsEvent; - assetCtxs: AssetCtxsEvent; - bbo: BboEvent; - candle: Candle; - clearinghouseState: ClearinghouseStateEvent; - fastAssetCtxs: FastAssetCtxsEvent; - l2: WsL2; - l2Book: OrderBookResponse; - notification: NotificationEvent; - openOrders: OpenOrdersEvent; - orderUpdates: OrderUpdateEvent[]; - outcomeMetaUpdates: OutcomeMetaUpdatesEvent; - pac: WsPac; - sac: WsSac; - spotAssetCtxs: SpotAssetCtxsEvent; - spotState: SpotStateEvent; - trades: TradeEvent[]; - twapStates: TwapStatesEvent; - userEvents: UserEvent; - userFills: UserFillsEvent; - userFundings: UserFundingsEvent; - userHistoricalOrders: UserHistoricalOrdersEvent; - userNonFundingLedgerUpdates: UserNonFundingLedgerUpdatesEvent; - userTwapHistory: UserTwapHistoryEvent; - userTwapSliceFills: UserTwapSliceFillsEvent; - webData3: WebData3Event; + }); + + try { + await websocketClient.subscribe({ type: 'allMids' }); + } catch (error) { + console.error('SOCKS5 stream subscription failed:', error); + } + + try { + const mids = await websocketApiClient.getAllMids(); + console.log('WebSocket API through SOCKS5:', mids.BTC); + } catch (error) { + console.error('SOCKS5 WebSocket API request failed:', error); + } } -⋮---- -export type WebsocketEventFor = - WebsocketSubscriptionData[S['type']]; -================ -File: .gitignore -================ -hyperliquidref -!.gitkeep -.DS_Store -*.log -*.tgz -.env -.env.test -localtest.sh -.eslintcache -.npm -.tmp-packed* -coverage -dist -node_modules -README_BEFORE_RELEASE.md -examples/tstests -/tmp/ -localtest.sh -rest-ts.ts +main(); +``` + +Set `keepAlive: false` so the REST API client preserves the SOCKS agent. Streaming subscriptions do not trigger REST API metadata lookups. Resolve readable aliases with the configured `restClient.nameToCoin()` first, then pass the result to `websocketClient.subscribe()`, so alias resolution also follows the SOCKS route. + +A proxy changes the network route, not the account, network, or available products. Monitor latency, disconnects, and the proxy's egress IP. + +## Understand Siebly referral and builder settings + +The SDK includes two separate Hyperliquid features: + +- Referral code: around the first supported trading action from a client instance, the SDK makes one passive attempt to apply `SIEBLY`. Hyperliquid leaves an existing referrer unchanged. Trading continues if the referral request fails. +- Builder code: after the account has approved Siebly's builder fee, the SDK can include the builder code on eligible orders. The configured maximum is 0.1%. Approval must be signed by the main wallet, not an API wallet. If a main-wallet private key is configured and approval is missing, the SDK may attempt that approval in the background. An API wallet cannot grant it. + +Builder approval is optional. Call `approveBuilderFee()` only from a client configured with the main wallet signer and only after reviewing Hyperliquid's current [builder-code documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/builder-codes). The approval sets a maximum and can be revoked through Hyperliquid. + +## Production checklist + +- **Keep signers isolated.** Use a separate approved API wallet per trading process and, where practical, per subaccount. +- **Query the correct address.** Account reads use the master account, subaccount, or vault address rather than the API wallet address. +- **Keep time synchronized.** Signed nonces are millisecond timestamps and must remain inside Hyperliquid's accepted time window. +- **Use exact decimal strings.** Avoid JavaScript floating-point arithmetic for stored financial values. Trim trailing decimal zeroes before native wire-shaped actions. +- **Read current metadata.** Resolve assets and use the latest `szDecimals`, universe names, margin tables, and market status. +- **Meet minimum notional.** Hyperliquid currently requires at least 10 units of the quote asset for an order. +- **Check every action status.** A top-level `ok` response may contain an order-specific `error` entry. +- **Reconcile uncertain writes.** Query by [custom order ID](https://siebly.io/reference/glossary#custom-order-id) before retrying a timed-out submission. +- **Confirm final order state.** Treat the first response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then use `getOrderStatus()` or `orderUpdates`. +- **Use action deadlines where useful.** `expiresAfter` limits how long a signed action remains valid. A stale deadline rejection currently consumes extra address-based rate-limit allowance. +- **Use a dead-man switch.** Refresh `setCancelAllAfter()` from a monitored process when unattended resting orders need automatic cancellation. +- **Recover after gaps.** Rebuild the affected balances, positions, orders, and fills after a reconnect. +- **Respect current limits.** Hyperliquid applies IP, address, open-order, connection, subscription, and in-flight request limits. Check the current [rate-limit documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits). +- **Keep raw keys server-side.** Browser apps can use a connected browser or embedded wallet client as the signer; never bundle a raw private key. +- **Monitor the route.** Track latency, reconnect frequency, and egress IP when using a proxy or custom endpoint. + +## Frequently asked questions + +### Can I use the SDK with plain JavaScript? + +Yes. Examples use JavaScript unless marked TypeScript. The package also includes TypeScript declarations. + +### Which client should I start with? + +Start with `RestClient` for public market data and account state. Add `WebsocketClient` for live subscriptions. Use `WebsocketAPIClient` when you need awaitable Info or Exchange requests over WebSocket. + +### Why do account reads work without a private key? + +Hyperliquid Info queries use a public account address. A signer is needed for Exchange actions that change orders, funds, leverage, or account settings. + +### Why are my balances empty when I use an API wallet? + +Account queries need the master account, subaccount, or vault address. The API wallet address identifies the signer, not the account whose state is being queried. Set `accountAddress` on the client. + +### What is the difference between a wallet and an API wallet? + +The main wallet owns the account. An approved API wallet signs actions on its behalf. Use an API wallet for an automated process and keep the main wallet key outside that process. + +### Why are REST API response shapes different? + +Hyperliquid's Info endpoint selects an operation through the request body, and each operation has its own response schema. The SDK returns that response directly. + +### Why did an order fail when the response status was `ok`? + +The top-level status describes the action request. Each order has its own entry under `response.data.statuses`, which may contain `resting`, `filled`, or `error`. + +### Does `submitMarketOrder()` send a native market order? + +It sends an immediate-or-cancel limit order with a protection price. The SDK derives and rounds that price from the midpoint when one is not supplied. + +### How do I tell perpetual and Spot assets apart? + +Perpetuals commonly use names such as `BTC`. Spot markets use native universe names such as `PURR/USDC` or `@107`. REST API helpers can resolve readable metadata-derived aliases such as `HYPE/USDC`. For streaming subscriptions, call `nameToCoin()` explicitly to resolve an alias, then subscribe with the returned native coin name. + +### Do account WebSocket streams require authentication? + +They use the public account address. The SDK isolates user-scoped channels when needed and resubscribes after reconnecting. + +### How do subscription acknowledgements appear? + +Listen for `response` events with `channel === 'subscriptionResponse'`. Snapshot and update envelopes arrive through `message`. Both events include `wsKey`, and the promise returned by `subscribe()` only confirms that the subscription request was sent. + +### What is the difference between `WebsocketClient` and `WebsocketAPIClient`? + +`WebsocketClient` consumes ongoing subscriptions. `WebsocketAPIClient` sends one Info or Exchange request and resolves the matching response as a promise. + +### Should I retry a timed-out order submission? + +Not immediately. Query `getOrderStatus()` with the client order ID first. A request can reach Hyperliquid even when the response does not reach your process. + +### How do I use a vault or subaccount? + +Set its address as `vaultAddress` for signed actions and use the same address for its account-state queries. The API wallet must be approved to act for the relevant account. + +### Can I use Mainnet credentials on Testnet? + +Keep the networks separate. Approval state, account balances, assets, and API-wallet registration differ between Mainnet and Testnet. + +### Does a proxy change which network I use? + +No. `testnet`, `baseUrl`, and `wsUrl` select the destination. A proxy only changes the network path used to reach it. + +## Next steps + +1. Run the public REST API example and inspect the current BTC metadata and order book. +2. Set a public account address and load balances, positions, open orders, and fills. +3. Add public and account WebSocket subscriptions, including reconnect handling. +4. Approve a Testnet API wallet and run the perpetual order lifecycle. +5. Add client order IDs, action deadlines, dead-man-switch refresh, and scoped recovery before moving a strategy to Mainnet. + +Continue with the [Hyperliquid SDK examples](https://siebly.io/examples/Hyperliquid), browse the [source repository](https://github.com/sieblyio/hyperliquid-api), and check the [official Hyperliquid API documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) for current exchange behavior. ================ File: src/types/response/info.types.ts @@ -3899,19 +4083,25 @@ export type UserRoleResponse = | { role: 'subAccount'; data: { master: string } }; ⋮---- export interface OrderBookLevel { + /** Number of orders at this price level. */ n: number; px: string; sz: string; } ⋮---- +/** Number of orders at this price level. */ +⋮---- export interface OrderBookResponse { coin: string; fast?: true; levels: [OrderBookLevel[], OrderBookLevel[]]; + /** Present only when nSigFigs is set; not necessarily the gap between grouped levels. */ spread?: string; time: number; } ⋮---- +/** Present only when nSigFigs is set; not necessarily the gap between grouped levels. */ +⋮---- export interface Candle { T: number; c: string; @@ -3940,6 +4130,7 @@ export interface Candle { } ⋮---- export interface OpenOrder { + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ cloid?: string | null; coin: string; limitPx: string; @@ -3951,19 +4142,30 @@ export interface OpenOrder { [key: string]: unknown; } ⋮---- +/** Client order ID: 0x followed by 32 hex characters (128 bits). */ +⋮---- export interface SpotBalance { coin: string; entryNtl: string; + /** Decimal string; can be negative under portfolio margin. */ hold: string; token: number; + /** Decimal string; can be negative under portfolio margin. */ total: string; } ⋮---- +/** Decimal string; can be negative under portfolio margin. */ +⋮---- +/** Decimal string; can be negative under portfolio margin. */ +⋮---- export interface SpotBalancesResponse { balances: SpotBalance[]; + /** Available token amounts after maintenance requirements, keyed by spot token index. */ tokenToAvailableAfterMaintenance?: Array<[token: number, available: string]>; } ⋮---- +/** Available token amounts after maintenance requirements, keyed by spot token index. */ +⋮---- export interface PerpMarginSummary { accountValue: string; totalMarginUsed: string; @@ -4046,6 +4248,7 @@ export interface UserFill { ⋮---- export interface FrontendOpenOrder { children?: FrontendOpenOrder[]; + /** Client order ID: 0x followed by 32 hex characters (128 bits). */ cloid?: string | null; coin: string; isPositionTpsl: boolean; @@ -4063,43 +4266,141 @@ export interface FrontendOpenOrder { triggerPx: string; } ⋮---- +/** Client order ID: 0x followed by 32 hex characters (128 bits). */ +⋮---- export type OrderState = + /** Rejected due to post-only immediate match */ | 'badAloPxRejected' + /** Rejected due to invalid TP/SL price */ | 'badTriggerPxRejected' + /** Canceled by user */ | 'canceled' + /** Canceled due to asset delisting */ | 'delistedCanceled' + /** Filled */ | 'filled' + /** Rejected due to insufficient spot balance */ | 'insufficientSpotBalanceRejected' - /** Returned by Hyperliquid, not yet in their docs. */ + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'insufficientWeiCanceled' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'internalCancel' + /** Rejected due to IOC not able to match */ | 'iocCancelRejected' + /** Canceled due to liquidation */ | 'liquidatedCanceled' + /** Canceled because insufficient margin to fill */ | 'marginCanceled' + /** Rejected due to lack of liquidity for market order */ | 'marketOrderNoLiquidityRejected' + /** Rejected due to order notional below minimum */ | 'minTradeNtlRejected' + /** Placed successfully */ | 'open' + /** Canceled due to order being too aggressive when open interest was at cap */ | 'openInterestCapCanceled' + /** Rejected due to open interest cap */ | 'openInterestIncreaseRejected' + /** Rejected due to price too far from oracle */ | 'oracleRejected' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'outcomeSettledCanceled' + /** Rejected due to insufficient margin */ | 'perpMarginRejected' + /** Rejected due to exceeding margin tier limit at current leverage */ | 'perpMaxPositionRejected' + /** Rejected due to open interest cap */ | 'positionFlipAtOpenInterestCapRejected' + /** Rejected due to open interest cap */ | 'positionIncreaseAtOpenInterestCapRejected' + /** Canceled reduced-only order that does not reduce position */ | 'reduceOnlyCanceled' + /** Rejected due to reduce only */ | 'reduceOnlyRejected' + /** Rejected at time of placement */ | 'rejected' + /** API only. Canceled due to exceeding scheduled cancel deadline (dead man's switch) */ | 'scheduledCancel' + /** Canceled due to self-trade prevention */ | 'selfTradeCanceled' + /** TP/SL only. Canceled due to sibling ordering being filled */ | 'siblingFilledCanceled' + /** Rejected due to invalid tick price */ | 'tickRejected' + /** Rejected due to price too aggressive at open interest cap */ | 'tooAggressiveAtOpenInterestCapRejected' + /** Returned by Hyperliquid; not described in the official order-status table. */ | 'tooManyOpenOrdersRejected' + /** Trigger order triggered */ | 'triggered' + /** Vaults only. Canceled due to a user's withdrawal from vault */ | 'vaultWithdrawalCanceled'; ⋮---- -/** Returned by Hyperliquid, not yet in their docs. */ +/** Rejected due to post-only immediate match */ +⋮---- +/** Rejected due to invalid TP/SL price */ +⋮---- +/** Canceled by user */ +⋮---- +/** Canceled due to asset delisting */ +⋮---- +/** Filled */ +⋮---- +/** Rejected due to insufficient spot balance */ +⋮---- +/** Returned by Hyperliquid; not described in the official order-status table. */ +⋮---- +/** Returned by Hyperliquid; not described in the official order-status table. */ +⋮---- +/** Rejected due to IOC not able to match */ +⋮---- +/** Canceled due to liquidation */ +⋮---- +/** Canceled because insufficient margin to fill */ +⋮---- +/** Rejected due to lack of liquidity for market order */ +⋮---- +/** Rejected due to order notional below minimum */ +⋮---- +/** Placed successfully */ +⋮---- +/** Canceled due to order being too aggressive when open interest was at cap */ +⋮---- +/** Rejected due to open interest cap */ +⋮---- +/** Rejected due to price too far from oracle */ +⋮---- +/** Returned by Hyperliquid; not described in the official order-status table. */ +⋮---- +/** Rejected due to insufficient margin */ +⋮---- +/** Rejected due to exceeding margin tier limit at current leverage */ +⋮---- +/** Rejected due to open interest cap */ +⋮---- +/** Rejected due to open interest cap */ +⋮---- +/** Canceled reduced-only order that does not reduce position */ +⋮---- +/** Rejected due to reduce only */ +⋮---- +/** Rejected at time of placement */ +⋮---- +/** API only. Canceled due to exceeding scheduled cancel deadline (dead man's switch) */ +⋮---- +/** Canceled due to self-trade prevention */ +⋮---- +/** TP/SL only. Canceled due to sibling ordering being filled */ +⋮---- +/** Rejected due to invalid tick price */ +⋮---- +/** Rejected due to price too aggressive at open interest cap */ +⋮---- +/** Returned by Hyperliquid; not described in the official order-status table. */ +⋮---- +/** Trigger order triggered */ +⋮---- +/** Vaults only. Canceled due to a user's withdrawal from vault */ ⋮---- export interface OrderStatusDetails { order: FrontendOpenOrder; @@ -4247,10 +4548,17 @@ export interface VaultSummary { } ⋮---- export interface UserVaultDeposit { + /** Vault equity in decimal units. */ equity: string; + /** Withdrawal unlock time in milliseconds; matches followerState.lockupUntil. */ + lockedUntilTimestamp: number; vaultAddress: string; } ⋮---- +/** Vault equity in decimal units. */ +⋮---- +/** Withdrawal unlock time in milliseconds; matches followerState.lockupUntil. */ +⋮---- export interface ReferralTokenState { builderRewards: string; claimedRewards: string; @@ -4392,12 +4700,18 @@ export interface StakingReward { } ⋮---- export type UserAbstraction = + /** Default mode for addresses that have not explicitly selected an abstraction. */ | 'default' + /** Discontinued DEX abstraction mode; prefer unifiedAccount or portfolioMargin. */ | 'dexAbstraction' | 'disabled' | 'portfolioMargin' | 'unifiedAccount'; ⋮---- +/** Default mode for addresses that have not explicitly selected an abstraction. */ +⋮---- +/** Discontinued DEX abstraction mode; prefer unifiedAccount or portfolioMargin. */ +⋮---- export interface BorrowLendBalance { basis: string; value: string; @@ -4440,6 +4754,7 @@ export type BorrowLendReserveEntry = [ export interface PerpAsset { deployerFeeScale?: string; growthMode?: 'enabled'; + /** Delisted markets remain in universe and can still resolve; they have no mid or open interest. */ isDelisted?: boolean; lastFeeScaleChangeTime?: string; /** @@ -4455,6 +4770,8 @@ export interface PerpAsset { szDecimals: number; } ⋮---- +/** Delisted markets remain in universe and can still resolve; they have no mid or open interest. */ +⋮---- /** * "strictIsolated" means margin cannot be removed. * "noCross" means only isolated margin is allowed. @@ -4473,11 +4790,14 @@ export interface PerpMarginTable { } ⋮---- export interface PerpMeta { + /** Spot token index of this DEX's collateral; look up in getSpotMetadata().tokens. */ collateralToken: number; marginTables: Array<[id: number, table: PerpMarginTable]>; universe: PerpAsset[]; } ⋮---- +/** Spot token index of this DEX's collateral; look up in getSpotMetadata().tokens. */ +⋮---- export interface PerpAssetContext { dayBaseVlm: string; dayNtlVlm: string; @@ -4597,6 +4917,10 @@ export type UserNonFundingLedgerDelta = user: string; } | { amount: string; token: string; type: 'deployGasAuction' | 'spotGenesis' } + /** Observed in public non-funding ledgers. */ + | { type: 'gossipPriorityGasAuction'; token: string; amount: string } + /** Observed in public non-funding ledgers. */ + | { type: 'accountActivationGas'; token: string; amount: string } | { amount: string; isDeposit: boolean; @@ -4617,6 +4941,10 @@ export type UserNonFundingLedgerDelta = type: 'activateDexAbstraction'; }; ⋮---- +/** Observed in public non-funding ledgers. */ +⋮---- +/** Observed in public non-funding ledgers. */ +⋮---- export interface UserNonFundingLedgerUpdate { delta: UserNonFundingLedgerDelta; hash: string; @@ -4624,11 +4952,20 @@ export interface UserNonFundingLedgerUpdate { } ⋮---- export interface PredictedFundingQuote { + /** Venue funding interval in hours; can be absent, so do not assume 1. */ fundingIntervalHours?: number; + /** Decimal rate per venue interval, not necessarily hourly. Divide by the known interval to compare. */ fundingRate: string; + /** Milliseconds; observed HlPerp values mark the current hour boundary. Zero means none. */ nextFundingTime: number; } ⋮---- +/** Venue funding interval in hours; can be absent, so do not assume 1. */ +⋮---- +/** Decimal rate per venue interval, not necessarily hourly. Divide by the known interval to compare. */ +⋮---- +/** Milliseconds; observed HlPerp values mark the current hour boundary. Zero means none. */ +⋮---- export type PredictedFunding = [ coin: string, venues: Array<[venue: string, quote: PredictedFundingQuote | null]>, @@ -4819,17 +5156,26 @@ export interface SettledOutcomeQuestion { description: string; name: string; question: { + /** Settled question identifier shared by its outcomes, not a settlement timestamp. */ settled: number; }; } ⋮---- +/** Settled question identifier shared by its outcomes, not a settlement timestamp. */ +⋮---- export interface SettledOutcome { + /** Exchange-provided settlement details. */ details: string; question?: SettledOutcomeQuestion; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; spec: Outcome; } ⋮---- +/** Exchange-provided settlement details. */ +⋮---- +/** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ +⋮---- export interface OutcomeDeployerLimits { nActiveOutcomesRemaining: number; nDailyOutcomesRemaining: number; @@ -4887,6 +5233,7 @@ export type OutcomeGovernanceAction = settleOutcome: { details: string; outcome: number; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; }; } @@ -4905,6 +5252,7 @@ export type OutcomeGovernanceAction = details: string; nameAndDescription: [string, string]; outcome: number; + /** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ settleFraction: string; sideNames: [string, string]; }>; @@ -4912,6 +5260,10 @@ export type OutcomeGovernanceAction = }; }; ⋮---- +/** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ +⋮---- +/** Quote tokens per Yes share at settlement; No converts to 1 minus this value. */ +⋮---- export type ValidatorL1VoteAction = | { C: string[] } | { D: string } @@ -5019,16 +5371,26 @@ close(wsKey?: WsKey): void * Topics are cached before connecting and restored automatically after reconnect. * The promise confirms local sending; server acknowledgements emit 'response'. * Resolve display aliases explicitly with nameToCoin() when needed. + * Identical topics are merged; one unsubscribe removes the topic for all callers. + * Subscribe to activeAssetCtx for both perps and spot; spot messages arrive + * on activeSpotAssetCtx (which is not a subscription type). + * A rejected first subscribe still leaves the topic cached for automatic retries. */ async subscribe( subscriptions: WebsocketSubscription | readonly WebsocketSubscription[], ): Promise ⋮---- -/** Remove cached topics independently of event listeners, including while disconnected. */ +/** + * Remove cached topics independently of event listeners, including while disconnected. + * Identical topics are merged; one unsubscribe removes the topic for all callers. + */ async unsubscribe( subscriptions: WebsocketSubscription | readonly WebsocketSubscription[], ): Promise ⋮---- +/** Copy of cached topics to restore on reconnect; omit wsKey to include every connection. */ +getActiveTopics(wsKey?: WsKey): readonly Readonly[] +⋮---- async sendWSAPIRequest( endpoint: 'action' | 'info', body: unknown, @@ -5094,6 +5456,9 @@ import { marketLimitPrice, normalizeUserRequest, positiveDecimal, + validateCloid, + validateDestination, + validatePrice, } from './lib/request-utils.js'; import { USER_SIGNED_ACTIONS } from './lib/user-signed-actions.js'; import type { @@ -5247,6 +5612,7 @@ constructor( networkOptions: RestClientNetworkOptions = {}, ) ⋮---- +/** Resolve metadata, including delisted markets; resolution does not imply tradability. */ resolveAsset(identifier: AssetIdentifier): Promise ⋮---- nameToCoin(name: string): Promise @@ -5259,7 +5625,8 @@ getAccountAddress(): Promise * Mid prices for all coins (`allMids`). * * An empty book falls back to the last trade price. Spot mids are included - * only when `dex` is omitted or empty. + * only when `dex` is omitted or empty. HIP-3 mids require that DEX name in `dex`. + * Outcome sides appear under `#<10 * outcome + side>` coin names. */ getAllMids(params: { dex?: string } = {}): Promise ⋮---- @@ -5282,7 +5649,7 @@ getAllBorrowLendReserveStates(): Promise * Metadata for every perp DEX (`allPerpMetas`). * * Each entry is one DEX: universe, margin tables, and collateral token. - * Index 0 is the default perp DEX. + * Index 0 is the default perp DEX. Entry i belongs to getPerpDexs()[i]. */ getAllPerpMetadata(): Promise ⋮---- @@ -5310,8 +5677,10 @@ getUserBorrowLendState( /** * Candle snapshot (`candleSnapshot`). * - * Only the most recent 5000 candles are available. HIP-3 coins use a - * `dex:COIN` name. + * Returns up to 5000 newest bars in the requested range, oldest first. + * Retention is roughly the latest 5000 bars per interval; an additional older + * page can be available. Page backwards with endTime = page[0].t - 1 until + * a short or empty page. HIP-3 coins use `dex:COIN`; outcomes use `#`. */ async getCandles(params: GetCandlesRequest): Promise ⋮---- @@ -5320,7 +5689,8 @@ async getCandles(params: GetCandlesRequest): Promise * * `assetPositions[].position.szi` is signed: positive is long, negative is short. * Under unified account or portfolio margin, use spot balances for the - * trading account balance across spot and perps. + * trading account balance across spot and perps. HIP-3 positions require + * the DEX name in `dex`; omitted means the default perp DEX. */ getPerpAccountSummary( params: AccountDexRequest = {}, @@ -5361,6 +5731,7 @@ getExtraAgents(params: AccountRequest = {}): Promise /** * Open orders with trigger and reduce-only fields (`frontendOpenOrders`). * + * HIP-3 orders require that DEX name in `dex`; omitted means the default perp DEX. * Spot orders are included only for the first perp DEX. */ getFrontendOpenOrders( @@ -5381,7 +5752,10 @@ getGossipRootIps(): Promise /** * Recent historical orders (`historicalOrders`). * - * Returns at most 2000 orders. `status` uses the same values as `getOrderStatus()`. + * Returns at most 2000 status-change rows, newest first. An order can appear + * several times; the first row for an oid is its latest status. There is no + * time-range option; retain your own history to extend this window. + * `status` uses the same values as `getOrderStatus()`. */ getOrderHistory(params: AccountRequest = {}): Promise ⋮---- @@ -5392,10 +5766,9 @@ getVipStatus(params: AccountRequest = {}): Promise * * At most 20 levels per side. `nSigFigs` aggregates prices. `mantissa` is * only valid when `nSigFigs` is 5. + * @throws RangeError for unknown or incorrectly cased coins, or a missing book. */ -async getOrderBook( - params: GetOrderBookRequest, - ): Promise +async getOrderBook(params: GetOrderBookRequest): Promise ⋮---- getLeadingVaults(params: AccountRequest = {}): Promise ⋮---- @@ -5435,6 +5808,7 @@ getPerpAssetContexts( /** * Open orders (`openOrders`). * + * HIP-3 orders require that DEX name in `dex`; omitted means the default perp DEX. * Spot orders are included only for the first perp DEX. `side` `"B"` is bid * and `"A"` is ask. */ @@ -5442,6 +5816,8 @@ getOpenOrders(params: AccountDexRequest = {}): Promise ⋮---- /** * Order status by order id or client order id (`orderStatus`). + * Decimal-digit strings are converted to safe integers; cloids use 0x plus + * 32 hex characters. Invalid or unsafe IDs throw RangeError before the request. * * `status: "unknownOid"` means the order was not found. Otherwise * `status` is `"order"` and `order.status` is the order state. @@ -5534,7 +5910,7 @@ getPreTransferCheck( * * Only the first perp DEX is supported. Each entry is `[coin, venues]`, * and each venue is `[venue, quote]`. `quote` is `null` when that venue - * has no predicted rate. + * has no predicted rate. Delisted coins are included. */ getPredictedFundingRates(): Promise ⋮---- @@ -5558,6 +5934,11 @@ getSettledOutcome(params: { outcome: number; }): Promise ⋮---- +/** + * Returns perp and spot balances side by side, without querying the account mode. + * Under unified account or portfolio margin, spot holds the trading balance + * across both. Use getUserAbstraction() to interpret the account mode. + */ async getBalances( params: AccountDexRequest = {}, ): Promise @@ -5566,7 +5947,7 @@ async getBalances( * Spot token balances (`spotClearinghouseState`). * * Under unified account or portfolio margin, this is the trading-account - * balance across spot and perps. + * balance across spot and perps. Portfolio margin can report negative total/hold. */ getSpotBalances(params: AccountRequest = {}): Promise ⋮---- @@ -5587,6 +5968,7 @@ getSpotMetadata(): Promise * * The tuple is `[meta, contexts]`. Contexts include mark price, volume, * and supply. `midPx` is `null` when there is no mid. + * Outcome sides appear under `#<10 * outcome + side>` coin names. */ getSpotAssetContexts(): Promise ⋮---- @@ -5666,6 +6048,9 @@ getUserFundingHistory( * * `startTime` is inclusive, in milliseconds. `endTime` defaults to now. * Read `delta.type` to see which delta fields are set. + * Pages contain up to 2000 rows, oldest first from startTime. The exchange + * documents startTime as required. If omitted, observed responses contain + * the newest 2000 rows in reverse order; do not page by their last time. */ getUserNonFundingLedgerUpdates( params: GetUserNonFundingLedgerUpdatesRequest = {}, @@ -5703,7 +6088,9 @@ getUserTwapSliceFillsByTime( ): Promise ⋮---- /** - * Vault equity for this user (`userVaultEquities`). + * One row per vault for this user (`userVaultEquities`). Equity is a decimal + * string; lockedUntilTimestamp is the withdrawal unlock time in milliseconds + * (the same value as vaultDetails.followerState.lockupUntil). */ getUserVaultDeposits( params: AccountRequest = {}, @@ -5736,7 +6123,8 @@ getAlignedQuoteTokenStatus(params: { * Place one or more orders (`order`). * * Each status is `resting`, `filled`, or `error`. The request can succeed - * while an individual order is rejected. + * while an individual order is rejected. Statuses usually has one entry per + * order; a pre-validation error can return a single entry for the entire batch. */ async submitOrder( params: SubmitOrderRequest, @@ -5767,7 +6155,9 @@ async submitMarketClose( /** * Place a limit order (`order`). * - * `postOnly` sends ALO. `timeInForce: "IOC"` sends IOC. Otherwise the order is GTC. + * `postOnly` sends ALO. `timeInForce: "IOC"` or "Ioc" sends IOC; "GTC" and + * "Gtc" send GTC. Prices violating known asset precision throw RangeError + * before signing; prices are never rounded. */ async submitLimitOrder( params: SubmitLimitOrderRequest, @@ -5793,7 +6183,8 @@ async modifyOrder( * Modify multiple resting orders (`batchModify`). * * Statuses match `submitOrder()`. `alwaysPlace` has the same meaning as - * on `modifyOrder()`. + * on `modifyOrder()`. A pre-validation error can return a single status for + * the entire batch, rather than one per order. oid is a number or a cloid. */ async modifyOrders( params: ModifyOrdersRequest, @@ -5903,6 +6294,7 @@ registerReferrer( * Approve the configured builder fee (`approveBuilderFee`). * * `maxFeeRate` is a percent string such as `"0.001%"`. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ async approveBuilderFee( options: UserSignedRequestOptions = {}, @@ -5914,6 +6306,7 @@ async approveBuilderFee( * An account can have one unnamed agent and up to three named agents. * Append `valid_until {timestamp}` to the name to set an expiration, * at most 180 days ahead. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ approveApiWallet( params: ApproveApiWalletRequest, @@ -5924,6 +6317,8 @@ approveApiWallet( * Send USDC to another address on HyperCore (`usdSend`). * * This does not touch the EVM bridge. `expiresAfter` is not supported. + * Ledger rows can be internalTransfer or send with both DEX names empty. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendUsd( params: SendUsdRequest, @@ -5934,6 +6329,8 @@ sendUsd( * Send a spot token to another address on HyperCore (`spotSend`). * * This does not touch the EVM bridge. `token` is `name:tokenId`. + * Ledger rows can be spotTransfer or send with both DEX names "spot". + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendSpotAsset( params: SendSpotAssetRequest, @@ -5942,6 +6339,8 @@ sendSpotAsset( ⋮---- /** * Start a USDC withdrawal to the bridge (`withdraw3`). + * The ledger row is withdraw and does not include the destination. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ withdrawUsd( params: WithdrawUsdRequest, @@ -5951,7 +6350,8 @@ withdrawUsd( /** * Move USDC between spot and perp (`usdClassTransfer`). * - * `toPerp: true` sends spot to perp. + * `toPerp: true` sends spot to perp. For API wallets, use sendAssetFromApiWallet(). + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ transferUsdBetweenSpotAndPerp( params: TransferUsdBetweenSpotAndPerpRequest, @@ -5963,6 +6363,8 @@ transferUsdBetweenSpotAndPerp( * * Use `""` for the default USDC perp DEX and `"spot"` for spot. * Only the collateral token can move to or from a perp DEX. + * For API wallets, use sendAssetFromApiWallet(). + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendAsset( params: SendAssetRequest, @@ -5973,6 +6375,7 @@ sendAsset( * Send tokens from Core to EVM with calldata (`sendToEvmWithData`). * * The linked contract must implement `coreReceiveWithData`. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ sendToEvmWithData( params: SendToEvmWithDataRequest, @@ -5993,6 +6396,7 @@ sendAssetFromApiWallet( * Move native token from spot into staking (`cDeposit`). * * `wei` is the amount in wei. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ depositIntoStaking( params: { wei: number }, @@ -6003,6 +6407,7 @@ depositIntoStaking( * Move native token from staking back to spot (`cWithdraw`). * * The transfer waits in a 7-day unstaking queue. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ withdrawFromStaking( params: { wei: number }, @@ -6013,27 +6418,40 @@ withdrawFromStaking( * Delegate or undelegate stake to a validator (`tokenDelegate`). * * A delegation to one validator locks for 1 day. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ delegateOrUndelegateStake( params: DelegateOrUndelegateStakeRequest, options: UserSignedRequestOptions = {}, ): Promise ⋮---- +/** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ convertToMultiSigUser( params: ConvertToMultiSigUserRequest, options: UserSignedRequestOptions = {}, ): Promise ⋮---- +/** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ linkStakingAccount( params: LinkStakingAccountRequest, options: UserSignedRequestOptions = {}, ): Promise ⋮---- +/** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ disableStakingTradingLink( params: { tradingUser: string }, options: UserSignedRequestOptions = {}, ): Promise ⋮---- +/** + * Requires the account owner's signer; accountAddress does not authorize an API wallet. + */ setUserPortfolioMargin( params: UserToggleRequest, options: UserSignedRequestOptions = {}, @@ -6043,6 +6461,8 @@ setUserPortfolioMargin( * Set account abstraction (`userSetAbstraction`). * * `abstraction` is `"disabled"`, `"unifiedAccount"`, or `"portfolioMargin"`. + * `user` is required; it is not filled from the signer or accountAddress. + * Requires the account owner's signer; accountAddress does not authorize an API wallet. */ setUserAbstraction( params: SetUserAbstractionRequest, @@ -6179,6 +6599,7 @@ transferSpotToOrFromSubAccount( options: L1RequestOptions = {}, ): Promise ⋮---- +/** Transfer USDC in integer micro-units: 1 USDC = 1_000_000 usd. */ transferUsdToOrFromSubAccount( params: TransferUsdToOrFromSubAccountRequest, options: L1RequestOptions = {}, @@ -6259,7 +6680,7 @@ File: package.json ================ { "name": "@siebly/hyperliquid-api", - "version": "1.0.5", + "version": "1.1.0", "description": "Professional JavaScript & Node.js SDK for Hyperliquid's REST APIs and WebSockets, built in TypeScript with strong end to end tests.", "scripts": { "clean": "node scripts/clean.mjs", @@ -6387,7 +6808,9 @@ File: README.md [1]: https://www.npmjs.com/package/@siebly/hyperliquid-api -Professional Node.js, JavaScript & TypeScript SDK for the HyperLiquid REST APIs, WebSocket APIs & WebSocket Events: +Professional Node.js, JavaScript & TypeScript SDK for the Hyperliquid REST APIs, WebSocket APIs & WebSocket Events. + +Take a look at our dedicated [HyperLiquid API quickstart guides for major frameworks and JavaScript runtimes](#frameworks--quickstart-guides). - Complete integration with all HyperLiquid REST APIs & WebSockets, including the WebSocket API. - Actively maintained with a modern, promise-driven interface. @@ -6420,6 +6843,7 @@ Professional Node.js, JavaScript & TypeScript SDK for the HyperLiquid REST APIs, ## Overview - [Installation](#installation) + - [Frameworks & Quickstart Guides](#frameworks--quickstart-guides) - [Documentation](#documentation) - [Issues & Discussion](#issues--discussion) - [Related Projects](#related-projects) @@ -6427,8 +6851,10 @@ Professional Node.js, JavaScript & TypeScript SDK for the HyperLiquid REST APIs, ## REST API Examples - [REST API](#rest-api) +- [Edge runtimes / native fetch (optional)](#edge-runtimes--native-fetch-optional) - [Assets](#assets) -- [Custom Signer](#custom-signer) +- [Use a viem account, browser wallet or Privy/embedded wallet signer](#use-a-viem-account-browser-wallet-or-privyembedded-wallet-signer) +- [Nonces](#nonces) ## WebSocket Integration & Examples @@ -6459,8 +6885,26 @@ npm install @siebly/hyperliquid-api Node.js 22 or newer is supported. +### Frameworks & Quickstart Guides + +Our complete Hyperliquid SDK supports all the major JavaScript runtimes. For maximum convenience, we've included guides to quickly get you started with the most popular runtimes. If you're not sure how to use this SDK with a runtime or framework not listed here, feel free to [open an issue on GitHub](https://github.com/sieblyio/hyperliquid-api/issues). + +| Runtime | Details | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Backend (trading bots) | Using [Node.js and JavaScript](https://sieblyio.github.io/docs/hyperliquid/environments/node.html), [Node.js and TypeScript](https://sieblyio.github.io/docs/hyperliquid/environments/typescript.html), [Bun](https://sieblyio.github.io/docs/hyperliquid/environments/bun.html), or [Deno](https://sieblyio.github.io/docs/hyperliquid/environments/deno.html). This is the recommendation for algorithmic trading systems. | +| Frontend / Web Development | Using [React with Vite](https://sieblyio.github.io/docs/hyperliquid/environments/react.html) or [Vite with plain JavaScript](https://sieblyio.github.io/docs/hyperliquid/environments/vite.html). Display REST and WebSocket prices in the browser. | +| Next.js App Router | Using the [Next.js App Router](https://sieblyio.github.io/docs/hyperliquid/environments/next.html) to serve the price from a Route Handler running on Node.js. | +| Mobile (iOS & Android) | Using [React Native with Expo for iOS and Android](https://sieblyio.github.io/docs/hyperliquid/environments/expo.html). The example guides you to display the current price of an asset via HyperLiquid and stream updates over WebSockets. | +| Cloudflare Workers | [Cloudflare Workers](https://sieblyio.github.io/docs/hyperliquid/environments/cloudflare-workers.html). Return a public price from a Worker, with a separate example for authenticated orders. | + +Refer to [runtime compatibility](https://sieblyio.github.io/docs/hyperliquid/compatibility.html) for a complete list of runtimes that we've actively tested, including setup guides. + ## Documentation +The [Hyperliquid SDK documentation](https://sieblyio.github.io/docs/hyperliquid/) page covers complete guidance on installation, client setup, public APIs (e.g. market data), private APIs (e.g. trading, order management), and WebSockets (subscriptions, WebSocket API, authentication, etc). + +**Hyperliquid exchange API reference** + - [Hyperliquid API documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) - [Info endpoint](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint) - [Exchange endpoint](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint) @@ -6485,8 +6929,9 @@ Exchange methods share one response wrapper: `ExchangeResponse` for acknowledgem Check out our JavaScript/TypeScript/Node.js SDKs & Projects: -- Visit our website: [https://Siebly.io](https://siebly.io/) -- Try our REST API & WebSocket SDKs published on npmjs: +- Visit our website: [Siebly JavaScript SDKs for Crypto Exchange APIs](https://siebly.io/) +- Visit our rich technical documentation: [Documentation for Siebly JavaScript SDKs](https://sieblyio.github.io/docs) +- Try our REST API & WebSocket SDKs published on npmjs & open-sourced on GitHub: - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - [Hyperliquid JavaScript SDK: @siebly/hyperliquid-api](https://www.npmjs.com/package/@siebly/hyperliquid-api) - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) @@ -6502,7 +6947,8 @@ Check out our JavaScript/TypeScript/Node.js SDKs & Projects: - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) - + + ## REST API @@ -6600,7 +7046,7 @@ const postOnlyOrder = await client.submitLimitOrder({ `submitMarketOrder()` uses Hyperliquid's immediate-or-cancel market order mechanism. It loads the current midpoint, applies the requested maximum slippage, rounds the protection price to Hyperliquid's rules, rounds size down to the asset's supported precision, and submits an IOC order that cannot rest on the book. `maxSlippage` defaults to `0.05`, meaning 5%. Spot size is always the base asset quantity. -Both convenience methods support `clientOrderId` and `reduceOnly`. `submitMarketClose()` looks up the perpetual position, infers buy/sell from the signed size, and submits a reduce-only IOC order. Omit `size` to close the full position. `submitLimitOrder()` defaults to `timeInForce: 'GTC'`; use `'IOC'` for immediate-or-cancel or `postOnly: true` for add-liquidity-only behavior. Use `submitOrder()` when submitting batches, TP/SL orders, or other native wire shapes. +Both convenience methods support `clientOrderId` and `reduceOnly`. `submitMarketClose()` looks up the perpetual position, infers buy/sell from the signed size, and submits a reduce-only IOC order. Omit `size` to close the full position. `submitLimitOrder()` accepts `'GTC'`/`'Gtc'` (the default) and `'IOC'`/`'Ioc'` for immediate-or-cancel or `postOnly: true` for add-liquidity-only behavior. Use `submitOrder()` when submitting batches, TP/SL orders, or other native wire shapes. Prices, sizes, amounts, and trigger prices are exact decimal strings. JavaScript numbers are not accepted for decimal fields. @@ -6636,6 +7082,54 @@ Set `vaultAddress` on the client or per request when signing for a vault or suba Account getters such as `getBalances()`, `getSpotBalances()`, `getPerpAccountSummary()`, and `getPortfolio()` can omit `user` on an authenticated client. The SDK uses `vaultAddress` or `accountAddress` when configured. Otherwise it resolves an API wallet to its master account with one `userRole` request and caches the result for that client instance. Call `getAccountAddress()` to inspect the resolved address. Public clients without an account or signer must pass `user`. +## Edge runtimes / native fetch (optional) + +Axios remains the default REST transport. Opt in to the runtime's native fetch +on a client, without adding dependencies: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; + +const client = new RestClient({ customFetch: fetch }); +const metadata = await client.getPerpMetadata(); +``` + +For a Cloudflare Workers service binding or an egress fetcher: + +```ts +const client = new RestClient({ + customFetch: (url, init) => env.MY_FETCHER.fetch(url, init), +}); +``` + +Wrappers can add runtime-specific options such as `cache: 'no-store'` or their +own abort signal. The SDK calls the fetch function detached, passes the same +request URL and JSON body, and parses JSON or plain-text responses through its +existing response/error handling. HTTP errors remain `HyperliquidApiError`; +errors thrown by your fetcher (including network and abort errors) pass through +unchanged. + +Axios-only settings in the second constructor argument, including adapters, +agents, interceptors, headers, and transforms, are not applied in this mode. +The exception is `timeout` (including the SDK default), which becomes +`AbortSignal.timeout(timeout)` when supported; `timeout: 0` disables it. +Binary and multipart bodies are rejected locally; use the default axios +transport for those requests. Axios remains installed, so this option does not +remove it from the package or guarantee a smaller bundle. + +`CustomFetch`, `CustomFetchRequestInit`, and `CustomFetchResponse` are exported +structural types, requiring no DOM library. WebSocket metadata reads receive +the transport through the existing REST `requestOptions` object: + +```ts +import { WebsocketClient } from '@siebly/hyperliquid-api'; + +const ws = new WebsocketClient({ requestOptions: { customFetch: fetch } }); +``` + +`WebsocketAPIClient({ customFetch: fetch })` forwards it to its internal REST +metadata client; its WebSocket requests continue to use WebSockets. + ## Assets Trading actions accept official identifiers, numeric asset IDs, and aliases derived from live metadata: @@ -6665,27 +7159,67 @@ Spot, HIP-3, and outcome asset IDs follow Hyperliquid's current offset rules. Th Balance responses keep Hyperliquid's token names. For example, SOL shown in the portfolio UI is currently returned as `USOL` by the API. -## Custom Signer +## Use a viem account, browser wallet or Privy/embedded wallet signer -You can provide an external signer instead of a private key: +Pass a viem local account or wallet client directly as `signer`; no adapter is needed. +Install viem in your application yourself. The SDK has no viem dependency. +Avoid viem **2.57.12–2.57.16**, which reject Hyperliquid's `HyperliquidTransaction:*` +EIP-712 type names; use 2.57.11 or 2.57.17 and later. + +For a server-side local account: ```ts -const client = new RestClient({ - signer: { - address: walletAddress, - signTypedData: (domain, types, value) => - walletClient.signTypedData({ - account: walletAddress, - domain, - types, - primaryType: Object.keys(types)[0], - message: value, - }), - }, +import { RestClient } from '@siebly/hyperliquid-api'; +import { privateKeyToAccount } from 'viem/accounts'; + +const key = process.env.HYPERLIQUID_PRIVATE_KEY; +if (!key) throw new Error('Set HYPERLIQUID_PRIVATE_KEY.'); +const account = privateKeyToAccount(key as `0x${string}`); +const client = new RestClient({ signer: account }); +``` + +For a browser wallet, create the wallet client with an account: + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +// window.ethereum is supplied by the user's browser wallet. +const provider = window.ethereum; +if (!provider) throw new Error('Connect a browser wallet first.'); +const [address] = await provider.request({ method: 'eth_requestAccounts' }); +const walletClient = createWalletClient({ + account: address, + chain: arbitrum, + transport: custom(provider), +}); +const client = new RestClient({ signer: walletClient }); +``` + +For a Privy-style embedded wallet (using the wallet returned by your provider): + +```ts +import { RestClient } from '@siebly/hyperliquid-api'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; + +const provider = await embeddedWallet.getEthereumProvider(); +const walletClient = createWalletClient({ + account: embeddedWallet.address as `0x${string}`, + chain: arbitrum, + transport: custom(provider), }); +const client = new RestClient({ signer: walletClient }); ``` -The signer must expose `signTypedData`. It may also expose `address` or `getAddress()`. +Wallet clients without an account fail at construction with a clear error. +Ethers wallets and custom signers using `signTypedData(domain, types, value)` +with `address` or `getAddress()` continue to work, as does `privateKey`. +The SDK selects the primary EIP-712 type for every action and normalizes viem inputs +once. The same inputs work in multisig `signers` arrays and `WebsocketAPIClient`. +Use `accountAddress` with an API wallet to identify the master account; transfers, +withdrawals, and other user-signed actions still require the account owner's signer. For an API wallet, pass the master account address to avoid an extra `userRole` lookup: @@ -6704,7 +7238,40 @@ const client = new RestClient({ If `accountAddress` is omitted, the first account getter or builder preflight resolves the API wallet's master address from `userRole`. Concurrent requests share the same lookup. -The nonce manager is shared by signer address across client instances. Supply `nonceProvider` when a process needs a different source of monotonic nonces. +## Nonces + +The default manager shares monotonic nonces by signer address across clients in the +same module instance. Each worker thread and process has its own manager. Workers +sharing a signer must coordinate through `nonceProvider`, or use a separate API +wallet per worker. See the [exchange nonce rules](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets). + +The SDK awaits `nonceProvider.nextNonce(lowerCaseSignerAddress)`. Return a non-negative +safe integer; otherwise it throws `RangeError` before sending. Your allocator must +allocate atomically across callers and keep nonces within the exchange's time window. +For example, delegate allocation to your own HTTP service: + +```ts +const client = new RestClient({ + signer: account, + nonceProvider: { + async nextNonce(signerAddress) { + const response = await fetch(process.env.NONCE_SERVICE_URL!, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ signerAddress }), + }); + if (!response.ok) throw new Error('Nonce allocation failed'); + const { nonce } = await response.json(); + return nonce; + }, + }, +}); +``` + +`L1ActionOptions.nonce` and `UserSignedActionOptions.nonce` override the provider for +one call; you must coordinate those values too. `invalidateNonce()` sends a signed +no-op to consume a nonce; it does not reset local allocation. A SharedArrayBuffer +manager is not included. ## WebSockets @@ -6719,6 +7286,35 @@ Connections open when first needed. Heartbeats, reconnection, resubscription, re ```ts import { WebsocketClient } from '@siebly/hyperliquid-api'; +const ws = new WebsocketClient(); +const prices: Record = {}; + +// A reconnect supplies a fresh snapshot; discard stale coins from the old cache. +ws.on('reconnected', () => { + for (const coin of Object.keys(prices)) delete prices[coin]; +}); +ws.on('message', (event) => { + if (event.channel !== 'fastAssetCtxs') return; + for (const [coin, ctx] of Object.entries(event.data)) { + prices[coin] = { ...prices[coin], ...ctx }; + } + console.log('BTC mark', prices.BTC?.markPx, 'mid', prices.BTC?.midPx); +}); +ws.on('exception', (error) => console.error(error)); +await ws.subscribe({ type: 'fastAssetCtxs' }); +``` + +The SDK decompresses `fastAssetCtxs` into `event.data`: the first message is a +snapshot, subsequent messages contain only changed coins and fields. Merge fields +per coin; `midPx: null` means no book mid. Reconnection supplies a fresh snapshot. +Hyperliquid recommends this feed instead of its deprecated upstream `allMids` +WebSocket feed; REST `getAllMids()` remains supported. + +For order books and account fills: + +```ts +import { WebsocketClient } from '@siebly/hyperliquid-api'; + const ws = new WebsocketClient(); ws.on('reconnected', ({ wsKey }) => { @@ -6760,7 +7356,11 @@ await ws.unsubscribe([book, fills]); ws.closeAll(); ``` -`subscribe()` and `unsubscribe()` manage topics independently of listeners and accept one topic or an array. The subscribe promise resolves after the socket opens and the request is sent; server acknowledgements emit through `response`. Incoming data emits once per wire message through `message`, preserving the upstream envelope and adding `wsKey`. +`subscribe()` and `unsubscribe()` manage topics independently of listeners and accept one topic or an array. Identical topics are merged; one unsubscribe removes the topic for all callers. `getActiveTopics(wsKey?)` returns a copy of cached topics (all connections when omitted). Reference counting is not provided. A rejected first subscribe leaves its topics cached for automatic retries. + +`l2Book` messages do not identify `nSigFigs` or `mantissa`; use separate clients for different groupings of one coin. `fast: true` sends 5 levels per side, compared with the default 20. Subscribe with `type: 'activeAssetCtx'` for both perps and spot, but listen for `channel: 'activeSpotAssetCtx'` for spot. There is no `activeSpotAssetCtx` subscription type. + +The subscribe promise resolves after the socket opens and the request is sent; server acknowledgements emit through `response`. Incoming data emits once per wire message through `message`, preserving the upstream envelope and adding `wsKey`. `fastAssetCtxs` payloads are decompressed inside the event's `data` field. User streams whose server events omit the user address use separate connections with a `user:
` key. Other streams share `public`. @@ -6878,7 +7478,7 @@ The npm package includes ES module and CommonJS builds. You do not need to build Use the [Vite guide](https://sieblyio.github.io/docs/hyperliquid/environments/vite.html) or [React guide](https://sieblyio.github.io/docs/hyperliquid/environments/react.html) for a complete public market-data project that imports `@siebly/hyperliquid-api` from npm. -The Vite example uses the package's browser entry points without extra bundler aliases or polyfills. These browser examples use public Hyperliquid REST data and WebSocket subscriptions. Keep private keys and API credentials in a secure server-side environment and make authenticated calls there. +The Vite example uses the package's browser entry points without extra bundler aliases or polyfills. These browser examples use public Hyperliquid REST data and WebSocket subscriptions. Keep raw private keys and API credentials server-side. Browser applications can sign through the connected wallet client shown above. Browser REST requests also depend on Hyperliquid's CORS policy. If a request is blocked, call the SDK through your application's server route instead. A development proxy does not solve CORS for a deployed application. @@ -6940,6 +7540,15 @@ Have my projects helped you? Share the love, there are many ways you can show yo - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 - Kucoin (receive a 10% fee discount!): https://www.kucoin.com/r/broker/SIEBLYSDK + ### Contributions & Pull Requests @@ -6951,7 +7560,6 @@ Contributions are encouraged, I will review any incoming pull requests. See the ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) -