@proof-labs/trading-sdk 7.3.0 → 8.1.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 (52) hide show
  1. package/README.md +88 -24
  2. package/dist/account-recovery.d.ts +117 -0
  3. package/dist/account-recovery.d.ts.map +1 -0
  4. package/dist/account-recovery.js +330 -0
  5. package/dist/account-recovery.js.map +1 -0
  6. package/dist/client.d.ts +42 -54
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +138 -160
  9. package/dist/client.js.map +1 -1
  10. package/dist/codec-adapter.d.ts.map +1 -1
  11. package/dist/codec-adapter.js +13 -0
  12. package/dist/codec-adapter.js.map +1 -1
  13. package/dist/errors.d.ts +23 -1
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/errors.js +73 -2
  16. package/dist/errors.js.map +1 -1
  17. package/dist/feed-types.d.ts +22 -0
  18. package/dist/feed-types.d.ts.map +1 -1
  19. package/dist/feed.d.ts +52 -0
  20. package/dist/feed.d.ts.map +1 -1
  21. package/dist/feed.js +342 -24
  22. package/dist/feed.js.map +1 -1
  23. package/dist/financial-state.d.ts.map +1 -1
  24. package/dist/financial-state.js +16 -4
  25. package/dist/financial-state.js.map +1 -1
  26. package/dist/gateway-reads.d.ts +5 -0
  27. package/dist/gateway-reads.d.ts.map +1 -1
  28. package/dist/gateway-reads.js +7 -0
  29. package/dist/gateway-reads.js.map +1 -1
  30. package/dist/governance-query.d.ts.map +1 -1
  31. package/dist/governance-query.js +69 -0
  32. package/dist/governance-query.js.map +1 -1
  33. package/dist/index.d.ts +6 -3
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +4 -2
  36. package/dist/index.js.map +1 -1
  37. package/dist/insurance-funding.d.ts +6 -0
  38. package/dist/insurance-funding.d.ts.map +1 -0
  39. package/dist/insurance-funding.js +54 -0
  40. package/dist/insurance-funding.js.map +1 -0
  41. package/dist/liquidation-config.d.ts +11 -0
  42. package/dist/liquidation-config.d.ts.map +1 -0
  43. package/dist/liquidation-config.js +54 -0
  44. package/dist/liquidation-config.js.map +1 -0
  45. package/dist/liquidation-events.d.ts +135 -0
  46. package/dist/liquidation-events.d.ts.map +1 -0
  47. package/dist/liquidation-events.js +273 -0
  48. package/dist/liquidation-events.js.map +1 -0
  49. package/dist/types.d.ts +88 -13
  50. package/dist/types.d.ts.map +1 -1
  51. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  52. package/package.json +1 -1
@@ -47,6 +47,12 @@ export interface AccountSnapshotFrame {
47
47
  type: "snapshot";
48
48
  owner: string;
49
49
  account: unknown;
50
+ /** `"initial"` for a subscription's first snapshot, `"resent"` for one
51
+ * resent to a listener that joined later. Absent before gateway 7.9.0. */
52
+ snapshot?: "initial" | "resent";
53
+ /** The block height the snapshot was read at. Absent from gateways and
54
+ * nodes that do not report it. */
55
+ height?: number;
50
56
  }
51
57
  /** A live engine event for a subscribed owner. `type` is the gateway's
52
58
  * normalised family (`"order_update"`, `"fill"`, …); `eventType` is the
@@ -57,6 +63,22 @@ export interface AccountEventFrame {
57
63
  eventType: string;
58
64
  owner: string;
59
65
  height: number;
66
+ /** The event's `/v1/history/account-events` row key (gateway 7.9.0 and
67
+ * later): the row's `tx_hash` (the uppercase transaction hash, or
68
+ * `height-{h}-kind-block-event-{i}` for a block-level event). */
69
+ txHash?: string | null;
70
+ /** The transaction's position in its block. Live frames carry it (gateway
71
+ * 7.9.0 and later; read as 0 when the block omits it, `null` for a
72
+ * block-level event). A backfilled event carries the history row's
73
+ * `tx_position`, which history serves only when one block carries the
74
+ * same transaction hash more than once, and `null` otherwise. */
75
+ txIndex?: number | null;
76
+ /** The row's `event_index`: the event's index among its transaction's (or
77
+ * block's) events. */
78
+ eventIndex?: number;
79
+ /** True when the SDK delivered this event from history after a reconnect
80
+ * rather than from the live feed. */
81
+ backfilled?: boolean;
60
82
  payload: Record<string, unknown>;
