@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.
Files changed (30) hide show
  1. package/build/cjs/src/clients/v2/index.js +20 -1
  2. package/build/cjs/src/utils/__tests__/numbers.spec.js +15 -0
  3. package/build/cjs/src/utils/numbers/utils.js +8 -2
  4. package/build/cjs/src/utils/prices/api.js +15 -1
  5. package/build/cjs/src/utils/stream/WsStreamClient.js +363 -0
  6. package/build/cjs/src/utils/stream/__tests__/WsStreamClient.spec.js +383 -0
  7. package/build/cjs/src/utils/stream/__tests__/stream.integration.spec.js +133 -0
  8. package/build/cjs/src/utils/stream/index.js +11 -0
  9. package/build/cjs/src/utils/stream/subscription.js +61 -0
  10. package/build/cjs/src/utils/stream/types.js +2 -0
  11. package/build/esm/src/clients/v2/index.js +21 -2
  12. package/build/esm/src/utils/__tests__/numbers.spec.js +15 -0
  13. package/build/esm/src/utils/numbers/utils.js +8 -2
  14. package/build/esm/src/utils/prices/api.js +12 -0
  15. package/build/esm/src/utils/stream/WsStreamClient.js +355 -0
  16. package/build/esm/src/utils/stream/__tests__/WsStreamClient.spec.js +381 -0
  17. package/build/esm/src/utils/stream/__tests__/stream.integration.spec.js +131 -0
  18. package/build/esm/src/utils/stream/index.js +5 -0
  19. package/build/esm/src/utils/stream/subscription.js +57 -0
  20. package/build/esm/src/utils/stream/types.js +1 -0
  21. package/build/tsconfig.tsbuildinfo +1 -1
  22. package/build/types/src/clients/v2/index.d.ts +23 -5
  23. package/build/types/src/utils/prices/api.d.ts +8 -0
  24. package/build/types/src/utils/stream/WsStreamClient.d.ts +63 -0
  25. package/build/types/src/utils/stream/__tests__/WsStreamClient.spec.d.ts +1 -0
  26. package/build/types/src/utils/stream/__tests__/stream.integration.spec.d.ts +1 -0
  27. package/build/types/src/utils/stream/index.d.ts +5 -0
  28. package/build/types/src/utils/stream/subscription.d.ts +3 -0
  29. package/build/types/src/utils/stream/types.d.ts +43 -0
  30. package/package.json +14 -2
@@ -23,6 +23,7 @@ const api_12 = require("../../utils/positions/api");
23
23
  const api_13 = require("../../utils/prices/api");
24
24
  const api_14 = require("../../utils/rates/api");
25
25
  const api_15 = require("../../utils/staking/api");
26
+ const stream_1 = require("../../utils/stream");
26
27
  const api_16 = require("../../utils/subaccount/api");
27
28
  const sdkClient_1 = require("../../utils/subaccount/sdkClient");
28
29
  const api_17 = require("../../utils/tokens/api");
