With the Hyperliquid vault API and sub-accounts, the signing wallet, the master account and the vault or sub-account that owns an order each have a different address. Sending the correct signer with the wrong account address can return empty balances or target the wrong account.
With @siebly/hyperliquid-api, use the account address for reads and set vaultAddress on signed actions for a vault or sub-account.
Three addresses: master, API wallet, and sub-account or vault
Most confusion comes from mixing up three different addresses.
| Address | Has a private key? | What it does | SDK option |
|---|---|---|---|
| Master account | Yes | Owns funds, sub-accounts and the vaults it leads | accountAddress |
| API wallet (agent wallet) | Yes | Signs on behalf of the master and its sub-accounts. Holds nothing | privateKey |
| Sub-account or vault | No | A separate account with its own balances and positions | vaultAddress |
Hyperliquid’s exchange endpoint docs put it in one line: “Subaccounts and vaults do not have private keys. To perform actions on behalf of a subaccount or vault signing should be done by the master account and the vaultAddress field should be set to the address of the subaccount or vault.” The nonces and API wallets page adds that “a master account can approve API wallets to sign on behalf of the master account or any of the sub-accounts”. So the signer is always the master key or an API wallet the master approved. If you are not sure which key that is, or why an approved key stopped working, see Hyperliquid API wallet expiry, pruning and rotation.
In the SDK, these map to three RestClient options:
privateKey: the key that signs. Master key or API wallet key.accountAddress: the master account. Needed wheneverprivateKeyis an API wallet, because the API wallet itself holds nothing.vaultAddress: the sub-account or vault to act as. Orders and cancels from that client are placed for that account, and account reads default to it.
For account reads, the SDK picks the address in this order, as its authentication guide says and the source confirms: the user you pass to the method, then vaultAddress, then accountAddress, then the signer’s own account.
Hyperliquid calls HyperCore vaults “legacy” to distinguish them from HyperEVM vault contracts. The vaultDetails, vaultTransfer and vaultAddress examples use HyperCore vaults.
Before you start
- Node.js 24, which runs the
.tsfiles below directly withnode file.ts. @siebly/hyperliquid-api1.0.5, plusethersfor one example that needs a throwaway key.- No key for the read examples. The signed examples read
HYPERLIQUID_PRIVATE_KEYandHYPERLIQUID_ACCOUNT_ADDRESSfrom the environment and point at testnet.
npm init -y
npm pkg set type=module
npm install @siebly/hyperliquid-api ethers
New to the SDK? Getting started with the Hyperliquid JavaScript SDK covers API wallets, REST calls and a first order.
Read a vault with the Hyperliquid vault API: getVaultDetails
getVaultDetails() wraps the vaultDetails info request and needs no key. The example reads HLP, the protocol vault, because its address is public and appears in Hyperliquid’s own docs:
import { RestClient, type VaultDetails } from '@siebly/hyperliquid-api';
const client = new RestClient(); // public reads need no key
export async function readVault(vaultAddress: string): Promise<VaultDetails> {
const vault = await client.getVaultDetails({ vaultAddress });
// Not a vault (or a typo): Hyperliquid answers null, not an error.
if (vault === null) throw new Error(`${vaultAddress} is not a vault on this network`);
return vault;
}
const HLP = '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303';
const vault = await readVault(HLP);
console.log({
name: vault.name,
leader: vault.leader,
relationship: vault.relationship.type,
childVaults: vault.relationship.type === 'parent' ? vault.relationship.data.childAddresses.length : 0,
allowDeposits: vault.allowDeposits,
isClosed: vault.isClosed,
followerRows: vault.followers.length,
});
// One follower row is the leader's own share, with the literal user "Leader".
const depositors = vault.followers.filter((f) => f.user.startsWith('0x'));
console.log('rows that are not addresses:', vault.followers.filter((f) => !f.user.startsWith('0x')).map((f) => f.user));
console.log('depositor rows:', depositors.length);
try {
await readVault('0x0000000000000000000000000000000000000001');
} catch (error) {
console.log((error as Error).message);
}
{
name: 'Hyperliquidity Provider (HLP)',
leader: '0x677d831aef5328190852e24f13c46cac05f984e7',
relationship: 'parent',
childVaults: 7,
allowDeposits: true,
isClosed: false,
followerRows: 100
}
rows that are not addresses: [ 'Leader' ]
depositor rows: 99
0x0000000000000000000000000000000000000001 is not a vault on this network
- A wrong address returns
null, not an error. The SDK types the result asVaultDetails | null, so TypeScript makes you handle it. Sub-account addresses also returnnullhere, since a sub-account is not a vault. relationshiptells you how vaults nest. HLP isparentwith sevenchildAddresses. Reading one of those children returnsrelationship: { type: 'child' }with HLP as itsleader. A standalone vault isnormal. Adding up the children is covered in Parent and child vaults.- One follower row is not an address. Its
useris the literal stringLeader. Pass it to another info call and you get an HTTP 422 (shown below), so filter onstartsWith('0x')first. followersis not a full depositor list. It holds at most 100 rows, and HLP returns exactly 100. To check one address, pass it asuser:getVaultDetails({ vaultAddress, user })fillsfollowerStatefor a depositor and returnsfollowerState: nullfor an address with no deposit.
The response also includes description, portfolio (history per window, covered below), apr, leaderFraction, leaderCommission, maxDistributable, maxWithdrawable and alwaysCloseOnWithdraw. Every field name above matches the SDK’s VaultDetails type.
Can I list every vault from the Hyperliquid API?
getVaultSummaries() can return an empty array, so it cannot serve as a complete directory. Start with known vault addresses, the vaults an account leads or its deposit records.
Chart a vault’s history with portfolio and pnlHistory
History is the part of the Hyperliquid vault API in Node.js that trips people up, because portfolio is not an object keyed by window name. It is an array of pairs: [window, { accountValueHistory, pnlHistory, vlm }]. The SDK types the window as PortfolioPeriod. Object.fromEntries(vault.portfolio) turns the pairs into an object you can index, and every history point is [timestampMs, "decimal string"]: a number, then a string.
Join the two histories by timestamp for each HLP window. The example output uses UTC.
import { RestClient, type PortfolioPeriod, type PortfolioSnapshot, type VaultDetails } from '@siebly/hyperliquid-api';
export interface SeriesPoint {
time: number; // milliseconds since the epoch
pnl: number; // pnlHistory: the one to chart
accountValue: number; // accountValueHistory: also moves with deposits and withdrawals
}
/** Pick one window from the [window, snapshot] pairs. */
export function snapshotFor(vault: VaultDetails, window: PortfolioPeriod): PortfolioSnapshot {
const snapshot = Object.fromEntries(vault.portfolio)[window];
if (!snapshot) throw new Error(`${vault.name} has no "${window}" window`);
return snapshot;
}
/** Join the two histories on their timestamps and turn the decimal strings into numbers for a chart. */
export function chartSeries(snapshot: PortfolioSnapshot): SeriesPoint[] {
const accountValues = new Map(snapshot.accountValueHistory);
return snapshot.pnlHistory.map(([time, pnl]) => {
const accountValue = accountValues.get(time);
if (accountValue === undefined) throw new Error(`No account value at ${time}`);
return { time, pnl: Number(pnl), accountValue: Number(accountValue) };
});
}
/** The step where account value moved furthest from what PnL explains. */
export function biggestNonPnlMove(series: SeriesPoint[]) {
let best = { from: series[0], to: series[0], accountValueChange: 0, pnlChange: 0 };
for (let i = 1; i < series.length; i++) {
const accountValueChange = series[i].accountValue - series[i - 1].accountValue;
const pnlChange = series[i].pnl - series[i - 1].pnl;
if (Math.abs(accountValueChange - pnlChange) > Math.abs(best.accountValueChange - best.pnlChange)) {
best = { from: series[i - 1], to: series[i], accountValueChange, pnlChange };
}
}
return best;
}
const stamp = (ms: number) => new Date(ms).toISOString().slice(0, 16) + 'Z';
if (import.meta.main) {
const client = new RestClient();
const vault = await client.getVaultDetails({ vaultAddress: '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303' });
if (vault === null) throw new Error('HLP not found');
for (const [window, snapshot] of vault.portfolio) {
const t = snapshot.pnlHistory.map(([time]) => time);
console.log(
window.padEnd(12),
`${String(t.length).padStart(3)} points`,
`${stamp(t[0])} to ${stamp(t[t.length - 1])}`,
`first pnl ${snapshot.pnlHistory[0][1]}`,
`latest value ${snapshot.accountValueHistory[snapshot.accountValueHistory.length - 1][1]}`,
`vlm ${JSON.stringify(snapshot.vlm)}`,
);
}
const allTime = chartSeries(snapshotFor(vault, 'allTime'));
const gaps = allTime.slice(1).map((p, i) => (p.time - allTime[i].time) / 3_600_000);
console.log(`allTime gaps: shortest ${Math.min(...gaps).toFixed(1)} h, longest ${Math.max(...gaps).toFixed(1)} h`);
console.log('last two allTime points:', JSON.stringify(allTime.slice(-2)));
const day = chartSeries(snapshotFor(vault, 'day'));
const move = biggestNonPnlMove(day);
console.log(
`day window, ${stamp(move.from.time)} to ${stamp(move.to.time)}:`,
`account value ${move.accountValueChange.toFixed(0)}, pnl ${move.pnlChange.toFixed(0)}`,
);
}
day 57 points 2026-11-28T11:06Z to 2026-11-29T11:16Z first pnl 0.0 latest value 152643473.4329650104 vlm "0.0"
week 71 points 2026-11-22T08:46Z to 2026-11-29T11:16Z first pnl 0.0 latest value 152643473.4329650104 vlm "0.0"
month 48 points 2026-10-29T23:49Z to 2026-11-29T11:16Z first pnl 0.0 latest value 152643473.4329650104 vlm "0.0"
allTime 104 points 2023-05-10T22:45Z to 2026-11-29T11:16Z first pnl 0.0 latest value 152643473.4329650104 vlm "0.0"
perpDay 57 points 2026-11-28T11:06Z to 2026-11-29T11:16Z first pnl 0.0 latest value 12494011.0704340003 vlm "0.0"
perpWeek 71 points 2026-11-22T08:46Z to 2026-11-29T11:16Z first pnl 0.0 latest value 12494011.0704340003 vlm "0.0"
perpMonth 49 points 2026-10-29T23:49Z to 2026-11-29T11:16Z first pnl 0.0 latest value 12494011.0704340003 vlm "0.0"
perpAllTime 84 points 2024-05-01T23:59Z to 2026-11-29T11:16Z first pnl 0.0 latest value 12494011.0704340003 vlm "0.0"
allTime gaps: shortest 1.0 h, longest 337.6 h
last two allTime points: [{"time":1795478013052,"pnl":141110369.372959,"accountValue":150137775.662959},{"time":1795950980572,"pnl":141203051.822965,"accountValue":152643473.432965}]
day window, 2026-11-29T08:40Z to 2026-11-29T09:12Z: account value 500772, pnl 222
- Eight windows.
day,week,month,allTime, and the same four with aperpprefix. Theperpwindows end on a different value from their counterparts (12.5 million against 152.6 million for HLP in the example output), so they appear to cover the perpetuals part of the account only. Hyperliquid’s info endpoint docs list the names without defining them, so confirm what a window covers before you build on it. - Each window starts its own PnL at zero. The first
pnlHistoryvalue is"0.0"in all eight windows, sodayPnL andallTimePnL are separate series, not slices of one. - The series is sampled, not dense. In the example output
dayhas 57 points over about 24 hours andallTimehas 104 over three and a half years, with gaps from 1.0 to 337.6 hours. Plot against the timestamp, never the array index, and do not assume even spacing. If you need a fixed grid, resample it yourself. - Both histories share timestamps. That is why
chartSeries()can join them ontime, and it throws if one is missing. vlmis a string as well, and it is"0.0"in every window for HLP, so the example leaves it alone.
Chart pnlHistory, not accountValueHistory
The last line of the output shows why. Across one 32-minute step in the day window, account value rises by 500,772 while PnL rises by 222. A step that size is money going into the vault rather than trading, and accountValueHistory counts it. pnlHistory does not. A line chart of account value therefore shows every deposit and withdrawal as a jump. Chart pnlHistory for trading results, and use accountValueHistory for how large the vault is.
chartSeries() converts the strings with Number(), which is fine for drawing a line. For a sum you will show as money, keep the strings and add them as exact decimals, as the next section does.
Parent and child vaults: read the whole family
In the Hyperliquid vault API, vaults can be nested, and relationship is a union with three shapes: { type: 'parent', data: { childAddresses: string[] } }, { type: 'child' } and { type: 'normal' }. Only a parent carries data, so TypeScript makes you check type === 'parent' before it lets you read childAddresses. The values are decimal strings, and HLP’s carry ten decimals (152643473.4329650104 in the output above), so the first file is a small exact-decimal helper:
const SCALE = 18;
/** Parse a decimal string such as "152643332.5679309964" into an integer count of 1e-18 units. */
export function toUnits(value: string): bigint {
const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(value);
if (!match) throw new RangeError(`Not a decimal string: "${value}"`);
const [, sign, whole, fraction = ''] = match;
if (fraction.length > SCALE) throw new RangeError(`More than ${SCALE} decimals: "${value}"`);
const units = BigInt(whole + fraction.padEnd(SCALE, '0'));
return sign ? -units : units;
}
/** Format units back to a string with `places` decimals, rounding half away from zero. */
export function fromUnits(units: bigint, places = 2): string {
const negative = units < 0n;
const step = 10n ** BigInt(SCALE - places);
const rounded = ((negative ? -units : units) + step / 2n) / step;
const digits = rounded.toString().padStart(places + 1, '0');
const text = places === 0 ? digits : `${digits.slice(0, -places)}.${digits.slice(-places)}`;
return negative && rounded !== 0n ? `-${text}` : text;
}
export function sumDecimals(values: string[]): string {
return fromUnits(values.reduce((total, value) => total + toUnits(value), 0n));
}
The second reads a parent, reads each child, and adds up the children’s latest account values:
import { RestClient, type PortfolioPeriod, type VaultDetails } from '@siebly/hyperliquid-api';
import { fromUnits, toUnits } from './decimal.ts';
const client = new RestClient();
export interface VaultFamily {
parent: { address: string; name: string; accountValue: string; perpAccountValue: string };
children: Array<{ address: string; name: string; accountValue: string; asOf: number }>;
childrenTotal: string; // two decimals, summed from exact decimal strings
}
/** Latest account value from one window: the last point is the newest sample. */
function latestAccountValue(vault: VaultDetails, window: PortfolioPeriod = 'day'): { value: string; time: number } {
const snapshot = Object.fromEntries(vault.portfolio)[window];
const last = snapshot?.accountValueHistory.at(-1);
if (!last) throw new Error(`${vault.name} has no ${window} account value history`);
return { time: last[0], value: last[1] };
}
async function mustRead(vaultAddress: string): Promise<VaultDetails> {
const vault = await client.getVaultDetails({ vaultAddress });
if (vault === null) throw new Error(`${vaultAddress} is not a vault on this network`);
return vault;
}
export async function readFamily(parentAddress: string): Promise<VaultFamily> {
const parent = await mustRead(parentAddress);
// Only a parent has data. A child or normal vault has just { type }.
const childAddresses = parent.relationship.type === 'parent' ? parent.relationship.data.childAddresses : [];
const children = await Promise.all(
childAddresses.map(async (address) => {
const child = await mustRead(address);
const latest = latestAccountValue(child);
return { address, name: child.name, accountValue: latest.value, asOf: latest.time };
}),
);
const total = children.reduce((sum, child) => sum + toUnits(child.accountValue), 0n);
return {
parent: {
address: parentAddress,
name: parent.name,
accountValue: latestAccountValue(parent).value,
perpAccountValue: latestAccountValue(parent, 'perpDay').value,
},
children,
childrenTotal: fromUnits(total),
};
}
if (import.meta.main) {
const HLP = '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303';
const family = await readFamily(HLP);
console.log(`${family.parent.name}: ${family.children.length} child vaults`);
for (const child of family.children) {
console.log(` ${child.address.slice(0, 6)}...${child.address.slice(-4)} ${child.name.padEnd(16)} ${fromUnits(toUnits(child.accountValue)).padStart(15)}`);
}
console.log('sum of the child account values:', family.childrenTotal);
console.log('parent account value:', fromUnits(toUnits(family.parent.accountValue)));
console.log('parent minus children:', fromUnits(toUnits(family.parent.accountValue) - toUnits(family.childrenTotal)));
console.log('parent perpDay value:', fromUnits(toUnits(family.parent.perpAccountValue)));
// Going the other way: a child's relationship carries no address, but its leader is the parent.
const first = await client.getVaultDetails({ vaultAddress: family.children[0].address });
console.log('child relationship:', JSON.stringify(first?.relationship), 'leader is the parent:', first?.leader === HLP);
}
Hyperliquidity Provider (HLP): 7 child vaults
0x0104...703a HLP Strategy A 3156949.79
0x2e3d...dd14 HLP Liquidator 999998.57
0x2ed5...8308 HLP Liquidator 4 1000000.00
0x31ca...974b HLP Strategy B 3029812.38
0x469f...d7d8 HLP Strategy X 100962665.94
0x5e17...cb70 HLP Liquidator 3 1000006.25
0xb0a5...9540 HLP Liquidator 2 30000000.00
sum of the child account values: 140149432.94
parent account value: 152643446.35
parent minus children: 12494013.41
parent perpDay value: 12494013.50
child relationship: {"type":"child"} leader is the parent: true
- One call per child. HLP has seven, so the family costs eight
getVaultDetails()requests. Count that against the budget in the rate limits post before looping over many parents. - The total is close to now, not one instant. Each child’s newest point has its own timestamp, which
readFamily()keeps asasOf. - Account values for a parent vault can already include its children. Summing the parent and child values can double-count equity. Hyperliquid does not document the aggregation rule.
- Going back up. A child’s
relationshipis just{ type: 'child' }with no address. For all seven HLP children theleaderis the parent’s address, sochild.leaderis the way back to the parent for these vaults. - Other vaults. A
normalvault gives an emptychildrenlist and a total of0.00, and an address that is not a vault throws.
Find an account’s sub-accounts, vaults and vault deposits
Four info requests answer “what is this address, and what does it own?”:
import { RestClient } from '@siebly/hyperliquid-api';
const client = new RestClient();
export async function accountOverview(user: string) {
const [role, subAccounts, leading, deposits] = await Promise.all([
client.getUserRole({ user }),
client.getSubAccounts({ user }), // null when the address has none
client.getLeadingVaults({ user }),
client.getUserVaultDeposits({ user }),
]);
return {
role: role.role,
subAccounts: (subAccounts ?? []).map((s) => ({ name: s.name, address: s.subAccountUser })),
leads: leading.map((v) => v.name),
depositedIn: deposits.map((d) => d.vaultAddress),
};
}
const mask = (a: string) => `${a.slice(0, 6)}...${a.slice(-4)}`;
const HLP = '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303';
const hlp = await client.getVaultDetails({ vaultAddress: HLP });
const depositor = hlp!.followers.find((f) => f.user.startsWith('0x'))!.user;
for (const [label, user] of [
['HLP leader', hlp!.leader],
['HLP vault', HLP],
[`an HLP depositor (${mask(depositor)})`, depositor],
['an unused address', '0x' + '42'.repeat(20)],
]) {
console.log(label, JSON.stringify(await accountOverview(user)));
}
HLP leader {"role":"user","subAccounts":[],"leads":["Hyperliquidity Provider (HLP)"],"depositedIn":["0x63c621a33714ec48660e32f2374895c8026a3a00","0xdfc24b077bc1425ad1dea75bcb6f8158e10df303"]}
HLP vault {"role":"vault","subAccounts":[],"leads":["HLP Strategy A","HLP Liquidator","HLP Liquidator 4","HLP Strategy B","HLP Strategy X","HLP Liquidator 3","HLP Liquidator 2"],"depositedIn":["0x010461c14e146ac35fe42271bdc1134ee31c703a","0x2e3d94f0562703b25c83308a05046ddaf9a8dd14","0x2ed5c4484ea3ff8b57d5f2fb152a40d9f2b68308","0x31ca8395cf837de08b24da3f660e77761dfb974b","0x469f690213c467c39a23efacfd2816896009d7d8","0x5e177e5e39c0f4e421f5865a6d8beed8d921cb70","0xb0a55f13d22f66e6d495ac98113841b2326e9540"]}
an HLP depositor (0x029f...a945) {"role":"user","subAccounts":[],"leads":[],"depositedIn":["0xdfc24b077bc1425ad1dea75bcb6f8158e10df303"]}
an unused address {"role":"missing","subAccounts":[],"leads":[],"depositedIn":[]}
getUserRole()returnsuser,agent(an API wallet, with the account it signs for),vault,subAccount(with itsmaster) ormissing.getSubAccounts()takes the master address and can returnnullwhen there are no entries. Each entry includesname,subAccountUser,master,clearinghouseStateandspotState.getLeadingVaults()returns{ address, name }for each vault the address leads. The HLP vault itself leads its seven child vaults, which is how the parent and child structure shows up from this side.getUserVaultDeposits()(userVaultEquities) returnsvaultAddress,equityandlockedUntilTimestampfor each vault the address has deposited into. Below it is compared withfollowerState.
Mind the request weight if you run this over many addresses. Hyperliquid’s rate limits page gives userRole a weight of 60 and most other info requests 20, against 1,200 per minute per IP. At that weight, checking the roles of about a hundred vault followers one after another exceeds the budget and ends in Request failed with status code 429. Hyperliquid API rate limits in Node.js covers budgeting for this.
userVaultEquities and followerState: one deposit, two reads
A small helper over the Hyperliquid vault API shows how the two relate. getUserVaultDeposits({ user }) starts from the user and returns one row per vault they hold: vaultAddress, equity (a decimal string) and lockedUntilTimestamp (milliseconds). getVaultDetails({ vaultAddress, user }) starts from the vault and puts the same person’s row in followerState, in the same shape as an entry of followers: vaultEquity, pnl, allTimePnl, daysFollowing, vaultEntryTime and lockupUntil. This reads both for every vault a user holds. The first address is an HLP depositor, masked, and the second is the public HLP leader:
import { RestClient, type UserVaultDeposit } from '@siebly/hyperliquid-api';
const client = new RestClient();
// The live response also carries lockedUntilTimestamp (milliseconds).
type Deposit = UserVaultDeposit & { lockedUntilTimestamp: number };
export interface DepositView {
vault: string;
equity: string; // userVaultEquities
followerEquity: string | null; // followerState.vaultEquity, from vaultDetails with `user`
lockedUntil: number;
stillLocked: boolean;
}
/** Every vault `user` has deposited into, with the same deposit read both ways. */
export async function depositViews(user: string): Promise<DepositView[]> {
const deposits = (await client.getUserVaultDeposits({ user })) as Deposit[];
return Promise.all(
deposits.map(async (deposit) => {
const vault = await client.getVaultDetails({ vaultAddress: deposit.vaultAddress, user });
return {
vault: vault?.name ?? deposit.vaultAddress,
equity: deposit.equity,
followerEquity: vault?.followerState?.vaultEquity ?? null,
lockedUntil: deposit.lockedUntilTimestamp,
stillLocked: deposit.lockedUntilTimestamp > Date.now(),
};
}),
);
}
if (import.meta.main) {
const HLP = '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303';
const hlp = await client.getVaultDetails({ vaultAddress: HLP });
const depositor = hlp!.followers.find((f) => f.user.startsWith('0x'))!.user;
const mask = (a: string) => `${a.slice(0, 6)}...${a.slice(-4)}`;
for (const [label, user] of [
[`an HLP depositor (${mask(depositor)})`, depositor],
['the HLP leader', hlp!.leader],
]) {
console.log(label);
for (const view of await depositViews(user)) {
console.log(' ', JSON.stringify({ ...view, lockedUntil: new Date(view.lockedUntil).toISOString().slice(0, 10) }));
}
}
}
an HLP depositor (0x029f...a945)
{"vault":"Hyperliquidity Provider (HLP)","equity":"317289.152864","followerEquity":"317289.1530806918","lockedUntil":"2025-05-19","stillLocked":false}
the HLP leader
{"vault":"Liquidator","equity":"4712.624718","followerEquity":"4712.6247185607","lockedUntil":"2023-04-22","stillLocked":false}
{"vault":"Hyperliquidity Provider (HLP)","equity":"368328.702137","followerEquity":"368328.6960086199","lockedUntil":"2023-06-25","stillLocked":false}
- Same deposit, two requests.
equityandfollowerState.vaultEquityagree to well under a cent in the example output. They come from separate requests, and the first carries six decimals against ten for the second, so compare them with a tolerance, not===. - Deposits find the vaults, followerState adds the detail. The deposits call answers “which vaults?” for any address in one request.
followerStateadds PnL, days held and entry time, but for one vault per call. - The lockup is one value under two names.
lockedUntilTimestampequalsfollowerState.lockupUntil, which the script checks for the depositor. All three dates above are in the past, sostillLockedisfalse. Hyperliquid’s depositor docs give the lock-up as 4 days for HLP and 1 day for user vaults. - No deposit, no state. An address with no deposit gets
[]from the first call andfollowerState: nullfrom the second.
Turn an address into the right client options
For WebSocket subscriptions, pass the vault or sub-account address as user. See the Hyperliquid WebSocket post.
Since getUserRole() says what an address is, a bot can check its configuration at startup instead of failing on its first order. This helper takes the account you want to act as, your master address and the signing key, and returns RestClient options or a clear error:
import { RestClient, type RestClientOptions } from '@siebly/hyperliquid-api';
import { Wallet } from 'ethers';
const info = new RestClient();
/**
* Build RestClient options for acting on `target` (your master account, one of
* its sub-accounts, or a vault it leads), signed by `privateKey` (the master key
* or an API wallet approved by the master).
*/
export async function optionsFor(target: string, master: string, privateKey: string): Promise<RestClientOptions> {
const role = await info.getUserRole({ user: target });
switch (role.role) {
case 'user':
if (target.toLowerCase() !== master.toLowerCase()) throw new Error(`${target} is another user's account`);
return { privateKey, accountAddress: master };
case 'subAccount':
if (role.data.master.toLowerCase() !== master.toLowerCase()) throw new Error(`${target} belongs to ${role.data.master}`);
return { privateKey, accountAddress: master, vaultAddress: target };
case 'vault': {
const led = await info.getLeadingVaults({ user: master });
if (!led.some((v) => v.address.toLowerCase() === target.toLowerCase())) throw new Error(`${master} does not lead vault ${target}`);
return { privateKey, accountAddress: master, vaultAddress: target };
}
case 'agent':
throw new Error(`${target} is an API wallet for ${role.data.user}. Pass the account address, not the signer.`);
case 'missing':
throw new Error(`${target} is not a Hyperliquid account on this network`);
}
}
// Demo with public addresses. The key is a throwaway: nothing here signs.
const throwaway = Wallet.createRandom().privateKey;
const HLP = '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303';
const HLP_LEADER = '0x677d831aef5328190852e24f13c46cac05f984e7';
const opts = await optionsFor(HLP, HLP_LEADER, throwaway);
console.log('vault options:', { accountAddress: opts.accountAddress, vaultAddress: opts.vaultAddress });
const asVault = new RestClient(opts);
console.log('account reads now resolve to:', await asVault.getAccountAddress());
// A common mistake: passing the API wallet's own address as the account.
const [apiWallet] = await info.getExtraAgents({ user: HLP_LEADER });
for (const [target, master] of [
[apiWallet.address, HLP_LEADER],
[HLP, '0x' + '42'.repeat(20)],
['0x' + '42'.repeat(20), '0x' + '42'.repeat(20)],
]) {
try {
await optionsFor(target, master, throwaway);
} catch (error) {
console.log((error as Error).message);
}
}
vault options: {
accountAddress: '0x677d831aef5328190852e24f13c46cac05f984e7',
vaultAddress: '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303'
}
account reads now resolve to: 0xdfc24b077bc1425ad1dea75bcb6f8158e10df303
0xeeb5fb0d32a403733ebbf6e1c694f9253b37cf4c is an API wallet for 0x677d831aef5328190852e24f13c46cac05f984e7. Pass the account address, not the signer.
0x4242424242424242424242424242424242424242 does not lead vault 0xdfc24b077bc1425ad1dea75bcb6f8158e10df303
0x4242424242424242424242424242424242424242 is not a Hyperliquid account on this network
For a sub-account, set accountAddress to the master and vaultAddress to the sub-account. Using the signing wallet as the account address can return empty results.
Create and fund a sub-account through the API
Hyperliquid’s sub-accounts page sets the requirement: “Up to 10 sub-accounts can be created after reaching $100,000 in volume.” An account below that cannot create one through the API either.
USDC amounts are integers with 6 decimals
transferUsdToOrFromSubAccount(), transferVaultFunds(), distributeVaultFunds() and createVault() take usd or initialUsd as a number, and the SDK sends it unchanged. That number is USDC with 6 decimals: Hyperliquid’s own reference SDK example sends 5_000_000 for a 5 USD vault deposit and 1_000_000 for a 1 USD sub-account transfer. Pass 25 and you are asking for 0.000025 USDC. Multiplying a float by 1e6 is not safe either, so convert from a string:
/** "25" -> 25000000. Sub-account and vault transfers take USDC as an integer with 6 decimals. */
export function usdToMicros(amount: string): number {
if (!/^\d+(\.\d{1,6})?$/.test(amount)) {
throw new RangeError(`Expected a USDC amount with at most 6 decimals, got "${amount}"`);
}
const [whole, fraction = ''] = amount.split('.');
const micros = Number(whole) * 1_000_000 + Number(fraction.padEnd(6, '0'));
if (!Number.isSafeInteger(micros)) throw new RangeError(`Amount too large: "${amount}"`);
return micros;
}
import { strict as assert } from 'node:assert';
import { usdToMicros } from './usd.ts';
assert.equal(usdToMicros('25'), 25_000_000);
assert.equal(usdToMicros('5'), 5_000_000);
assert.equal(usdToMicros('100'), 100_000_000);
assert.equal(usdToMicros('0.1'), 100_000);
assert.equal(usdToMicros('1.234567'), 1_234_567);
assert.equal(usdToMicros('8.2'), 8_200_000);
for (const bad of ['1.2345678', '-1', '1e3', '', '12,5']) assert.throws(() => usdToMicros(bad), RangeError);
console.log('usdToMicros: all assertions passed');
console.log('for comparison, 8.2 * 1e6 =', 8.2 * 1e6);
usdToMicros: all assertions passed
for comparison, 8.2 * 1e6 = 8199999.999999999
Spot transfers are different: transferSpotToOrFromSubAccount() takes token and amount as a decimal string such as '1.5', not an integer.
Create the sub-account, find its address, move USDC in
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
import { usdToMicros } from './usd.ts';
const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY; // master key, or an API wallet the master approved
const master = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; // the master account address
if (!privateKey || !master) throw new Error('Set HYPERLIQUID_PRIVATE_KEY and HYPERLIQUID_ACCOUNT_ADDRESS.');
// The master account creates and funds its sub-accounts.
const client = new RestClient({ testnet: true, privateKey, accountAddress: master });
async function findSubAccount(name: string) {
const subs = (await client.getSubAccounts({ user: master })) ?? [];
return subs.find((s) => s.name === name);
}
async function ensureSubAccount(name: string): Promise<string> {
const existing = await findSubAccount(name);
if (existing) return existing.subAccountUser;
await client.createSubAccount({ name });
const created = await findSubAccount(name);
if (!created) throw new Error(`Sub-account "${name}" was not listed after creation`);
return created.subAccountUser;
}
try {
const sub = await ensureSubAccount('bot-1');
// Move 25 USDC of perp collateral from the master into the sub-account.
await client.transferUsdToOrFromSubAccount({ subAccountUser: sub, isDeposit: true, usd: usdToMicros('25') });
console.log('funded', sub);
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`Rejected (HTTP ${error.status}): ${error.message}`);
else throw error;
}
The new sub-account is looked up by name with getSubAccounts() rather than taken from the create response, so a rerun after a crash finds the existing account instead of creating a second one. Set isDeposit: false to move USDC back to the master.
An unknown signer must be registered or approved on the target network. See the Hyperliquid API errors post for the error and recovery steps.
Trade as a sub-account or a vault you lead
Give the client a vaultAddress and every order and cancel it signs is placed for that account. Trading as a vault works the same way: set vaultAddress to a vault your master account leads.
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY; // master key or its API wallet
const master = process.env.HYPERLIQUID_ACCOUNT_ADDRESS; // master account
const subAccount = process.env.HYPERLIQUID_SUB_ACCOUNT; // sub-account (or a vault you lead)
if (!privateKey || !master || !subAccount) {
throw new Error('Set HYPERLIQUID_PRIVATE_KEY, HYPERLIQUID_ACCOUNT_ADDRESS and HYPERLIQUID_SUB_ACCOUNT.');
}
// Orders and cancels from this client are placed for the sub-account, and
// account reads default to the sub-account instead of the master.
const bot = new RestClient({ testnet: true, privateKey, accountAddress: master, vaultAddress: subAccount });
console.log('reads resolve to', await bot.getAccountAddress());
try {
const book = await bot.getOrderBook({ coin: 'ETH' });
const bid = book?.levels[0][4]; // well below the best ask, so it rests
if (!bid) throw new Error('No ETH bids returned');
const order = await bot.submitLimitOrder({ symbol: 'ETH', side: 'buy', price: bid.px, size: '0.01', postOnly: true });
const status = order.status === 'ok' ? order.response.data.statuses[0] : undefined;
if (status && 'resting' in status) {
await bot.cancelOrders({ cancels: [{ a: 'ETH', o: status.resting.oid }] });
}
console.log(status);
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`Rejected (HTTP ${error.status}): ${error.message}`);
else throw error;
}
If one process trades several accounts, use the per call option instead of the client option. Order and cancel methods take an options object as their last argument, and it accepts vaultAddress: client.cancelOrders({ cancels }, { vaultAddress: subAccount }).
One API wallet per sub-account
Hyperliquid tracks nonces per signer, not per account. Its docs say: “a single API wallet signing for a user, vault, or subaccount all share the same nonce set”, and recommend that you “generate two separate API wallets under the master account, and use one API wallet for each subaccount”. Hyperliquid’s sub-accounts page says the number of API wallets “starts at 3 for all master accounts and increases by 2 per sub-account”, while the exchange endpoint docs say an account can have 1 unnamed approved wallet and up to 3 named ones, plus 2 more named agents per sub-account. The two pages disagree on the starting number, so plan for three and check your own account. The duplicate nonce section of the errors post shows what happens when two processes share one signer.
Deposit into and withdraw from a Hyperliquid vault
transferVaultFunds() sends the vaultTransfer action: vaultAddress, isDeposit and usd in 6 decimal units. Withdrawals are not possible straight after a deposit. Hyperliquid’s docs give “HLP has a lock-up period of 4 days. User vaults have a lock-up period of 1 day”. The example deposits into the testnet HLP vault, reads the deposit back with getUserVaultDeposits(), and has a withdraw helper that checks a deposit exists first:
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
import { usdToMicros } from './usd.ts';
const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY;
const account = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!privateKey || !account) throw new Error('Set HYPERLIQUID_PRIVATE_KEY and HYPERLIQUID_ACCOUNT_ADDRESS.');
const TESTNET_HLP = '0xa15099a30bbf2e68942d6f4c43d70d04faeab0a0';
const client = new RestClient({ testnet: true, privateKey, accountAddress: account });
async function depositIn(vaultAddress: string) {
const deposits = await client.getUserVaultDeposits({ user: account });
return deposits.find((d) => d.vaultAddress === vaultAddress.toLowerCase());
}
export async function withdrawFromVault(vaultAddress: string, amount: string) {
const deposit = await depositIn(vaultAddress);
if (!deposit) throw new Error(`No deposit in ${vaultAddress}`);
return client.transferVaultFunds({ vaultAddress, isDeposit: false, usd: usdToMicros(amount) });
}
try {
await client.transferVaultFunds({ vaultAddress: TESTNET_HLP, isDeposit: true, usd: usdToMicros('5') });
console.log('deposit', await depositIn(TESTNET_HLP));
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`Rejected (HTTP ${error.status}): ${error.message}`);
else throw error;
}
Resolve the vault address on the target network. The testnet HLP address in the example is specific to testnet.
Vault leader actions: createVault, modifyVault, distributeVaultFunds
The leader account signs these directly:
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
import { usdToMicros } from './usd.ts';
const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY;
const leader = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!privateKey || !leader) throw new Error('Set HYPERLIQUID_PRIVATE_KEY and HYPERLIQUID_ACCOUNT_ADDRESS.');
// Leader actions are signed by the leader account.
const client = new RestClient({ testnet: true, privateKey, accountAddress: leader });
try {
const created = await client.createVault({
name: 'my-api-vault', // cannot be changed later
description: 'Vault used to test API access from Node.js',
initialUsd: usdToMicros('100'), // integer USDC with 6 decimals
});
console.log(created);
const [vault] = await client.getLeadingVaults({ user: leader });
if (vault) {
await client.modifyVault({ vaultAddress: vault.address, allowDeposits: false });
}
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`Rejected (HTTP ${error.status}): ${error.message}`);
else throw error;
}
Rejected (HTTP 200): User or API Wallet 0x2e12d92355d426bab6edf3ce2d865c865faa6a03 does not exist.
createVault({ name, description, initialUsd }): Hyperliquid’s vault leader page says to “deposit a minimum of 100 USDC” and that the name and description “cannot be changed later”. Read that page for the full requirements before calling it. The SDK adds the action’snoncefield for you, and types the responsedataas a string.modifyVault({ vaultAddress, allowDeposits, alwaysCloseOnWithdraw }): the SDK sends any flag you leave out asnull.distributeVaultFunds({ vaultAddress, usd }):usduses the same 6 decimal units.- The leader page also says the leader “must maintain ≥5% of the vault at all times”, so a leader’s own withdrawal that would go below that share is refused.
Trading for the vault is the vaultAddress pattern from the previous section, signed by the leader key or one of its API wallets.
Errors and empty results you will see
| What you get | Where | Cause and fix |
|---|---|---|
User or API Wallet 0x... does not exist. |
Any signed action | The signer is not an account or approved API wallet on this network. Approve the API wallet from the master on the right network |
The signer is not a Hyperliquid account on this network. Set accountAddress when using an API wallet. |
Account reads with no user, accountAddress or vaultAddress |
Thrown by the SDK. Set accountAddress to the master |
null |
getVaultDetails() |
Not a vault on this network, or a sub-account address |
null |
getSubAccounts() |
No sub-accounts, or you queried a sub-account instead of its master |
[] |
getVaultSummaries() |
The result can be empty. Look up a known vault address directly. |
HTTP 422 Failed to deserialize the JSON body into the target type |
Any info call | A user that is not an address, such as the Leader follower row |
HTTP 429 Request failed with status code 429 |
Info calls in a loop | Over the per IP weight budget. userRole costs 60 |
The 422 from the Leader row on mainnet:
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
const client = new RestClient();
const vault = await client.getVaultDetails({ vaultAddress: '0xdfc24b077bc1425ad1dea75bcb6f8158e10df303' });
const leaderRow = vault?.followers.find((f) => f.user === 'Leader');
try {
await client.getUserVaultDeposits({ user: leaderRow!.user }); // "Leader" is not an address
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`HTTP ${error.status}: ${error.message}`);
}
HTTP 422: Failed to deserialize the JSON body into the target type
See the Hyperliquid API errors hub and the SDK’s troubleshooting guide for signer and account-address errors.
Further reading
- The SDK’s API wallets and vaults guide and the RestClient reference
- The Hyperliquid JavaScript tutorial and runnable Hyperliquid examples on siebly.io
- Hyperliquid JavaScript and TypeScript SDK on siebly.io, and the source on GitHub
- Hyperliquid’s exchange endpoint and info endpoint docs, and the vaults overview
