Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 176 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ 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)
- [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

Expand Down Expand Up @@ -255,7 +257,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.

Expand Down Expand Up @@ -291,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:
Expand Down Expand Up @@ -320,27 +370,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:

Expand All @@ -359,7 +449,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

Expand All @@ -374,6 +497,35 @@ Connections open when first needed. Heartbeats, reconnection, resubscription, re
```ts
import { WebsocketClient } from '@siebly/hyperliquid-api';

const ws = new WebsocketClient();
const prices: Record<string, { markPx?: string; midPx?: string | null }> = {};

// 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 }) => {
Expand Down Expand Up @@ -415,7 +567,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:<address>` key. Other streams share `public`.

Expand Down Expand Up @@ -533,7 +689,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.

Expand Down
Loading
Loading