61
83
  }
62
84
  export type AccountFrame = AccountSnapshotFrame | AccountE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AAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;sEAIkE;IAClE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB;2BACuB;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;0CACsC;IACtC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,MAAM,MAAM,YAAY,GAAG,oBAAoB,GAAG,iBAAiB,CAAC;AAEpE,+DAA+D;AAC/D,MAAM,MAAM,SAAS,GAAG,cAAc,GAAG,UAAU,GAAG,YAAY,CAAC;AAEnE;iEACiE;AACjE,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,OAAO,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,iDAAiD;AACjD,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,YAAY,GAAG,MAAM,GAAG,cAAc,CAAC"}
package/dist/feed.d.ts CHANGED
@@ -72,6 +72,19 @@ type FrameHandler = (frame: FeedFrame) => void;
72
72
  * - **auto-reconnect** — on an unexpected close it reconnects with
73
73
  * exponential backoff and **replays every active subscription**, so a
74
74
  * fresh snapshot arrives. Missed live events are not replayed.
75
+ * - **late listeners** — the gateway sends one snapshot per socket
76
+ * subscription. A listener that joins an active `orderbook` channel
77
+ * receives a snapshot of the book the feed has built; one that joins an
78
+ * active `accountEvents` channel re-subscribes, and the gateway resends
79
+ * the account snapshot. Neither sees an update or event before its
80
+ * snapshot. A gateway too old to resend leaves the account listener on
81
+ * the live events, as before.
82
+ * - **subscribe retry** — when signing an account subscribe fails, or the
83
+ * gateway refuses it with 401, 429 or 503, and the channel has no
84
+ * subscription on the socket, listeners get an `error` frame and the
85
+ * subscribe is retried with the reconnect backoff. After
86
+ * `MAX_AUTH_RETRIES` consecutive failures it gives up with one final
87
+ * `error` frame; a replaced socket starts a fresh retry budget.
75
88
  * - **heartbeat** — an app-level `ping` runs on an interval; a missing
76
89
  * `pong` forces a reconnect, catching half-open sockets the OS hasn't
77
90
  * torn down.
@@ -149,8 +162,47 @@ export declare class GatewayFeed {
149
162
  private stopHeartbeat;
150
163
  private sendSubscribe;
151
164
  private sendUnsubscribe;
165
+ /** False when there is no socket or the send threw. */
152
166
  private send;
153
167
  private handleMessage;
168
+ /** A gateway that predates resending (its repeat ack has no
169
+ * `snapshot: "resent"`) sends no snapshot, so waiting account listeners
170
+ * are released to the live events instead of waiting for ever. */
171
+ private handleSubscribed;
172
+ private confirm;
173
+ /** Account listeners waiting on a snapshot that will not come take the
174
+ * live events instead, as before the gateway could resend one: the events
175
+ * held while they waited are delivered first, in order. Orderbook
176
+ * listeners never wait on the gateway once a local book exists. */
177
+ private releaseAwaiting;
178
+ private recordForId;
179
+ private deliver;
180
+ private primeLateListener;
181
+ /** Give an awaiting listener a snapshot of the local book. With no book yet
182
+ * it keeps waiting for the gateway's own snapshot. */
183
+ private primeFromBook;
184
+ /** A new socket starts from the gateway's next snapshot, never from a book
185
+ * the old socket built. The subscribe in flight died with the socket; the
186
+ * replay on open sends a fresh one. */
187
+ private forgetBooks;
188
+ private cancelRetry;
189
+ /**
190
+ * The authentication for a subscribe failed. When the channel already has a
191
+ * subscription on this socket (a repeat for a late listener), live delivery
192
+ * goes on. Otherwise nothing is subscribed while the socket stays healthy,
193
+ * so the failure goes to the listeners as an `error` frame and the
194
+ * subscribe is retried with the reconnect backoff until it succeeds, the
195
+ * subscription is dropped, the retry budget runs out, or the socket is
196
+ * replaced.
197
+ */
198
+ private authFailed;
199
+ /** The subscribe retry budget is spent: tell the listeners once and leave
200
+ * the subscription unconfirmed but quiet. A replaced socket replays it
201
+ * with a fresh budget. */
202
+ private giveUpRetrying;
203
+ /** Subscribe again after the reconnect backoff, on this socket only, while
204
+ * the subscription is still unconfirmed. Returns the delay. */
205
+ private scheduleRetry;
154
206
  private dispatchError;
155
207
  private setState;
156
208
  }
