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