@nktkas/hyperliquid 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CONTRIBUTING.md +4 -7
  2. package/README.md +297 -103
  3. package/esm/mod.d.ts +3 -12
  4. package/esm/mod.d.ts.map +1 -1
  5. package/esm/mod.js +2 -2
  6. package/esm/src/{transports/base.d.ts → base.d.ts} +11 -14
  7. package/esm/src/base.d.ts.map +1 -0
  8. package/esm/src/base.js +14 -0
  9. package/esm/src/clients/event.d.ts +4 -4
  10. package/esm/src/clients/event.d.ts.map +1 -1
  11. package/esm/src/clients/event.js +2 -2
  12. package/esm/src/clients/public.d.ts +109 -6
  13. package/esm/src/clients/public.d.ts.map +1 -1
  14. package/esm/src/clients/public.js +106 -3
  15. package/esm/src/clients/wallet.d.ts +232 -29
  16. package/esm/src/clients/wallet.d.ts.map +1 -1
  17. package/esm/src/clients/wallet.js +859 -243
  18. package/esm/src/signing.d.ts +135 -0
  19. package/esm/src/signing.d.ts.map +1 -0
  20. package/esm/src/signing.js +188 -0
  21. package/esm/src/transports/http/http_transport.d.ts +2 -4
  22. package/esm/src/transports/http/http_transport.d.ts.map +1 -1
  23. package/esm/src/transports/http/http_transport.js +8 -13
  24. package/{script/src/transports/websocket/hyperliquid_event_target.d.ts → esm/src/transports/websocket/_hyperliquid_event_target.d.ts} +7 -15
  25. package/esm/src/transports/websocket/_hyperliquid_event_target.d.ts.map +1 -0
  26. package/esm/src/transports/websocket/{hyperliquid_event_target.js → _hyperliquid_event_target.js} +4 -22
  27. package/esm/src/transports/websocket/{reconnecting_websocket.d.ts → _reconnecting_websocket.d.ts} +26 -26
  28. package/esm/src/transports/websocket/_reconnecting_websocket.d.ts.map +1 -0
  29. package/esm/src/transports/websocket/{reconnecting_websocket.js → _reconnecting_websocket.js} +91 -76
  30. package/esm/src/transports/websocket/{websocket_request_dispatcher.d.ts → _websocket_request_dispatcher.d.ts} +3 -7
  31. package/esm/src/transports/websocket/_websocket_request_dispatcher.d.ts.map +1 -0
  32. package/esm/src/transports/websocket/{websocket_request_dispatcher.js → _websocket_request_dispatcher.js} +3 -7
  33. package/esm/src/transports/websocket/websocket_transport.d.ts +13 -16
  34. package/esm/src/transports/websocket/websocket_transport.d.ts.map +1 -1
  35. package/esm/src/transports/websocket/websocket_transport.js +49 -49
  36. package/esm/src/types/exchange/requests.d.ts +172 -20
  37. package/esm/src/types/exchange/requests.d.ts.map +1 -1
  38. package/esm/src/types/exchange/responses.d.ts +32 -32
  39. package/esm/src/types/exchange/responses.d.ts.map +1 -1
  40. package/esm/src/types/explorer/requests.d.ts +12 -12
  41. package/esm/src/types/explorer/requests.d.ts.map +1 -1
  42. package/esm/src/types/explorer/responses.d.ts +36 -1
  43. package/esm/src/types/explorer/responses.d.ts.map +1 -1
  44. package/esm/src/types/info/accounts.d.ts +130 -105
  45. package/esm/src/types/info/accounts.d.ts.map +1 -1
  46. package/esm/src/types/info/assets.d.ts +154 -152
  47. package/esm/src/types/info/assets.d.ts.map +1 -1
  48. package/esm/src/types/info/delegations.d.ts +20 -20
  49. package/esm/src/types/info/delegations.d.ts.map +1 -1
  50. package/esm/src/types/info/orders.d.ts +55 -55
  51. package/esm/src/types/info/orders.d.ts.map +1 -1
  52. package/esm/src/types/info/requests.d.ts +73 -10
  53. package/esm/src/types/info/requests.d.ts.map +1 -1
  54. package/esm/src/types/info/vaults.d.ts +1 -1
  55. package/esm/src/types/info/vaults.d.ts.map +1 -1
  56. package/esm/src/types/mod.d.ts +14 -0
  57. package/esm/src/types/mod.d.ts.map +1 -0
  58. package/esm/src/types/subscriptions/requests.d.ts +1 -1
  59. package/esm/src/types/subscriptions/requests.d.ts.map +1 -1
  60. package/{script/src/types/subscriptions/common.d.ts → esm/src/types/subscriptions/responses.d.ts} +16 -4
  61. package/esm/src/types/subscriptions/responses.d.ts.map +1 -0
  62. package/package.json +20 -4
  63. package/script/mod.d.ts +3 -12
  64. package/script/mod.d.ts.map +1 -1
  65. package/script/mod.js +3 -5
  66. package/script/src/{transports/base.d.ts → base.d.ts} +11 -14
  67. package/script/src/base.d.ts.map +1 -0
  68. package/script/src/{transports/base.js → base.js} +13 -12
  69. package/script/src/clients/event.d.ts +4 -4
  70. package/script/src/clients/event.d.ts.map +1 -1
  71. package/script/src/clients/event.js +2 -2
  72. package/script/src/clients/public.d.ts +109 -6
  73. package/script/src/clients/public.d.ts.map +1 -1
  74. package/script/src/clients/public.js +106 -3
  75. package/script/src/clients/wallet.d.ts +232 -29
  76. package/script/src/clients/wallet.d.ts.map +1 -1
  77. package/script/src/clients/wallet.js +860 -244
  78. package/script/src/signing.d.ts +135 -0
  79. package/script/src/signing.d.ts.map +1 -0
  80. package/script/src/signing.js +203 -0
  81. package/script/src/transports/http/http_transport.d.ts +2 -4
  82. package/script/src/transports/http/http_transport.d.ts.map +1 -1
  83. package/script/src/transports/http/http_transport.js +9 -14
  84. package/{esm/src/transports/websocket/hyperliquid_event_target.d.ts → script/src/transports/websocket/_hyperliquid_event_target.d.ts} +7 -15
  85. package/script/src/transports/websocket/_hyperliquid_event_target.d.ts.map +1 -0
  86. package/script/src/transports/websocket/{hyperliquid_event_target.js → _hyperliquid_event_target.js} +4 -22
  87. package/script/src/transports/websocket/{reconnecting_websocket.d.ts → _reconnecting_websocket.d.ts} +26 -26
  88. package/script/src/transports/websocket/_reconnecting_websocket.d.ts.map +1 -0
  89. package/script/src/transports/websocket/{reconnecting_websocket.js → _reconnecting_websocket.js} +94 -78
  90. package/script/src/transports/websocket/{websocket_request_dispatcher.d.ts → _websocket_request_dispatcher.d.ts} +3 -7
  91. package/script/src/transports/websocket/_websocket_request_dispatcher.d.ts.map +1 -0
  92. package/script/src/transports/websocket/{websocket_request_dispatcher.js → _websocket_request_dispatcher.js} +4 -8
  93. package/script/src/transports/websocket/websocket_transport.d.ts +13 -16
  94. package/script/src/transports/websocket/websocket_transport.d.ts.map +1 -1
  95. package/script/src/transports/websocket/websocket_transport.js +55 -55
  96. package/script/src/types/exchange/requests.d.ts +172 -20
  97. package/script/src/types/exchange/requests.d.ts.map +1 -1
  98. package/script/src/types/exchange/responses.d.ts +32 -32
  99. package/script/src/types/exchange/responses.d.ts.map +1 -1
  100. package/script/src/types/explorer/requests.d.ts +12 -12
  101. package/script/src/types/explorer/requests.d.ts.map +1 -1
  102. package/script/src/types/explorer/responses.d.ts +36 -1
  103. package/script/src/types/explorer/responses.d.ts.map +1 -1
  104. package/script/src/types/info/accounts.d.ts +130 -105
  105. package/script/src/types/info/accounts.d.ts.map +1 -1
  106. package/script/src/types/info/assets.d.ts +154 -152
  107. package/script/src/types/info/assets.d.ts.map +1 -1
  108. package/script/src/types/info/delegations.d.ts +20 -20
  109. package/script/src/types/info/delegations.d.ts.map +1 -1
  110. package/script/src/types/info/orders.d.ts +55 -55
  111. package/script/src/types/info/orders.d.ts.map +1 -1
  112. package/script/src/types/info/requests.d.ts +73 -10
  113. package/script/src/types/info/requests.d.ts.map +1 -1
  114. package/script/src/types/info/vaults.d.ts +1 -1
  115. package/script/src/types/info/vaults.d.ts.map +1 -1
  116. package/script/src/types/mod.d.ts +14 -0
  117. package/script/src/types/mod.d.ts.map +1 -0
  118. package/script/src/types/subscriptions/requests.d.ts +1 -1
  119. package/script/src/types/subscriptions/requests.d.ts.map +1 -1
  120. package/{esm/src/types/subscriptions/common.d.ts → script/src/types/subscriptions/responses.d.ts} +16 -4
  121. package/script/src/types/subscriptions/responses.d.ts.map +1 -0
  122. package/esm/src/transports/base.d.ts.map +0 -1
  123. package/esm/src/transports/base.js +0 -14
  124. package/esm/src/transports/websocket/hyperliquid_event_target.d.ts.map +0 -1
  125. package/esm/src/transports/websocket/reconnecting_websocket.d.ts.map +0 -1
  126. package/esm/src/transports/websocket/websocket_request_dispatcher.d.ts.map +0 -1
  127. package/esm/src/types/common.d.ts +0 -3
  128. package/esm/src/types/common.d.ts.map +0 -1
  129. package/esm/src/types/exchange/common.d.ts +0 -36
  130. package/esm/src/types/exchange/common.d.ts.map +0 -1
  131. package/esm/src/types/explorer/common.d.ts +0 -37
  132. package/esm/src/types/explorer/common.d.ts.map +0 -1
  133. package/esm/src/types/explorer/common.js +0 -1
  134. package/esm/src/types/subscriptions/common.d.ts.map +0 -1
  135. package/esm/src/types/subscriptions/common.js +0 -1
  136. package/esm/src/utils/key_sort.d.ts +0 -21
  137. package/esm/src/utils/key_sort.d.ts.map +0 -1
  138. package/esm/src/utils/key_sort.js +0 -124
  139. package/esm/src/utils/signing.d.ts +0 -109
  140. package/esm/src/utils/signing.d.ts.map +0 -1
  141. package/esm/src/utils/signing.js +0 -164
  142. package/script/src/transports/base.d.ts.map +0 -1
  143. package/script/src/transports/websocket/hyperliquid_event_target.d.ts.map +0 -1
  144. package/script/src/transports/websocket/reconnecting_websocket.d.ts.map +0 -1
  145. package/script/src/transports/websocket/websocket_request_dispatcher.d.ts.map +0 -1
  146. package/script/src/types/common.d.ts +0 -3
  147. package/script/src/types/common.d.ts.map +0 -1
  148. package/script/src/types/exchange/common.d.ts +0 -36
  149. package/script/src/types/exchange/common.d.ts.map +0 -1
  150. package/script/src/types/explorer/common.d.ts +0 -37
  151. package/script/src/types/explorer/common.d.ts.map +0 -1
  152. package/script/src/types/explorer/common.js +0 -12
  153. package/script/src/types/subscriptions/common.d.ts.map +0 -1
  154. package/script/src/types/subscriptions/common.js +0 -12
  155. package/script/src/utils/key_sort.d.ts +0 -21
  156. package/script/src/utils/key_sort.d.ts.map +0 -1
  157. package/script/src/utils/key_sort.js +0 -137
  158. package/script/src/utils/signing.d.ts +0 -109
  159. package/script/src/utils/signing.d.ts.map +0 -1
  160. package/script/src/utils/signing.js +0 -182
  161. /package/esm/src/types/{common.js → mod.js} +0 -0
  162. /package/esm/src/types/{exchange/common.js → subscriptions/responses.js} +0 -0
  163. /package/script/src/types/{common.js → mod.js} +0 -0
  164. /package/script/src/types/{exchange/common.js → subscriptions/responses.js} +0 -0
