@nktkas/hyperliquid 0.13.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 (145) hide show
  1. package/CONTRIBUTING.md +59 -0
  2. package/LICENSE +21 -0
  3. package/README.md +363 -0
  4. package/SECURITY.md +7 -0
  5. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.d.ts +2 -0
  6. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.d.ts.map +1 -0
  7. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.js +1 -0
  8. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.d.ts +95 -0
  9. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.d.ts.map +1 -0
  10. package/esm/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.js +10 -0
  11. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.d.ts +23 -0
  12. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.d.ts.map +1 -0
  13. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.js +43 -0
  14. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.d.ts +55 -0
  15. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.d.ts.map +1 -0
  16. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.js +65 -0
  17. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.d.ts +2 -0
  18. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.d.ts.map +1 -0
  19. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.js +1 -0
  20. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.d.ts +52 -0
  21. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.d.ts.map +1 -0
  22. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.js +283 -0
  23. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/utils.d.ts +120 -0
  24. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/utils.d.ts.map +1 -0
  25. package/esm/deps/jsr.io/@noble/hashes/1.7.1/src/utils.js +211 -0
  26. package/esm/deps/jsr.io/@std/bytes/1.0.4/concat.d.ts +19 -0
  27. package/esm/deps/jsr.io/@std/bytes/1.0.4/concat.d.ts.map +1 -0
  28. package/esm/deps/jsr.io/@std/bytes/1.0.4/concat.js +32 -0
  29. package/esm/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.d.ts +2 -0
  30. package/esm/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.d.ts.map +1 -0
  31. package/esm/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.js +26 -0
  32. package/esm/deps/jsr.io/@std/encoding/1.0.6/hex.d.ts +37 -0
  33. package/esm/deps/jsr.io/@std/encoding/1.0.6/hex.d.ts.map +1 -0
  34. package/esm/deps/jsr.io/@std/encoding/1.0.6/hex.js +109 -0
  35. package/esm/deps/jsr.io/@std/msgpack/1.0.2/encode.d.ts +37 -0
  36. package/esm/deps/jsr.io/@std/msgpack/1.0.2/encode.d.ts.map +1 -0
  37. package/esm/deps/jsr.io/@std/msgpack/1.0.2/encode.js +237 -0
  38. package/esm/mod.d.ts +24 -0
  39. package/esm/mod.d.ts.map +1 -0
  40. package/esm/mod.js +9 -0
  41. package/esm/package.json +3 -0
  42. package/esm/src/clients/event.d.ts +374 -0
  43. package/esm/src/clients/event.d.ts.map +1 -0
  44. package/esm/src/clients/event.js +490 -0
  45. package/esm/src/clients/public.d.ts +695 -0
  46. package/esm/src/clients/public.d.ts.map +1 -0
  47. package/esm/src/clients/public.js +704 -0
  48. package/esm/src/clients/wallet.d.ts +682 -0
  49. package/esm/src/clients/wallet.d.ts.map +1 -0
  50. package/esm/src/clients/wallet.js +984 -0
  51. package/esm/src/transports/base.d.ts +55 -0
  52. package/esm/src/transports/base.d.ts.map +1 -0
  53. package/esm/src/transports/base.js +14 -0
  54. package/esm/src/transports/http/http_transport.d.ts +78 -0
  55. package/esm/src/transports/http/http_transport.d.ts.map +1 -0
  56. package/esm/src/transports/http/http_transport.js +170 -0
  57. package/esm/src/transports/websocket/hyperliquid_event_target.d.ts +66 -0
  58. package/esm/src/transports/websocket/hyperliquid_event_target.d.ts.map +1 -0
  59. package/esm/src/transports/websocket/hyperliquid_event_target.js +33 -0
  60. package/esm/src/transports/websocket/reconnecting_websocket.d.ts +160 -0
  61. package/esm/src/transports/websocket/reconnecting_websocket.d.ts.map +1 -0
  62. package/esm/src/transports/websocket/reconnecting_websocket.js +370 -0
  63. package/esm/src/transports/websocket/websocket_request_dispatcher.d.ts +63 -0
  64. package/esm/src/transports/websocket/websocket_request_dispatcher.d.ts.map +1 -0
  65. package/esm/src/transports/websocket/websocket_request_dispatcher.js +201 -0
  66. package/esm/src/transports/websocket/websocket_transport.d.ts +117 -0
  67. package/esm/src/transports/websocket/websocket_transport.d.ts.map +1 -0
  68. package/esm/src/transports/websocket/websocket_transport.js +233 -0
  69. package/esm/src/utils/key_sort.d.ts +21 -0
  70. package/esm/src/utils/key_sort.d.ts.map +1 -0
  71. package/esm/src/utils/key_sort.js +124 -0
  72. package/esm/src/utils/signing.d.ts +109 -0
  73. package/esm/src/utils/signing.d.ts.map +1 -0
  74. package/esm/src/utils/signing.js +164 -0
  75. package/package.json +34 -0
  76. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.d.ts +2 -0
  77. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.d.ts.map +1 -0
  78. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/mod.js +17 -0
  79. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.d.ts +95 -0
  80. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.d.ts.map +1 -0
  81. package/script/deps/jsr.io/@derzade/typescript-event-target/1.1.1/src/TypedEventTarget.js +14 -0
  82. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.d.ts +23 -0
  83. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.d.ts.map +1 -0
  84. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_assert.js +49 -0
  85. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.d.ts +55 -0
  86. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.d.ts.map +1 -0
  87. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/_u64.js +88 -0
  88. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.d.ts +2 -0
  89. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.d.ts.map +1 -0
  90. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/crypto.js +4 -0
  91. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.d.ts +52 -0
  92. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.d.ts.map +1 -0
  93. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/sha3.js +288 -0
  94. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/utils.d.ts +120 -0
  95. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/utils.d.ts.map +1 -0
  96. package/script/deps/jsr.io/@noble/hashes/1.7.1/src/utils.js +235 -0
  97. package/script/deps/jsr.io/@std/bytes/1.0.4/concat.d.ts +19 -0
  98. package/script/deps/jsr.io/@std/bytes/1.0.4/concat.d.ts.map +1 -0
  99. package/script/deps/jsr.io/@std/bytes/1.0.4/concat.js +35 -0
  100. package/script/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.d.ts +2 -0
  101. package/script/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.d.ts.map +1 -0
  102. package/script/deps/jsr.io/@std/encoding/1.0.6/_validate_binary_like.js +29 -0
  103. package/script/deps/jsr.io/@std/encoding/1.0.6/hex.d.ts +37 -0
  104. package/script/deps/jsr.io/@std/encoding/1.0.6/hex.d.ts.map +1 -0
  105. package/script/deps/jsr.io/@std/encoding/1.0.6/hex.js +113 -0
  106. package/script/deps/jsr.io/@std/msgpack/1.0.2/encode.d.ts +37 -0
  107. package/script/deps/jsr.io/@std/msgpack/1.0.2/encode.d.ts.map +1 -0
  108. package/script/deps/jsr.io/@std/msgpack/1.0.2/encode.js +240 -0
  109. package/script/mod.d.ts +24 -0
  110. package/script/mod.d.ts.map +1 -0
  111. package/script/mod.js +27 -0
  112. package/script/package.json +3 -0
  113. package/script/src/clients/event.d.ts +374 -0
  114. package/script/src/clients/event.d.ts.map +1 -0
  115. package/script/src/clients/event.js +494 -0
  116. package/script/src/clients/public.d.ts +695 -0
  117. package/script/src/clients/public.d.ts.map +1 -0
  118. package/script/src/clients/public.js +708 -0
  119. package/script/src/clients/wallet.d.ts +682 -0
  120. package/script/src/clients/wallet.d.ts.map +1 -0
  121. package/script/src/clients/wallet.js +989 -0
  122. package/script/src/transports/base.d.ts +55 -0
  123. package/script/src/transports/base.d.ts.map +1 -0
  124. package/script/src/transports/base.js +18 -0
  125. package/script/src/transports/http/http_transport.d.ts +78 -0
  126. package/script/src/transports/http/http_transport.d.ts.map +1 -0
  127. package/script/src/transports/http/http_transport.js +175 -0
  128. package/script/src/transports/websocket/hyperliquid_event_target.d.ts +66 -0
  129. package/script/src/transports/websocket/hyperliquid_event_target.d.ts.map +1 -0
  130. package/script/src/transports/websocket/hyperliquid_event_target.js +37 -0
  131. package/script/src/transports/websocket/reconnecting_websocket.d.ts +160 -0
  132. package/script/src/transports/websocket/reconnecting_websocket.d.ts.map +1 -0
  133. package/script/src/transports/websocket/reconnecting_websocket.js +374 -0
  134. package/script/src/transports/websocket/websocket_request_dispatcher.d.ts +63 -0
  135. package/script/src/transports/websocket/websocket_request_dispatcher.d.ts.map +1 -0
  136. package/script/src/transports/websocket/websocket_request_dispatcher.js +206 -0
  137. package/script/src/transports/websocket/websocket_transport.d.ts +117 -0
  138. package/script/src/transports/websocket/websocket_transport.d.ts.map +1 -0
  139. package/script/src/transports/websocket/websocket_transport.js +237 -0
  140. package/script/src/utils/key_sort.d.ts +21 -0
  141. package/script/src/utils/key_sort.d.ts.map +1 -0
  142. package/script/src/utils/key_sort.js +127 -0
  143. package/script/src/utils/signing.d.ts +109 -0
  144. package/script/src/utils/signing.d.ts.map +1 -0
  145. package/script/src/utils/signing.js +172 -0