@@ -43,8 +44,10 @@ Object.defineProperty(exports, "HttpClientWithFallback", { enumerable: true, get
43
44
  var express_1 = require("../../configs/express");
44
45
  Object.defineProperty(exports, "getGasPaymentTokens", { enumerable: true, get: function () { return express_1.getGasPaymentTokens; } });
45
46
  class GmxApiSdk {
46
- constructor({ chainId, apiUrl, api }) {
47
+ constructor({ chainId, apiUrl, api, streamUrl, webSocketImpl, }) {
47
48
  this.preparedSubaccountApprovals = new Map();
49
+ this.streamUrlOverride = streamUrl;
50
+ this.webSocketImpl = webSocketImpl;
48
51
  if (api) {
49
52
  this.ctx = { chainId, api };
50
53
  return;
@@ -107,6 +110,22 @@ class GmxApiSdk {
107
110
  fetchTokens() {
108
111
  return (0, api_17.fetchApiTokens)(this.ctx);
109
112
  }
113
+ getStreamClient() {
114
+ if (!this._streamClient) {
115
+ const url = this.streamUrlOverride ?? (0, stream_1.toStreamUrl)(this.ctx.api.url);
116
+ this._streamClient = new stream_1.WsStreamClient({ url, webSocketImpl: this.webSocketImpl });
117
+ }
118
+ return this._streamClient;
119
+ }
120
+ fetchTokenPrices() {
121
+ return (0, api_13.fetchApiTokenPrices)(this.ctx);
122
+ }
123
+ watchTokenPrices() {
124
+ return (0, stream_1.createChannelSubscription)(this.getStreamClient(), "prices", api_13.parseApiTokenPrices);
125
+ }
126
+ watchCandles(params) {
127
+ return (0, stream_1.createChannelSubscription)(this.getStreamClient(), `candles:${params.symbol}:${params.timeframe}`, (raw) => raw);
128
+ }
110
129
  fetchPositionsInfo(params) {
111
130
  return (0, api_12.fetchApiPositionsInfo)(this.ctx, params);
112
131
  }
@@ -259,6 +259,21 @@ const ONE_USD = 1000000000000000000000000000000n;
259
259
  (0, vitest_1.expect)((0, numbers_1.formatUsdPrice)(ONE_USD / 10000000000n)).toBe("<\u00a0$\u200a0.000000001");
260
260
  });
261
261
  });
262
+ (0, vitest_1.describe)("formatBigUsd", () => {
263
+ (0, vitest_1.it)("shows cents for sub-dollar amounts and whole dollars otherwise PRO-4565", () => {
264
+ const cases = [
265
+ [0n, "$ 0"],
266
+ [ONE_USD / 200n, "< $ 0.01"],
267
+ [(ONE_USD * 229n) / 10000n, "$ 0.02"],
268
+ [(ONE_USD * 99n) / 100n, "$ 0.99"],
269
+ [ONE_USD, "$ 1"],
270
+ [(ONE_USD * 7058342n) / 10n, "$ 705,834"],
271
+ ];
272
+ for (const [amount, expected] of cases) {
273
+ (0, vitest_1.expect)((0, numbers_1.formatBigUsd)(amount)).toBe(expected);
274
+ }
275
+ });
276
+ });
262
277
  (0, vitest_1.describe)("formatNumberHuman", () => {
263
278
  vitest_1.it.each([
264
279
  [999.94, 1, "999.9"],
@@ -34,6 +34,7 @@ exports.isUint256 = isUint256;
34
34
  exports.PERCENT_PRECISION_DECIMALS = exports.PRECISION_DECIMALS - 2;
35
35
  const MAX_EXCEEDING_THRESHOLD = "1000000000";
36
36
  const MIN_EXCEEDING_THRESHOLD = "0.01";
37
+ const MIN_EXCEEDING_THRESHOLD_DECIMALS = 2;
37
38
  exports.TRIGGER_PREFIX_ABOVE = ">";
38
39
  exports.TRIGGER_PREFIX_BELOW = "<";
39
40
  function isNonZero(value) {
@@ -201,7 +202,10 @@ function formatUsdParts(usd, opts = {}) {
201
202
  const maybePlus = opts.displayPlus ? "+" : "";
202
203
  const sign = usd < 0n ? "-" : maybePlus;
203
204
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol}\u00a0` : "";
204
- const displayUsd = (0, exports.formatAmount)(exceedingInfo.value, exports.USD_DECIMALS, displayDecimals, true);
205
+ const valueDecimals = exceedingInfo.symbol === exports.TRIGGER_PREFIX_BELOW
206
+ ? Math.max(displayDecimals, MIN_EXCEEDING_THRESHOLD_DECIMALS)
207
+ : displayDecimals;
208
+ const displayUsd = (0, exports.formatAmount)(exceedingInfo.value, exports.USD_DECIMALS, valueDecimals, true);
205
209
  return (0, parts_1.numberParts)(symbol, sign, parts_1.USD_PART, displayUsd);
206
210
  }
207
211
  exports.formatUsdParts = formatUsdParts;
@@ -211,9 +215,11 @@ function formatUsd(usd, opts = {}) {
211
215
  }
212
216
  exports.formatUsd = formatUsd;
213
217
  function formatBigUsdParts(amount, opts = {}) {
218
+ // whole dollars would show a few cents as $0
219
+ const defaultDisplayDecimals = amount !== 0n && roundsToZero(amount, exports.USD_DECIMALS, 0) ? 2 : 0;
214
220
  return formatUsdParts(amount, {
215
221
  maxThreshold: "9999999999999999999999999",
216
- displayDecimals: opts.displayDecimals ?? 0,
222
+ displayDecimals: opts.displayDecimals ?? defaultDisplayDecimals,
217
223
  });
218
224
  }
219
225
  exports.formatBigUsdParts = formatBigUsdParts;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchApiOhlcv = void 0;
3
+ exports.fetchApiTokenPrices = exports.parseApiTokenPrices = exports.fetchApiOhlcv = void 0;
4
+ const numbers_1 = require("../numbers");
5
+ const objects_1 = require("../objects");
4
6
  async function fetchApiOhlcv(ctx, params) {
5
7
  return ctx.api.fetchJson("/v1/prices/ohlcv", {
6
8
  query: {
@@ -12,3 +14,15 @@ async function fetchApiOhlcv(ctx, params) {
12
14
  });
13
15
  }
14
16
  exports.fetchApiOhlcv = fetchApiOhlcv;
17
+ function parseApiTokenPrices(raw) {
18
+ return (0, numbers_1.deserializeBigIntsInObject)(raw, { handleInts: true });
19
+ }
20
+ exports.parseApiTokenPrices = parseApiTokenPrices;
21
+ async function fetchApiTokenPrices(ctx) {
22
+ const raw = await ctx.api.fetchJson("/v1/prices/tickers");
23
+ if (!(0, objects_1.isRecord)(raw) || !(0, objects_1.isRecord)(raw.prices) || typeof raw.originTs !== "number") {
24
+ throw new Error("Invalid /v1/prices/tickers response");
25
+ }
26
+ return { prices: parseApiTokenPrices(raw.prices), originTs: raw.originTs };
27
+ }
28
+ exports.fetchApiTokenPrices = fetchApiTokenPrices;
@@ -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;