package/CONTRIBUTING.md CHANGED
@@ -40,20 +40,17 @@ git push origin feature/your-feature-name
40
40
  - **Create a Pull Request**: Go to the original repository and click on "New Pull Request". Select your branch and
41
41
  submit the pull request.
42
42
 
43
- ### Coding Guidelines
43
+ #### Coding Guidelines
44
44
 
45
45
  - **TypeScript**: Ensure your code passes TypeScript compilation without errors.
46
- - **Style**: Follow existing code style and conventions.
46
+ - **Style**: Follow Deno formatting convention ([deno fmt](https://docs.deno.com/runtime/reference/cli/fmt/)) and code
47
+ style ([deno lint](https://docs.deno.com/runtime/reference/cli/lint/)).
47
48
  - **Dependencies**: Avoid adding unnecessary dependencies.
48
49
  - **Docs**: Update or add JSDoc comments where appropriate.
49
50
 
50
- ### Testing
51
+ #### Testing
51
52
 
52
53
  Before submitting your pull request:
53
54
 
54
55
  - Run existing tests to ensure nothing breaks.
55
56
  - If you add new features, consider adding tests for them.
56
-
57
- ### License
58
-
59
- By contributing, you agree that your contributions will be licensed under the MIT License.
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # Hyperliquid API TypeScript SDK
2
2
 
3
- [![JSR](https://jsr.io/badges/@nktkas/hyperliquid)](https://jsr.io/@nktkas/hyperliquid)
4
- [![JSR Score](https://jsr.io/badges/@nktkas/hyperliquid/score)](https://jsr.io/@nktkas/hyperliquid)
5
- [![bundlephobia](https://badgen.net/bundlephobia/minzip/@nktkas/hyperliquid)](https://bundlephobia.com/package/@nktkas/hyperliquid)
3
+ [![NPM](https://img.shields.io/npm/v/@nktkas/hyperliquid?style=flat-square&color=blue)](https://www.npmjs.com/package/@nktkas/hyperliquid)
4
+ [![JSR](https://img.shields.io/jsr/v/@nktkas/hyperliquid?style=flat-square&color=blue)](https://jsr.io/@nktkas/hyperliquid)
5
+ [![Coveralls](https://img.shields.io/coverallsCoverage/github/nktkas/hyperliquid?style=flat-square)](https://coveralls.io/github/nktkas/hyperliquid)
6
+ [![bundlejs](https://img.shields.io/bundlejs/size/@nktkas/hyperliquid?style=flat-square)](https://bundlejs.com/?q=@nktkas/hyperliquid)
6
7
 
7
8
  Unofficial [Hyperliquid API](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) SDK for all major JS
8
9
  runtimes, written in TypeScript and provided with tests.
@@ -10,12 +11,12 @@ runtimes, written in TypeScript and provided with tests.
10
11
  ## Features
11
12
 
12
13
  - 🖋️ **Typed**: Source code is 100% TypeScript.
13
- - 🧪 **Tested**: Good code coverage and type validation.
14
+ - 🧪 **Tested**: Good code coverage and type testing.
14
15
  - 📦 **Minimal dependencies**: Few small dependencies, standard JS is favored.
15
16
  - 🌐 **Cross-Environment Support**: Compatible with all major JS runtimes, including Node.js, Deno, Bun, and browser
16
17
  environments.
17
- - 🔧 **Extensible**: Easily integrates with [viem](https://github.com/wevm/viem) and
18
- [ethers](https://github.com/ethers-io/ethers.js).
18
+ - 🔧 **Integratable**: Easy to use with [viem](https://github.com/wevm/viem),
19
+ [ethers](https://github.com/ethers-io/ethers.js) and web3 wallets.
19
20
  - 📚 **Documented**: Comprehensive documentation and usage examples, provided directly in JSDoc annotations within the
20
21
  source code.
21
22
 
@@ -51,21 +52,15 @@ First, choose and configure your transport layer (more details in the [API Refer
51
52
  import * as hl from "@nktkas/hyperliquid";
52
53
 
53
54
  // HTTP Transport
54
- const httpTransport = new hl.HttpTransport({ // All options are optional
55
- url: "https://api.hyperliquid.xyz", // API base URL for /info, /exchange, /explorer
56
- timeout: 10_000, // Request timeout in ms
57
- });
55
+ const httpTransport = new hl.HttpTransport(); // Accepts optional parameters (e.g. url, timeout, fetchOptions)
58
56
 
59
- // OR WebSocket Transport
60
- const wsTransport = new hl.WebSocketTransport({ // All options are optional
61
- url: "wss://api.hyperliquid.xyz/ws", // WebSocket URL
62
- timeout: 10_000, // Request timeout in ms
63
- });
57
+ // or WebSocket Transport
58
+ const wsTransport = new hl.WebSocketTransport(); // Accepts optional parameters (e.g. url, timeout, keepAlive, reconnect)
64
59
  ```
65
60
 
66
61
  ### Initialize Client
67
62
 
68
- Next, initialize the client with the transport layer (more details in the [API Reference](#clients)):
63
+ Next, initialize a client with the transport layer (more details in the [API Reference](#clients)):
69
64
 
70
65
  #### Create PublicClient
71
66
 
@@ -97,7 +92,10 @@ const ethersClient = new hl.WalletClient({ wallet: ethersWallet, transport });
97
92
  // 3. Using external wallet (e.g. MetaMask) via Viem
98
93
  const [account] = await window.ethereum.request({ method: "eth_requestAccounts" });
99
94
  const externalWallet = createWalletClient({ account, transport: custom(window.ethereum) });
100
- const metamaskClient = new hl.WalletClient({ wallet: externalWallet, transport });
95
+ const viemMetamaskClient = new hl.WalletClient({ wallet: externalWallet, transport });
96
+
97
+ // 4. Using external wallet (e.g. MetaMask) via `window.ethereum` directly
98
+ const windowMetamaskClient = new hl.WalletClient({ wallet: window.ethereum, transport });
101
99
  ```
102
100
 
103
101
  #### Create EventClient
@@ -105,8 +103,99 @@ const metamaskClient = new hl.WalletClient({ wallet: externalWallet, transport }
105
103
  ```typescript
106
104
  import * as hl from "@nktkas/hyperliquid";
107
105
 
106
+ const transport = new hl.WebSocketTransport(); // Only WebSocketTransport is supported
107
+ const client = new hl.EventClient({ transport });
108
+ ```
109
+
110
+ ### Use Client
111
+
112
+ Finally, use client methods to interact with the Hyperliquid API (more details in the [API Reference](#clients)):
113
+
114
+ #### Example of using a public client
115
+
116
+ ```typescript
117
+ import * as hl from "@nktkas/hyperliquid";
118
+
119
+ const transport = new hl.HttpTransport(); // or WebSocketTransport
120
+ const client = new hl.PublicClient({ transport });
121
+
122
+ // L2 Book
123
+ const l2Book = await client.l2Book({ coin: "BTC" });
124
+
125
+ // Account clearinghouse state
126
+ const clearinghouseState = await client.clearinghouseState({ user: "0x..." });
127
+
128
+ // Open orders
129
+ const openOrders = await client.openOrders({ user: "0x..." });
130
+ ```
131
+
132
+ #### Example of using a wallet client
133
+
134
+ ```typescript
135
+ import * as hl from "@nktkas/hyperliquid";
136
+ import { privateKeyToAccount } from "viem/accounts";
137
+
138
+ const account = privateKeyToAccount("0x...");
139
+ const transport = new hl.HttpTransport();
140
+ const client = new hl.WalletClient({ wallet: account, transport });
141
+
142
+ // Place an orders
143
+ const result = await client.order({
144
+ orders: [{
145
+ a: 0, // Asset index
146
+ b: true, // Buy order
147
+ p: "30000", // Price
148
+ s: "0.1", // Size
149
+ r: false, // Not reduce-only
150
+ t: {
151
+ limit: {
152
+ tif: "Gtc", // Good-til-cancelled
153
+ },
154
+ },
155
+ }],
156
+ grouping: "na", // No grouping
157
+ });
158
+
159
+ // Approve an agent
160
+ const result = await client.approveAgent({
161
+ agentAddress: "0x...",
162
+ agentName: "agentName",
163
+ });
164
+
165
+ // Withdraw funds
166
+ const result = await client.withdraw3({
167
+ destination: account.address, // Withdraw funds to your address
168
+ amount: "100", // 100 USD
169
+ });
170
+ ```
171
+
172
+ #### Example of using an event client
173
+
174
+ ```typescript
175
+ import * as hl from "@nktkas/hyperliquid";
176
+
108
177
  const transport = new hl.WebSocketTransport();
109
178
  const client = new hl.EventClient({ transport });
179
+
180
+ // L2 Book updates
181
+ // Promise is resolved when the subscription is set up
182
+ const sub = await client.l2Book({ coin: "BTC" }, (data) => {
183
+ console.log(data);
184
+ });
185
+ // Later, you can unsubscribe from receiving events
186
+ await sub.unsubscribe();
187
+
188
+ // User fills
189
+ const sub = await client.userFills({ user: "0x..." }, (data) => {
190
+ console.log(data);
191
+ });
192
+ await sub.unsubscribe();
193
+
194
+ // Explorer block updates
195
+ const sub = await client.explorerBlock((data) => {
196
+ console.log(data);
197
+ });
198
+ await sub.unsubscribe();
110
199
  ```
111
200
 
112
201
  ## API Reference
@@ -126,20 +215,18 @@ A Public Client which provides access to
126
215
  The Public Client class sets up with a given [Transport](#transports).
127
216
 
128
217
  ```typescript
129
- interface PublicClientParameters<T extends IRequestTransport = IRequestTransport> {
130
- transport: T; // HttpTransport or WebSocketTransport
131
- }
132
-
133
- class PublicClient<T extends IRESTTransport> {
134
- constructor(args: PublicClientParameters<T>);
218
+ class PublicClient {
219
+ constructor(args: {
220
+ transport: HttpTransport | WebSocketTransport;
221
+ });
135
222
 
136
223
  // Market
137
224
  allMids(): Promise<AllMids>;
138
- candleSnapshot(args: CandleSnapshotParameters): Promise<CandleSnapshot[]>;
225
+ candleSnapshot(args: CandleSnapshotParameters): Promise<Candle[]>;
139
226
  fundingHistory(args: FundingHistoryParameters): Promise<FundingHistory[]>;
140
- l2Book(args: L2BookParameters): Promise<L2Book>;
141
- meta(): Promise<Meta>;
142
- metaAndAssetCtxs(): Promise<MetaAndAssetCtxs>;
227
+ l2Book(args: L2BookParameters): Promise<Book>;
228
+ meta(): Promise<PerpsMeta>;
229
+ metaAndAssetCtxs(): Promise<PerpsMetaAndAssetCtxs>;
143
230
  perpsAtOpenInterestCap(): Promise<string[]>;
144
231
  predictedFundings(): Promise<PredictedFunding[]>;
145
232
  spotDeployState(args: SpotDeployStateParameters): Promise<SpotDeployState>;
@@ -148,28 +235,30 @@ class PublicClient<T extends IRESTTransport> {
148
235
  tokenDetails(args: TokenDetailsParameters): Promise<TokenDetails>;
149
236
 
150
237
  // Account
151
- clearinghouseState(args: ClearinghouseStateParameters): Promise<ClearinghouseState>;
238
+ clearinghouseState(args: ClearinghouseStateParameters): Promise<PerpsClearinghouseState>;
152
239
  extraAgents(args: ExtraAgentsParameters): Promise<ExtraAgent[]>;
240
+ isVip(args: IsVipParameters): Promise<boolean>;
241
+ legalCheck(args: LegalCheckParameters): Promise<LegalCheck>;
153
242
  maxBuilderFee(args: MaxBuilderFeeParameters): Promise<number>;
154
243
  portfolio(args: PortfolioParameters): Promise<PortfolioPeriods>;
155
244
  referral(args: ReferralParameters): Promise<Referral>;
156
245
  spotClearinghouseState(args: SpotClearinghouseStateParameters): Promise<SpotClearinghouseState>;
157
- subAccounts(args: SubAccountsParameters): Promise<SubAccount[]>;
246
+ subAccounts(args: SubAccountsParameters): Promise<SubAccount[] | null>;
158
247
  userFees(args: UserFeesParameters): Promise<UserFees>;
159
- userFunding(args: UserFundingParameters): Promise<UserFunding[]>;
160
- userNonFundingLedgerUpdates(args: UserNonFundingLedgerUpdatesParameters): Promise<UserNonFundingLedgerUpdates[]>;
248
+ userFunding(args: UserFundingParameters): Promise<UserFundingUpdate[]>;
249
+ userNonFundingLedgerUpdates(args: UserNonFundingLedgerUpdatesParameters): Promise<UserNonFundingLedgerUpdate[]>;
161
250
  userRateLimit(args: UserRateLimitParameters): Promise<UserRateLimit>;
162
251
  userRole(args: UserRoleParameters): Promise<UserRole>;
163
252
 
164
253
  // Order
165
- frontendOpenOrders(args: FrontendOpenOrdersParameters): Promise<FrontendOpenOrder[]>;
166
- historicalOrders(args: HistoricalOrdersParameters): Promise<OrderStatus[]>;
167
- openOrders(args: OpenOrdersParameters): Promise<OpenOrder[]>;
168
- orderStatus(args: OrderStatusParameters): Promise<OrderStatusResponse>;
169
- twapHistory(args: TwapHistoryParameters): Promise<TwapHistory>;
170
- userFills(args: UserFillsParameters): Promise<UserFill[]>;
171
- userFillsByTime(args: UserFillsByTimeParameters): Promise<UserFill[]>;
172
- userTwapSliceFills(args: UserTwapSliceFillsParameters): Promise<UserTwapSliceFill[]>;
254
+ frontendOpenOrders(args: FrontendOpenOrdersParameters): Promise<FrontendOrder[]>;
255
+ historicalOrders(args: HistoricalOrdersParameters): Promise<OrderStatus<FrontendOrder>[]>;
256
+ openOrders(args: OpenOrdersParameters): Promise<Order[]>;
257
+ orderStatus(args: OrderStatusParameters): Promise<OrderLookup>;
258
+ twapHistory(args: TwapHistoryParameters): Promise<TwapHistory[]>;
259
+ userFills(args: UserFillsParameters): Promise<Fill[]>;
260
+ userFillsByTime(args: UserFillsByTimeParameters): Promise<Fill[]>;
261
+ userTwapSliceFills(args: UserTwapSliceFillsParameters): Promise<TwapSliceFill[]>;
173
262
 
174
263
  // Staking
175
264
  delegations(args: DelegationsParameters): Promise<Delegation[]>;
@@ -179,7 +268,7 @@ class PublicClient<T extends IRESTTransport> {
179
268
  validatorSummaries(): Promise<ValidatorSummary[]>;
180
269
 
181
270
  // Vault
182
- userVaultEquities(args: UserVaultEquitiesParameters): Promise<UserVaultEquity[]>;
271
+ userVaultEquities(args: UserVaultEquitiesParameters): Promise<VaultEquity[]>;
183
272
  vaultDetails(args: VaultDetailsParameters): Promise<VaultDetails | null>;
184
273
  vaultSummaries(): Promise<VaultSummary[]>;
185
274
 
@@ -201,21 +290,18 @@ The Wallet Client class sets up with a given [Transport](#transports) and a wall
201
290
  [Ethers Wallet](https://docs.ethers.org/v6/api/providers/#Signer).
202
291
 
203
292
  ```typescript
204
- interface WalletClientParameters<
205
- T extends ISubscriptionTransport,
206
- W extends AbstractViemWalletClient | AbstractEthersSigner | AbstractEthersV5Signer,
207
- > {
208
- transport: T; // HttpTransport or WebSocketTransport
209
- wallet: W; // viem, ethers, or ethers v5
210
- isTestnet?: boolean; // Whether to use testnet API (default: false)
211
- defaultVaultAddress?: Hex; // Vault address used by default if not provided in method call
212
- }
213
-
214
- class WalletClient<
215
- T extends IRESTTransport,
216
- W extends AbstractViemWalletClient | AbstractEthersSigner | AbstractEthersV5Signer,
217
- > {
218
- constructor(args: WalletClientParameters<T, W>);
293
+ class WalletClient {
294
+ constructor(args: {
295
+ transport: HttpTransport | WebSocketTransport;
296
+ wallet:
297
+ | AbstractViemWalletClient // viem
298
+ | AbstractExtendedViemWalletClient // extended viem (e.g. privy)
299
+ | AbstractEthersSigner // ethers
300
+ | AbstractEthersV5Signer // ethers v5
301
+ | AbstractWindowEthereum; // window.ethereum (EIP-1193) directly
302
+ isTestnet?: boolean; // Whether to use testnet API (default: false)
303
+ defaultVaultAddress?: Hex; // Vault address used by default if not provided in method call
304
+ });
219
305
 
220
306
  // Order
221
307
  batchModify(args: BatchModifyParameters): Promise<OrderResponseSuccess>;
@@ -232,21 +318,30 @@ class WalletClient<
232
318
  // Account
233
319
  approveAgent(args: ApproveAgentParameters): Promise<SuccessResponse>;
234
320
  approveBuilderFee(args: ApproveBuilderFeeParameters): Promise<SuccessResponse>;
321
+ claimRewards(args: ClaimRewardsParameters): Promise<SuccessResponse>;
235
322
  createSubAccount(args: CreateSubAccountParameters): Promise<CreateSubAccountResponse>;
323
+ evmUserModify(args: EvmUserModifyParameters): Promise<SuccessResponse>;
324
+ setDisplayName(args: SetDisplayNameParameters): Promise<SuccessResponse>;
236
325
  setReferrer(args: SetReferrerParameters): Promise<SuccessResponse>;
326
+ spotUser(args: SpotUserParameters): Promise<SuccessResponse>;
237
327
 
238
328
  // Transfers & Withdrawals
239
329
  spotSend(args: SpotSendParameters): Promise<SuccessResponse>;
330
+ subAccountSpotTransfer(args: SubAccountSpotTransferParameters): Promise<SuccessResponse>;
240
331
  subAccountTransfer(args: SubAccountTransferParameters): Promise<SuccessResponse>;
241
332
  usdClassTransfer(args: UsdClassTransferParameters): Promise<SuccessResponse>;
242
333
  usdSend(args: UsdSendParameters): Promise<SuccessResponse>;
243
- vaultTransfer(args: VaultTransferParameters): Promise<SuccessResponse>;
244
334
  withdraw3(args: Withdraw3Parameters): Promise<SuccessResponse>;
245
335
 
246
336
  // Staking
247
337
  cDeposit(args: CDepositParameters): Promise<SuccessResponse>;
248
338
  cWithdraw(args: CWithdrawParameters): Promise<SuccessResponse>;
249
339
  tokenDelegate(args: TokenDelegateParameters): Promise<SuccessResponse>;
340
+
341
+ // Vault
342
+ vaultDistribute(args: VaultDistributeParameters): Promise<SuccessResponse>;
343
+ vaultModify(args: VaultModifyParameters): Promise<SuccessResponse>;
344
+ vaultTransfer(args: VaultTransferParameters): Promise<SuccessResponse>;
250
345
  }
251
346
  ```
252
347
 
@@ -260,12 +355,10 @@ The Event Client class sets up with a given [WebSocket Transport](#websocket-tra
260
355
 
261
356
  <!-- deno-fmt-ignore-start -->
262
357
  ```typescript
263
- interface EventClientParameters<T extends ISubscriptionTransport> {
264
- transport: T; // WebSocketTransport
265
- }
266
-
267
- class EventClient<T extends ISubscriptionTransport> {
268
- constructor(args: EventClientParameters<T>);
358
+ class EventClient {
359
+ constructor(args: {
360
+ transport: WebSocketTransport;
361
+ });
269
362
 
270
363
  // Market
271
364
  activeAssetCtx(args: EventActiveAssetCtxParameters, listener: (data: WsActiveAssetCtx | WsActiveSpotAssetCtx) => void): Promise<Subscription>;
@@ -308,18 +401,16 @@ A HTTP Transport that executes requests via a [fetch](https://developer.mozilla.
308
401
  API.
309
402
 
310
403
  ```typescript
311
- class HttpTransport implements IRequestTransport, HttpTransportOptions {
312
- constructor(options?: HttpTransportOptions);
313
-
314
- request(endpoint: "info" | "action" | "explorer", payload: unknown, signal?: AbortSignal): Promise<unknown>;
315
- }
316
-
317
- interface HttpTransportOptions {
318
- url?: string | URL; // Base URL for API endpoints (default: "https://api.hyperliquid.xyz")
319
- timeout?: number; // Request timeout in ms (default: 10_000)
320
- fetchOptions?: RequestInit; // A custom fetch options
321
- onRequest?: (request: Request) => MaybePromise<Request | void | null | undefined>; // A callback before request is sent
322
- onResponse?: (response: Response) => MaybePromise<Response | void | null | undefined>; // A callback after response is received
404
+ class HttpTransport {
405
+ constructor(options?: {
406
+ url?: string | URL; // Base URL for API endpoints (default: "https://api.hyperliquid.xyz")
407
+ timeout?: number; // Request timeout in ms (default: 10_000)
408
+ fetchOptions?: RequestInit; // A custom fetch options
409
+ onRequest?: (request: Request) => MaybePromise<Request | void | null | undefined>; // A callback before request is sent
410
+ onResponse?: (response: Response) => MaybePromise<Response | void | null | undefined>; // A callback after response is received
411
+ });
412
+
413
+ request(endpoint: "info" | "exchange" | "explorer", payload: unknown, signal?: AbortSignal): Promise<unknown>;
323
414
  }
324
415
  ```
325
416
 
@@ -329,10 +420,23 @@ A WebSocket Transport that executes requests and subscribes to events via a
329
420
  [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection.
330
421
 
331
422
  ```typescript
332
- class WebSocketTransport implements IRESTTransport, ISubscriptionTransport {
333
- constructor(options?: WebSocketTransportOptions);
334
-
335
- request(endpoint: "info" | "action" | "explorer", payload: unknown, signal?: AbortSignal): Promise<unknown>;
423
+ class WebSocketTransport {
424
+ constructor(options?: {
425
+ url?: string | URL; // WebSocket URL (default: "wss://api.hyperliquid.xyz/ws")
426
+ timeout?: number; // Request timeout in ms (default: 10_000)
427
+ keepAlive?: { // Keep-alive configuration
428
+ interval?: number; // Ping interval in ms (default: 20_000)
429
+ };
430
+ reconnect?: { // Reconnection policy configuration for closed connections
431
+ maxRetries?: number; // Maximum number of reconnection attempts (default: 3)
432
+ connectionTimeout?: number; // Connection timeout in ms (default: 10_000)
433
+ connectionDelay?: number | ((attempt: number) => number | Promise<number>); // Delay between reconnection (default: Exponential backoff (max 10s))
434
+ shouldReconnect?: (event: CloseEvent) => boolean | Promise<boolean>; // Custom reconnection logic (default: Always reconnect)
435
+ messageBuffer?: MessageBufferStrategy; // Message buffering strategy between reconnection (default: FIFO buffer)
436
+ };
437
+ });
438
+
439
+ request(endpoint: "info" | "exchange" | "explorer", payload: unknown, signal?: AbortSignal): Promise<unknown>;
336
440
  subscribe(
337
441
  channel: string,
338
442
  payload: unknown,
@@ -343,40 +447,130 @@ class WebSocketTransport implements IRESTTransport, ISubscriptionTransport {
343
447
  ready(signal?: AbortSignal): Promise<void>;
344
448
  close(signal?: AbortSignal): Promise<void>;
345
449
  }
450
+ ```
451
+
452
+ ## Additional Import Points
453
+
454
+ The SDK exports additional import points to access internal functions.
455
+
456
+ ### `/types`
457
+
458
+ The import point gives access to all Hyperliquid-related types, including the base types on which class methods are
459
+ based.
460
+
461
+ Useful if you want to get all Hyperliquid types.
462
+
463
+ ### `/signing`
464
+
465
+ The import point gives access to functions that generate signatures for Hyperliquid transactions.
466
+
467
+ Useful if you want to sign a Hyperliquid transaction yourself.
468
+
469
+ ### Examples
470
+
471
+ #### Cancel an order without a client
346
472
 
347
- interface WebSocketTransportOptions {
348
- url?: string | URL; // WebSocket URL (default: "wss://api.hyperliquid.xyz/ws")
349
- timeout?: number; // Request timeout in ms (default: 10_000)
350
- keepAlive?: { // Keep-alive configuration
351
- interval?: number; // Ping interval in ms (default: 20_000)
352
- };
353
- reconnect?: { // Reconnection policy configuration for closed connections
354
- maxRetries?: number; // Maximum number of reconnection attempts (default: 3)
355
- connectionTimeout?: number; // Connection timeout in ms (default: 10_000)
356
- connectionDelay?: number | ((attempt: number) => number | Promise<number>); // Delay between reconnection (default: Exponential backoff (max 10s))
357
- shouldReconnect?: (event: CloseEvent) => boolean | Promise<boolean>; // Custom reconnection logic (default: Always reconnect)
358
- messageBuffer?: MessageBufferStrategy; // Message buffering strategy between reconnection (default: FIFO buffer)
359
- WebSocketConstructor?: typeof WebSocket; // Custom WebSocket constructor (default: globalThis.WebSocket)
360
- };
473
+ ```typescript
474
+ import { signL1Action } from "@nktkas/hyperliquid/signing";
475
+ import type { CancelRequest, CancelResponse } from "@nktkas/hyperliquid/types";
476
+ import { privateKeyToAccount } from "viem/accounts";
477
+
478
+ // —————————— Prepare ——————————
479
+
480
+ const wallet = privateKeyToAccount("0x..."); // Change to your private key
481
+
482
+ // The CancelRequest["action"] type ensures that we collect the correct cancel request action
483
+ const action: CancelRequest["action"] = {
484
+ type: "cancel",
485
+ cancels: [
486
+ { a: 0, o: 12345 },
487
+ ],
488
+ };
489
+ const nonce = Date.now();
490
+
491
+ // —————————— Signing ——————————
492
+
493
+ const signature = await signL1Action({ wallet, action, nonce, isTestnet: true });
494
+
495
+ // —————————— Request ——————————
496
+
497
+ // The CancelRequest type guarantees us that the object we want to send is valid in terms of types
498
+ const request: CancelRequest = { action, signature, nonce };
499
+
500
+ const response = await fetch("https://api.hyperliquid-testnet.xyz/exchange", {
501
+ method: "POST",
502
+ headers: { "Content-Type": "application/json" },
503
+ body: JSON.stringify(request),
504
+ });
505
+
506
+ if (!response.ok) {
507
+ const body = await response.text();
508
+ throw new Error(`Failed to cancel order: ${response.statusText} ${body}`);
361
509
  }
510
+
511
+ // If we sent a cancel request and received a successful response, then we got exactly the CancelResponse type
512
+ const body = await response.json() as CancelResponse;
513
+ console.log("Order cancel response:", body);
362
514
  ```
363
515
 
364
- ## Semantic Versioning
516
+ #### Approve an agent without a client
517
+
518
+ ```typescript
519
+ import { signUserSignedAction } from "@nktkas/hyperliquid/signing";
520
+ import type { ApproveAgentRequest, ErrorResponse, SuccessResponse } from "@nktkas/hyperliquid/types";
521
+ import { privateKeyToAccount } from "viem/accounts";
522
+
523
+ // —————————— Prepare ——————————
524
+
525
+ const wallet = privateKeyToAccount("0x..."); // Change to your private key
526
+
527
+ // The ApproveAgentRequest["action"] type ensures that we collect the correct approve agent request action
528
+ const action: ApproveAgentRequest["action"] = {
529
+ type: "approveAgent",
530
+ hyperliquidChain: "Testnet",
531
+ signatureChainId: "0x66eee",
532
+ nonce: Date.now(),
533
+ agentAddress: "0x...", // Change to the agent address you want to approve
534
+ agentName: "TempAgent",
535
+ };
536
+
537
+ // —————————— Signing ——————————
538
+
539
+ const signature = await signUserSignedAction({
540
+ wallet,
541
+ action,
542
+ types: {
543
+ "HyperliquidTransaction:ApproveAgent": [
544
+ { name: "hyperliquidChain", type: "string" },
545
+ { name: "agentAddress", type: "address" },
546
+ { name: "agentName", type: "string" },
547
+ { name: "nonce", type: "uint64" },
548
+ ],
549
+ },
550
+ chainId: parseInt(action.signatureChainId, 16),
551
+ });
365
552
 
366
- This library follows [Semantic Versioning](https://semver.org/) (or rather
367
- [this proposal](https://github.com/semver/semver/pull/923)) for its releases.
553
+ // —————————— Request ——————————
368
554
 
369
- > [!IMPORTANT]
370
- > To avoid rapid increase in the main version of the SDK due to changes in Hyperliquid API types, such changes are
371
- > reflected in updates to the patch version of this SDK.
555
+ // The ApproveAgentRequest type guarantees us that the object we want to send is valid in terms of types
556
+ const request: ApproveAgentRequest = { action, signature, nonce: action.nonce };
372
557
 
373
- ## CI/CD and Release
558
+ const response = await fetch("https://api.hyperliquid-testnet.xyz/exchange", {
559
+ method: "POST",
560
+ headers: { "Content-Type": "application/json" },
561
+ body: JSON.stringify(request),
562
+ });
374
563
 
375
- Before publishing a new version of the SDK, tests are always run in
376
- [Github Actions](https://github.com/nktkas/hyperliquid/actions). Only if all tests pass successfully, the process of
377
- publishing the package takes place.
564
+ if (!response.ok) {
565
+ const body = await response.text();
566
+ throw new Error(`Failed to approve agent: ${response.statusText} ${body}`);
567
+ }
378
568
 
379
- For more details, see our [CI/CD configuration files](./.github/workflows/).
569
+ // If we sent a request for agent approval and received a successful response,
570
+ // we will get either a SuccessResponse type or an ErrorResponse type
571
+ const body = await response.json() as SuccessResponse | ErrorResponse;
572
+ console.log("Agent approval response:", body);
573
+ ```
380
574
 
381
575
  ## Contributing
382
576
 
package/esm/mod.d.ts CHANGED
@@ -1,25 +1,16 @@
1
+ export * from "./src/base.js";
2
+ export type { AbstractEthersSigner, AbstractEthersV5Signer, AbstractExtendedViemWalletClient, AbstractViemWalletClient, AbstractWindowEthereum, } from "./src/signing.js";
1
3
  export * from "./src/clients/event.js";
2
4
  export * from "./src/clients/public.js";
3
5
  export * from "./src/clients/wallet.js";
4
- export * from "./src/transports/base.js";
5
6
  export * from "./src/transports/http/http_transport.js";
6
7
  export * from "./src/transports/websocket/websocket_transport.js";
7
- export type { MessageBufferStrategy, ReconnectingWebSocketOptions, } from "./src/transports/websocket/reconnecting_websocket.js";
8
- export { WebSocketRequestError } from "./src/transports/websocket/websocket_request_dispatcher.js";
9
- export type * from "./src/types/common.js";
10
- export type * from "./src/types/exchange/common.js";
11
- export type * from "./src/types/exchange/requests.js";
12
8
  export type * from "./src/types/exchange/responses.js";
13
- export type * from "./src/types/explorer/common.js";
14
- export type * from "./src/types/explorer/requests.js";
15
9
  export type * from "./src/types/explorer/responses.js";
16
10
  export type * from "./src/types/info/accounts.js";
17
11
  export type * from "./src/types/info/assets.js";
18
12
  export type * from "./src/types/info/delegations.js";
19
13
  export type * from "./src/types/info/orders.js";
20
- export type * from "./src/types/info/requests.js";
21
14
  export type * from "./src/types/info/vaults.js";
22
- export type * from "./src/types/subscriptions/common.js";
23
- export type * from "./src/types/subscriptions/requests.js";
24
- export type { AbstractEthersSigner, AbstractEthersV5Signer, AbstractViemWalletClient } from "./src/utils/signing.js";
15
+ export type * from "./src/types/subscriptions/responses.js";
25
16
  //# sourceMappingURL=mod.d.ts.map
package/esm/mod.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../src/mod.ts"],"names":[],"mappings":"AACA,cAAc,wBAAwB,CAAC;AACvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AAGxC,cAAc,0BAA0B,CAAC;AAEzC,cAAc,yCAAyC,CAAC;AAExD,cAAc,mDAAmD,CAAC;AAClE,YAAY,EACR,qBAAqB,EACrB,4BAA4B,GAC/B,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,4DAA4D,CAAC;AAGnG,mBAAmB,uBAAuB,CAAC;AAE3C,mBAAmB,gCAAgC,CAAC;AACpD,mBAAmB,kCAAkC,CAAC;AACtD,mBAAmB,mCAAmC,CAAC;AAEvD,mBAAmB,gCAAgC,CAAC;AACpD,mBAAmB,kCAAkC,CAAC;AACtD,mBAAmB,mCAAmC,CAAC;AAEvD,mBAAmB,8BAA8B,CAAC;AAClD,mBAAmB,4BAA4B,CAAC;AAChD,mBAAmB,iCAAiC,CAAC;AACrD,mBAAmB,4BAA4B,CAAC;AAChD,mBAAmB,8BAA8B,CAAC;AAClD,mBAAmB,4BAA4B,CAAC;AAEhD,mBAAmB,qCAAqC,CAAC;AACzD,mBAAmB,uCAAuC,CAAC;AAG3D,YAAY,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC"}
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../src/mod.ts"],"names":[],"mappings":"AACA,cAAc,eAAe,CAAC;AAG9B,YAAY,EACR,oBAAoB,EACpB,sBAAsB,EACtB,gCAAgC,EAChC,wBAAwB,EACxB,sBAAsB,GACzB,MAAM,kBAAkB,CAAC;AAG1B,cAAc,wBAAwB,CAAC;AACvC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AAGxC,cAAc,yCAAyC,CAAC;AACxD,cAAc,mDAAmD,CAAC;AAGlE,mBAAmB,mCAAmC,CAAC;AACvD,mBAAmB,mCAAmC,CAAC;AACvD,mBAAmB,8BAA8B,CAAC;AAClD,mBAAmB,4BAA4B,CAAC;AAChD,mBAAmB,iCAAiC,CAAC;AACrD,mBAAmB,4BAA4B,CAAC;AAChD,mBAAmB,4BAA4B,CAAC;AAChD,mBAAmB,wCAAwC,CAAC"}
package/esm/mod.js CHANGED
@@ -1,9 +1,9 @@
1
+ // Base interfaces
2
+ export * from "./src/base.js";
1
3
  // Clients
2
4
  export * from "./src/clients/event.js";
3
5
  export * from "./src/clients/public.js";
4
6
  export * from "./src/clients/wallet.js";
5
7
  // Transports
6
- export * from "./src/transports/base.js";
7
8
  export * from "./src/transports/http/http_transport.js";
8
9
  export * from "./src/transports/websocket/websocket_transport.js";
9
- export { WebSocketRequestError } from "./src/transports/websocket/websocket_request_dispatcher.js";