@@ -0,0 +1,370 @@
1
+ // deno-lint-ignore-file no-explicit-any
2
+ /**
3
+ * Simple FIFO (First In, First Out) buffer implementation.
4
+ */
5
+ class FIFOMessageBuffer {
6
+ constructor() {
7
+ Object.defineProperty(this, "messages", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: []
12
+ });
13
+ }
14
+ push(data) {
15
+ this.messages.push(data);
16
+ }
17
+ shift() {
18
+ return this.messages.shift();
19
+ }
20
+ clear() {
21
+ this.messages = [];
22
+ }
23
+ }
24
+ /**
25
+ * A WebSocket that automatically reconnects when disconnected.
26
+ * Fully compatible with standard WebSocket API.
27
+ */
28
+ export class ReconnectingWebSocket {
29
+ /**
30
+ * Creates a new reconnecting WebSocket.
31
+ * @param url - The WebSocket URL to connect to.
32
+ * @param protocols - The WebSocket protocols to use.
33
+ * @param options - The configuration options.
34
+ */
35
+ constructor(url, protocols, options) {
36
+ /** Controller for handling connection termination */
37
+ Object.defineProperty(this, "terminationController", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: new AbortController()
42
+ });
43
+ /** WebSocket protocols */
44
+ Object.defineProperty(this, "protocols", {
45
+ enumerable: true,
46
+ configurable: true,
47
+ writable: true,
48
+ value: void 0
49
+ });
50
+ /** The underlying WebSocket instance */
51
+ Object.defineProperty(this, "socket", {
52
+ enumerable: true,
53
+ configurable: true,
54
+ writable: true,
55
+ value: void 0
56
+ });
57
+ /** Current number of reconnection attempts */
58
+ Object.defineProperty(this, "reconnectCount", {
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ value: 0
63
+ });
64
+ /** Array of registered event listeners */
65
+ Object.defineProperty(this, "eventListeners", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: []
70
+ });
71
+ /** Configuration options */
72
+ Object.defineProperty(this, "reconnectOptions", {
73
+ enumerable: true,
74
+ configurable: true,
75
+ writable: true,
76
+ value: void 0
77
+ });
78
+ /** An AbortSignal that is triggered when the connection is permanently closed */
79
+ Object.defineProperty(this, "terminationSignal", {
80
+ enumerable: true,
81
+ configurable: true,
82
+ writable: true,
83
+ value: this.terminationController.signal
84
+ });
85
+ Object.defineProperty(this, "CLOSED", {
86
+ enumerable: true,
87
+ configurable: true,
88
+ writable: true,
89
+ value: WebSocket.CLOSED
90
+ });
91
+ Object.defineProperty(this, "CLOSING", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: WebSocket.CLOSING
96
+ });
97
+ Object.defineProperty(this, "CONNECTING", {
98
+ enumerable: true,
99
+ configurable: true,
100
+ writable: true,
101
+ value: WebSocket.CONNECTING
102
+ });
103
+ Object.defineProperty(this, "OPEN", {
104
+ enumerable: true,
105
+ configurable: true,
106
+ writable: true,
107
+ value: WebSocket.OPEN
108
+ });
109
+ this.reconnectOptions = {
110
+ maxRetries: options?.maxRetries ?? 3,
111
+ connectionTimeout: options?.connectionTimeout === undefined ? 10_000 : options.connectionTimeout,
112
+ connectionDelay: options?.connectionDelay ?? ((attempt) => Math.min(~~(1 << attempt) * 150, 10_000)),
113
+ shouldReconnect: options?.shouldReconnect ?? (() => true),
114
+ messageBuffer: options?.messageBuffer ?? new FIFOMessageBuffer(),
115
+ WebSocketConstructor: options?.WebSocketConstructor ?? WebSocket,
116
+ };
117
+ this.protocols = protocols;
118
+ this.socket = this.reconnectOptions.connectionTimeout
119
+ ? this.connectWithTimeout(url, this.protocols, this.reconnectOptions.connectionTimeout)
120
+ : new this.reconnectOptions.WebSocketConstructor(url, this.protocols);
121
+ this.initEventListeners();
122
+ }
123
+ /**
124
+ * Creates a WebSocket connection with timeout.
125
+ * @param url - The WebSocket URL to connect to.
126
+ * @param protocols - The WebSocket protocols to use.
127
+ * @param timeout - The connection timeout in ms.
128
+ * @returns A new WebSocket instance.
129
+ */
130
+ connectWithTimeout(url, protocols, timeout) {
131
+ const socket = new this.reconnectOptions.WebSocketConstructor(url, protocols);
132
+ const timeoutId = setTimeout(() => {
133
+ socket.removeEventListener("open", openHandler);
134
+ socket.removeEventListener("close", closeHandler);
135
+ socket.close(3008, "Timeout"); // https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
136
+ }, timeout);
137
+ const openHandler = () => {
138
+ socket.removeEventListener("close", closeHandler);
139
+ clearTimeout(timeoutId);
140
+ };
141
+ const closeHandler = () => {
142
+ socket.removeEventListener("open", openHandler);
143
+ clearTimeout(timeoutId);
144
+ };
145
+ socket.addEventListener("open", openHandler, { once: true });
146
+ socket.addEventListener("close", closeHandler, { once: true });
147
+ return socket;
148
+ }
149
+ /**
150
+ * Initializes the internal event listeners for the WebSocket.
151
+ */
152
+ initEventListeners() {
153
+ this.socket.addEventListener("open", () => {
154
+ // Reset reconnection count
155
+ this.reconnectCount = 0;
156
+ // Send all buffered messages
157
+ let message;
158
+ while ((message = this.reconnectOptions.messageBuffer.shift()) !== undefined) {
159
+ this.socket.send(message);
160
+ }
161
+ }, { once: true });
162
+ this.socket.addEventListener("close", async (event) => {
163
+ try {
164
+ // If the termination signal is already aborted, do not attempt to reconnect
165
+ if (this.terminationSignal.aborted)
166
+ return;
167
+ // Check if reconnection should be attempted
168
+ if (++this.reconnectCount > this.reconnectOptions.maxRetries) {
169
+ this.cleanup(new Error("RECONNECTION_LIMIT_REACHED", { cause: event }));
170
+ return;
171
+ }
172
+ const userDecision = await this.reconnectOptions.shouldReconnect(event);
173
+ if (this.terminationSignal.aborted)
174
+ return; // Check again after the await
175
+ if (!userDecision) {
176
+ this.cleanup(new Error("RECONNECTION_STOPPED_BY_USER", { cause: event }));
177
+ return;
178
+ }
179
+ // Delay before reconnecting
180
+ const delay = typeof this.reconnectOptions.connectionDelay === "number"
181
+ ? this.reconnectOptions.connectionDelay
182
+ : await this.reconnectOptions.connectionDelay(this.reconnectCount);
183
+ if (this.terminationSignal.aborted)
184
+ return; // Check again after the await
185
+ await sleep(delay, this.terminationSignal);
186
+ // Reconnect the socket
187
+ this.socket = this.reconnectOptions.connectionTimeout
188
+ ? this.connectWithTimeout(this.url, this.protocols, this.reconnectOptions.connectionTimeout)
189
+ : new this.reconnectOptions.WebSocketConstructor(this.url, this.protocols);
190
+ // Reconnect all listeners
191
+ this.initEventListeners();
192
+ this.eventListeners.forEach(({ type, listenerProxy, options }) => {
193
+ this.socket.addEventListener(type, listenerProxy, options);
194
+ });
195
+ }
196
+ catch (error) {
197
+ this.cleanup(new Error("RECONNECTION_ERROR", { cause: { error, event } }));
198
+ }
199
+ }, { once: true });
200
+ }
201
+ /**
202
+ * Clean up internal resources.
203
+ * @param reason - The reason for cleanup.
204
+ */
205
+ cleanup(reason) {
206
+ this.terminationController.abort(reason);
207
+ this.reconnectOptions.messageBuffer.clear();
208
+ this.eventListeners = [];
209
+ }
210
+ /**
211
+ * Check if two event listeners are the same (just like EventTarget).
212
+ * @param a - First event listener configuration.
213
+ * @param b - Second event listener configuration.
214
+ * @returns True if the listeners match.
215
+ */
216
+ isListenerMatch(a, b) {
217
+ const aCapture = Boolean(typeof a.options === "object" ? a.options.capture : a.options);
218
+ const bCapture = Boolean(typeof b.options === "object" ? b.options.capture : b.options);
219
+ return a.type === b.type && a.listener === b.listener && aCapture === bCapture;
220
+ }
221
+ // WebSocket property implementations
222
+ get url() {
223
+ return this.socket.url;
224
+ }
225
+ get readyState() {
226
+ return this.socket.readyState;
227
+ }
228
+ get bufferedAmount() {
229
+ return this.socket.bufferedAmount;
230
+ }
231
+ get extensions() {
232
+ return this.socket.extensions;
233
+ }
234
+ get protocol() {
235
+ return this.socket.protocol;
236
+ }
237
+ get binaryType() {
238
+ return this.socket.binaryType;
239
+ }
240
+ set binaryType(value) {
241
+ this.socket.binaryType = value;
242
+ }
243
+ get onclose() {
244
+ return this.socket.onclose;
245
+ }
246
+ set onclose(value) {
247
+ this.socket.onclose = value;
248
+ }
249
+ get onerror() {
250
+ return this.socket.onerror;
251
+ }
252
+ set onerror(value) {
253
+ this.socket.onerror = value;
254
+ }
255
+ get onmessage() {
256
+ return this.socket.onmessage;
257
+ }
258
+ set onmessage(value) {
259
+ this.socket.onmessage = value;
260
+ }
261
+ get onopen() {
262
+ return this.socket.onopen;
263
+ }
264
+ set onopen(value) {
265
+ this.socket.onopen = value;
266
+ }
267
+ /**
268
+ * @param permanently - If true, the connection will be permanently closed. Default is true.
269
+ */
270
+ close(code, reason, permanently = true) {
271
+ if (permanently)
272
+ this.cleanup(new Error("USER_INITIATED_CLOSE"));
273
+ this.socket.close(code, reason);
274
+ }
275
+ /**
276
+ * @note If the connection is not open, the data will be buffered and sent when the connection is established.
277
+ */
278
+ send(data) {
279
+ if (this.socket.readyState !== WebSocket.OPEN && !this.terminationSignal.aborted) {
280
+ this.reconnectOptions.messageBuffer.push(data);
281
+ }
282
+ else {
283
+ this.socket.send(data);
284
+ }
285
+ }
286
+ addEventListener(type, listener, options) {
287
+ // Check if the listener is already added
288
+ const exists = this.eventListeners.some((e) => this.isListenerMatch(e, { type, listener, options }));
289
+ if (exists)
290
+ return;
291
+ // Wrap the original listener to follow the once option when reconnecting
292
+ const listenerProxy = (event) => {
293
+ try {
294
+ if (typeof listener === "function") {
295
+ listener.call(this, event);
296
+ }
297
+ else {
298
+ listener.handleEvent(event);
299
+ }
300
+ }
301
+ finally {
302
+ if (typeof options === "object" && options.once === true) {
303
+ const index = this.eventListeners.findIndex((e) => this.isListenerMatch(e, { type, listener, options }));
304
+ if (index !== -1)
305
+ this.eventListeners.splice(index, 1);
306
+ }
307
+ }
308
+ };
309
+ this.eventListeners.push({ type, listener, options, listenerProxy });
310
+ this.socket.addEventListener(type, listenerProxy, options);
311
+ }
312
+ removeEventListener(type, listener, options) {
313
+ const index = this.eventListeners.findIndex((e) => this.isListenerMatch(e, { type, listener, options }));
314
+ if (index !== -1) {
315
+ const { listenerProxy } = this.eventListeners[index];
316
+ this.socket.removeEventListener(type, listenerProxy, options);
317
+ this.eventListeners.splice(index, 1);
318
+ }
319
+ }
320
+ dispatchEvent(event) {
321
+ return this.socket.dispatchEvent(event);
322
+ }
323
+ }
324
+ Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
325
+ enumerable: true,
326
+ configurable: true,
327
+ writable: true,
328
+ value: WebSocket.CLOSED
329
+ });
330
+ Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
331
+ enumerable: true,
332
+ configurable: true,
333
+ writable: true,
334
+ value: WebSocket.CLOSING
335
+ });
336
+ Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
337
+ enumerable: true,
338
+ configurable: true,
339
+ writable: true,
340
+ value: WebSocket.CONNECTING
341
+ });
342
+ Object.defineProperty(ReconnectingWebSocket, "OPEN", {
343
+ enumerable: true,
344
+ configurable: true,
345
+ writable: true,
346
+ value: WebSocket.OPEN
347
+ });
348
+ /**
349
+ * Returns a promise that resolves after the specified number of ms,
350
+ * or rejects as soon as the given signal is aborted.
351
+ * @param ms - The number of ms to sleep.
352
+ * @param signal - An optional abort signal.
353
+ * @returns A promise that resolves after the specified delay.
354
+ */
355
+ function sleep(ms, signal) {
356
+ return new Promise((resolve, reject) => {
357
+ if (signal?.aborted) {
358
+ return reject(signal.reason);
359
+ }
360
+ const onAbort = function () {
361
+ clearTimeout(timer);
362
+ reject(this.reason);
363
+ };
364
+ const timer = setTimeout(() => {
365
+ signal?.removeEventListener("abort", onAbort);
366
+ resolve();
367
+ }, ms);
368
+ signal?.addEventListener("abort", onAbort, { once: true });
369
+ });
370
+ }
@@ -0,0 +1,63 @@
1
+ import { TransportError } from "../base.js";
2
+ import type { HyperliquidEventTarget } from "./hyperliquid_event_target.js";
3
+ /**
4
+ * Error thrown when a WebSocket request fails:
5
+ * - When the WebSocket connection is closed
6
+ * - When the server responds with an error message
7
+ */
8
+ export declare class WebSocketRequestError extends TransportError {
9
+ /**
10
+ * Creates a new WebSocket request error.
11
+ * @param message - The error message.
12
+ */
13
+ constructor(message: string);
14
+ }
15
+ /**
16
+ * Manages WebSocket requests to the Hyperliquid API.
17
+ * Handles request creation, sending, and mapping responses to their corresponding requests.
18
+ */
19
+ export declare class WebSocketRequestDispatcher {
20
+ protected socket: WebSocket;
21
+ /** Last used request ID */
22
+ protected lastId: number;
23
+ /** Map of pending requests waiting for responses */
24
+ protected pending: Map<number | string, {
25
+ resolve: (value: unknown) => void;
26
+ reject: (reason: unknown) => void;
27
+ }>;
28
+ /**
29
+ * Creates a new WebSocket request dispatcher.
30
+ * @param socket - WebSocket connection instance for sending requests to the Hyperliquid WebSocket API
31
+ * @param hlEvents - Used to recognize Hyperliquid responses and match them with sent requests
32
+ */
33
+ constructor(socket: WebSocket, hlEvents: HyperliquidEventTarget);
34
+ /** Gets the next request ID */
35
+ protected get nextId(): number;
36
+ /**
37
+ * Sends a request to the Hyperliquid API.
38
+ * @param method - The method of websocket request.
39
+ * @param payload - The payload to send with the request.
40
+ * @param signal - An optional abort signal.
41
+ * @returns A promise that resolves with the parsed JSON response body.
42
+ */
43
+ request(method: "post" | "subscribe" | "unsubscribe", payload: unknown, signal?: AbortSignal): Promise<unknown>;
44
+ /**
45
+ * Resolves a pending request.
46
+ * @param id - A request ID or a stringified request.
47
+ * @param value - A resolution value.
48
+ */
49
+ protected resolve(id: number | string, value: unknown): void;
50
+ /**
51
+ * Rejects a pending request.
52
+ * @param id - A request ID or a stringified request.
53
+ * @param reason - A rejection reason.
54
+ */
55
+ protected reject(id: number | string, reason: unknown): void;
56
+ /**
57
+ * Normalizes a request object to an ID.
58
+ * @param value - A request object.
59
+ * @returns A stringified request.
60
+ */
61
+ static requestToId(value: unknown): string;
62
+ }
63
+ //# sourceMappingURL=websocket_request_dispatcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket_request_dispatcher.d.ts","sourceRoot":"","sources":["../../../../src/src/transports/websocket/websocket_request_dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAE5E;;;;GAIG;AACH,qBAAa,qBAAsB,SAAQ,cAAc;IACrD;;;OAGG;gBACS,OAAO,EAAE,MAAM;CAI9B;AAED;;;GAGG;AACH,qBAAa,0BAA0B;IAevB,SAAS,CAAC,MAAM,EAAE,SAAS;IAdvC,2BAA2B;IAC3B,SAAS,CAAC,MAAM,EAAE,MAAM,CAAK;IAE7B,oDAAoD;IACpD,SAAS,CAAC,OAAO,EAAE,GAAG,CAClB,MAAM,GAAG,MAAM,EACf;QAAE,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;QAAC,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAA;KAAE,CAC3E,CAAa;IAEd;;;;OAIG;gBACmB,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,sBAAsB;IAkDzE,+BAA+B;IAC/B,SAAS,KAAK,MAAM,IAAI,MAAM,CAE7B;IAED;;;;;;OAMG;IACH,OAAO,CACH,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,aAAa,EAC5C,OAAO,EAAE,OAAO,EAChB,MAAM,CAAC,EAAE,WAAW,GACrB,OAAO,CAAC,OAAO,CAAC;IAkCnB;;;;OAIG;IACH,SAAS,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAK5D;;;;OAIG;IACH,SAAS,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAK5D;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM;CAK7C"}
@@ -0,0 +1,201 @@
1
+ import { TransportError } from "../base.js";
2
+ /**
3
+ * Error thrown when a WebSocket request fails:
4
+ * - When the WebSocket connection is closed
5
+ * - When the server responds with an error message
6
+ */
7
+ export class WebSocketRequestError extends TransportError {
8
+ /**
9
+ * Creates a new WebSocket request error.
10
+ * @param message - The error message.
11
+ */
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "WebSocketRequestError";
15
+ }
16
+ }
17
+ /**
18
+ * Manages WebSocket requests to the Hyperliquid API.
19
+ * Handles request creation, sending, and mapping responses to their corresponding requests.
20
+ */
21
+ export class WebSocketRequestDispatcher {
22
+ /**
23
+ * Creates a new WebSocket request dispatcher.
24
+ * @param socket - WebSocket connection instance for sending requests to the Hyperliquid WebSocket API
25
+ * @param hlEvents - Used to recognize Hyperliquid responses and match them with sent requests
26
+ */
27
+ constructor(socket, hlEvents) {
28
+ Object.defineProperty(this, "socket", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: socket
33
+ });
34
+ /** Last used request ID */
35
+ Object.defineProperty(this, "lastId", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: 0
40
+ });
41
+ /** Map of pending requests waiting for responses */
42
+ Object.defineProperty(this, "pending", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: new Map()
47
+ });
48
+ // Monitor responses and match the pending request
49
+ hlEvents.addEventListener("subscriptionResponse", (event) => {
50
+ // Use a stringified request as an id
51
+ const id = WebSocketRequestDispatcher.requestToId(event.detail.subscription);
52
+ this.resolve(id, event.detail);
53
+ });
54
+ hlEvents.addEventListener("post", (event) => {
55
+ const data = event.detail.response.type === "info"
56
+ ? event.detail.response.payload.data
57
+ : event.detail.response.payload;
58
+ this.resolve(event.detail.id, data);
59
+ });
60
+ hlEvents.addEventListener("error", (event) => {
61
+ try {
62
+ // Error event doesn't have an id, use original request to match
63
+ const request = event.detail.match(/{.*}/)?.[0];
64
+ if (request) {
65
+ const parsedRequest = JSON.parse(request);
66
+ if ("id" in parsedRequest && typeof parsedRequest.id === "number") {
67
+ // If a post request was sent, it is possible to get the id from the request
68
+ this.reject(parsedRequest.id, new WebSocketRequestError(event.detail));
69
+ }
70
+ else if ("subscription" in parsedRequest &&
71
+ typeof parsedRequest.subscription === "object" &&
72
+ parsedRequest.subscription !== null) {
73
+ // If a subscription/unsubscribe request was sent, use the request as an id
74
+ const id = WebSocketRequestDispatcher.requestToId(parsedRequest.subscription);
75
+ this.reject(id, new WebSocketRequestError(event.detail));
76
+ }
77
+ else {
78
+ // If the request is not recognized, use the parsed request as an id
79
+ const id = WebSocketRequestDispatcher.requestToId(parsedRequest);
80
+ this.reject(id, new WebSocketRequestError(event.detail));
81
+ }
82
+ }
83
+ }
84
+ catch {
85
+ // Ignore JSON parsing errors
86
+ }
87
+ });
88
+ // Throws all pending requests if the connection is dropped
89
+ socket.addEventListener("close", () => {
90
+ this.pending.forEach(({ reject }) => {
91
+ reject(new WebSocketRequestError("The WebSocket connection has been closed."));
92
+ });
93
+ this.pending.clear();
94
+ });
95
+ }
96
+ /** Gets the next request ID */
97
+ get nextId() {
98
+ return ++this.lastId;
99
+ }
100
+ /**
101
+ * Sends a request to the Hyperliquid API.
102
+ * @param method - The method of websocket request.
103
+ * @param payload - The payload to send with the request.
104
+ * @param signal - An optional abort signal.
105
+ * @returns A promise that resolves with the parsed JSON response body.
106
+ */
107
+ request(method, payload, signal) {
108
+ signal?.throwIfAborted();
109
+ // Create a request object
110
+ let id;
111
+ let request;
112
+ if (method === "post") {
113
+ id = this.nextId;
114
+ request = { method, id, request: payload };
115
+ }
116
+ else {
117
+ id = WebSocketRequestDispatcher.requestToId(payload);
118
+ request = { method, subscription: payload };
119
+ }
120
+ // Send the request
121
+ this.socket.send(JSON.stringify(request));
122
+ // Wait for a response
123
+ let onAbort;
124
+ return new Promise((resolve, reject) => {
125
+ // Add an abort listener
126
+ onAbort = () => reject(signal?.reason);
127
+ signal?.addEventListener("abort", onAbort, { once: true });
128
+ // Add the promise to the pending list
129
+ this.pending.set(id, { resolve, reject });
130
+ }).finally(() => {
131
+ // Remove the abort listener when the promise is settled
132
+ signal?.removeEventListener("abort", onAbort);
133
+ });
134
+ }
135
+ /**
136
+ * Resolves a pending request.
137
+ * @param id - A request ID or a stringified request.
138
+ * @param value - A resolution value.
139
+ */
140
+ resolve(id, value) {
141
+ this.pending.get(id)?.resolve(value);
142
+ this.pending.delete(id);
143
+ }
144
+ /**
145
+ * Rejects a pending request.
146
+ * @param id - A request ID or a stringified request.
147
+ * @param reason - A rejection reason.
148
+ */
149
+ reject(id, reason) {
150
+ this.pending.get(id)?.reject(reason);
151
+ this.pending.delete(id);
152
+ }
153
+ /**
154
+ * Normalizes a request object to an ID.
155
+ * @param value - A request object.
156
+ * @returns A stringified request.
157
+ */
158
+ static requestToId(value) {
159
+ const lowerHex = deepLowerHex(value);
160
+ const sorted = deepSortKeys(lowerHex);
161
+ return JSON.stringify(sorted);
162
+ }
163
+ }
164
+ /**
165
+ * Convert all hexadecimal strings to lowercase in an object/array.
166
+ * @param obj - The object/array to convert hexadecimal strings to lowercase.
167
+ * @returns A new object/array with hexadecimal strings converted to lowercase.
168
+ */
169
+ function deepLowerHex(obj) {
170
+ if (Array.isArray(obj)) {
171
+ return obj.map(deepLowerHex);
172
+ }
173
+ else if (obj && typeof obj === "object") {
174
+ return Object.entries(obj).reduce((acc, [key, val]) => ({
175
+ ...acc,
176
+ [key]: deepLowerHex(val),
177
+ }), {});
178
+ }
179
+ else if (typeof obj === "string" && /^0x[0-9A-Fa-f]+$/.test(obj)) {
180
+ return obj.toLowerCase();
181
+ }
182
+ else {
183
+ return obj;
184
+ }
185
+ }
186
+ /**
187
+ * Deeply sort the keys of an object.
188
+ * @param obj - An object to sort the keys of.
189
+ * @returns A new object with sorted keys.
190
+ */
191
+ function deepSortKeys(obj) {
192
+ if (obj === null || typeof obj !== "object") {
193
+ return obj;
194
+ }
195
+ if (Array.isArray(obj)) {
196
+ return obj.map(deepSortKeys);
197
+ }
198
+ return Object.fromEntries(Object.entries(obj)
199
+ .sort(([a], [b]) => a.localeCompare(b))
200
+ .map(([k, v]) => [k, deepSortKeys(v)]));
201
+ }