@gmx-io/sdk 2.7.0 → 2.9.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 (47) hide show
  1. package/build/cjs/scripts/check-eip6492-relay-signature.js +116 -0
  2. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +2 -2
  3. package/build/cjs/src/clients/v2/index.js +20 -1
  4. package/build/cjs/src/configs/contracts.js +49 -49
  5. package/build/cjs/src/utils/__tests__/numbers.spec.js +15 -0
  6. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +6 -4
  7. package/build/cjs/src/utils/express/utils/relayParamsUtils.js +9 -1
  8. package/build/cjs/src/utils/express/utils/relayParamsUtils.spec.js +21 -0
  9. package/build/cjs/src/utils/multichain/__tests__/api.spec.js +11 -7
  10. package/build/cjs/src/utils/numbers/utils.js +8 -2
  11. package/build/cjs/src/utils/prices/api.js +15 -1
  12. package/build/cjs/src/utils/stream/WsStreamClient.js +363 -0
  13. package/build/cjs/src/utils/stream/__tests__/WsStreamClient.spec.js +383 -0
  14. package/build/cjs/src/utils/stream/__tests__/stream.integration.spec.js +133 -0
  15. package/build/cjs/src/utils/stream/index.js +11 -0
  16. package/build/cjs/src/utils/stream/subscription.js +61 -0
  17. package/build/cjs/src/utils/stream/types.js +2 -0
  18. package/build/esm/scripts/check-eip6492-relay-signature.js +114 -0
  19. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +2 -2
  20. package/build/esm/src/clients/v2/index.js +21 -2
  21. package/build/esm/src/configs/contracts.js +49 -49
  22. package/build/esm/src/utils/__tests__/numbers.spec.js +15 -0
  23. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +6 -4
  24. package/build/esm/src/utils/express/utils/relayParamsUtils.js +8 -1
  25. package/build/esm/src/utils/express/utils/relayParamsUtils.spec.js +19 -0
  26. package/build/esm/src/utils/multichain/__tests__/api.spec.js +11 -7
  27. package/build/esm/src/utils/numbers/utils.js +8 -2
  28. package/build/esm/src/utils/prices/api.js +12 -0
  29. package/build/esm/src/utils/stream/WsStreamClient.js +355 -0
  30. package/build/esm/src/utils/stream/__tests__/WsStreamClient.spec.js +381 -0
  31. package/build/esm/src/utils/stream/__tests__/stream.integration.spec.js +131 -0
  32. package/build/esm/src/utils/stream/index.js +5 -0
  33. package/build/esm/src/utils/stream/subscription.js +57 -0
  34. package/build/esm/src/utils/stream/types.js +1 -0
  35. package/build/tsconfig.tsbuildinfo +1 -1
  36. package/build/types/scripts/check-eip6492-relay-signature.d.ts +1 -0
  37. package/build/types/src/clients/v2/index.d.ts +23 -5
  38. package/build/types/src/utils/express/utils/relayParamsUtils.d.ts +1 -0
  39. package/build/types/src/utils/express/utils/relayParamsUtils.spec.d.ts +1 -0
  40. package/build/types/src/utils/prices/api.d.ts +8 -0
  41. package/build/types/src/utils/stream/WsStreamClient.d.ts +63 -0
  42. package/build/types/src/utils/stream/__tests__/WsStreamClient.spec.d.ts +1 -0
  43. package/build/types/src/utils/stream/__tests__/stream.integration.spec.d.ts +1 -0
  44. package/build/types/src/utils/stream/index.d.ts +5 -0
  45. package/build/types/src/utils/stream/subscription.d.ts +3 -0
  46. package/build/types/src/utils/stream/types.d.ts +43 -0
  47. package/package.json +14 -2
