@gmx-io/sdk 2.7.0 → 2.8.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.
- package/build/cjs/src/clients/v2/index.js +20 -1
- package/build/cjs/src/utils/__tests__/numbers.spec.js +15 -0
- package/build/cjs/src/utils/numbers/utils.js +8 -2
- package/build/cjs/src/utils/prices/api.js +15 -1
- package/build/cjs/src/utils/stream/WsStreamClient.js +363 -0
- package/build/cjs/src/utils/stream/__tests__/WsStreamClient.spec.js +383 -0
- package/build/cjs/src/utils/stream/__tests__/stream.integration.spec.js +133 -0
- package/build/cjs/src/utils/stream/index.js +11 -0
- package/build/cjs/src/utils/stream/subscription.js +61 -0
- package/build/cjs/src/utils/stream/types.js +2 -0
- package/build/esm/src/clients/v2/index.js +21 -2
- package/build/esm/src/utils/__tests__/numbers.spec.js +15 -0
- package/build/esm/src/utils/numbers/utils.js +8 -2
- package/build/esm/src/utils/prices/api.js +12 -0
- package/build/esm/src/utils/stream/WsStreamClient.js +355 -0
- package/build/esm/src/utils/stream/__tests__/WsStreamClient.spec.js +381 -0
- package/build/esm/src/utils/stream/__tests__/stream.integration.spec.js +131 -0
- package/build/esm/src/utils/stream/index.js +5 -0
- package/build/esm/src/utils/stream/subscription.js +57 -0
- package/build/esm/src/utils/stream/types.js +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/clients/v2/index.d.ts +23 -5
- package/build/types/src/utils/prices/api.d.ts +8 -0
- package/build/types/src/utils/stream/WsStreamClient.d.ts +63 -0
- package/build/types/src/utils/stream/__tests__/WsStreamClient.spec.d.ts +1 -0
- package/build/types/src/utils/stream/__tests__/stream.integration.spec.d.ts +1 -0
- package/build/types/src/utils/stream/index.d.ts +5 -0
- package/build/types/src/utils/stream/subscription.d.ts +3 -0
- package/build/types/src/utils/stream/types.d.ts +43 -0
- package/package.json +14 -2
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const vitest_1 = require("vitest");
|
|
4
|
+
const WsStreamClient_1 = require("../WsStreamClient");
|
|
5
|
+
const OPEN = 1;
|
|
6
|
+
const CLOSED = 3;
|
|
7
|
+
class FakeSocket {
|
|
8
|
+
constructor(url) {
|
|
9
|
+
this.url = url;
|
|
10
|
+
this.readyState = 0;
|
|
11
|
+
this.onopen = null;
|
|
12
|
+
this.onmessage = null;
|
|
13
|
+
this.onclose = null;
|
|
14
|
+
this.onerror = null;
|
|
15
|
+
this.send = vitest_1.vi.fn();
|
|
16
|
+
this.close = vitest_1.vi.fn(() => {
|
|
17
|
+
this.readyState = CLOSED;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
open() {
|
|
21
|
+
this.readyState = OPEN;
|
|
22
|
+
this.onopen?.({});
|
|
23
|
+
}
|
|
24
|
+
emit(frame) {
|
|
25
|
+
this.onmessage?.({ data: typeof frame === "string" ? frame : JSON.stringify(frame) });
|
|
26
|
+
}
|
|
27
|
+
emitRaw(data) {
|
|
28
|
+
this.onmessage?.({ data });
|
|
29
|
+
}
|
|
30
|
+
serverClose() {
|
|
31
|
+
this.readyState = CLOSED;
|
|
32
|
+
this.onclose?.({});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function makeWsImpl(opts = {}) {
|
|
36
|
+
const sockets = [];
|
|
37
|
+
const failFirst = opts.failFirst ?? 0;
|
|
38
|
+
let attempts = 0;
|
|
39
|
+
const Ctor = vitest_1.vi.fn(function (url) {
|
|
40
|
+
attempts += 1;
|
|
41
|
+
if (attempts <= failFirst) {
|
|
42
|
+
throw new Error("connect failed");
|
|
43
|
+
}
|
|
44
|
+
const socket = new FakeSocket(url);
|
|
45
|
+
sockets.push(socket);
|
|
46
|
+
return socket;
|
|
47
|
+
});
|
|
48
|
+
return { Ctor, sockets, getAttempts: () => attempts };
|
|
49
|
+
}
|
|
50
|
+
const URL = "ws://localhost:3004/v1/stream";
|
|
51
|
+
function makeClient(opts = {}) {
|
|
52
|
+
const impl = makeWsImpl({ failFirst: opts.failFirst });
|
|
53
|
+
const client = new WsStreamClient_1.WsStreamClient({
|
|
54
|
+
url: URL,
|
|
55
|
+
webSocketImpl: impl.Ctor,
|
|
56
|
+
reconnectBaseMs: opts.reconnectBaseMs,
|
|
57
|
+
reconnectMaxMs: opts.reconnectMaxMs,
|
|
58
|
+
probeIntervalMs: opts.probeIntervalMs,
|
|
59
|
+
random: opts.random ?? (() => 1),
|
|
60
|
+
});
|
|
61
|
+
return { client, ...impl };
|
|
62
|
+
}
|
|
63
|
+
function parseSends(socket) {
|
|
64
|
+
return socket.send.mock.calls.map((call) => JSON.parse(call[0]));
|
|
65
|
+
}
|
|
66
|
+
(0, vitest_1.beforeEach)(() => {
|
|
67
|
+
vitest_1.vi.useFakeTimers();
|
|
68
|
+
});
|
|
69
|
+
(0, vitest_1.afterEach)(() => {
|
|
70
|
+
vitest_1.vi.clearAllTimers();
|
|
71
|
+
vitest_1.vi.useRealTimers();
|
|
72
|
+
vitest_1.vi.unstubAllGlobals();
|
|
73
|
+
vitest_1.vi.restoreAllMocks();
|
|
74
|
+
});
|
|
75
|
+
(0, vitest_1.describe)("WsStreamClient connection", () => {
|
|
76
|
+
(0, vitest_1.it)("connects on first subscribe and transitions connecting -> live", () => {
|
|
77
|
+
const { client, sockets, getAttempts } = makeClient();
|
|
78
|
+
const statuses = [];
|
|
79
|
+
client.subscribeConnectionStatus((s) => statuses.push(s));
|
|
80
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
81
|
+
(0, vitest_1.expect)(getAttempts()).toBe(1);
|
|
82
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("connecting");
|
|
83
|
+
sockets[0].open();
|
|
84
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("live");
|
|
85
|
+
(0, vitest_1.expect)(statuses).toEqual(["connecting", "live"]);
|
|
86
|
+
});
|
|
87
|
+
(0, vitest_1.it)("sends subscribe for all channels on open", () => {
|
|
88
|
+
const { client, sockets } = makeClient();
|
|
89
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
90
|
+
client.subscribe("candles", vitest_1.vi.fn());
|
|
91
|
+
sockets[0].open();
|
|
92
|
+
(0, vitest_1.expect)(parseSends(sockets[0])).toContainEqual({ op: "subscribe", channels: ["prices", "candles"] });
|
|
93
|
+
});
|
|
94
|
+
(0, vitest_1.it)("sends subscribe immediately when subscribing while already live", () => {
|
|
95
|
+
const { client, sockets } = makeClient();
|
|
96
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
97
|
+
sockets[0].open();
|
|
98
|
+
sockets[0].send.mockClear();
|
|
99
|
+
client.subscribe("candles", vitest_1.vi.fn());
|
|
100
|
+
(0, vitest_1.expect)(parseSends(sockets[0])).toContainEqual({ op: "subscribe", channels: ["candles"] });
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
(0, vitest_1.describe)("WsStreamClient messages", () => {
|
|
104
|
+
function connected() {
|
|
105
|
+
const ctx = makeClient();
|
|
106
|
+
const listener = vitest_1.vi.fn();
|
|
107
|
+
ctx.client.subscribe("prices", listener);
|
|
108
|
+
ctx.sockets[0].open();
|
|
109
|
+
listener.mockClear();
|
|
110
|
+
return { ...ctx, listener };
|
|
111
|
+
}
|
|
112
|
+
(0, vitest_1.it)("delivers a snapshot frame to the channel listener with meta", () => {
|
|
113
|
+
const { sockets, listener } = connected();
|
|
114
|
+
sockets[0].emit({ ch: "prices", type: "snapshot", serverTs: 1000, originTs: 900, data: { p: 1 } });
|
|
115
|
+
(0, vitest_1.expect)(listener).toHaveBeenCalledTimes(1);
|
|
116
|
+
(0, vitest_1.expect)(listener).toHaveBeenCalledWith(vitest_1.expect.objectContaining({
|
|
117
|
+
data: { p: 1 },
|
|
118
|
+
serverTs: 1000,
|
|
119
|
+
originTs: 900,
|
|
120
|
+
receivedAt: vitest_1.expect.any(Number),
|
|
121
|
+
}));
|
|
122
|
+
});
|
|
123
|
+
vitest_1.it.each([
|
|
124
|
+
["a frame for an unsubscribed channel", JSON.stringify({ ch: "candles", type: "snapshot", serverTs: 1, data: {} })],
|
|
125
|
+
["a non-snapshot frame", JSON.stringify({ ch: "prices", type: "delta", serverTs: 1, data: {} })],
|
|
126
|
+
["a snapshot without data", JSON.stringify({ ch: "prices", type: "snapshot", serverTs: 1 })],
|
|
127
|
+
["an ack", JSON.stringify({ op: "ack", channels: ["prices"] })],
|
|
128
|
+
["an error without channels", JSON.stringify({ op: "error", message: "x" })],
|
|
129
|
+
["invalid JSON", "{ not json"],
|
|
130
|
+
["JSON null", "null"],
|
|
131
|
+
["a JSON number", "42"],
|
|
132
|
+
["a JSON array", "[]"],
|
|
133
|
+
])("ignores %s and delivers the next frame, sent as a Buffer", (_, data) => {
|
|
134
|
+
const { sockets, listener } = connected();
|
|
135
|
+
sockets[0].emitRaw(data);
|
|
136
|
+
(0, vitest_1.expect)(listener).not.toHaveBeenCalled();
|
|
137
|
+
sockets[0].emitRaw(Buffer.from(JSON.stringify({ ch: "prices", type: "snapshot", serverTs: 2, data: 42 })));
|
|
138
|
+
(0, vitest_1.expect)(listener).toHaveBeenCalledTimes(1);
|
|
139
|
+
(0, vitest_1.expect)(listener).toHaveBeenCalledWith(vitest_1.expect.objectContaining({ data: 42 }));
|
|
140
|
+
});
|
|
141
|
+
vitest_1.it.each([
|
|
142
|
+
{ held: 1000, next: 2000, applied: true },
|
|
143
|
+
{ held: 1000, next: 1000, applied: true },
|
|
144
|
+
{ held: 1000, next: 999, applied: false },
|
|
145
|
+
{ held: 1000, next: undefined, applied: true },
|
|
146
|
+
{ held: undefined, next: 5, applied: true },
|
|
147
|
+
])("after a reconnect applies a frame with originTs $next over $held: $applied", ({ held, next, applied }) => {
|
|
148
|
+
const { client, sockets } = makeClient();
|
|
149
|
+
const listener = vitest_1.vi.fn();
|
|
150
|
+
client.subscribe("prices", listener);
|
|
151
|
+
sockets[0].open();
|
|
152
|
+
sockets[0].emit({ ch: "prices", type: "snapshot", serverTs: 1, originTs: held, data: "held" });
|
|
153
|
+
sockets[0].serverClose();
|
|
154
|
+
vitest_1.vi.advanceTimersByTime(500);
|
|
155
|
+
sockets[1].open();
|
|
156
|
+
sockets[1].emit({ ch: "prices", type: "snapshot", serverTs: 2, originTs: next, data: "next" });
|
|
157
|
+
(0, vitest_1.expect)(listener).toHaveBeenLastCalledWith(vitest_1.expect.objectContaining({ data: applied ? "next" : "held" }));
|
|
158
|
+
});
|
|
159
|
+
const CANDLES = "candles:ETH:1m";
|
|
160
|
+
vitest_1.it.each([
|
|
161
|
+
{
|
|
162
|
+
name: "an error naming the channel, then the ack",
|
|
163
|
+
probe: false,
|
|
164
|
+
frames: [
|
|
165
|
+
{ op: "error", message: "subscription limit reached", channels: [CANDLES] },
|
|
166
|
+
{ op: "ack", channels: ["prices"] },
|
|
167
|
+
],
|
|
168
|
+
refusals: ["subscription limit reached"],
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
name: "an old server's error without channels, then an ack without the channel",
|
|
172
|
+
probe: false,
|
|
173
|
+
frames: [
|
|
174
|
+
{ op: "error", message: "subscription limit reached" },
|
|
175
|
+
{ op: "ack", channels: ["prices"] },
|
|
176
|
+
],
|
|
177
|
+
refusals: ["subscription refused"],
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
name: "the ack of a probe sent before the channel's subscribe",
|
|
181
|
+
probe: true,
|
|
182
|
+
frames: [
|
|
183
|
+
{ op: "ack", channels: ["prices"] },
|
|
184
|
+
{ op: "ack", channels: ["prices", CANDLES] },
|
|
185
|
+
],
|
|
186
|
+
refusals: [],
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
name: "an unknown op before the ack",
|
|
190
|
+
probe: false,
|
|
191
|
+
frames: [{ op: "heartbeat" }, { op: "ack", channels: ["prices", CANDLES] }],
|
|
192
|
+
refusals: [],
|
|
193
|
+
},
|
|
194
|
+
])("matches acks and errors to the ops that caused them: $name", ({ probe, frames, refusals }) => {
|
|
195
|
+
const { client, sockets } = makeClient();
|
|
196
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
197
|
+
sockets[0].open();
|
|
198
|
+
sockets[0].emit({ op: "ack", channels: ["prices"] });
|
|
199
|
+
if (probe) {
|
|
200
|
+
vitest_1.vi.advanceTimersByTime(15000);
|
|
201
|
+
}
|
|
202
|
+
const onError = vitest_1.vi.fn();
|
|
203
|
+
client.subscribe(CANDLES, vitest_1.vi.fn(), onError);
|
|
204
|
+
frames.forEach((frame) => sockets[0].emit(frame));
|
|
205
|
+
(0, vitest_1.expect)(onError.mock.calls.map(([error]) => error.message)).toEqual(refusals);
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
(0, vitest_1.describe)("WsStreamClient reconnect / backoff", () => {
|
|
209
|
+
vitest_1.it.each([
|
|
210
|
+
{ jitter: "lowest", random: 0, delays: [50, 100, 200, 200] },
|
|
211
|
+
{ jitter: "middle", random: 0.5, delays: [75, 150, 300, 300] },
|
|
212
|
+
{ jitter: "highest", random: 1, delays: [100, 200, 400, 400] },
|
|
213
|
+
])("backs off with equal jitter capped at the max ($jitter)", ({ random, delays }) => {
|
|
214
|
+
const { client, getAttempts } = makeClient({
|
|
215
|
+
failFirst: 5,
|
|
216
|
+
reconnectBaseMs: 100,
|
|
217
|
+
reconnectMaxMs: 400,
|
|
218
|
+
random: () => random,
|
|
219
|
+
});
|
|
220
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
221
|
+
delays.forEach((delay, index) => {
|
|
222
|
+
vitest_1.vi.advanceTimersByTime(delay - 1);
|
|
223
|
+
(0, vitest_1.expect)(getAttempts()).toBe(index + 1);
|
|
224
|
+
vitest_1.vi.advanceTimersByTime(1);
|
|
225
|
+
(0, vitest_1.expect)(getAttempts()).toBe(index + 2);
|
|
226
|
+
});
|
|
227
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("reconnecting");
|
|
228
|
+
});
|
|
229
|
+
(0, vitest_1.it)("keeps backing off while sockets drop soon after opening, and resets after one stayed up 30 s", () => {
|
|
230
|
+
const { client, sockets, getAttempts } = makeClient({
|
|
231
|
+
reconnectBaseMs: 100,
|
|
232
|
+
reconnectMaxMs: 400,
|
|
233
|
+
probeIntervalMs: 60000,
|
|
234
|
+
});
|
|
235
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
236
|
+
sockets[0].open();
|
|
237
|
+
sockets[0].emit({ op: "ack", channels: ["prices"] });
|
|
238
|
+
sockets[0].serverClose();
|
|
239
|
+
vitest_1.vi.advanceTimersByTime(100);
|
|
240
|
+
sockets[1].open();
|
|
241
|
+
sockets[1].emit({ op: "ack", channels: ["prices"] });
|
|
242
|
+
sockets[1].serverClose();
|
|
243
|
+
vitest_1.vi.advanceTimersByTime(199);
|
|
244
|
+
(0, vitest_1.expect)(getAttempts()).toBe(2);
|
|
245
|
+
vitest_1.vi.advanceTimersByTime(1);
|
|
246
|
+
(0, vitest_1.expect)(getAttempts()).toBe(3);
|
|
247
|
+
sockets[2].open();
|
|
248
|
+
vitest_1.vi.advanceTimersByTime(30000);
|
|
249
|
+
sockets[2].serverClose();
|
|
250
|
+
vitest_1.vi.advanceTimersByTime(99);
|
|
251
|
+
(0, vitest_1.expect)(getAttempts()).toBe(3);
|
|
252
|
+
vitest_1.vi.advanceTimersByTime(1);
|
|
253
|
+
(0, vitest_1.expect)(getAttempts()).toBe(4);
|
|
254
|
+
});
|
|
255
|
+
(0, vitest_1.it)("probes a live socket every 15 s and replaces it with backoff when a probe goes unanswered", () => {
|
|
256
|
+
const { client, sockets, getAttempts } = makeClient();
|
|
257
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
258
|
+
sockets[0].open();
|
|
259
|
+
sockets[0].send.mockClear();
|
|
260
|
+
vitest_1.vi.advanceTimersByTime(15000);
|
|
261
|
+
(0, vitest_1.expect)(parseSends(sockets[0])).toEqual([{ op: "subscribe", channels: [] }]);
|
|
262
|
+
sockets[0].emit({ op: "ack", channels: ["prices"] });
|
|
263
|
+
vitest_1.vi.advanceTimersByTime(10000);
|
|
264
|
+
(0, vitest_1.expect)(sockets[0].close).not.toHaveBeenCalled();
|
|
265
|
+
vitest_1.vi.advanceTimersByTime(15000);
|
|
266
|
+
(0, vitest_1.expect)(sockets[0].close).toHaveBeenCalled();
|
|
267
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("reconnecting");
|
|
268
|
+
vitest_1.vi.advanceTimersByTime(499);
|
|
269
|
+
(0, vitest_1.expect)(getAttempts()).toBe(1);
|
|
270
|
+
vitest_1.vi.advanceTimersByTime(1);
|
|
271
|
+
(0, vitest_1.expect)(getAttempts()).toBe(2);
|
|
272
|
+
});
|
|
273
|
+
(0, vitest_1.it)("does not double-connect while a reconnect is pending", () => {
|
|
274
|
+
const { client, getAttempts } = makeClient({ failFirst: 1 });
|
|
275
|
+
client.subscribe("prices", vitest_1.vi.fn()); // attempt 1 throws -> reconnect pending
|
|
276
|
+
client.subscribe("candles", vitest_1.vi.fn()); // must not trigger a second connect now
|
|
277
|
+
(0, vitest_1.expect)(getAttempts()).toBe(1);
|
|
278
|
+
});
|
|
279
|
+
(0, vitest_1.it)("re-subscribes all channels on reconnect", () => {
|
|
280
|
+
const { client, sockets } = makeClient();
|
|
281
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
282
|
+
client.subscribe("candles", vitest_1.vi.fn());
|
|
283
|
+
sockets[0].open();
|
|
284
|
+
sockets[0].serverClose();
|
|
285
|
+
vitest_1.vi.advanceTimersByTime(500);
|
|
286
|
+
sockets[1].open();
|
|
287
|
+
(0, vitest_1.expect)(parseSends(sockets[1])).toContainEqual({ op: "subscribe", channels: ["prices", "candles"] });
|
|
288
|
+
});
|
|
289
|
+
(0, vitest_1.it)("ignores a closed socket's late close event after a resubscribe", () => {
|
|
290
|
+
const { client, sockets, getAttempts } = makeClient();
|
|
291
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
292
|
+
sockets[0].open();
|
|
293
|
+
client.close();
|
|
294
|
+
const listener = vitest_1.vi.fn();
|
|
295
|
+
client.subscribe("prices", listener);
|
|
296
|
+
sockets[0].serverClose();
|
|
297
|
+
vitest_1.vi.advanceTimersByTime(1000);
|
|
298
|
+
sockets[1].open();
|
|
299
|
+
sockets[1].emit({ ch: "prices", type: "snapshot", serverTs: 1, data: 1 });
|
|
300
|
+
(0, vitest_1.expect)(getAttempts()).toBe(2);
|
|
301
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("live");
|
|
302
|
+
(0, vitest_1.expect)(listener).toHaveBeenCalledTimes(1);
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
(0, vitest_1.describe)("WsStreamClient unsubscribe / lifecycle", () => {
|
|
306
|
+
(0, vitest_1.it)("sends unsubscribe and closes 10 s after the last channel is dropped", () => {
|
|
307
|
+
const { client, sockets } = makeClient();
|
|
308
|
+
const unsub = client.subscribe("prices", vitest_1.vi.fn());
|
|
309
|
+
sockets[0].open();
|
|
310
|
+
sockets[0].send.mockClear();
|
|
311
|
+
unsub();
|
|
312
|
+
(0, vitest_1.expect)(parseSends(sockets[0])).toContainEqual({ op: "unsubscribe", channels: ["prices"] });
|
|
313
|
+
vitest_1.vi.advanceTimersByTime(9999);
|
|
314
|
+
(0, vitest_1.expect)(sockets[0].close).not.toHaveBeenCalled();
|
|
315
|
+
vitest_1.vi.advanceTimersByTime(1);
|
|
316
|
+
(0, vitest_1.expect)(sockets[0].close).toHaveBeenCalled();
|
|
317
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("closed");
|
|
318
|
+
});
|
|
319
|
+
(0, vitest_1.it)("keeps the socket for a channel subscribed within 10 s of the last one dropped", () => {
|
|
320
|
+
const { client, sockets } = makeClient();
|
|
321
|
+
const unsub = client.subscribe("prices", vitest_1.vi.fn());
|
|
322
|
+
sockets[0].open();
|
|
323
|
+
unsub();
|
|
324
|
+
vitest_1.vi.advanceTimersByTime(9999);
|
|
325
|
+
client.subscribe("candles:ETH:1m", vitest_1.vi.fn());
|
|
326
|
+
vitest_1.vi.advanceTimersByTime(10000);
|
|
327
|
+
(0, vitest_1.expect)(sockets.length).toBe(1);
|
|
328
|
+
(0, vitest_1.expect)(sockets[0].close).not.toHaveBeenCalled();
|
|
329
|
+
(0, vitest_1.expect)(parseSends(sockets[0])).toContainEqual({ op: "subscribe", channels: ["candles:ETH:1m"] });
|
|
330
|
+
});
|
|
331
|
+
(0, vitest_1.it)("keeps the channel while another listener remains", () => {
|
|
332
|
+
const { client, sockets } = makeClient();
|
|
333
|
+
const off1 = client.subscribe("prices", vitest_1.vi.fn());
|
|
334
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
335
|
+
sockets[0].open();
|
|
336
|
+
sockets[0].send.mockClear();
|
|
337
|
+
off1();
|
|
338
|
+
(0, vitest_1.expect)(sockets[0].send).not.toHaveBeenCalled();
|
|
339
|
+
(0, vitest_1.expect)(sockets[0].close).not.toHaveBeenCalled();
|
|
340
|
+
});
|
|
341
|
+
(0, vitest_1.it)("closes without sending unsubscribe when not yet live", () => {
|
|
342
|
+
const { client, sockets } = makeClient();
|
|
343
|
+
const unsub = client.subscribe("prices", vitest_1.vi.fn()); // connecting (not open)
|
|
344
|
+
unsub();
|
|
345
|
+
vitest_1.vi.advanceTimersByTime(10000);
|
|
346
|
+
(0, vitest_1.expect)(sockets[0].send).not.toHaveBeenCalled();
|
|
347
|
+
(0, vitest_1.expect)(sockets[0].close).toHaveBeenCalled();
|
|
348
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("closed");
|
|
349
|
+
});
|
|
350
|
+
(0, vitest_1.it)("close() stops a pending reconnect", () => {
|
|
351
|
+
const { client, getAttempts } = makeClient({ failFirst: 1 });
|
|
352
|
+
client.subscribe("prices", vitest_1.vi.fn()); // reconnect pending
|
|
353
|
+
client.close();
|
|
354
|
+
vitest_1.vi.advanceTimersByTime(5000);
|
|
355
|
+
(0, vitest_1.expect)(getAttempts()).toBe(1);
|
|
356
|
+
(0, vitest_1.expect)(client.connectionStatus).toBe("closed");
|
|
357
|
+
});
|
|
358
|
+
(0, vitest_1.it)("drops late frames after close", () => {
|
|
359
|
+
const { client, sockets } = makeClient();
|
|
360
|
+
const listener = vitest_1.vi.fn();
|
|
361
|
+
client.subscribe("prices", listener);
|
|
362
|
+
sockets[0].open();
|
|
363
|
+
client.close();
|
|
364
|
+
listener.mockClear();
|
|
365
|
+
sockets[0].emit({ ch: "prices", type: "snapshot", serverTs: 1, data: {} });
|
|
366
|
+
(0, vitest_1.expect)(listener).not.toHaveBeenCalled();
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
(0, vitest_1.describe)("WsStreamClient status listeners", () => {
|
|
370
|
+
(0, vitest_1.it)("notifies on transitions and stops after removal", () => {
|
|
371
|
+
const { client, sockets } = makeClient();
|
|
372
|
+
const cb = vitest_1.vi.fn();
|
|
373
|
+
const remove = client.subscribeConnectionStatus(cb);
|
|
374
|
+
client.subscribe("prices", vitest_1.vi.fn());
|
|
375
|
+
sockets[0].open();
|
|
376
|
+
(0, vitest_1.expect)(cb).toHaveBeenCalledWith("connecting");
|
|
377
|
+
(0, vitest_1.expect)(cb).toHaveBeenCalledWith("live");
|
|
378
|
+
remove();
|
|
379
|
+
cb.mockClear();
|
|
380
|
+
sockets[0].serverClose();
|
|
381
|
+
(0, vitest_1.expect)(cb).not.toHaveBeenCalled();
|
|
382
|
+
});
|
|
383
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const vitest_1 = require("vitest");
|
|
4
|
+
const ws_1 = require("ws");
|
|
5
|
+
const v2_1 = require("../../../clients/v2");
|
|
6
|
+
const ARBITRUM = 42161;
|
|
7
|
+
function startServer() {
|
|
8
|
+
const wss = new ws_1.WebSocketServer({ port: 0, path: "/v1/stream" });
|
|
9
|
+
const received = [];
|
|
10
|
+
const connections = [];
|
|
11
|
+
wss.on("connection", (socket) => {
|
|
12
|
+
connections.push(socket);
|
|
13
|
+
const channels = new Set();
|
|
14
|
+
socket.on("message", (raw) => {
|
|
15
|
+
let message;
|
|
16
|
+
try {
|
|
17
|
+
message = JSON.parse(raw.toString());
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
received.push(message);
|
|
23
|
+
for (const channel of message.channels ?? []) {
|
|
24
|
+
if (message.op === "subscribe") {
|
|
25
|
+
channels.add(channel);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
channels.delete(channel);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
socket.send(JSON.stringify({ op: "ack", channels: [...channels] }));
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
received,
|
|
36
|
+
connections,
|
|
37
|
+
async ready() {
|
|
38
|
+
await new Promise((resolve) => wss.once("listening", () => resolve()));
|
|
39
|
+
return wss.address().port;
|
|
40
|
+
},
|
|
41
|
+
broadcast(frame) {
|
|
42
|
+
const data = JSON.stringify(frame);
|
|
43
|
+
for (const socket of connections) {
|
|
44
|
+
if (socket.readyState === ws_1.WebSocket.OPEN) {
|
|
45
|
+
socket.send(data);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
subscribeCount() {
|
|
50
|
+
return received.filter((m) => m.op === "subscribe").length;
|
|
51
|
+
},
|
|
52
|
+
async close() {
|
|
53
|
+
connections.forEach((socket) => socket.terminate());
|
|
54
|
+
await new Promise((resolve) => wss.close(() => resolve()));
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const snapshot = (min, max) => ({
|
|
59
|
+
ch: "prices",
|
|
60
|
+
type: "snapshot",
|
|
61
|
+
serverTs: 1,
|
|
62
|
+
data: { "0xabc": { minPrice: min, maxPrice: max } },
|
|
63
|
+
});
|
|
64
|
+
(0, vitest_1.describe)("stream integration (real client <-> real ws server)", () => {
|
|
65
|
+
let server;
|
|
66
|
+
let sdk;
|
|
67
|
+
const open = [];
|
|
68
|
+
(0, vitest_1.beforeEach)(async () => {
|
|
69
|
+
server = startServer();
|
|
70
|
+
const port = await server.ready();
|
|
71
|
+
sdk = new v2_1.GmxApiSdk({
|
|
72
|
+
chainId: ARBITRUM,
|
|
73
|
+
apiUrl: `http://localhost:${port}`,
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
(0, vitest_1.afterEach)(async () => {
|
|
77
|
+
open.forEach((sub) => sub.close());
|
|
78
|
+
open.length = 0;
|
|
79
|
+
await server.close();
|
|
80
|
+
});
|
|
81
|
+
(0, vitest_1.it)("connects over a real socket, subscribes, and deserializes a pushed snapshot", async () => {
|
|
82
|
+
const sub = sdk.watchTokenPrices();
|
|
83
|
+
open.push(sub);
|
|
84
|
+
const values = [];
|
|
85
|
+
sub.subscribe((value) => values.push(value));
|
|
86
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.connectionStatus).toBe("live"));
|
|
87
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(server.received).toContainEqual({ op: "subscribe", channels: ["prices"] }));
|
|
88
|
+
server.broadcast(snapshot("123", "124"));
|
|
89
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(values.length).toBeGreaterThan(0));
|
|
90
|
+
(0, vitest_1.expect)(sub.get()).toEqual({ "0xabc": { minPrice: 123n, maxPrice: 124n } });
|
|
91
|
+
});
|
|
92
|
+
(0, vitest_1.it)("reconnects, resubscribes, and resumes delivery after the server drops the socket", async () => {
|
|
93
|
+
const sub = sdk.watchTokenPrices();
|
|
94
|
+
open.push(sub);
|
|
95
|
+
const statuses = [];
|
|
96
|
+
sub.subscribeConnectionStatus((status) => statuses.push(status));
|
|
97
|
+
sub.subscribe(vitest_1.vi.fn());
|
|
98
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.connectionStatus).toBe("live"));
|
|
99
|
+
(0, vitest_1.expect)(server.connections.length).toBe(1);
|
|
100
|
+
server.connections[0].close();
|
|
101
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(server.connections.length).toBe(2));
|
|
102
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.connectionStatus).toBe("live"));
|
|
103
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(server.subscribeCount()).toBeGreaterThanOrEqual(2));
|
|
104
|
+
(0, vitest_1.expect)(statuses).toContain("reconnecting");
|
|
105
|
+
server.broadcast(snapshot("200", "201"));
|
|
106
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.get()).toEqual({ "0xabc": { minPrice: 200n, maxPrice: 201n } }));
|
|
107
|
+
});
|
|
108
|
+
(0, vitest_1.it)("unsubscribes on close() and stops delivering", async () => {
|
|
109
|
+
const sub = sdk.watchTokenPrices();
|
|
110
|
+
open.push(sub);
|
|
111
|
+
const listener = vitest_1.vi.fn();
|
|
112
|
+
sub.subscribe(listener);
|
|
113
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.connectionStatus).toBe("live"));
|
|
114
|
+
sub.close();
|
|
115
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(server.received).toContainEqual({ op: "unsubscribe", channels: ["prices"] }));
|
|
116
|
+
server.broadcast(snapshot("300", "301"));
|
|
117
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
118
|
+
(0, vitest_1.expect)(listener).not.toHaveBeenCalled();
|
|
119
|
+
(0, vitest_1.expect)(server.connections.length).toBe(1);
|
|
120
|
+
});
|
|
121
|
+
(0, vitest_1.it)("subscribes to a per-token candle channel and delivers the forming bar", async () => {
|
|
122
|
+
const sub = sdk.watchCandles({ symbol: "BTC", timeframe: "1m" });
|
|
123
|
+
open.push(sub);
|
|
124
|
+
const values = [];
|
|
125
|
+
sub.subscribe((value) => values.push(value));
|
|
126
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(sub.connectionStatus).toBe("live"));
|
|
127
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(server.received).toContainEqual({ op: "subscribe", channels: ["candles:BTC:1m"] }));
|
|
128
|
+
const bar = { timestamp: 1700000060000, open: "4", high: "6", low: "3", close: "5" };
|
|
129
|
+
server.broadcast({ ch: "candles:BTC:1m", type: "snapshot", serverTs: 1, data: bar });
|
|
130
|
+
await vitest_1.vi.waitFor(() => (0, vitest_1.expect)(values.length).toBeGreaterThan(0));
|
|
131
|
+
(0, vitest_1.expect)(sub.get()).toEqual(bar);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toStreamUrl = exports.createChannelSubscription = exports.WsStreamClient = void 0;
|
|
4
|
+
var WsStreamClient_1 = require("./WsStreamClient");
|
|
5
|
+
Object.defineProperty(exports, "WsStreamClient", { enumerable: true, get: function () { return WsStreamClient_1.WsStreamClient; } });
|
|
6
|
+
var subscription_1 = require("./subscription");
|
|
7
|
+
Object.defineProperty(exports, "createChannelSubscription", { enumerable: true, get: function () { return subscription_1.createChannelSubscription; } });
|
|
8
|
+
function toStreamUrl(apiUrl) {
|
|
9
|
+
return apiUrl.replace(/^http/, "ws").replace(/\/$/, "") + "/v1/stream";
|
|
10
|
+
}
|
|
11
|
+
exports.toStreamUrl = toStreamUrl;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createChannelSubscription = void 0;
|
|
4
|
+
const WsStreamClient_1 = require("./WsStreamClient");
|
|
5
|
+
function createChannelSubscription(client, channel, transform) {
|
|
6
|
+
let value;
|
|
7
|
+
let meta;
|
|
8
|
+
const listeners = new Set();
|
|
9
|
+
const refusalListeners = new Set();
|
|
10
|
+
const connectionStatusUnsubscribers = new Set();
|
|
11
|
+
const unsubscribeTransport = client.subscribe(channel, (frame) => {
|
|
12
|
+
value = transform(frame.data);
|
|
13
|
+
meta = {
|
|
14
|
+
serverTs: frame.serverTs,
|
|
15
|
+
receivedAt: frame.receivedAt,
|
|
16
|
+
originTs: frame.originTs,
|
|
17
|
+
};
|
|
18
|
+
for (const listener of listeners) {
|
|
19
|
+
(0, WsStreamClient_1.callListener)(listener, value);
|
|
20
|
+
}
|
|
21
|
+
}, (error) => {
|
|
22
|
+
for (const listener of refusalListeners) {
|
|
23
|
+
(0, WsStreamClient_1.callListener)(listener, error);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
return {
|
|
27
|
+
get: () => value,
|
|
28
|
+
getMeta: () => meta,
|
|
29
|
+
get connectionStatus() {
|
|
30
|
+
return client.connectionStatus;
|
|
31
|
+
},
|
|
32
|
+
subscribe(listener) {
|
|
33
|
+
listeners.add(listener);
|
|
34
|
+
return () => {
|
|
35
|
+
listeners.delete(listener);
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
subscribeConnectionStatus(listener) {
|
|
39
|
+
const remove = client.subscribeConnectionStatus(listener);
|
|
40
|
+
connectionStatusUnsubscribers.add(remove);
|
|
41
|
+
return () => {
|
|
42
|
+
connectionStatusUnsubscribers.delete(remove);
|
|
43
|
+
remove();
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
subscribeRefusal(listener) {
|
|
47
|
+
refusalListeners.add(listener);
|
|
48
|
+
return () => {
|
|
49
|
+
refusalListeners.delete(listener);
|
|
50
|
+
};
|
|
51
|
+
},
|
|
52
|
+
close() {
|
|
53
|
+
listeners.clear();
|
|
54
|
+
refusalListeners.clear();
|
|
55
|
+
connectionStatusUnsubscribers.forEach((remove) => remove());
|
|
56
|
+
connectionStatusUnsubscribers.clear();
|
|
57
|
+
unsubscribeTransport();
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
exports.createChannelSubscription = createChannelSubscription;
|
|
@@ -15,9 +15,10 @@ import { fetchApiPairs } from "../../utils/pairs/api";
|
|
|
15
15
|
import { fetchApiTransitAuthorization, fetchApiTransitFeeTier, fetchApiTransitOrder, fetchApiTransitOrders, fetchApiTransitQuote, fetchApiTransitRoutes, } from "../../utils/paxos/api";
|
|
16
16
|
import { fetchApiPerformanceAnnualized, fetchApiPerformanceSnapshots } from "../../utils/performance/api";
|
|
17
17
|
import { fetchApiPositionsInfo } from "../../utils/positions/api";
|
|
18
|
-
import { fetchApiOhlcv } from "../../utils/prices/api";
|
|
18
|
+
import { fetchApiOhlcv, fetchApiTokenPrices, parseApiTokenPrices } from "../../utils/prices/api";
|
|
19
19
|
import { fetchApiRates } from "../../utils/rates/api";
|
|
20
20
|
import { fetchApiStakingPower } from "../../utils/staking/api";
|
|
21
|
+
import { WsStreamClient, createChannelSubscription, toStreamUrl } from "../../utils/stream";
|
|
21
22
|
import { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "../../utils/subaccount/api";
|
|
22
23
|
import { activateSdkSubaccount, clearSdkSubaccount, executeExpressOrderWithSubaccount, generateSdkSubaccount, getSdkSubaccountApprovalMessage, hasActiveSdkSubaccount, prepareWithSubaccount, refreshSdkSubaccountState, signOrderWithSubaccount, submitOrderWithSubaccount, } from "../../utils/subaccount/sdkClient";
|
|
23
24
|
import { fetchApiTokens } from "../../utils/tokens/api";
|
|
@@ -32,8 +33,10 @@ export { HttpError } from "../../utils/http/http";
|
|
|
32
33
|
export { HttpClientWithFallback } from "../../utils/http/httpFallback";
|
|
33
34
|
export { getGasPaymentTokens } from "../../configs/express";
|
|
34
35
|
export class GmxApiSdk {
|
|
35
|
-
constructor({ chainId, apiUrl, api }) {
|
|
36
|
+
constructor({ chainId, apiUrl, api, streamUrl, webSocketImpl, }) {
|
|
36
37
|
this.preparedSubaccountApprovals = new Map();
|
|
38
|
+
this.streamUrlOverride = streamUrl;
|
|
39
|
+
this.webSocketImpl = webSocketImpl;
|
|
37
40
|
if (api) {
|
|
38
41
|
this.ctx = { chainId, api };
|
|
39
42
|
return;
|
|
@@ -96,6 +99,22 @@ export class GmxApiSdk {
|
|
|
96
99
|
fetchTokens() {
|
|
97
100
|
return fetchApiTokens(this.ctx);
|
|
98
101
|
}
|
|
102
|
+
getStreamClient() {
|
|
103
|
+
if (!this._streamClient) {
|
|
104
|
+
const url = this.streamUrlOverride ?? toStreamUrl(this.ctx.api.url);
|
|
105
|
+
this._streamClient = new WsStreamClient({ url, webSocketImpl: this.webSocketImpl });
|
|
106
|
+
}
|
|
107
|
+
return this._streamClient;
|
|
108
|
+
}
|
|
109
|
+
fetchTokenPrices() {
|
|
110
|
+
return fetchApiTokenPrices(this.ctx);
|
|
111
|
+
}
|
|
112
|
+
watchTokenPrices() {
|
|
113
|
+
return createChannelSubscription(this.getStreamClient(), "prices", parseApiTokenPrices);
|
|
114
|
+
}
|
|
115
|
+
watchCandles(params) {
|
|
116
|
+
return createChannelSubscription(this.getStreamClient(), `candles:${params.symbol}:${params.timeframe}`, (raw) => raw);
|
|
117
|
+
}
|
|
99
118
|
fetchPositionsInfo(params) {
|
|
100
119
|
return fetchApiPositionsInfo(this.ctx, params);
|
|
101
120
|
}
|
|
@@ -257,6 +257,21 @@ describe("formatUsdPrice", () => {
|
|
|
257
257
|
expect(formatUsdPrice(ONE_USD / 10000000000n)).toBe("<\u00a0$\u200a0.000000001");
|
|
258
258
|
});
|
|
259
259
|
});
|
|
260
|
+
describe("formatBigUsd", () => {
|
|
261
|
+
it("shows cents for sub-dollar amounts and whole dollars otherwise PRO-4565", () => {
|
|
262
|
+
const cases = [
|
|
263
|
+
[0n, "$ 0"],
|
|
264
|
+
[ONE_USD / 200n, "< $ 0.01"],
|
|
265
|
+
[(ONE_USD * 229n) / 10000n, "$ 0.02"],
|
|
266
|
+
[(ONE_USD * 99n) / 100n, "$ 0.99"],
|
|
267
|
+
[ONE_USD, "$ 1"],
|
|
268
|
+
[(ONE_USD * 7058342n) / 10n, "$ 705,834"],
|
|
269
|
+
];
|
|
270
|
+
for (const [amount, expected] of cases) {
|
|
271
|
+
expect(formatBigUsd(amount)).toBe(expected);
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
});
|
|
260
275
|
describe("formatNumberHuman", () => {
|
|
261
276
|
it.each([
|
|
262
277
|
[999.94, 1, "999.9"],
|