@@ -1 +1 @@
1
- {"version":3,"file":"feed.d.ts","sourceRoot":"","sources":["../src/feed.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,WAAW,EACX,cAAc,EACd,SAAS,EACT,SAAS,EACT,cAAc,EACd,UAAU,EACX,MAAM,iBAAiB,CAAC;AAEzB;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,IAAI,IAAI,CAAC;IACd,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACvC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACxC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACxC,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;CACrD;AAED;;wEAEwE;AACxE,MAAM,MAAM,gBAAgB,GAAG,CAC7B,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,KAC3C,aAAa,CAAC;AAEnB,wDAAwD;AACxD,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AACD,oFAAoF;AACpF,MAAM,MAAM,mBAAmB,GAAG,CAChC,KAAK,EAAE,MAAM,KACV,OAAO,CAAC,eAAe,GAAG,MAAM,CAA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ribed", "pong", "error"]);
2
+ /** Gateway refusal codes of an account subscribe that a retry can pass. */
3
+ const RETRYABLE_REFUSALS = new Set([401, 429, 503]);
4
+ /** Consecutive failed authentications after which a first subscribe stops
5
+ * being retried: a deterministic failure (the signer's key is not the
6
+ * account's key) would otherwise retry for ever. */
7
+ const MAX_AUTH_RETRIES = 5;
2
8
  /**
3
9
  * Lifecycle manager for the gateway's multiplexed `/ws` feed.
4
10
  *
@@ -10,6 +16,19 @@ const CONTROL_TYPES = new Set(["subscribed", "unsubscribed", "pong", "error"]);
10
16
  * - **auto-reconnect** — on an unexpected close it reconnects with
11
17
  * exponential backoff and **replays every active subscription**, so a
12
18
  * fresh snapshot arrives. Missed live events are not replayed.
19
+ * - **late listeners** — the gateway sends one snapshot per socket
20
+ * subscription. A listener that joins an active `orderbook` channel
21
+ * receives a snapshot of the book the feed has built; one that joins an
22
+ * active `accountEvents` channel re-subscribes, and the gateway resends
23
+ * the account snapshot. Neither sees an update or event before its
24
+ * snapshot. A gateway too old to resend leaves the account listener on
25
+ * the live events, as before.
26
+ * - **subscribe retry** — when signing an account subscribe fails, or the
27
+ * gateway refuses it with 401, 429 or 503, and the channel has no
28
+ * subscription on the socket, listeners get an `error` frame and the
29
+ * subscribe is retried with the reconnect backoff. After
30
+ * `MAX_AUTH_RETRIES` consecutive failures it gives up with one final
31
+ * `error` frame; a replaced socket starts a fresh retry budget.
13
32
  * - **heartbeat** — an app-level `ping` runs on an interval; a missing
14
33
  * `pong` forces a reconnect, catching half-open sockets the OS hasn't
15
34
  * torn down.
@@ -119,6 +138,27 @@ export class GatewayFeed {
119
138
  let record = this.subs.get(key);
120
139
  if (record) {
121
140
  record.listeners.add(listener);
141
+ // The gateway sends a snapshot once per socket subscription, so a late
142
+ // orderbook listener is given one built from the local book. Delivered
143
+ // after `subscribe` returns, never inside it.
144
+ if (record.channel === "orderbook") {
145
+ const joined = record;
146
+ joined.awaitingSnapshot.add(listener);
147
+ queueMicrotask(() => this.primeLateListener(key, joined, listener));
148
+ }
149
+ else if (record.channel === "accountEvents") {
150
+ // Account events cannot be rebuilt locally, so a repeat subscribe
151
+ // asks the gateway to resend the account snapshot. Closed or
152
+ // reconnecting, the replay on open brings a snapshot anyway. One
153
+ // resend in flight serves every listener that joins while it is
154
+ // pending: its snapshot releases them all.
155
+ record.awaitingSnapshot.add(listener);
156
+ // A pending retry brings the first snapshot, which releases it.
157
+ if (this.state === "open" &&
158
+ !record.resendPending &&
159
+ record.retryTimer == null)
160
+ this.sendSubscribe(record);
161
+ }
122
162
  }
123
163
  else {
124
164
  record = {
@@ -128,6 +168,14 @@ export class GatewayFeed {
128
168
  lastId: 0,
129
169
  auth,
130
170
  generation: 0,
171
+ book: null,
172
+ awaitingSnapshot: new Set(),
173
+ pendingEvents: new Map(),
174
+ resendPending: false,
175
+ confirmed: false,
176
+ snapshotOnSocket: false,
177
+ retryTimer: null,
178
+ retryAttempts: 0,
131
179
  };
132
180
  this.subs.set(key, record);
133
181
  this.ensureConnected();
@@ -139,6 +187,8 @@ export class GatewayFeed {
139
187
  if (!r || r !== record)
140
188
  return;
141
189
  r.listeners.delete(listener);
190
+ r.awaitingSnapshot.delete(listener);
191
+ r.pendingEvents.delete(listener);
142
192
  if (r.listeners.size === 0)
143
193
  this.dropRecord(key, r);
144
194
  };
@@ -147,6 +197,7 @@ export class GatewayFeed {
147
197
  * close the socket once the last subscription is gone. Shared by the
148
198
  * per-listener disposer and the by-key `unsubscribe*` methods. */
