• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nktkas / hyperliquid / 19931273441

04 Dec 2025 01:16PM UTC coverage: 96.688% (+1.9%) from 94.811%
19931273441

push

github

nktkas
docs: improve design

343 of 455 branches covered (75.38%)

Branch coverage included in aggregate %.

11977 of 12287 relevant lines covered (97.48%)

1183.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.22
/bin/cli.ts
1
#!/usr/bin/env node
2

3
/**
4
 * Command-line interface for interacting with Hyperliquid API.
5
 *
6
 * @example
7
 * ```sh
8
 * npx @nktkas/hyperliquid <endpoint> <method> [options]
9
 * ```
10
 */
11

12
// @ts-ignore: Ignore missing TS types when building npm
13
import process from "node:process";
221✔
14
import { type Args, extractArgs, transformArgs } from "./_utils.ts";
221✔
15
import { ExchangeClient, HttpTransport, InfoClient } from "../src/mod.ts";
221✔
16
import { PrivateKeySigner } from "../src/signing/mod.ts";
221✔
17

18
// ============================================================
19
// Execute
20
// ============================================================
21

22
function transformParams(method: string, params: Args<false>) {
332✔
23
  switch (method) {
332✔
24
    case "spotUser": {
665✔
25
      return { toggleSpotDusting: { ...params } };
1,665✔
26
    }
333✔
27
    case "twapOrder": {
665✔
28
      return { twap: { ...params } };
1,665✔
29
    }
333✔
30
    default: {
773✔
31
      return params;
441✔
32
    }
441✔
33
  }
332✔
34
}
332✔
35

36
class EchoTransport extends HttpTransport {
221✔
37
  constructor(isTestnet: boolean) {
221✔
38
    super({ isTestnet });
996✔
39
  }
332✔
40
  override request<T>(_: string, payload: unknown): Promise<T> {
221✔
41
    return new Promise((resolve) => resolve({ status: "ok", response: payload } as T));
1,550✔
42
  }
332✔
43
}
221✔
44

45
/** Execute CLI command on info/exchange endpoint */
46
async function executeEndpointMethod(endpoint: string, method: string, args: Args<false>): Promise<unknown> {
221✔
47
  // Parse CLI flags
48
  const isTestnet = "testnet" in args;
332✔
49
  const timeout = Number(args.timeout) || undefined;
332✔
50
  const isOffline = "offline" in args;
332✔
51

52
  // Create transport (echo for offline, http for online)
53
  const transport = isOffline ? new EchoTransport(isTestnet) : new HttpTransport({ isTestnet, timeout });
×
54
  let client: InfoClient | ExchangeClient;
332✔
55

56
  // Create client based on endpoint
57
  switch (endpoint) {
332✔
58
    case "info":
332✔
59
      client = new InfoClient({ transport });
1,197✔
60
      break;
399✔
61
    case "exchange": {
708✔
62
      const wallet = new PrivateKeySigner(args["private-key"] as `0x${string}`);
376✔
63
      delete args["private-key"]; // remove before uncontrolled transfer of arguments (just in case)
376✔
64

65
      const defaultVaultAddress = args.vault as `0x${string}` | undefined;
376✔
66

67
      client = new ExchangeClient({ transport, wallet, defaultVaultAddress });
1,880✔
68
      break;
376✔
69
    }
376✔
70
    default:
×
71
      throw new Error(`Invalid endpoint "${endpoint}". Use "info" or "exchange"`);
×
72
  }
332✔
73

74
  // Check if method exists on client
75
  if (!(method in client)) throw new Error(`Unknown "${method}" method for "${endpoint}" endpoint`);
×
76

77
  // Execute method and return result
78
  const params = transformParams(method, args);
332✔
79
  // @ts-expect-error: dynamic method access
80
  const response = await client[method](params);
332✔
81
  return isOffline ? response.response : response; // for offline mode, we want to see the request payload, not the wrapper
×
82
}
332✔
83

84
// ============================================================
85
// CLI
86
// ============================================================
87

