@paradex/sdk 0.8.0 → 0.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.
@@ -0,0 +1,747 @@
1
+ import { buildAuthTypedData, buildOrderTypedData, jwtExpiry, SESSION_AUTH_MAX_TTL, sessionAuthPath, } from './session-auth.js';
2
+ import { SESSIONS_PATH } from './session-connector.js';
3
+ import { defaultApiUrl, defaultWebSocketFactory, defaultWsUrl, fetchTransport, SessionApiError, } from './session-transport.js';
4
+ import { assertGrantActive, canonicalFelt, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
5
+ /** setTimeout's delay is a signed 32-bit millisecond count. */
6
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
7
+ const WS_OPEN = 1;
8
+ const RECONNECT_BASE_MS = 1000;
9
+ const RECONNECT_MAX_MS = 30000;
10
+ const DEFAULT_RPC_TIMEOUT_MS = 10000;
11
+ /** `/auth` is rate-limited per IP; `start()` mints this many at a time. */
12
+ const START_CONCURRENCY = 10;
13
+ function hasOnBehalfOf(value) {
14
+ if (Array.isArray(value))
15
+ return value.some(hasOnBehalfOf);
16
+ if (value != null && typeof value === 'object') {
17
+ return Object.entries(value).some(([key, v]) => key.toLowerCase().startsWith('on_behalf_of') || hasOnBehalfOf(v));
18
+ }
19
+ return false;
20
+ }
21
+ function pathMentionsOnBehalfOf(path) {
22
+ let decoded;
23
+ try {
24
+ decoded = decodeURIComponent(path);
25
+ }
26
+ catch {
27
+ return true;
28
+ }
29
+ return decoded.toLowerCase().includes('on_behalf_of');
30
+ }
31
+ /** Codes the server gives `/auth` for a session that no longer exists. */
32
+ const SESSION_GONE_CODES = [
33
+ 'SESSION_REVOKED',
34
+ 'SESSION_EXPIRED',
35
+ ];
36
+ /**
37
+ * `/auth` refusals that mean "this session key was not accepted". They
38
+ * trigger a status check; only the grant's status ever drops a session.
39
+ */
40
+ /**
41
+ * The server no longer has the grant, as opposed to a 404 for an unrouted
42
+ * path, whose body names no `NOT_FOUND` error.
43
+ */
44
+ function isGrantNotFound(error) {
45
+ return (error instanceof SessionApiError &&
46
+ error.status === 404 &&
47
+ error.code === 'NOT_FOUND');
48
+ }
49
+ function isAuthRefusal(error) {
50
+ return (error.status === 401 ||
51
+ error.status === 403 ||
52
+ (error.code != null && SESSION_GONE_CODES.includes(error.code)));
53
+ }
54
+ /**
55
+ * Trades every account a grant lists with one session key: a JWT per account
56
+ * (`POST /v1/auth/{session_public_key}` with `PARADEX-STARKNET-ACCOUNT`,
57
+ * signed by the session key), one
58
+ * websocket per account, and requests routed by account. Sessions never use
59
+ * `on_behalf_of`; each account authenticates as itself.
60
+ *
61
+ * When the grant expires or is revoked, every account is dropped: tokens are
62
+ * discarded, sockets closed, and later calls throw. Whenever the server
63
+ * refuses a session token or the session key, the grant's state is re-checked
64
+ * with `GET /v2/sessions/{grant_id}/status`; any other answer is transient.
65
+ *
66
+ * @experimental
67
+ */
68
+ export class SessionAccounts {
69
+ constructor(params) {
70
+ this.tokens = new Map();
71
+ this.inflight = new Map();
72
+ this.refreshTimers = new Map();
73
+ this.sockets = new Map();
74
+ this.closed = false;
75
+ const { grant, key } = params.session;
76
+ if ((params.environment != null &&
77
+ grant.environment !== params.environment) ||
78
+ (params.paradexChain != null &&
79
+ grant.paradexChain !== params.paradexChain)) {
80
+ throw new SessionGrantError('ENVIRONMENT_MISMATCH', `grant is for ${grant.environment}/${grant.paradexChain}, not ${params.environment ?? grant.environment}/${params.paradexChain ?? grant.paradexChain}`);
81
+ }
82
+ if (grant.sessionKey !== key.publicKey) {
83
+ throw new SessionGrantError('INVALID_FIELD', 'sessionKey: the grant names a different session key');
84
+ }
85
+ this.params = params;
86
+ this.now = params.now ?? nowSeconds;
87
+ assertGrantActive(grant, this.now());
88
+ this.accounts = grantAccounts(grant);
89
+ this.transport = params.transport ?? fetchTransport;
90
+ this.apiUrl = params.apiUrl ?? defaultApiUrl(grant.environment);
91
+ this.wsUrl = params.wsUrl ?? defaultWsUrl(grant.environment);
92
+ this.webSocketFactory = params.webSocketFactory ?? defaultWebSocketFactory;
93
+ this.refreshMargin = params.refreshMarginSeconds ?? 60;
94
+ this.scheduleExpiry();
95
+ }
96
+ /** Why the accounts were dropped, if they were. */
97
+ get dropReason() {
98
+ return this.dropped;
99
+ }
100
+ /**
101
+ * Mints a JWT for every listed account, at most 10 at a time to stay
102
+ * inside the server's per-IP `/auth` rate limit.
103
+ */
104
+ async start() {
105
+ let next = 0;
106
+ const worker = async () => {
107
+ while (next < this.accounts.length) {
108
+ const account = this.accounts[next++];
109
+ if (account != null)
110
+ await this.getJwt(account);
111
+ }
112
+ };
113
+ await Promise.all(Array.from({ length: Math.min(START_CONCURRENCY, this.accounts.length) }, worker));
114
+ }
115
+ /** A valid JWT for `account`, minted or refreshed as needed. */
116
+ async getJwt(account) {
117
+ const id = this.resolveAccount(account);
118
+ const cached = this.tokens.get(id);
119
+ if (cached != null && !this.needsRefresh(cached))
120
+ return cached.token;
121
+ return await this.mint(id);
122
+ }
123
+ /** Authenticated REST call as `account`. */
124
+ async request(account, req) {
125
+ // The path is appended to the API root; anything but an absolute path
126
+ // could point the bearer token at another host.
127
+ if (!/^\/[A-Za-z0-9]/.test(req.path) || req.path.includes('//')) {
128
+ throw new Error('request path must be an absolute API path like /v1/x');
129
+ }
130
+ if (hasOnBehalfOf(req.body) || pathMentionsOnBehalfOf(req.path)) {
131
+ throw new Error('Sessions never use on_behalf_of; route by account');
132
+ }
133
+ const id = this.resolveAccount(account);
134
+ const token = await this.getJwt(id);
135
+ let result = await this.send(req, token);
136
+ // Only a 401 means the token was refused; a 403 is about the request.
137
+ if (result instanceof SessionApiError && result.status === 401) {
138
+ await this.confirmActive();
139
+ // The token may have expired in flight: mint once and retry. Another
140
+ // request may already have replaced it; keep that one.
141
+ if (this.tokens.get(id)?.token === token)
142
+ this.tokens.delete(id);
143
+ result = await this.send(req, await this.getJwt(id));
144
+ if (result instanceof SessionApiError && result.status === 401) {
145
+ await this.confirmActive();
146
+ }
147
+ }
148
+ if (result instanceof SessionApiError)
149
+ throw result;
150
+ return result;
151
+ }
152
+ /** Signs `order` with the session key for `account` and submits it. */
153
+ async placeOrder(account, order) {
154
+ const id = this.resolveAccount(account);
155
+ const timestamp = Date.now();
156
+ const typedData = buildOrderTypedData(this.params.session.grant.paradexChain, order, timestamp);
157
+ const signature = await this.params.session.key.signTypedData(typedData, id);
158
+ return await this.request(id, {
159
+ method: 'POST',
160
+ path: '/v1/orders',
161
+ body: {
162
+ market: order.market,
163
+ side: order.side,
164
+ type: order.type,
165
+ size: order.size,
166
+ price: order.type === 'MARKET' ? '0' : order.price,
167
+ instruction: order.instruction ?? 'GTC',
168
+ signature: JSON.stringify(signature),
169
+ signature_timestamp: timestamp,
170
+ ...(order.clientId != null ? { client_id: order.clientId } : {}),
171
+ ...(order.reduceOnly === true ? { flags: ['REDUCE_ONLY'] } : {}),
172
+ },
173
+ });
174
+ }
175
+ async cancelOrder(account, orderId) {
176
+ return await this.request(account, {
177
+ method: 'DELETE',
178
+ path: `/v1/orders/${encodeURIComponent(orderId)}`,
179
+ });
180
+ }
181
+ /** The grant's details (`GET /v2/sessions/{grant_id}`). */
182
+ async status() {
183
+ return (await this.request(this.accounts[0] ?? '', {
184
+ method: 'GET',
185
+ path: this.grantPath(),
186
+ }));
187
+ }
188
+ /**
189
+ * Revokes the grant on the server (every account under it) and drops
190
+ * every account locally.
191
+ *
192
+ * With `cancelOrders` (the default) the server also cancels the session's
193
+ * resting orders, TWAPs and untriggered stops on every account. Once the
194
+ * grant is revoked this key can no longer cancel anything, so a bot or
195
+ * builder session cancels by default. The Paradex app's own sign-out does
196
+ * the opposite, because orders placed through it are the owner's own
197
+ * trading.
198
+ *
199
+ * With `cancelOrders: false`, a grant without a builder signs out: its
200
+ * resting orders, TWAPs and stops keep working. A builder grant still has
201
+ * its TWAPs and untriggered stops cancelled, and keeps only its resting
202
+ * orders.
203
+ *
204
+ * A 404 `NOT_FOUND` means the server no longer has the grant, so it counts
205
+ * as revoked and drops the session too. Any other refusal (a 403, a 404
206
+ * for an unrouted path, a 5xx) throws and leaves the session live, so the
207
+ * call can be retried.
208
+ */
209
+ async revoke({ cancelOrders = true } = {}) {
210
+ const query = cancelOrders ? '?cancel_orders=true' : '';
211
+ try {
212
+ await this.request(this.accounts[0] ?? '', {
213
+ method: 'DELETE',
214
+ path: `${this.grantPath()}${query}`,
215
+ });
216
+ }
217
+ catch (error) {
218
+ if (!isGrantNotFound(error))
219
+ throw error;
220
+ }
221
+ this.drop(new SessionGrantError('GRANT_REVOKED', 'session revoked'));
222
+ }
223
+ /**
224
+ * Subscribes to a channel on `account`'s socket, opening and authenticating
225
+ * it if needed. Returns an unsubscribe function; the socket closes once its
226
+ * last subscription is gone.
227
+ */
228
+ async subscribe(account, channel, handler) {
229
+ const id = this.resolveAccount(account);
230
+ let socket = this.sockets.get(id);
231
+ if (socket == null) {
232
+ socket = new AccountSocket(this, id, this.params.rpcTimeoutMs);
233
+ this.sockets.set(id, socket);
234
+ }
235
+ return await socket.subscribe(channel, handler);
236
+ }
237
+ /** Closes sockets and timers. The session itself stays valid. */
238
+ close() {
239
+ this.closed = true;
240
+ this.teardown();
241
+ }
242
+ /** @internal */
243
+ createWebSocket() {
244
+ return this.webSocketFactory(this.wsUrl);
245
+ }
246
+ /** @internal */
247
+ get isLive() {
248
+ return !this.closed && this.dropped == null;
249
+ }
250
+ /** @internal Drops every account. Idempotent. */
251
+ drop(reason) {
252
+ if (this.dropped != null)
253
+ return;
254
+ this.dropped = reason;
255
+ this.teardown();
256
+ this.params.onDropped?.(reason);
257
+ }
258
+ /** @internal The cached JWT for `account`, if any. */
259
+ cachedToken(account) {
260
+ return this.tokens.get(account)?.token;
261
+ }
262
+ /** @internal The socket for `account` has no subscriptions left. */
263
+ socketIdle(account, socket) {
264
+ if (this.sockets.get(account) !== socket)
265
+ return;
266
+ this.sockets.delete(account);
267
+ this.clearRefresh(account);
268
+ socket.close();
269
+ }
270
+ /**
271
+ * @internal Called when the server refused a session token or the session
272
+ * key. Asks the server whether the grant is still active; drops every
273
+ * account and throws if it is not.
274
+ */
275
+ async confirmActive() {
276
+ this.statusCheck ?? (this.statusCheck = this.checkGrantState().finally(() => {
277
+ this.statusCheck = undefined;
278
+ }));
279
+ await this.statusCheck;
280
+ if (this.dropped != null)
281
+ throw this.dropped;
282
+ }
283
+ /**
284
+ * `GET /v2/sessions/{grant_id}/status` needs no token, so it still answers
285
+ * once the session's tokens are refused. A 404 with `NOT_FOUND` means the
286
+ * grant is gone; any other 404 (e.g. an unrouted path) is transient.
287
+ */
288
+ async checkGrantState() {
289
+ let response;
290
+ try {
291
+ response = await this.transport({
292
+ method: 'GET',
293
+ url: `${this.apiUrl}${this.grantPath()}/status`,
294
+ headers: {},
295
+ });
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ let state;
301
+ if (response.status === 404) {
302
+ const error = response.body?.error;
303
+ if (error === 'NOT_FOUND')
304
+ state = 'revoked';
305
+ }
306
+ else if (response.status >= 200 && response.status < 300) {
307
+ state = response.body?.state;
308
+ }
309
+ if (state === 'revoked') {
310
+ this.drop(new SessionGrantError('GRANT_REVOKED', 'session revoked'));
311
+ }
312
+ else if (state === 'expired') {
313
+ this.drop(new SessionGrantError('GRANT_EXPIRED', 'session expired'));
314
+ }
315
+ // Anything else is transient: callers fail this attempt, and sockets
316
+ // retry with backoff.
317
+ return state === 'active' || state === 'revoked' || state === 'expired'
318
+ ? state
319
+ : undefined;
320
+ }
321
+ grantPath() {
322
+ return `${SESSIONS_PATH}/${encodeURIComponent(this.params.session.grantId)}`;
323
+ }
324
+ async send(req, token) {
325
+ const response = await this.transport({
326
+ method: req.method,
327
+ url: `${this.apiUrl}${req.path}`,
328
+ headers: {
329
+ Authorization: `Bearer ${token}`,
330
+ ...(req.body !== undefined
331
+ ? { 'Content-Type': 'application/json' }
332
+ : {}),
333
+ },
334
+ body: req.body !== undefined ? JSON.stringify(req.body) : undefined,
335
+ });
336
+ if (response.status >= 200 && response.status < 300)
337
+ return response.body;
338
+ return new SessionApiError(response.status, response.body);
339
+ }
340
+ teardown() {
341
+ this.tokens.clear();
342
+ for (const timer of this.refreshTimers.values())
343
+ clearTimeout(timer);
344
+ this.refreshTimers.clear();
345
+ if (this.expiryTimer != null)
346
+ clearTimeout(this.expiryTimer);
347
+ this.expiryTimer = undefined;
348
+ for (const socket of this.sockets.values())
349
+ socket.close();
350
+ this.sockets.clear();
351
+ }
352
+ assertLive() {
353
+ if (this.dropped != null)
354
+ throw this.dropped;
355
+ if (this.closed)
356
+ throw new Error('SessionAccounts is closed');
357
+ try {
358
+ assertGrantActive(this.params.session.grant, this.now());
359
+ }
360
+ catch (error) {
361
+ // Only expiry ends the session; a skewed local clock does not.
362
+ if (error instanceof SessionGrantError &&
363
+ error.code === 'GRANT_EXPIRED') {
364
+ this.drop(error);
365
+ throw error;
366
+ }
367
+ }
368
+ }
369
+ resolveAccount(account) {
370
+ this.assertLive();
371
+ let id;
372
+ try {
373
+ id = canonicalFelt(account);
374
+ }
375
+ catch {
376
+ id = account;
377
+ }
378
+ if (!this.accounts.includes(id)) {
379
+ throw new SessionGrantError('ACCOUNT_NOT_IN_GRANT', `${account} is not listed in the grant`);
380
+ }
381
+ return id;
382
+ }
383
+ /**
384
+ * A token needs refreshing within the margin before it expires. Tokens cut
385
+ * short by the grant's own expiry are kept to the end: re-minting cannot
386
+ * extend them, and the expiry timer drops everything at that point.
387
+ */
388
+ needsRefresh(token) {
389
+ const now = this.now();
390
+ if (token.expiresAt >= this.params.session.grant.expiresAt) {
391
+ return now >= token.expiresAt;
392
+ }
393
+ const margin = Math.min(this.refreshMargin, Math.floor((token.expiresAt - token.mintedAt) / 2));
394
+ return now >= token.expiresAt - margin;
395
+ }
396
+ async mint(account) {
397
+ const pending = this.inflight.get(account);
398
+ if (pending != null)
399
+ return await pending;
400
+ const promise = this.doMint(account).finally(() => {
401
+ this.inflight.delete(account);
402
+ });
403
+ this.inflight.set(account, promise);
404
+ return await promise;
405
+ }
406
+ async doMint(account) {
407
+ const { grant, key } = this.params.session;
408
+ const now = this.now();
409
+ const expiration = Math.min(now + SESSION_AUTH_MAX_TTL, grant.expiresAt);
410
+ const typedData = buildAuthTypedData(this.params.session.grant.paradexChain, now, expiration);
411
+ const signature = await key.signTypedData(typedData, account);
412
+ // No `token_usage` parameter: the server derives it from the grant. The
413
+ // key goes in the path, or the server checks the account's main key.
414
+ const response = await this.transport({
415
+ method: 'POST',
416
+ url: `${this.apiUrl}${sessionAuthPath(key.publicKey)}`,
417
+ headers: {
418
+ 'PARADEX-STARKNET-ACCOUNT': account,
419
+ 'PARADEX-STARKNET-SIGNATURE': JSON.stringify(signature),
420
+ 'PARADEX-TIMESTAMP': String(now),
421
+ 'PARADEX-SIGNATURE-EXPIRATION': String(expiration),
422
+ },
423
+ });
424
+ if (response.status < 200 || response.status >= 300) {
425
+ const error = new SessionApiError(response.status, response.body);
426
+ if (isAuthRefusal(error))
427
+ await this.confirmActive();
428
+ throw error;
429
+ }
430
+ const token = response.body?.jwt_token;
431
+ if (typeof token !== 'string' || token === '') {
432
+ throw new SessionApiError(response.status, {
433
+ error: 'INVALID_RESPONSE',
434
+ message: '/auth returned no jwt_token',
435
+ });
436
+ }
437
+ // The grant may have been dropped while /auth was in flight.
438
+ this.assertLive();
439
+ const expiresAt = Math.min(jwtExpiry(token) ?? expiration, expiration);
440
+ const cached = { token, mintedAt: now, expiresAt };
441
+ this.tokens.set(account, cached);
442
+ const socket = this.sockets.get(account);
443
+ if (socket != null) {
444
+ this.scheduleRefresh(account);
445
+ // A REST call may have minted this token; move the socket onto it.
446
+ void socket.reauthenticate(token);
447
+ }
448
+ return token;
449
+ }
450
+ clearRefresh(account) {
451
+ const existing = this.refreshTimers.get(account);
452
+ if (existing != null)
453
+ clearTimeout(existing);
454
+ this.refreshTimers.delete(account);
455
+ }
456
+ /** @internal Keeps an account's socket authenticated across JWT expiry. */
457
+ scheduleRefresh(account) {
458
+ this.clearRefresh(account);
459
+ const token = this.tokens.get(account);
460
+ // A token that runs to the grant's expiry is never refreshed.
461
+ if (token == null ||
462
+ token.expiresAt >= this.params.session.grant.expiresAt) {
463
+ return;
464
+ }
465
+ const margin = Math.min(this.refreshMargin, Math.floor((token.expiresAt - token.mintedAt) / 2));
466
+ const delayMs = Math.max(1000, (token.expiresAt - margin - this.now()) * 1000);
467
+ this.refreshTimers.set(account, setTimeout(() => {
468
+ this.refreshTimers.delete(account);
469
+ if (!this.isLive)
470
+ return;
471
+ this.tokens.delete(account);
472
+ void this.getJwt(account)
473
+ .then(async (fresh) => {
474
+ await this.sockets.get(account)?.reauthenticate(fresh);
475
+ })
476
+ .catch(() => {
477
+ // Restart the socket; its reconnect path retries /auth with
478
+ // backoff. Drops have already torn everything down.
479
+ this.sockets.get(account)?.restart();
480
+ });
481
+ }, Math.min(delayMs, MAX_TIMER_DELAY_MS)));
482
+ }
483
+ scheduleExpiry() {
484
+ const remainingMs = (this.params.session.grant.expiresAt - this.now()) * 1000;
485
+ this.expiryTimer = setTimeout(() => {
486
+ this.expiryTimer = undefined;
487
+ if (!this.isLive)
488
+ return;
489
+ if (this.now() >= this.params.session.grant.expiresAt) {
490
+ this.drop(new SessionGrantError('GRANT_EXPIRED', 'session grant expired'));
491
+ }
492
+ else {
493
+ this.scheduleExpiry();
494
+ }
495
+ }, Math.max(0, Math.min(remainingMs, MAX_TIMER_DELAY_MS)));
496
+ }
497
+ }
498
+ /** One authenticated websocket for one account. */
499
+ class AccountSocket {
500
+ constructor(owner, account, rpcTimeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
501
+ this.owner = owner;
502
+ this.account = account;
503
+ this.rpcTimeoutMs = rpcTimeoutMs;
504
+ this.handlers = new Map();
505
+ /** Subscriptions sent on the current connection, settled or pending. */
506
+ this.subscribed = new Map();
507
+ this.pending = new Map();
508
+ this.nextId = 1;
509
+ this.reconnectAttempts = 0;
510
+ this.closed = false;
511
+ }
512
+ async subscribe(channel, handler) {
513
+ let set = this.handlers.get(channel);
514
+ if (set == null) {
515
+ set = new Set();
516
+ this.handlers.set(channel, set);
517
+ }
518
+ set.add(handler);
519
+ try {
520
+ await this.connect();
521
+ await this.ensureSubscribed(channel);
522
+ }
523
+ catch (error) {
524
+ this.removeHandler(channel, handler, false);
525
+ throw error;
526
+ }
527
+ return () => {
528
+ this.removeHandler(channel, handler, true);
529
+ };
530
+ }
531
+ async reauthenticate(token) {
532
+ // Not authenticated yet (open() will use the newest token), or already
533
+ // on this token.
534
+ if (this.ws?.readyState !== WS_OPEN || this.authedToken == null)
535
+ return;
536
+ if (this.authedToken === token)
537
+ return;
538
+ this.authedToken = token;
539
+ try {
540
+ await this.call('auth', { bearer: token });
541
+ }
542
+ catch {
543
+ void this.owner.confirmActive().catch(() => { });
544
+ this.restart();
545
+ }
546
+ }
547
+ /** Drops the connection; the reconnect path takes over. */
548
+ restart() {
549
+ this.ws?.close();
550
+ }
551
+ close() {
552
+ this.closed = true;
553
+ if (this.reconnectTimer != null)
554
+ clearTimeout(this.reconnectTimer);
555
+ this.reconnectTimer = undefined;
556
+ this.rejectPending(new Error('socket closed'));
557
+ const ws = this.ws;
558
+ this.ws = undefined;
559
+ this.ready = undefined;
560
+ ws?.close(1000, 'closed');
561
+ }
562
+ removeHandler(channel, handler, unsubscribe) {
563
+ const current = this.handlers.get(channel);
564
+ if (current?.delete(handler) !== true || current.size > 0)
565
+ return;
566
+ this.handlers.delete(channel);
567
+ const wasSubscribed = this.subscribed.delete(channel);
568
+ if (this.handlers.size === 0) {
569
+ this.owner.socketIdle(this.account, this);
570
+ }
571
+ else if (unsubscribe &&
572
+ wasSubscribed &&
573
+ this.ws?.readyState === WS_OPEN) {
574
+ this.call('unsubscribe', { channel }).catch(() => { });
575
+ }
576
+ }
577
+ async ensureSubscribed(channel) {
578
+ let pending = this.subscribed.get(channel);
579
+ if (pending == null) {
580
+ pending = this.call('subscribe', { channel }).then(() => undefined);
581
+ this.subscribed.set(channel, pending);
582
+ pending.catch(() => {
583
+ if (this.subscribed.get(channel) === pending) {
584
+ this.subscribed.delete(channel);
585
+ }
586
+ });
587
+ }
588
+ await pending;
589
+ }
590
+ async connect() {
591
+ if (this.closed)
592
+ throw new Error('socket closed');
593
+ this.ready ?? (this.ready = this.open());
594
+ await this.ready;
595
+ }
596
+ async open() {
597
+ const ws = this.owner.createWebSocket();
598
+ this.ws = ws;
599
+ this.subscribed.clear();
600
+ this.authedToken = undefined;
601
+ try {
602
+ await new Promise((resolve, reject) => {
603
+ ws.onopen = () => {
604
+ resolve();
605
+ };
606
+ ws.onerror = () => {
607
+ reject(new Error('websocket error'));
608
+ };
609
+ ws.onclose = () => {
610
+ reject(new Error('websocket closed before opening'));
611
+ };
612
+ });
613
+ }
614
+ catch (error) {
615
+ if (this.ws === ws)
616
+ this.ws = undefined;
617
+ this.ready = undefined;
618
+ throw error;
619
+ }
620
+ ws.onmessage = (event) => {
621
+ this.onMessage(event.data);
622
+ };
623
+ ws.onclose = () => {
624
+ this.onClose(ws);
625
+ };
626
+ ws.onerror = null;
627
+ try {
628
+ const token = await this.owner.getJwt(this.account);
629
+ await this.call('auth', { bearer: token });
630
+ this.authedToken = token;
631
+ }
632
+ catch (error) {
633
+ this.ready = undefined;
634
+ ws.close();
635
+ void this.owner.confirmActive().catch(() => { });
636
+ throw error;
637
+ }
638
+ this.owner.scheduleRefresh(this.account);
639
+ // A REST call may have minted a newer token while `auth` was in flight.
640
+ const latest = this.owner.cachedToken(this.account);
641
+ if (latest != null && latest !== this.authedToken) {
642
+ void this.reauthenticate(latest);
643
+ }
644
+ this.reconnectAttempts = 0;
645
+ if (this.reconnectTimer != null)
646
+ clearTimeout(this.reconnectTimer);
647
+ this.reconnectTimer = undefined;
648
+ // Every connection carries every channel, including ones a pending
649
+ // reconnect would have restored.
650
+ for (const channel of this.handlers.keys()) {
651
+ this.ensureSubscribed(channel).catch(() => { });
652
+ }
653
+ }
654
+ async call(method, params) {
655
+ const ws = this.ws;
656
+ if (ws == null || ws.readyState !== WS_OPEN) {
657
+ throw new Error('websocket is not open');
658
+ }
659
+ const id = this.nextId++;
660
+ return await new Promise((resolve, reject) => {
661
+ const timer = setTimeout(() => {
662
+ if (!this.pending.delete(id))
663
+ return;
664
+ reject(new Error(`websocket ${method} timed out`));
665
+ // A silent connection is not trustworthy; start over.
666
+ this.restart();
667
+ }, this.rpcTimeoutMs);
668
+ this.pending.set(id, { resolve, reject, timer });
669
+ ws.send(JSON.stringify({ jsonrpc: '2.0', method, params, id }));
670
+ });
671
+ }
672
+ onMessage(data) {
673
+ let message;
674
+ try {
675
+ message = JSON.parse(String(data));
676
+ }
677
+ catch {
678
+ return;
679
+ }
680
+ if (typeof message.id === 'number' && this.pending.has(message.id)) {
681
+ const call = this.pending.get(message.id);
682
+ this.pending.delete(message.id);
683
+ if (call != null)
684
+ clearTimeout(call.timer);
685
+ if (message.error != null)
686
+ call?.reject(message.error);
687
+ else
688
+ call?.resolve(message.result);
689
+ return;
690
+ }
691
+ if (message.error != null) {
692
+ // An unsolicited error may mean the session was revoked.
693
+ void this.owner.confirmActive().catch(() => { });
694
+ return;
695
+ }
696
+ const channel = message.params?.channel;
697
+ if (message.method === 'subscription' && typeof channel === 'string') {
698
+ for (const handler of this.handlers.get(channel) ?? []) {
699
+ handler(message.params?.data);
700
+ }
701
+ }
702
+ }
703
+ onClose(ws) {
704
+ if (this.ws !== ws)
705
+ return;
706
+ this.ws = undefined;
707
+ this.ready = undefined;
708
+ this.subscribed.clear();
709
+ this.authedToken = undefined;
710
+ this.rejectPending(new Error('websocket closed'));
711
+ this.scheduleReconnect();
712
+ }
713
+ scheduleReconnect() {
714
+ if (this.closed ||
715
+ !this.owner.isLive ||
716
+ this.handlers.size === 0 ||
717
+ this.reconnectTimer != null) {
718
+ return;
719
+ }
720
+ const delay = Math.min(RECONNECT_BASE_MS * 2 ** this.reconnectAttempts, RECONNECT_MAX_MS);
721
+ this.reconnectAttempts++;
722
+ this.reconnectTimer = setTimeout(() => {
723
+ this.reconnectTimer = undefined;
724
+ void this.resubscribe();
725
+ }, delay);
726
+ }
727
+ async resubscribe() {
728
+ if (this.closed || !this.owner.isLive)
729
+ return;
730
+ try {
731
+ await this.connect();
732
+ await Promise.all([...this.handlers.keys()].map(async (channel) => {
733
+ await this.ensureSubscribed(channel);
734
+ }));
735
+ }
736
+ catch {
737
+ this.scheduleReconnect();
738
+ }
739
+ }
740
+ rejectPending(error) {
741
+ for (const call of this.pending.values()) {
742
+ clearTimeout(call.timer);
743
+ call.reject(error);
744
+ }
745
+ this.pending.clear();
746
+ }
747
+ }