149
199
  dropRecord(key, record) {
200
+ this.cancelRetry(record);
150
201
  this.subs.delete(key);
151
202
  if (this.state === "open")
152
203
  this.sendUnsubscribe(record);
@@ -157,6 +208,8 @@ export class GatewayFeed {
157
208
  * the next `subscribe`. Idempotent. */
158
209
  close() {
159
210
  this.closedByUser = true;
211
+ for (const record of this.subs.values())
212
+ this.cancelRetry(record);
160
213
  this.subs.clear();
161
214
  this.clearReconnect();
162
215
  this.stopHeartbeat();
@@ -207,6 +260,7 @@ export class GatewayFeed {
207
260
  this.stopHeartbeat();
208
261
  ws.onopen = ws.onclose = ws.onerror = ws.onmessage = null;
209
262
  this.ws = null;
263
+ this.forgetBooks();
210
264
  if (this.closedByUser || this.subs.size === 0) {
211
265
  this.setState("closed");
212
266
  return;
@@ -220,6 +274,7 @@ export class GatewayFeed {
220
274
  return;
221
275
  ws.onopen = ws.onclose = ws.onerror = ws.onmessage = null;
222
276
  this.ws = null;
277
+ this.forgetBooks();
223
278
  try {
224
279
  ws.close();
225
280
  }
@@ -284,6 +339,8 @@ export class GatewayFeed {
284
339
  sendSubscribe(record) {
285
340
  const socket = this.ws;
286
341
  const generation = ++record.generation;
342
+ if (record.channel === "accountEvents")
343
+ record.resendPending = true;
287
344
  const key = subKey(record.channel, record.params);
288
345
  const active = () => this.ws === socket &&
289
346
  this.state === "open" &&
@@ -293,7 +350,7 @@ export class GatewayFeed {
293
350
  if (!active())
294
351
  return;
295
352
  record.lastId = this.nextId++;
296
- this.send({
353
+ const sent = this.send({
297
354
  method: "subscribe",
298
355
  id: record.lastId,
299
356
  params: {
@@ -305,6 +362,8 @@ export class GatewayFeed {
305
362
  : {}),
306
363
  },
307
364
  });
365
+ if (!sent)
366
+ this.releaseAwaiting(record);
308
367
  };
309
368
  const provider = record.channel === "accountEvents"
310
369
  ? (record.auth ?? this.accountAuth)
@@ -320,7 +379,8 @@ export class GatewayFeed {
320
379
  .catch((err) => {
321
380
  if (!active())
322
381
  return;
323
- this.onError?.(err instanceof Error ? err : new Error(String(err)));
382
+ // No subscribe goes out, so no snapshot comes back on this socket.
383
+ this.authFailed(record, err instanceof Error ? err : new Error(String(err)));
324
384
  });
325
385
  }
326
386
  sendUnsubscribe(record) {
@@ -330,14 +390,17 @@ export class GatewayFeed {
330
390
  params: { channel: record.channel, ...record.params },
331
391
  });
332
392
  }
393
+ /** False when there is no socket or the send threw. */
333
394
  send(msg) {
334
395
  if (!this.ws)
335
- return;
396
+ return false;
336
397
  try {
337
398
  this.ws.send(JSON.stringify(msg));
399
+ return true;
338
400
  }
339
401
  catch (err) {
340
402
  this.onError?.(err instanceof Error ? err : new Error(String(err)));
403
+ return false;
341
404
  }
342
405
  }
343
406
  handleMessage(text) {
@@ -368,8 +431,12 @@ export class GatewayFeed {
368
431
  this.dispatchError(msg);
369
432
  return;
370
433
  }
434
+ if (type === "subscribed") {
435
+ this.handleSubscribed(msg);
436
+ return;
437
+ }
371
438
  if (type && CONTROL_TYPES.has(type)) {
372
- // "subscribed" / "unsubscribed" acks — no listener action needed.
439
+ // "unsubscribed" acks — no listener action needed.
373
440
  return;
374
441
  }
375
442
  // Data frame: route by channel + key to the owning subscription.
@@ -380,33 +447,224 @@ export class GatewayFeed {
380
447
  const record = this.subs.get(key);
381
448
  if (!record)
382
449
  return;
450
+ this.confirm(record);
451
+ if (record.channel === "orderbook")
452
+ applyToBook(record, msg);
453
+ // A second account snapshot on one socket is a resend a late listener
454
+ // asked for: only the listeners waiting on a snapshot take it.
455
+ const resent = record.channel === "accountEvents" &&
456
+ msg.type === "snapshot" &&
457
+ record.snapshotOnSocket;
458
+ if (record.channel === "accountEvents" && msg.type === "snapshot")
459
+ record.snapshotOnSocket = true;
460
+ // A snapshot means the subscribe that brings it has landed, so a further
461
+ // late listener sends a fresh resend.
462
+ if (record.channel === "accountEvents" && msg.type === "snapshot")
463
+ record.resendPending = false;
383
464
  for (const listener of record.listeners) {
384
- try {
385
- listener(msg);
386
- }
387
- catch (err) {
388
- this.onError?.(err instanceof Error ? err : new Error(String(err)));
465
+ if (resent && !record.awaitingSnapshot.has(listener))
466
+ continue;
467
+ if (record.awaitingSnapshot.has(listener)) {
468
+ if (msg.type === "snapshot") {
469
+ record.awaitingSnapshot.delete(listener);
470
+ // The snapshot covers them, so the events a waiting listener held
471
+ // are dropped with it.
472
+ record.pendingEvents.delete(listener);
473
+ }
474
+ else {
475
+ // An orderbook update is already in the local book, so the snapshot
476
+ // built from it replaces the update. An account event is held until
477
+ // the snapshot arrives; if none does, release delivers the held
478
+ // events so the fallback loses nothing.
479
+ if (record.channel === "orderbook") {
480
+ this.primeFromBook(record, listener);
481
+ }
482
+ else {
483
+ const frame = msg;
484
+ const held = record.pendingEvents.get(listener);
485
+ if (held)
486
+ held.push(frame);
487
+ else
488
+ record.pendingEvents.set(listener, [frame]);
489
+ }
490
+ continue;
491
+ }
389
492
  }
493
+ this.deliver(listener, msg);
494
+ }
495
+ }
496
+ /** A gateway that predates resending (its repeat ack has no
497
+ * `snapshot: "resent"`) sends no snapshot, so waiting account listeners
498
+ * are released to the live events instead of waiting for ever. */
499
+ handleSubscribed(msg) {
500
+ const record = this.recordForId(msg.id);
501
+ if (record)
502
+ this.confirm(record);
503
+ if (msg.note !== "already subscribed" || msg.snapshot === "resent")
504
+ return;
505
+ if (record)
506
+ this.releaseAwaiting(record);
507
+ }
508
+ confirm(record) {
509
+ record.confirmed = true;
510
+ record.retryAttempts = 0;
511
+ this.cancelRetry(record);
512
+ }
513
+ /** Account listeners waiting on a snapshot that will not come take the
514
+ * live events instead, as before the gateway could resend one: the events
515
+ * held while they waited are delivered first, in order. Orderbook
516
+ * listeners never wait on the gateway once a local book exists. */
517
+ releaseAwaiting(record) {
518
+ if (record.channel !== "accountEvents")
519
+ return;
520
+ // No snapshot is coming for these listeners; the next one to join sends
521
+ // a fresh subscribe.
522
+ record.resendPending = false;
523
+ for (const listener of record.awaitingSnapshot) {
524
+ const held = record.pendingEvents.get(listener);
525
+ if (held)
526
+ for (const frame of held)
527
+ this.deliver(listener, frame);
528
+ }
529
+ record.awaitingSnapshot.clear();
530
+ record.pendingEvents.clear();
531
+ }
532
+ recordForId(id) {
533
+ if (typeof id !== "number")
534
+ return undefined;
535
+ for (const record of this.subs.values()) {
536
+ if (record.lastId === id)
537
+ return record;
538
+ }
539
+ return undefined;
540
+ }
541
+ deliver(listener, frame) {
542
+ try {
543
+ listener(frame);
544
+ }
545
+ catch (err) {
546
+ this.onError?.(err instanceof Error ? err : new Error(String(err)));
547
+ }
548
+ }
549
+ primeLateListener(key, record, listener) {
550
+ if (this.subs.get(key) !== record)
551
+ return;
552
+ if (!record.awaitingSnapshot.has(listener))
553
+ return;
554
+ this.primeFromBook(record, listener);
555
+ }
556
+ /** Give an awaiting listener a snapshot of the local book. With no book yet
557
+ * it keeps waiting for the gateway's own snapshot. */
558
+ primeFromBook(record, listener) {
559
+ if (!record.book)
560
+ return;
561
+ record.awaitingSnapshot.delete(listener);
562
+ this.deliver(listener, bookSnapshot(record.book));
563
+ }
564
+ /** A new socket starts from the gateway's next snapshot, never from a book
565
+ * the old socket built. The subscribe in flight died with the socket; the
566
+ * replay on open sends a fresh one. */
567
+ forgetBooks() {
568
+ for (const record of this.subs.values()) {
569
+ record.book = null;
570
+ record.resendPending = false;
571
+ record.confirmed = false;
572
+ record.snapshotOnSocket = false;
573
+ // The next socket's replay subscribes afresh, with a fresh retry
574
+ // budget: the failures on the dead socket were not consecutive with
575
+ // whatever the new socket brings.
576
+ record.retryAttempts = 0;
577
+ this.cancelRetry(record);
578
+ }
579
+ }
580
+ cancelRetry(record) {
581
+ if (record.retryTimer != null) {
582
+ this.clearTimer(record.retryTimer);
583
+ record.retryTimer = null;
584
+ }
585
+ }
586
+ /**
587
+ * The authentication for a subscribe failed. When the channel already has a
588
+ * subscription on this socket (a repeat for a late listener), live delivery
589
+ * goes on. Otherwise nothing is subscribed while the socket stays healthy,
590
+ * so the failure goes to the listeners as an `error` frame and the
591
+ * subscribe is retried with the reconnect backoff until it succeeds, the
592
+ * subscription is dropped, the retry budget runs out, or the socket is
593
+ * replaced.
594
+ */
595
+ authFailed(record, err) {
596
+ this.releaseAwaiting(record);
597
+ this.onError?.(err);
598
+ if (record.confirmed)
599
+ return;
600
+ if (record.retryAttempts >= MAX_AUTH_RETRIES) {
601
+ this.giveUpRetrying(record, `${record.channel} subscription authentication failed: ${err.message}; not retrying after ${MAX_AUTH_RETRIES} failed attempts`);
602
+ return;
390
603
  }
604
+ const delay = this.scheduleRetry(record);
605
+ const frame = {
606
+ type: "error",
607
+ channel: record.channel,
608
+ error: `${record.channel} subscription authentication failed: ${err.message}; retrying in ${delay}ms`,
609
+ };
610
+ for (const listener of record.listeners)
611
+ this.deliver(listener, frame);
612
+ }
613
+ /** The subscribe retry budget is spent: tell the listeners once and leave
614
+ * the subscription unconfirmed but quiet. A replaced socket replays it
615
+ * with a fresh budget. */
616
+ giveUpRetrying(record, reason) {
617
+ const frame = {
618
+ type: "error",
619
+ channel: record.channel,
620
+ error: reason,
621
+ };
622
+ for (const listener of record.listeners)
623
+ this.deliver(listener, frame);
624
+ }
625
+ /** Subscribe again after the reconnect backoff, on this socket only, while
626
+ * the subscription is still unconfirmed. Returns the delay. */
627
+ scheduleRetry(record) {
628
+ const delay = Math.min(this.maxBackoffMs, this.minBackoffMs * 2 ** record.retryAttempts);
629
+ record.retryAttempts += 1;
630
+ const socket = this.ws;
631
+ const key = subKey(record.channel, record.params);
632
+ this.cancelRetry(record);
633
+ record.retryTimer = this.setTimer(() => {
634
+ record.retryTimer = null;
635
+ if (this.ws === socket &&
636
+ this.state === "open" &&
637
+ this.subs.get(key) === record &&
638
+ !record.confirmed)
639
+ this.sendSubscribe(record);
640
+ }, delay);
641
+ return delay;
391
642
  }
392
643
  dispatchError(frame) {
393
644
  // Route to the subscription whose last subscribe carried this id, so a
394
645
  // rejected channel surfaces against the right caller.
395
- if (typeof frame.id === "number") {
396
- for (const record of this.subs.values()) {
397
- if (record.lastId === frame.id) {
398
- // Deliver as a frame the subscriber can pattern-match on `type`.
399
- for (const listener of record.listeners) {
400
- try {
401
- listener(frame);
402
- }
403
- catch (err) {
404
- this.onError?.(err instanceof Error ? err : new Error(String(err)));
405
- }
406
- }
407
- this.onError?.(frame);
408
- return;
409
- }
646
+ const record = this.recordForId(frame.id);
647
+ if (record) {
648
+ // Deliver as a frame the subscriber can pattern-match on `type`.
649
+ for (const listener of record.listeners) {
650
+ this.deliver(listener, frame);
651
+ }
652
+ // A refused repeat subscribe (the resent account snapshot could not be
653
+ // read) brings no snapshot: the waiting listeners take the live events.
654
+ this.releaseAwaiting(record);
655
+ // A refused first account subscribe leaves nothing subscribed on a
656
+ // healthy socket. An expired signature (401), a rate limit (429) or an
657
+ // unreadable snapshot (503) can pass, so it is retried; the listeners
658
+ // already have the gateway's error frame. Once the retry budget has
659
+ // run out the refusals repeat for ever, so it stops with one final
660
+ // error frame.
661
+ if (record.channel === "accountEvents" &&
662
+ !record.confirmed &&
663
+ RETRYABLE_REFUSALS.has(frame.code ?? 0)) {
664
+ if (record.retryAttempts >= MAX_AUTH_RETRIES)
665
+ this.giveUpRetrying(record, `${record.channel} subscription refused (${frame.code}): ${frame.error}; not retrying after ${MAX_AUTH_RETRIES} failed attempts`);
666
+ else
667
+ this.scheduleRetry(record);
410
668
  }
411
669
  }
412
670
  this.onError?.(frame);
@@ -432,6 +690,66 @@ function subKey(channel, src) {
432
690
  }
433
691
  return `${channel}:${src.market ?? ""}`;
434
692
  }
693
+ /** Fold an orderbook data frame into the record's local book. A snapshot
694
+ * replaces it; an update sets one level, and a zero quantity removes it. */
695
+ function applyToBook(record, msg) {
696
+ if (msg.type === "snapshot") {
697
+ record.book = {
698
+ market: Number(msg.market),
699
+ bids: levelMap(msg.bids),
700
+ asks: levelMap(msg.asks),
701
+ };
702
+ return;
703
+ }
704
+ const book = record.book;
705
+ if (msg.type !== "update" || !book)
706
+ return;
707
+ const side = msg.side === "buy" ? book.bids : msg.side === "sell" ? book.asks : null;
708
+ const { price, totalQuantity, orderCount } = msg;
709
+ if (!side ||
710
+ typeof price !== "number" ||
711
+ typeof totalQuantity !== "number" ||
712
+ typeof orderCount !== "number") {
713
+ return;
714
+ }
715
+ if (totalQuantity === 0)
716
+ side.delete(price);
717
+ else
718
+ side.set(price, [totalQuantity, orderCount]);
719
+ }
720
+ function levelMap(levels) {
721
+ const map = new Map();
722
+ if (!Array.isArray(levels))
723
+ return map;
724
+ for (const level of levels) {
725
+ if (!Array.isArray(level))
726
+ continue;
727
+ const [price, totalQuantity, orderCount] = level;
728
+ if (typeof price === "number" &&
729
+ typeof totalQuantity === "number" &&
730
+ typeof orderCount === "number") {
731
+ map.set(price, [totalQuantity, orderCount]);
732
+ }
733
+ }
734
+ return map;
735
+ }
736
+ /** The local book as the gateway orders a snapshot: best price first. */
737
+ function bookSnapshot(book) {
738
+ const levels = (side, bestFirst) => [...side.entries()]
739
+ .sort(([a], [b]) => bestFirst(a, b))
740
+ .map(([price, [totalQuantity, orderCount]]) => [
741
+ price,
742
+ totalQuantity,
743
+ orderCount,
744
+ ]);
745
+ return {
746
+ channel: "orderbook",
747
+ type: "snapshot",
748
+ market: book.market,
749
+ bids: levels(book.bids, (a, b) => b - a),
750
+ asks: levels(book.asks, (a, b) => a - b),
751
+ };
752
+ }
435
753
  function defaultFactory(Impl) {
436
754
  return (url, options) => {
437
755
  const Ctor = Impl ??