88
function printHelp() {
×
89
  console.log(`Hyperliquid CLI
×
90

91
Usage:
92
  npx @nktkas/hyperliquid <endpoint> <method> [options]
93

94
Endpoints:
95
  info      - Query blockchain and market information
96
  exchange  - Execute trading operations (requires --private-key)
97

98
Common Options:
99
  --testnet               Use testnet instead of mainnet
100
  --timeout <number>      Request timeout in milliseconds (default: 10000)
101
  --help, -h              Show this help message
102
  --offline               Generate transactions offline without broadcasting
103

104
Exchange Options:
105
  --private-key <key>     Private key for exchange operations (required)
106
  --vault <address>       Vault address for operations
107

108
=============================================================================
109
INFO ENDPOINT METHODS
110
=============================================================================
111

112
Market Data:
113
  alignedQuoteTokenInfo   --token <number>
114
  allMids                 [--dex <string>]
115
  allPerpMetas            (no params)
116
  candleSnapshot          --coin <string> --interval <1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d|3d|1w|1M>
117
                          --startTime <number> [--endTime <number>]
118
  fundingHistory          --coin <string> --startTime <number> [--endTime <number>]
119
  l2Book                  --coin <string> [--nSigFigs <2|3|4|5>] [--mantissa <2|5>]
120
  liquidatable            (no params)
121
  marginTable             --id <number>
122
  maxMarketOrderNtls      (no params)
123
  meta                    [--dex <string>]
124
  metaAndAssetCtxs        [--dex <string>]
125
  perpsAtOpenInterestCap  [--dex <string>]
126
  predictedFundings       (no params)
127
  recentTrades            --coin <string>
128
  spotMeta                (no params)
129
  spotMetaAndAssetCtxs    (no params)
130

131
User Account:
132
  activeAssetData         --user <address> --coin <string>
133
  clearinghouseState      --user <address> [--dex <string>]
134
  extraAgents             --user <address>
135
  isVip                   --user <address>
136
  legalCheck              --user <address>
137
  maxBuilderFee           --user <address> --builder <address>
138
  portfolio               --user <address>
139
  preTransferCheck        --user <address> --source <address>
140
  referral                --user <address>
141
  spotClearinghouseState  --user <address> [--dex <string>]
142
  subAccounts             --user <address>
143
  subAccounts2            --user <address>
144
  userDexAbstraction      --user <address>
145
  userFees                --user <address>
146
  userFunding             --user <address> --startTime <number> [--endTime <number>]
147
  userNonFundingLedgerUpdates  --user <address> --startTime <number> [--endTime <number>]
148
  userRateLimit           --user <address>
149
  userRole                --user <address>
150
  userToMultiSigSigners   --user <address>
151
  webData2                --user <address>
152

153
Orders & TWAP & Position:
154
  frontendOpenOrders      --user <address> [--dex <string>]
155
  historicalOrders        --user <address>
156
  openOrders              --user <address> [--dex <string>]
157
  orderStatus             --user <address> --oid <number|hex>
158
  twapHistory             --user <address>
159
  userFills               --user <address> [--aggregateByTime <bool>]
160
  userFillsByTime         --user <address> --startTime <number>
161
                          [--endTime <number>] [--aggregateByTime <bool>]
162
  userTwapSliceFills           --user <address>
163
  userTwapSliceFillsByTime     --user <address> --startTime <number>
164
                               [--endTime <number>] [--aggregateByTime <bool>]
165

166
Delegation & Validators:
167
  delegations             --user <address>
168
  delegatorHistory        --user <address>
169
  delegatorRewards        --user <address>
170
  delegatorSummary        --user <address>
171
  gossipRootIps           (no params)
172
  validatorL1Votes        (no params)
173
  validatorSummaries      (no params)
174

175
Vault:
176
  leadingVaults           --user <address>
177
  userVaultEquities       --user <address>
178
  vaultDetails            --vaultAddress <address> [--user <address>]
179
  vaultSummaries          (no params)
180

181
DEX:
182
  perpDexLimits           --dex <string>
183
  perpDexs                (no params)
184
  perpDexStatus           --dex <string>
185

186
Deploy Market:
187
  perpDeployAuctionStatus      (no params)
188
  spotDeployState              --user <address>
189
  spotPairDeployAuctionStatus  (no params)
190

191
Other:
192
  exchangeStatus          (no params)
193

194
Transaction & Block Details:
195
  blockDetails            --height <number>
196
  tokenDetails            --tokenId <hex>
197
  txDetails               --hash <hex>
198
  userDetails             --user <address>
199

200
=============================================================================
201
EXCHANGE ENDPOINT METHODS
202
=============================================================================
203

204
Order & TWAP & Position:
205
  batchModify             --modifies <json>
206
  cancel                  --cancels <json>
207
  cancelByCloid           --cancels <json>
208
  modify                  --oid <number|hex> --order <json>
209
  order                   --orders <json> [--grouping <na|normalTpsl|positionTpsl>] [--builder <json>]
210
  scheduleCancel          [--time <number>]
211
  twapCancel              --a <number> --t <number>
212
  twapOrder               --a <number> --b <bool> --s <number> --r <bool> --m <number> --t <bool>
213
  updateIsolatedMargin    --asset <number> --isBuy <bool> --ntli <number>
214
  updateLeverage          --asset <number> --isCross <bool> --leverage <number>
215

216
Account:
217
  agentEnableDexAbstraction  (no params)
218
  approveAgent            --agentAddress <address> [--agentName <string>]
219
  approveBuilderFee       --maxFeeRate <number> --builder <address>
220
  evmUserModify           --usingBigBlocks <bool>
221
  noop                    (no params)
222
  reserveRequestWeight    --weight <number>
223
  setDisplayName          --displayName <string>
224
  spotUser                --optOut <bool>
225
  userDexAbstraction      --user <address> --enabled <bool>
226

227
Fund Transfers:
228
  sendAsset               --destination <address> --token <name:address> --amount <number>
229
                          --sourceDex <string> --destinationDex <string> [--fromSubAccount <address>]
230
  spotSend                --destination <address> --token <name:address> --amount <number>
231
  usdClassTransfer        --amount <number> --toPerp <bool>
232
  usdSend                 --destination <address> --amount <number>
233
  withdraw3               --destination <address> --amount <number>
234

235
Sub-Account:
236
  createSubAccount        --name <string>
237
  subAccountModify        --subAccountUser <address> --name <string>
238
  subAccountSpotTransfer  --subAccountUser <address> --isDeposit <bool>
239
                          --token <name:address> --amount <number>
240
  subAccountTransfer      --subAccountUser <address> --isDeposit <bool> --usd <number>
241

242
Referrer:
243
  claimRewards            (no params)
244
  registerReferrer        --code <string>
245
  setReferrer             --code <string>
246

247
Staking & Delegation:
248
  cDeposit                --wei <number>
249
  cWithdraw               --wei <number>
250
  linkStakingUser         --user <address> --isFinalize <bool>
251
  tokenDelegate           --validator <address> --wei <number> --isUndelegate <bool>
252

253
Vault:
254
  createVault             --name <string> --description <string> --initialUsd <number>
255
  vaultDistribute         --vaultAddress <address> --usd <number>
256
  vaultModify             --vaultAddress <address> [--allowDeposits <bool>]
257
                          [--alwaysCloseOnWithdraw <bool>]
258
  vaultTransfer           --vaultAddress <address> --isDeposit <bool> --usd <number>
259

260
Deploy Market:
261
  perpDeploy              --<action> <json>
262
  spotDeploy              --<action> <json>
263

264
Validator Actions:
265
  cSignerAction           --jailSelf null | --unjailSelf null
266
  cValidatorAction        --<action> <json>
267
  validatorL1Stream       --riskFreeRate <number>
268

269
Other:
270
  convertToMultiSigUser   --authorizedUsers <json> --threshold <number>
271

272
=============================================================================
273

274
Examples:
275
  # Get all mid prices
276
  npx @nktkas/hyperliquid info allMids
277

278
  # Get ETH order book with 3 significant figures
279
  npx @nktkas/hyperliquid info l2Book --coin ETH --nSigFigs 3
280

281
  # Get user's portfolio
282
  npx @nktkas/hyperliquid info portfolio --user 0x...
283

284
  # Get candle data for BTC
285
  npx @nktkas/hyperliquid info candleSnapshot --coin BTC --interval 1h --startTime 1700000000000
286

287
  # Place a limit order
288
  npx @nktkas/hyperliquid exchange order --private-key 0x... --orders '[{\"a\":0,\"b\":true,\"p\":30000,\"s\":0.1,\"r\":false,\"t\":{\"limit\":{\"tif\":\"Gtc\"}}}]'
289

290
  # Modify an existing order
291
  npx @nktkas/hyperliquid exchange modify --private-key 0x... --oid 12345 --order '{\"a\":0,\"b\":true,\"p\":31000,\"s\":0.1,\"r\":false,\"t\":{\"limit\":{\"tif\":\"Gtc\"}}}'
292

293
  # Cancel orders
294
  npx @nktkas/hyperliquid exchange cancel --private-key 0x... --cancels '[{\"a\":0,\"o\":12345}]'
295

296
  # Update leverage
297
  npx @nktkas/hyperliquid exchange updateLeverage --private-key 0x... --asset 0 --isCross true --leverage 5
298

299
  # Withdraw funds
300
  npx @nktkas/hyperliquid exchange withdraw3 --private-key 0x... --destination 0x... --amount 100.5
301

302
  # Send USD to another user
303
  npx @nktkas/hyperliquid exchange usdSend --private-key 0x... --destination 0x... --amount 50
304

305
  # Create a vault
306
  npx @nktkas/hyperliquid exchange createVault --private-key 0x... --name "My Vault" --description "Test vault" --initialUsd 1000`);
×
307
}
×
308

309
// ============================================================
310
// Entry
311
// ============================================================
312

313
const rawArgs = extractArgs(process.argv.slice(2), {
221✔
314
  flags: ["testnet", "help", "h", "offline"],
1,326✔
315
  collect: false,
221✔
316
});
221✔
317
const args = transformArgs(rawArgs, { number: "string" });
663✔
318
const [endpoint, method] = args._;
221✔
319
if (args.help || args.h || !endpoint || !method) {
221✔
320
  printHelp();
441✔
321
} else {
221✔
322
  executeEndpointMethod(endpoint, method, args)
×
323
    .then((result) => console.log(JSON.stringify(result)))
×
324
    .catch((error) => console.error(error));
×
325
}
221✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc