@gmx-io/sdk 2.6.0-next.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/README.md +25 -0
- package/build/cjs/src/abis/ChainlinkPriceFeedProvider.js +27 -0
- package/build/cjs/src/abis/Pausable.js +11 -0
- package/build/cjs/src/abis/index.js +4 -0
- package/build/cjs/src/clients/v2/index.js +20 -1
- package/build/cjs/src/configs/express.js +1 -0
- package/build/cjs/src/configs/tokens.js +3 -0
- package/build/cjs/src/utils/__tests__/numbers.spec.js +15 -0
- package/build/cjs/src/utils/multichain/__tests__/api.spec.js +11 -1
- package/build/cjs/src/utils/multichain/api.js +3 -2
- 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/abis/ChainlinkPriceFeedProvider.js +25 -0
- package/build/esm/src/abis/Pausable.js +9 -0
- package/build/esm/src/abis/index.js +4 -0
- package/build/esm/src/clients/v2/index.js +21 -2
- package/build/esm/src/configs/express.js +1 -0
- package/build/esm/src/configs/tokens.js +3 -0
- package/build/esm/src/utils/__tests__/numbers.spec.js +15 -0
- package/build/esm/src/utils/multichain/__tests__/api.spec.js +11 -1
- package/build/esm/src/utils/multichain/api.js +2 -1
- 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/abis/ChainlinkPriceFeedProvider.d.ts +41 -0
- package/build/types/src/abis/Pausable.d.ts +12 -0
- package/build/types/src/abis/index.d.ts +51 -0
- package/build/types/src/clients/v2/index.d.ts +23 -5
- package/build/types/src/utils/multichain/api.d.ts +2 -1
- package/build/types/src/utils/orderTransactions/api.d.ts +2 -0
- 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
|
@@ -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
|
}
|
|
@@ -13,6 +13,7 @@ const GAS_PAYMENT_TOKENS = {
|
|
|
13
13
|
getTokenBySymbol(ARBITRUM, "USDC").address,
|
|
14
14
|
getTokenBySymbol(ARBITRUM, "WETH").address,
|
|
15
15
|
getTokenBySymbol(ARBITRUM, "USDT").address,
|
|
16
|
+
getTokenBySymbol(ARBITRUM, "USDG").address,
|
|
16
17
|
],
|
|
17
18
|
[AVALANCHE]: [
|
|
18
19
|
getTokenBySymbol(AVALANCHE, "USDC").address,
|
|
@@ -131,6 +131,9 @@ export const TOKENS = {
|
|
|
131
131
|
isStable: true,
|
|
132
132
|
imageUrl: "https://coin-images.coingecko.com/coins/images/51281/small/GDN_USDG_Token_200x200.png?1730484111",
|
|
133
133
|
explorerUrl: "https://arbiscan.io/token/0x004B506865409877C9fA29bfb1ebA929984B9bbC",
|
|
134
|
+
isPermitSupported: true,
|
|
135
|
+
// the contract has no version() to read it from
|
|
136
|
+
contractVersion: "1",
|
|
134
137
|
},
|
|
135
138
|
{
|
|
136
139
|
name: "Tether",
|
|
@@ -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"],
|
|
@@ -118,13 +118,23 @@ describe("multichain api: buildCrossChainWithdrawBridgeOutParams", () => {
|
|
|
118
118
|
const [decodedDstEid] = decodeAbiParameters([{ type: "uint32" }], params.data);
|
|
119
119
|
expect(decodedDstEid).toBe(CHAIN_ID_TO_ENDPOINT_ID[SOURCE_BASE_MAINNET]);
|
|
120
120
|
});
|
|
121
|
-
it("
|
|
121
|
+
it("leaves 50 bps for the bridge fee when slippage is unspecified", () => {
|
|
122
122
|
const params = buildCrossChainWithdrawBridgeOutParams({
|
|
123
123
|
tokenAddress: USDC_ARBITRUM,
|
|
124
124
|
amount: 1000000n,
|
|
125
125
|
dstChainId: SOURCE_BASE_MAINNET,
|
|
126
126
|
stargateAddress: STARGATE_USDC_ARBITRUM,
|
|
127
127
|
});
|
|
128
|
+
expect(params.minAmountOut).toBe(995000n);
|
|
129
|
+
});
|
|
130
|
+
it("keeps minAmountOut equal to amount with zero slippage", () => {
|
|
131
|
+
const params = buildCrossChainWithdrawBridgeOutParams({
|
|
132
|
+
tokenAddress: USDC_ARBITRUM,
|
|
133
|
+
amount: 1000000n,
|
|
134
|
+
dstChainId: SOURCE_BASE_MAINNET,
|
|
135
|
+
stargateAddress: STARGATE_USDC_ARBITRUM,
|
|
136
|
+
slippageBps: 0,
|
|
137
|
+
});
|
|
128
138
|
expect(params.minAmountOut).toBe(1000000n);
|
|
129
139
|
});
|
|
130
140
|
});
|
|
@@ -79,6 +79,7 @@ export function buildSameChainWithdrawTxn(request) {
|
|
|
79
79
|
});
|
|
80
80
|
return { to: router, data, value: 0n };
|
|
81
81
|
}
|
|
82
|
+
export const DEFAULT_CROSS_CHAIN_WITHDRAW_SLIPPAGE_BPS = 50;
|
|
82
83
|
/**
|
|
83
84
|
* `BridgeOutParams.data` for cross-chain delivery is a single `uint32 dstEid`
|
|
84
85
|
* pointing at the destination LayerZero endpoint; the on-chain provider takes
|
|
@@ -87,7 +88,7 @@ export function buildSameChainWithdrawTxn(request) {
|
|
|
87
88
|
* `utils/express/utils/bridgeOutUtils`.
|
|
88
89
|
*/
|
|
89
90
|
export function buildCrossChainWithdrawBridgeOutParams(params) {
|
|
90
|
-
const { tokenAddress, amount, dstChainId, stargateAddress, slippageBps =
|
|
91
|
+
const { tokenAddress, amount, dstChainId, stargateAddress, slippageBps = DEFAULT_CROSS_CHAIN_WITHDRAW_SLIPPAGE_BPS, } = params;
|
|
91
92
|
if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps >= 10000) {
|
|
92
93
|
throw new Error(`slippageBps must be an integer in range [0, 10000), got ${slippageBps}`);
|
|
93
94
|
}
|
|
@@ -28,6 +28,7 @@ export function isUint256(value) {
|
|
|
28
28
|
export const PERCENT_PRECISION_DECIMALS = PRECISION_DECIMALS - 2;
|
|
29
29
|
const MAX_EXCEEDING_THRESHOLD = "1000000000";
|
|
30
30
|
const MIN_EXCEEDING_THRESHOLD = "0.01";
|
|
31
|
+
const MIN_EXCEEDING_THRESHOLD_DECIMALS = 2;
|
|
31
32
|
export const TRIGGER_PREFIX_ABOVE = ">";
|
|
32
33
|
export const TRIGGER_PREFIX_BELOW = "<";
|
|
33
34
|
export function isNonZero(value) {
|
|
@@ -180,7 +181,10 @@ export function formatUsdParts(usd, opts = {}) {
|
|
|
180
181
|
const maybePlus = opts.displayPlus ? "+" : "";
|
|
181
182
|
const sign = usd < 0n ? "-" : maybePlus;
|
|
182
183
|
const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol}\u00a0` : "";
|
|
183
|
-
const
|
|
184
|
+
const valueDecimals = exceedingInfo.symbol === TRIGGER_PREFIX_BELOW
|
|
185
|
+
? Math.max(displayDecimals, MIN_EXCEEDING_THRESHOLD_DECIMALS)
|
|
186
|
+
: displayDecimals;
|
|
187
|
+
const displayUsd = formatAmount(exceedingInfo.value, USD_DECIMALS, valueDecimals, true);
|
|
184
188
|
return numberParts(symbol, sign, USD_PART, displayUsd);
|
|
185
189
|
}
|
|
186
190
|
export function formatUsd(usd, opts = {}) {
|
|
@@ -188,9 +192,11 @@ export function formatUsd(usd, opts = {}) {
|
|
|
188
192
|
return parts && joinNumberParts(parts);
|
|
189
193
|
}
|
|
190
194
|
export function formatBigUsdParts(amount, opts = {}) {
|
|
195
|
+
// whole dollars would show a few cents as $0
|
|
196
|
+
const defaultDisplayDecimals = amount !== 0n && roundsToZero(amount, USD_DECIMALS, 0) ? 2 : 0;
|
|
191
197
|
return formatUsdParts(amount, {
|
|
192
198
|
maxThreshold: "9999999999999999999999999",
|
|
193
|
-
displayDecimals: opts.displayDecimals ??
|
|
199
|
+
displayDecimals: opts.displayDecimals ?? defaultDisplayDecimals,
|
|
194
200
|
});
|
|
195
201
|
}
|
|
196
202
|
export function formatBigUsd(amount, opts = {}) {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { deserializeBigIntsInObject } from "../numbers";
|
|
2
|
+
import { isRecord } from "../objects";
|
|
1
3
|
export async function fetchApiOhlcv(ctx, params) {
|
|
2
4
|
return ctx.api.fetchJson("/v1/prices/ohlcv", {
|
|
3
5
|
query: {
|
|
@@ -8,3 +10,13 @@ export async function fetchApiOhlcv(ctx, params) {
|
|
|
8
10
|
},
|
|
9
11
|
});
|
|
10
12
|
}
|
|
13
|
+
export function parseApiTokenPrices(raw) {
|
|
14
|
+
return deserializeBigIntsInObject(raw, { handleInts: true });
|
|
15
|
+
}
|
|
16
|
+
export async function fetchApiTokenPrices(ctx) {
|
|
17
|
+
const raw = await ctx.api.fetchJson("/v1/prices/tickers");
|
|
18
|
+
if (!isRecord(raw) || !isRecord(raw.prices) || typeof raw.originTs !== "number") {
|
|
19
|
+
throw new Error("Invalid /v1/prices/tickers response");
|
|
20
|
+
}
|
|
21
|
+
return { prices: parseApiTokenPrices(raw.prices), originTs: raw.originTs };
|
|
22
|
+
}
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import IsomorphicWebSocket from "isomorphic-ws";
|
|
2
|
+
const DEFAULT_RECONNECT_BASE_MS = 500;
|
|
3
|
+
const DEFAULT_RECONNECT_MAX_MS = 10000;
|
|
4
|
+
const DEFAULT_PROBE_INTERVAL_MS = 15000;
|
|
5
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 10000;
|
|
6
|
+
const CONNECT_TIMEOUT_MS = 10000;
|
|
7
|
+
const IDLE_CLOSE_MS = 10000;
|
|
8
|
+
// a socket that stayed up this long proves the path works; one dropped sooner keeps backing off
|
|
9
|
+
const STABLE_CONNECTION_MS = 30000;
|
|
10
|
+
const REFUSED_MESSAGE = "subscription refused";
|
|
11
|
+
function resolveWebSocketCtor(injected) {
|
|
12
|
+
return injected ?? IsomorphicWebSocket;
|
|
13
|
+
}
|
|
14
|
+
export function callListener(listener, value) {
|
|
15
|
+
try {
|
|
16
|
+
listener(value);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
queueMicrotask(() => {
|
|
20
|
+
throw error;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export class WsStreamClient {
|
|
25
|
+
constructor(params) {
|
|
26
|
+
this.connectionStatus = "closed";
|
|
27
|
+
this.listeners = new Map();
|
|
28
|
+
this.connectionStatusListeners = new Set();
|
|
29
|
+
this.lastFrameByChannel = new Map();
|
|
30
|
+
this.originTsByChannel = new Map();
|
|
31
|
+
this.refusalByChannel = new Map();
|
|
32
|
+
this.pendingOps = [];
|
|
33
|
+
this.reconnectAttempt = 0;
|
|
34
|
+
this.messageCount = 0;
|
|
35
|
+
this.closedByUser = false;
|
|
36
|
+
this.url = params.url;
|
|
37
|
+
this.WebSocketImpl = resolveWebSocketCtor(params.webSocketImpl);
|
|
38
|
+
this.reconnectBaseMs = params.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
|
|
39
|
+
this.reconnectMaxMs = params.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
|
|
40
|
+
this.probeIntervalMs = params.probeIntervalMs ?? DEFAULT_PROBE_INTERVAL_MS;
|
|
41
|
+
this.probeTimeoutMs = params.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
42
|
+
this.random = params.random ?? Math.random;
|
|
43
|
+
}
|
|
44
|
+
subscribe(channel, listener, onError) {
|
|
45
|
+
const subscriber = { onFrame: listener, onError };
|
|
46
|
+
clearTimeout(this.idleCloseTimer);
|
|
47
|
+
const existing = this.listeners.get(channel);
|
|
48
|
+
if (existing) {
|
|
49
|
+
existing.add(subscriber);
|
|
50
|
+
const frame = this.lastFrameByChannel.get(channel);
|
|
51
|
+
const refusal = this.refusalByChannel.get(channel);
|
|
52
|
+
queueMicrotask(() => this.replay(channel, subscriber, frame, refusal));
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
this.listeners.set(channel, new Set([subscriber]));
|
|
56
|
+
}
|
|
57
|
+
this.ensureConnected();
|
|
58
|
+
if (!existing && this.connectionStatus === "live") {
|
|
59
|
+
this.sendOp("subscribe", [channel]);
|
|
60
|
+
}
|
|
61
|
+
return () => {
|
|
62
|
+
const current = this.listeners.get(channel);
|
|
63
|
+
if (!current?.delete(subscriber)) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (current.size === 0) {
|
|
67
|
+
this.listeners.delete(channel);
|
|
68
|
+
this.lastFrameByChannel.delete(channel);
|
|
69
|
+
this.originTsByChannel.delete(channel);
|
|
70
|
+
this.refusalByChannel.delete(channel);
|
|
71
|
+
if (this.connectionStatus === "live") {
|
|
72
|
+
this.sendOp("unsubscribe", [channel]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (this.listeners.size === 0) {
|
|
76
|
+
this.idleCloseTimer = setTimeout(() => this.close(), IDLE_CLOSE_MS);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
subscribeConnectionStatus(listener) {
|
|
81
|
+
this.connectionStatusListeners.add(listener);
|
|
82
|
+
return () => {
|
|
83
|
+
this.connectionStatusListeners.delete(listener);
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
ensureConnected() {
|
|
87
|
+
if (this.ws || this.reconnectTimer) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
this.closedByUser = false;
|
|
91
|
+
this.connect();
|
|
92
|
+
}
|
|
93
|
+
canConnect() {
|
|
94
|
+
return !this.ws && !this.closedByUser && this.listeners.size > 0;
|
|
95
|
+
}
|
|
96
|
+
connect() {
|
|
97
|
+
if (!this.canConnect()) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
this.setConnectionStatus(this.connectionStatus === "closed" ? "connecting" : "reconnecting");
|
|
101
|
+
if (!this.canConnect()) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
this.pendingOps = [];
|
|
105
|
+
this.refusalByChannel.clear();
|
|
106
|
+
this.openedAt = undefined;
|
|
107
|
+
let ws;
|
|
108
|
+
try {
|
|
109
|
+
ws = new this.WebSocketImpl(this.url);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
this.scheduleReconnect();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
this.ws = ws;
|
|
116
|
+
this.connectTimeoutTimer = setTimeout(() => {
|
|
117
|
+
if (this.ws === ws && this.connectionStatus !== "live") {
|
|
118
|
+
this.dropSocket();
|
|
119
|
+
this.scheduleReconnect();
|
|
120
|
+
}
|
|
121
|
+
}, CONNECT_TIMEOUT_MS);
|
|
122
|
+
ws.onopen = () => {
|
|
123
|
+
if (this.ws !== ws) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
clearTimeout(this.connectTimeoutTimer);
|
|
127
|
+
this.openedAt = Date.now();
|
|
128
|
+
const channels = [...this.listeners.keys()];
|
|
129
|
+
if (channels.length) {
|
|
130
|
+
this.sendOp("subscribe", channels);
|
|
131
|
+
}
|
|
132
|
+
this.setConnectionStatus("live");
|
|
133
|
+
};
|
|
134
|
+
ws.onmessage = (ev) => {
|
|
135
|
+
if (this.ws === ws) {
|
|
136
|
+
this.onMessage(ev.data);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
ws.onclose = () => {
|
|
140
|
+
if (this.ws === ws) {
|
|
141
|
+
this.onClose();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
ws.onerror = () => {
|
|
145
|
+
// a close event always follows; reconnection is handled there
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
onMessage(raw) {
|
|
149
|
+
this.messageCount += 1;
|
|
150
|
+
const text = typeof raw === "string" ? raw : String(raw);
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
parsed = JSON.parse(text);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const frame = parsed;
|
|
162
|
+
if ("op" in frame) {
|
|
163
|
+
this.onOp(frame);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (frame.type !== "snapshot") {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (frame.data === undefined) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const set = this.listeners.get(frame.ch);
|
|
173
|
+
if (!set) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (typeof frame.originTs === "number") {
|
|
177
|
+
const newest = this.originTsByChannel.get(frame.ch);
|
|
178
|
+
if (newest !== undefined && frame.originTs < newest) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
this.originTsByChannel.set(frame.ch, frame.originTs);
|
|
182
|
+
}
|
|
183
|
+
const payload = {
|
|
184
|
+
data: frame.data,
|
|
185
|
+
serverTs: frame.serverTs,
|
|
186
|
+
originTs: frame.originTs,
|
|
187
|
+
receivedAt: Date.now(),
|
|
188
|
+
};
|
|
189
|
+
this.lastFrameByChannel.set(frame.ch, payload);
|
|
190
|
+
this.refusalByChannel.delete(frame.ch);
|
|
191
|
+
for (const subscriber of set) {
|
|
192
|
+
callListener(subscriber.onFrame, payload);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
onOp(frame) {
|
|
196
|
+
if (frame.op === "error") {
|
|
197
|
+
if (!Array.isArray(frame.channels)) {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const pending = this.pendingOps[0];
|
|
201
|
+
for (const channel of frame.channels) {
|
|
202
|
+
if (pending?.op === "subscribe") {
|
|
203
|
+
pending.channels = pending.channels.filter((requested) => requested !== channel);
|
|
204
|
+
}
|
|
205
|
+
this.refuse(channel, frame.message);
|
|
206
|
+
}
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (frame.op !== "ack") {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const pending = this.pendingOps.shift();
|
|
213
|
+
if (pending?.op !== "subscribe" || !Array.isArray(frame.channels)) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
for (const channel of pending.channels) {
|
|
217
|
+
if (!frame.channels.includes(channel)) {
|
|
218
|
+
this.refuse(channel, REFUSED_MESSAGE);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
refuse(channel, message) {
|
|
223
|
+
const set = this.listeners.get(channel);
|
|
224
|
+
if (!set) {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const error = { message };
|
|
228
|
+
this.refusalByChannel.set(channel, error);
|
|
229
|
+
for (const subscriber of set) {
|
|
230
|
+
if (subscriber.onError) {
|
|
231
|
+
callListener(subscriber.onError, error);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
replay(channel, subscriber, frame, refusal) {
|
|
236
|
+
if (!this.listeners.get(channel)?.has(subscriber)) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
// only while still current: anything newer already reached this subscriber directly
|
|
240
|
+
if (frame && frame === this.lastFrameByChannel.get(channel)) {
|
|
241
|
+
callListener(subscriber.onFrame, frame);
|
|
242
|
+
}
|
|
243
|
+
if (refusal && refusal === this.refusalByChannel.get(channel) && subscriber.onError) {
|
|
244
|
+
callListener(subscriber.onError, refusal);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
onClose() {
|
|
248
|
+
this.ws = undefined;
|
|
249
|
+
clearTimeout(this.connectTimeoutTimer);
|
|
250
|
+
this.noteSocketEnded();
|
|
251
|
+
if (this.closedByUser || this.listeners.size === 0) {
|
|
252
|
+
this.setConnectionStatus("closed");
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
this.scheduleReconnect();
|
|
256
|
+
}
|
|
257
|
+
noteSocketEnded() {
|
|
258
|
+
if (this.openedAt !== undefined && Date.now() - this.openedAt >= STABLE_CONNECTION_MS) {
|
|
259
|
+
this.reconnectAttempt = 0;
|
|
260
|
+
}
|
|
261
|
+
this.openedAt = undefined;
|
|
262
|
+
}
|
|
263
|
+
scheduleReconnect() {
|
|
264
|
+
const ceiling = Math.min(this.reconnectMaxMs, this.reconnectBaseMs * 2 ** this.reconnectAttempt);
|
|
265
|
+
this.reconnectAttempt += 1;
|
|
266
|
+
this.reconnectTimer = setTimeout(() => {
|
|
267
|
+
this.reconnectTimer = undefined;
|
|
268
|
+
this.connect();
|
|
269
|
+
}, ceiling / 2 + (this.random() * ceiling) / 2);
|
|
270
|
+
this.setConnectionStatus("reconnecting");
|
|
271
|
+
}
|
|
272
|
+
startProbe() {
|
|
273
|
+
this.probeTimer = setTimeout(() => {
|
|
274
|
+
const messagesAtProbe = this.messageCount;
|
|
275
|
+
this.sendOp("subscribe", []);
|
|
276
|
+
if (!this.probeTimeoutTimer) {
|
|
277
|
+
this.probeTimeoutTimer = setTimeout(() => {
|
|
278
|
+
this.probeTimeoutTimer = undefined;
|
|
279
|
+
if (this.messageCount === messagesAtProbe) {
|
|
280
|
+
this.dropSocket();
|
|
281
|
+
this.noteSocketEnded();
|
|
282
|
+
this.scheduleReconnect();
|
|
283
|
+
}
|
|
284
|
+
}, this.probeTimeoutMs);
|
|
285
|
+
}
|
|
286
|
+
this.startProbe();
|
|
287
|
+
}, this.probeIntervalMs);
|
|
288
|
+
}
|
|
289
|
+
stopProbe() {
|
|
290
|
+
clearTimeout(this.probeTimer);
|
|
291
|
+
clearTimeout(this.probeTimeoutTimer);
|
|
292
|
+
this.probeTimer = undefined;
|
|
293
|
+
this.probeTimeoutTimer = undefined;
|
|
294
|
+
}
|
|
295
|
+
sendOp(op, channels) {
|
|
296
|
+
try {
|
|
297
|
+
this.ws?.send(JSON.stringify({ op, channels }));
|
|
298
|
+
this.pendingOps.push({ op, channels });
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
// socket raced into a non-open state; resubscribe runs on reconnect
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
setConnectionStatus(status) {
|
|
305
|
+
if (this.connectionStatus === status) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
this.connectionStatus = status;
|
|
309
|
+
if (status === "live") {
|
|
310
|
+
this.startProbe();
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
this.stopProbe();
|
|
314
|
+
}
|
|
315
|
+
for (const listener of this.connectionStatusListeners) {
|
|
316
|
+
if (this.connectionStatus !== status) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
callListener(listener, status);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
dropSocket() {
|
|
323
|
+
const ws = this.ws;
|
|
324
|
+
this.ws = undefined;
|
|
325
|
+
clearTimeout(this.connectTimeoutTimer);
|
|
326
|
+
if (!ws) {
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
// onerror stays attached: ws in Node throws on an unhandled "error" when a CONNECTING socket is closed
|
|
330
|
+
ws.onopen = null;
|
|
331
|
+
ws.onmessage = null;
|
|
332
|
+
ws.onclose = null;
|
|
333
|
+
try {
|
|
334
|
+
ws.close();
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
// already closing
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
close() {
|
|
341
|
+
this.closedByUser = true;
|
|
342
|
+
clearTimeout(this.idleCloseTimer);
|
|
343
|
+
if (this.reconnectTimer) {
|
|
344
|
+
clearTimeout(this.reconnectTimer);
|
|
345
|
+
this.reconnectTimer = undefined;
|
|
346
|
+
}
|
|
347
|
+
this.listeners.clear();
|
|
348
|
+
this.lastFrameByChannel.clear();
|
|
349
|
+
this.originTsByChannel.clear();
|
|
350
|
+
this.refusalByChannel.clear();
|
|
351
|
+
this.reconnectAttempt = 0;
|
|
352
|
+
this.dropSocket();
|
|
353
|
+
this.setConnectionStatus("closed");
|
|
354
|
+
}
|
|
355
|
+
}
|