@@ -0,0 +1,363 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WsStreamClient = exports.callListener = void 0;
7
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
8
+ const DEFAULT_RECONNECT_BASE_MS = 500;
9
+ const DEFAULT_RECONNECT_MAX_MS = 10000;
10
+ const DEFAULT_PROBE_INTERVAL_MS = 15000;
11
+ const DEFAULT_PROBE_TIMEOUT_MS = 10000;
12
+ const CONNECT_TIMEOUT_MS = 10000;
13
+ const IDLE_CLOSE_MS = 10000;
14
+ // a socket that stayed up this long proves the path works; one dropped sooner keeps backing off
15
+ const STABLE_CONNECTION_MS = 30000;
16
+ const REFUSED_MESSAGE = "subscription refused";
17
+ function resolveWebSocketCtor(injected) {
18
+ return injected ?? isomorphic_ws_1.default;
19
+ }
20
+ function callListener(listener, value) {
21
+ try {
22
+ listener(value);
23
+ }
24
+ catch (error) {
25
+ queueMicrotask(() => {
26
+ throw error;
27
+ });
28
+ }
29
+ }
30
+ exports.callListener = callListener;
31
+ class WsStreamClient {
32
+ constructor(params) {
33
+ this.connectionStatus = "closed";
34
+ this.listeners = new Map();
35
+ this.connectionStatusListeners = new Set();
36
+ this.lastFrameByChannel = new Map();
37
+ this.originTsByChannel = new Map();
38
+ this.refusalByChannel = new Map();
39
+ this.pendingOps = [];
40
+ this.reconnectAttempt = 0;
41
+ this.messageCount = 0;
42
+ this.closedByUser = false;
43
+ this.url = params.url;
44
+ this.WebSocketImpl = resolveWebSocketCtor(params.webSocketImpl);
45
+ this.reconnectBaseMs = params.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
46
+ this.reconnectMaxMs = params.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
47
+ this.probeIntervalMs = params.probeIntervalMs ?? DEFAULT_PROBE_INTERVAL_MS;
48
+ this.probeTimeoutMs = params.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
49
+ this.random = params.random ?? Math.random;
50
+ }
51
+ subscribe(channel, listener, onError) {
52
+ const subscriber = { onFrame: listener, onError };
53
+ clearTimeout(this.idleCloseTimer);
54
+ const existing = this.listeners.get(channel);
55
+ if (existing) {
56
+ existing.add(subscriber);
57
+ const frame = this.lastFrameByChannel.get(channel);
58
+ const refusal = this.refusalByChannel.get(channel);
59
+ queueMicrotask(() => this.replay(channel, subscriber, frame, refusal));
60
+ }
61
+ else {
62
+ this.listeners.set(channel, new Set([subscriber]));
63
+ }
64
+ this.ensureConnected();
65
+ if (!existing && this.connectionStatus === "live") {
66
+ this.sendOp("subscribe", [channel]);
67
+ }
68
+ return () => {
69
+ const current = this.listeners.get(channel);
70
+ if (!current?.delete(subscriber)) {
71
+ return;
72
+ }
73
+ if (current.size === 0) {
74
+ this.listeners.delete(channel);
75
+ this.lastFrameByChannel.delete(channel);
76
+ this.originTsByChannel.delete(channel);
77
+ this.refusalByChannel.delete(channel);
78
+ if (this.connectionStatus === "live") {
79
+ this.sendOp("unsubscribe", [channel]);
80
+ }
81
+ }
82
+ if (this.listeners.size === 0) {
83
+ this.idleCloseTimer = setTimeout(() => this.close(), IDLE_CLOSE_MS);
84
+ }
85
+ };
86
+ }
87
+ subscribeConnectionStatus(listener) {
88
+ this.connectionStatusListeners.add(listener);
89
+ return () => {
90
+ this.connectionStatusListeners.delete(listener);
91
+ };
92
+ }
93
+ ensureConnected() {
94
+ if (this.ws || this.reconnectTimer) {
95
+ return;
96
+ }
97
+ this.closedByUser = false;
98
+ this.connect();
99
+ }
100
+ canConnect() {
101
+ return !this.ws && !this.closedByUser && this.listeners.size > 0;
102
+ }
103
+ connect() {
104
+ if (!this.canConnect()) {
105
+ return;
106
+ }
107
+ this.setConnectionStatus(this.connectionStatus === "closed" ? "connecting" : "reconnecting");
108
+ if (!this.canConnect()) {
109
+ return;
110
+ }
111
+ this.pendingOps = [];
112
+ this.refusalByChannel.clear();
113
+ this.openedAt = undefined;
114
+ let ws;
115
+ try {
116
+ ws = new this.WebSocketImpl(this.url);
117
+ }
118
+ catch {
119
+ this.scheduleReconnect();
120
+ return;
121
+ }
122
+ this.ws = ws;
123
+ this.connectTimeoutTimer = setTimeout(() => {
124
+ if (this.ws === ws && this.connectionStatus !== "live") {
125
+ this.dropSocket();
126
+ this.scheduleReconnect();
127
+ }
128
+ }, CONNECT_TIMEOUT_MS);
129
+ ws.onopen = () => {
130
+ if (this.ws !== ws) {
131
+ return;
132
+ }
133
+ clearTimeout(this.connectTimeoutTimer);
134
+ this.openedAt = Date.now();
135
+ const channels = [...this.listeners.keys()];
136
+ if (channels.length) {
137
+ this.sendOp("subscribe", channels);
138
+ }
139
+ this.setConnectionStatus("live");
140
+ };
141
+ ws.onmessage = (ev) => {
142
+ if (this.ws === ws) {
143
+ this.onMessage(ev.data);
144
+ }
145
+ };
146
+ ws.onclose = () => {
147
+ if (this.ws === ws) {
148
+ this.onClose();
149
+ }
150
+ };
151
+ ws.onerror = () => {
152
+ // a close event always follows; reconnection is handled there
153
+ };
154
+ }
155
+ onMessage(raw) {
156
+ this.messageCount += 1;
157
+ const text = typeof raw === "string" ? raw : String(raw);
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(text);
161
+ }
162
+ catch {
163
+ return;
164
+ }
165
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
166
+ return;
167
+ }
168
+ const frame = parsed;
169
+ if ("op" in frame) {
170
+ this.onOp(frame);
171
+ return;
172
+ }
173
+ if (frame.type !== "snapshot") {
174
+ return;
175
+ }
176
+ if (frame.data === undefined) {
177
+ return;
178
+ }
179
+ const set = this.listeners.get(frame.ch);
180
+ if (!set) {
181
+ return;
182
+ }
183
+ if (typeof frame.originTs === "number") {
184
+ const newest = this.originTsByChannel.get(frame.ch);
185
+ if (newest !== undefined && frame.originTs < newest) {
186
+ return;
187
+ }
188
+ this.originTsByChannel.set(frame.ch, frame.originTs);
189
+ }
190
+ const payload = {
191
+ data: frame.data,
192
+ serverTs: frame.serverTs,
193
+ originTs: frame.originTs,
194
+ receivedAt: Date.now(),
195
+ };
196
+ this.lastFrameByChannel.set(frame.ch, payload);
197
+ this.refusalByChannel.delete(frame.ch);
198
+ for (const subscriber of set) {
199
+ callListener(subscriber.onFrame, payload);
200
+ }
201
+ }
202
+ onOp(frame) {
203
+ if (frame.op === "error") {
204
+ if (!Array.isArray(frame.channels)) {
205
+ return;
206
+ }
207
+ const pending = this.pendingOps[0];
208
+ for (const channel of frame.channels) {
209
+ if (pending?.op === "subscribe") {
210
+ pending.channels = pending.channels.filter((requested) => requested !== channel);
211
+ }
212
+ this.refuse(channel, frame.message);
213
+ }
214
+ return;
215
+ }
216
+ if (frame.op !== "ack") {
217
+ return;
218
+ }
219
+ const pending = this.pendingOps.shift();
220
+ if (pending?.op !== "subscribe" || !Array.isArray(frame.channels)) {
221
+ return;
222
+ }
223
+ for (const channel of pending.channels) {
224
+ if (!frame.channels.includes(channel)) {
225
+ this.refuse(channel, REFUSED_MESSAGE);
226
+ }
227
+ }
228
+ }
229
+ refuse(channel, message) {
230
+ const set = this.listeners.get(channel);
231
+ if (!set) {
232
+ return;
233
+ }
234
+ const error = { message };
235
+ this.refusalByChannel.set(channel, error);
236
+ for (const subscriber of set) {
237
+ if (subscriber.onError) {
238
+ callListener(subscriber.onError, error);
239
+ }
240
+ }
241
+ }
242
+ replay(channel, subscriber, frame, refusal) {
243
+ if (!this.listeners.get(channel)?.has(subscriber)) {
244
+ return;
245
+ }
246
+ // only while still current: anything newer already reached this subscriber directly
247
+ if (frame && frame === this.lastFrameByChannel.get(channel)) {
248
+ callListener(subscriber.onFrame, frame);
249
+ }
250
+ if (refusal && refusal === this.refusalByChannel.get(channel) && subscriber.onError) {
251
+ callListener(subscriber.onError, refusal);
252
+ }
253
+ }
254
+ onClose() {
255
+ this.ws = undefined;
256
+ clearTimeout(this.connectTimeoutTimer);
257
+ this.noteSocketEnded();
258
+ if (this.closedByUser || this.listeners.size === 0) {
259
+ this.setConnectionStatus("closed");
260
+ return;
261
+ }
262
+ this.scheduleReconnect();
263
+ }
264
+ noteSocketEnded() {
265
+ if (this.openedAt !== undefined && Date.now() - this.openedAt >= STABLE_CONNECTION_MS) {
266
+ this.reconnectAttempt = 0;
267
+ }
268
+ this.openedAt = undefined;
269
+ }
270
+ scheduleReconnect() {
271
+ const ceiling = Math.min(this.reconnectMaxMs, this.reconnectBaseMs * 2 ** this.reconnectAttempt);
272
+ this.reconnectAttempt += 1;
273
+ this.reconnectTimer = setTimeout(() => {
274
+ this.reconnectTimer = undefined;
275
+ this.connect();
276
+ }, ceiling / 2 + (this.random() * ceiling) / 2);
277
+ this.setConnectionStatus("reconnecting");
278
+ }
279
+ startProbe() {
280
+ this.probeTimer = setTimeout(() => {
281
+ const messagesAtProbe = this.messageCount;
282
+ this.sendOp("subscribe", []);
283
+ if (!this.probeTimeoutTimer) {
284
+ this.probeTimeoutTimer = setTimeout(() => {
285
+ this.probeTimeoutTimer = undefined;
286
+ if (this.messageCount === messagesAtProbe) {
287
+ this.dropSocket();
288
+ this.noteSocketEnded();
289
+ this.scheduleReconnect();
290
+ }
291
+ }, this.probeTimeoutMs);
292
+ }
293
+ this.startProbe();
294
+ }, this.probeIntervalMs);
295
+ }
296
+ stopProbe() {
297
+ clearTimeout(this.probeTimer);
298
+ clearTimeout(this.probeTimeoutTimer);
299
+ this.probeTimer = undefined;
300
+ this.probeTimeoutTimer = undefined;
301
+ }
302
+ sendOp(op, channels) {
303
+ try {
304
+ this.ws?.send(JSON.stringify({ op, channels }));
305
+ this.pendingOps.push({ op, channels });
306
+ }
307
+ catch {
308
+ // socket raced into a non-open state; resubscribe runs on reconnect
309
+ }
310
+ }
311
+ setConnectionStatus(status) {
312
+ if (this.connectionStatus === status) {
313
+ return;
314
+ }
315
+ this.connectionStatus = status;
316
+ if (status === "live") {
317
+ this.startProbe();
318
+ }
319
+ else {
320
+ this.stopProbe();
321
+ }
322
+ for (const listener of this.connectionStatusListeners) {
323
+ if (this.connectionStatus !== status) {
324
+ return;
325
+ }
326
+ callListener(listener, status);
327
+ }
328
+ }
329
+ dropSocket() {
330
+ const ws = this.ws;
331
+ this.ws = undefined;
332
+ clearTimeout(this.connectTimeoutTimer);
333
+ if (!ws) {
334
+ return;
335
+ }
336
+ // onerror stays attached: ws in Node throws on an unhandled "error" when a CONNECTING socket is closed
337
+ ws.onopen = null;
338
+ ws.onmessage = null;
339
+ ws.onclose = null;
340
+ try {
341
+ ws.close();
342
+ }
343
+ catch {
344
+ // already closing
345
+ }
346
+ }
347
+ close() {
348
+ this.closedByUser = true;
349
+ clearTimeout(this.idleCloseTimer);
350
+ if (this.reconnectTimer) {
351
+ clearTimeout(this.reconnectTimer);
352
+ this.reconnectTimer = undefined;
353
+ }
354
+ this.listeners.clear();
355
+ this.lastFrameByChannel.clear();
356
+ this.originTsByChannel.clear();
357
+ this.refusalByChannel.clear();
358
+ this.reconnectAttempt = 0;
359
+ this.dropSocket();
360
+ this.setConnectionStatus("closed");
361
+ }
362
+ }
363
+ exports.WsStreamClient = WsStreamClient;