@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
package/README.md CHANGED
@@ -210,10 +210,11 @@ class ExchangeClient {
210
210
  getBlock(height?: number): Promise<Record<string, unknown>>;
211
211
  getBlockResults(height: number): Promise<Record<string, unknown>>;
212
212
 
213
- // Streams (gateway-native; mirror the Python SDK)
214
- subscribeAccountEvents(owner: Uint8Array | string, onEvent: (e: Record<string, unknown>) => void, opts?: WsStreamOptions): () => void;
215
- subscribeOrderbookDeltas(market: number, onMessage: (m: Record<string, unknown>) => void, opts?: WsStreamOptions): () => void;
216
- orderbookSnapshot(market: number): Promise<Record<string, unknown>>;
213
+ // Streams (gateway-native)
214
+ subscribeAccount(onFrame: (f: AccountFrame) => void, opts?: { owner?: string; auth?: false; recover?: boolean; onRecovery?: (s: AccountRecoveryStatus) => void }): () => void;
215
+ subscribeOrderbook(market: number, onFrame: (f: OrderbookFrame) => void): () => void;
216
+ subscribeTrades(market: number, onFrame: (f: TradeFrame) => void): () => void;
217
+ orderbookSnapshot(market: number, timeoutMs?: number): Promise<OrderbookSnapshotFrame>;
217
218
  disconnect(): void;
218
219
  }
219
220
  ```
@@ -319,6 +320,24 @@ pages too. Use the status response and block timestamps to present delay; a miss
319
320
  HTTP 404, and unavailable history remains an error. These reads never fabricate
320
321
  blocks or replace errors with empty results.
321
322
 
323
+ ### Candle and order-book mid history
324
+
325
+ ```typescript
326
+ const reads = client.reads();
327
+ const window = { market: 7400, resolution: "5m", limit: 1500 };
328
+ const trades = await (await reads.candles(window, { signal })).json();
329
+ const mid = await (await reads.bbo(window, { signal })).json();
330
+ ```
331
+
332
+ `candles()` reads `/v1/history/candles` (trade-price OHLC); `bbo()` reads
333
+ `/v1/history/bbo`, the same candles envelope built from the indexer's stored
334
+ best-bid/offer samples: OHLC of `(bid + ask) / 2`, each bucket also carrying
335
+ its closing `bid` and `ask`. A bucket with no two-sided sample is absent, so a
336
+ mid series can have gaps a trade series does not. Both take
337
+ `CandleHistoryParams` (`market`, `resolution`, optional ISO `from` / `to`,
338
+ `limit`, opaque `cursor`), return unmodified `Response` objects and preserve
339
+ HTTP errors and cancellation.
340
+
322
341
  ### Loaded engine identity
323
342
 
324
343
  For operational artifact evidence, `await client.reads().version({ signal })`
@@ -434,7 +453,7 @@ string—pass those strings and the cursor through unchanged.
434
453
  The `Action` type is a discriminated union. Every action is:
435
454
 
436
455
  ```typescript
437
- type Action = TraderAction | OperatorAction;
456
+ type Action = TraderAction | OperatorAction | GovernanceAction;
438
457
 
439
458
  type TraderAction =
440
459
  | { type: "PlaceOrder"; data: PlaceOrder }
@@ -460,6 +479,23 @@ operator-provisioned key. See [AGENTS.md](AGENTS.md) → "Operator actions" for
460
479
  usage (e.g. driving the BE-31 multi-source mark via `OracleUpdateComposite` +
461
480
  `UpdateMarketFees` `markSourceMode`).
462
481
 
482
+ #### Governance actions (admin multisig)
483
+
484
+ `GovernanceAction` covers the signer-registry multisig:
485
+
486
+ ```typescript
487
+ type GovernanceAction =
488
+ | { type: "ProposeAdminAction"; data: ProposeAdminAction }
489
+ | { type: "ApproveAdminAction"; data: ApproveAdminAction }
490
+ | { type: "RejectAdminAction"; data: RejectAdminAction }
491
+ | { type: "EmergencyAdminAction"; data: EmergencyAdminAction };
492
+ ```
493
+
494
+ `ProposeAdminAction` and `ApproveAdminAction` carry one `AdminAction` (create a
495
+ market, attach a conditional, schedule an upgrade, and the rest);
496
+ `EmergencyAdminAction` carries one single-signer `EmergencyAction`. Each is
497
+ refused unless the signer is in the current admin signer registry.
498
+
463
499
  ### Options
464
500
 
465
501
  ```typescript
@@ -530,28 +566,33 @@ code should read the structured `code` field: it is authoritative and needs no p
530
566
 
531
567
  ## WebSocket streams
532
568
 
533
- The SDK exposes the gateway's native multiplexed feed — the same two streams
534
- as the Python SDK. Each subscription opens its own connection, auto-reconnects
535
- with exponential backoff (500ms → 30s, ±25% jitter), and returns an
536
- unsubscribe function. `disconnect()` tears down every open stream.
569
+ The SDK exposes the gateway's native multiplexed feed on `/ws`. Account
570
+ events, trades and the orderbook are channels on that one shared connection
571
+ (`subscribeAccount`, `subscribeTrades`, `subscribeOrderbook`). The connection
572
+ auto-reconnects and re-subscribes; every subscription returns an unsubscribe
573
+ function, and `disconnect()` closes the feed.
537
574
 
538
575
  The WS base URL defaults to `gatewayUrl` with its scheme swapped to `ws`/`wss`.
539
576
  If your local stack serves WebSockets on a separate port, set `wsUrl`
540
577
  explicitly (e.g. `ws://localhost:9091`).
541
578
 
542
579
  ```typescript
543
- // Account events: snapshot frame, then incremental events. The SDK tracks
544
- // the highest event_id and replays via after_id on reconnect (no gaps).
545
- const unsub = client.subscribeAccountEvents(address, (event) => {
546
- console.log(event.event_type, event);
580
+ // Account events: a snapshot frame, then live event frames
581
+ // (`order_update`, `fill`, `position_update`, liquidation events, ...).
582
+ // Defaults to the connected signer's address; pass `owner` to watch another.
583
+ const unsub = client.subscribeAccount((frame) => {
584
+ if (frame.type === "snapshot") return;
585
+ console.log(frame.type, frame.eventType, frame.payload);
547
586
  });
548
587
 
549
- // L2 orderbook: first frame is a full `l2Book` snapshot, then deltas.
550
- const unsubBook = client.subscribeOrderbookDeltas(1, (msg) => {
551
- console.log(msg);
588
+ // Orderbook: a `snapshot` frame (`bids` / `asks` levels), then one `update`
589
+ // frame per changed level (a zero `totalQuantity` empties the level).
590
+ const unsubBook = client.subscribeOrderbook(1, (frame) => {
591
+ console.log(frame);
552
592
  });
553
593
 
554
- // One-shot snapshot (opens, reads the first l2Book frame, closes):
594
+ // One-shot snapshot over a connection of its own (never a cached book);
595
+ // rejects with FeedSubscriptionError when the gateway refuses the market:
555
596
  const book = await client.orderbookSnapshot(1);
556
597
 
557
598
  // later:
@@ -560,14 +601,37 @@ unsubBook();
560
601
  client.disconnect(); // closes everything
561
602
  ```
562
603
 
563
- `WsStreamOptions` (third arg) takes `onError?: (err) => void` and
564
- `reconnectBackoffMaxMs?: number`.
565
-
566
- **Auth.** Account streams require auth only when the gateway runs with
604
+ **Reconnect recovery.** A reconnect restores the account snapshot and, by
605
+ default, the account events missed while disconnected: the SDK reads
606
+ `/v1/history/account-events` back to the last event it delivered (or to the
607
+ previous snapshot's `height` when none was delivered), delivers the newer rows
608
+ in history order (marked `backfilled: true`), then the live frames that
609
+ arrived meanwhile, skipping any that history already delivered. It retries
610
+ while `/v1/history/status` shows history has not indexed up to the new
611
+ snapshot's `height`. Events are matched on `height` + `txHash` +
612
+ `eventIndex` + `eventType` + `txIndex`, a missing position matching any,
613
+ since history serves `tx_position` only when one block carries the same
614
+ transaction hash more than once. The settlement names
615
+ `conditional_settled` /
616
+ `conditional_voided` read as their canonical history names `condition_met` /
617
+ `condition_not_met`. A snapshot marked `snapshot: "resent"` (sent because
618
+ another listener joined) is not a reconnect. `onRecovery` reports each
619
+ reconnect's outcome once: `backfilled`, `unverified` (the snapshot carries no
620
+ `height`, so history's coverage cannot be checked), `unsupported` (a gateway
621
+ older than 7.9.0 sends no `txHash` / `eventIndex`; live delivery carries on),
622
+ `boundaryNotFound`, `historyBehind` or `failed`. Pass `recover: false` to turn
623
+ it off. Python's `AccountEventStream` does the same (`recover`,
624
+ `on_recovery`, `RecoveryStatus`); build it with
625
+ `client.account_event_stream(owner)` so its history reads use the gateway URL
626
+ even when `/ws` is on its own port.
627
+
628
+ **Auth.** Account subscriptions require auth only when the gateway runs with
567
629
  `--api-key`. Because a browser `WebSocket` cannot send the `X-Api-Key` header,
568
- the SDK uses the gateway's signed-query auth: with a private key loaded
569
- (`setPrivateKey`) it signs the stream-auth message and appends `public_key` /
570
- `signature` / `timestamp_ms` to the URL automatically. Against an
630
+ the SDK uses the gateway's signed subscription auth: with a private key or
631
+ external signer connected it signs the stream-auth message and adds
632
+ `public_key` / `signature` / `timestamp_ms` to the `accountEvents` subscribe
633
+ message automatically, re-signing on every reconnect. Pass `auth: false` for an
634
+ unsigned watch-only subscription. Against an
571
635
  unauthenticated gateway (e.g. devnet) the owner alone suffices.
572
636
 
573
637
  ## Wire Format
@@ -0,0 +1,117 @@
1
+ import type { AccountEventFrame, AccountFrame } from "./feed-types.js";
2
+ /**
3
+ * The position of one account event, shared by live `/ws` frames (gateway
4
+ * 7.9.0 and later) and `/v1/history/account-events` rows. A transaction hash
5
+ * can recur at different heights, and twice in one block, so all the fields
6
+ * together identify an event. A `txIndex` of `null` is a wildcard: history
7
+ * rows omit `tx_position` for normal blocks, where live frames still carry
8
+ * the real index.
9
+ */
10
+ export interface AccountEventKey {
11
+ height: number;
12
+ txHash: string;
13
+ eventIndex: number;
14
+ eventType: string;
15
+ txIndex: number | null;
16
+ }
17
+ /**
18
+ * What reconnect recovery did, reported once per reconnect.
19
+ *
20
+ * - `backfilled`: every history row after the last delivered event (or, when
21
+ * none was delivered, after the previous snapshot's height) was delivered,
22
+ * in history order, before live delivery resumed, and history had indexed
23
+ * up to the reconnect snapshot's height, so nothing in between is missing.
24
+ * - `unverified`: rows were backfilled as for `backfilled`, but the snapshot
25
+ * carries no `height` (an older gateway or node), so whether history had
26
+ * caught up cannot be checked. Events may be missing. When nothing was
27
+ * delivered before the outage and the previous snapshot had no height
28
+ * either, there is no boundary and nothing is backfilled.
29
+ * - `unsupported`: the live frames carry no history key (`txHash` /
30
+ * `eventIndex`), which means a gateway older than 7.9.0. Nothing was
31
+ * backfilled; events during the outage are not recovered.
32
+ * - `boundaryNotFound`: the last delivered event is not in the history
33
+ * window that was read. Only rows at a later height were delivered; events
34
+ * at the same height as the last delivered one may be missing.
35
+ * - `historyBehind`: history had not indexed up to the snapshot's height,
36
+ * even after waiting `maxAttempts` status reads. Events between the newest
37
+ * history row and the snapshot may be missing.
38
+ * - `failed`: a history read failed, or the gap held more rows than
39
+ * `maxPages` pages, so the boundary was never reached. Nothing was
40
+ * backfilled.
41
+ */
42
+ export type AccountRecoveryStatus = {
43
+ kind: "backfilled";
44
+ delivered: number;
45
+ } | {
46
+ kind: "unverified";
47
+ delivered: number;
48
+ } | {
49
+ kind: "unsupported";
50
+ } | {
51
+ kind: "boundaryNotFound";
52
+ delivered: number;
53
+ } | {
54
+ kind: "historyBehind";
55
+ delivered: number;
56
+ } | {
57
+ kind: "failed";
58
+ error: Error;
59
+ };
60
+ /** One `/v1/history/account-events` row, as the gateway returns it. */
61
+ export interface AccountHistoryRow {
62
+ event_id: number | string;
63
+ owner: string;
64
+ block_height: number;
65
+ tx_hash: string;
66
+ event_index: number;
67
+ event_type: string;
68
+ /** The transaction's position in its block. History serves it only when
69
+ * one block carries the same transaction hash more than once; it is
70
+ * absent otherwise. */
71
+ tx_position?: number;
72
+ payload: Record<string, unknown>;
73
+ }
74
+ /** One newest-first history page (`order=desc`). */
75
+ export interface AccountHistoryPage {
76
+ rows: AccountHistoryRow[];
77
+ nextCursor: string | null;
78
+ }
79
+ export interface AccountRecoveryOptions {
80
+ owner: string;
81
+ onFrame: (frame: AccountFrame) => void;
82
+ onRecovery?: (status: AccountRecoveryStatus) => void;
83
+ /** Read one newest-first page; `cursor` is the previous page's. */
84
+ fetchPage: (cursor: string | null, signal: AbortSignal) => Promise<AccountHistoryPage>;
85
+ /** The newest height history has fully indexed
86
+ * (`/v1/history/status` → `ingest.newest_height`). */
87
+ fetchIndexedHeight: (signal: AbortSignal) => Promise<number>;
88
+ /** Newest-first pages read before giving up on the boundary. */
89
+ maxPages?: number;
90
+ /** Status reads per reconnect, `retryDelayMs` apart, while history lags
91
+ * the snapshot; the default 30 waits out about 30 seconds of indexer lag. */
92
+ maxAttempts?: number;
93
+ retryDelayMs?: number;
94
+ }
95
+ /** The history key of a live frame, or null when the gateway sent none. */
96
+ export declare function liveKey(frame: AccountEventFrame): AccountEventKey | null;
97
+ /**
98
+ * Wrap an account listener so a reconnect backfills the events missed while
99
+ * disconnected.
100
+ *
101
+ * A snapshot after the first, other than one marked `snapshot: "resent"`
102
+ * (sent because another listener joined), marks a re-subscription. The
103
+ * snapshot is passed through at once: it is current state, not part of the
104
+ * event log. Until the backfill finishes, live events are buffered. The
105
+ * backfill waits while history has not indexed up to the new snapshot's
106
+ * height, reads history newest-first down to the last delivered event (or
107
+ * the previous snapshot's height when none was delivered), delivers the
108
+ * newer rows in history order, then flushes the buffer, dropping any live
109
+ * frame history already delivered. If the socket reconnects again during a
110
+ * backfill, only the frames before that snapshot are flushed; the next
111
+ * backfill starts from the last of them and the later frames stay buffered.
112
+ */
113
+ export declare function recoveringAccountHandler(opts: AccountRecoveryOptions): {
114
+ handle: (frame: AccountFrame) => void;
115
+ close: () => void;
116
+ };
117
+ //# sourceMappingURL=account-recovery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-recovery.d.ts","sourceRoot":"","sources":["../src/account-recovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,YAAY,EAEb,MAAM,iBAAiB,CAAC;AAEzB;;;;;;;GAOG;AACH,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAkCD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,MAAM,qBAAqB,GAC7B;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACzC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACzC;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,SAAS,EAAE,M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AgB,OAAO,CAAC,KAAK,EAAE,iBAAiB,GAAG,eAAe,GAAG,IAAI,CAcxE;AA4DD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,sBAAsB,GAAG;IACtE,MAAM,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC;IACtC,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAmMA"}
@@ -0,0 +1,330 @@
1
+ /** Whether two keys denote the same event: the four identifying fields are
2
+ * equal and the positions agree, where `null` agrees with anything. */
3
+ function sameEvent(a, b) {
4
+ return (a.height === b.height &&
5
+ a.txHash === b.txHash &&
6
+ a.eventIndex === b.eventIndex &&
7
+ a.eventType === b.eventType &&
8
+ (a.txIndex === null || b.txIndex === null || a.txIndex === b.txIndex));
9
+ }
10
+ /** Bucket `key` into the map keyed by its four identifying fields, so
11
+ * `sameEvent` only has to be tried against keys they already match. */
12
+ function addEvent(keys, key) {
13
+ const id = keyId(key);
14
+ const bucket = keys.get(id);
15
+ if (bucket)
16
+ bucket.push(key);
17
+ else
18
+ keys.set(id, [key]);
19
+ }
20
+ /** Whether `keys` holds an event `sameEvent` to `key`. */
21
+ function hasEvent(keys, key) {
22
+ return keys.get(keyId(key))?.some((k) => sameEvent(k, key)) ?? false;
23
+ }
24
+ /** Live event family for a history row; mirrors api-gateway
25
+ * `account_ws_message_type`. */
26
+ function familyOf(eventType) {
27
+ switch (eventType) {
28
+ case "trade_executed":
29
+ return "fill";
30
+ case "order_placed":
31
+ case "order_cancelled":
32
+ case "order_amended":
33
+ case "market_order_processed":
34
+ return "order_update";
35
+ case "position_updated":
36
+ case "position_closed":
37
+ return "position_update";
38
+ case "funding_settled":
39
+ return "funding";
40
+ case "position_triggers_set":
41
+ case "position_triggers_cancelled":
42
+ case "position_triggers_invalidated":
43
+ case "position_trigger_activated":
44
+ case "position_trigger_executed":
45
+ case "position_trigger_deferred":
46
+ return "trigger_update";
47
+ case "margin_warning":
48
+ return "margin_update";
49
+ default:
50
+ return "account_event";
51
+ }
52
+ }
53
+ /** Settlement event names before the canonical vocabulary, mapped to the
54
+ * names history rows carry. A gateway that already sends the canonical
55
+ * names passes through unchanged. */
56
+ const LEGACY_EVENT_TYPES = {
57
+ conditional_settled: "condition_met",
58
+ conditional_voided: "condition_not_met",
59
+ };
60
+ function canonicalEventType(eventType) {
61
+ return LEGACY_EVENT_TYPES[eventType] ?? eventType;
62
+ }
63
+ /** The history key of a live frame, or null when the gateway sent none. */
64
+ export function liveKey(frame) {
65
+ if (typeof frame.txHash !== "string" ||
66
+ typeof frame.eventIndex !== "number" ||
67
+ typeof frame.height !== "number")
68
+ return null;
69
+ return {
70
+ height: frame.height,
71
+ txHash: frame.txHash,
72
+ eventIndex: frame.eventIndex,
73
+ eventType: canonicalEventType(frame.eventType),
74
+ txIndex: typeof frame.txIndex === "number" ? frame.txIndex : null,
75
+ };
76
+ }
77
+ function rowKey(row) {
78
+ return {
79
+ height: Number(row.block_height),
80
+ txHash: row.tx_hash,
81
+ eventIndex: Number(row.event_index),
82
+ eventType: canonicalEventType(row.event_type),
83
+ txIndex: typeof row.tx_position === "number" ? row.tx_position : null,
84
+ };
85
+ }
86
+ function keyId(k) {
87
+ return `${k.height}|${k.txHash}|${k.eventIndex}|${k.eventType}`;
88
+ }
89
+ function rowFrame(row) {
90
+ return {
91
+ channel: "accountEvents",
92
+ type: familyOf(row.event_type),
93
+ owner: row.owner,
94
+ eventType: row.event_type,
95
+ height: Number(row.block_height),
96
+ txHash: row.tx_hash,
97
+ txIndex: typeof row.tx_position === "number" ? row.tx_position : null,
98
+ eventIndex: Number(row.event_index),
99
+ payload: row.payload,
100
+ backfilled: true,
101
+ };
102
+ }
103
+ /** A pause that ends early, rejecting, when `signal` aborts. */
104
+ function abortableSleep(ms, signal) {
105
+ return new Promise((resolve, reject) => {
106
+ if (signal.aborted)
107
+ return reject(new Error("closed"));
108
+ const timer = setTimeout(() => {
109
+ signal.removeEventListener("abort", onAbort);
110
+ resolve();
111
+ }, ms);
112
+ const onAbort = () => {
113
+ clearTimeout(timer);
114
+ reject(new Error("closed"));
115
+ };
116
+ signal.addEventListener("abort", onAbort, { once: true });
117
+ });
118
+ }
119
+ const heightOf = (frame) => typeof frame.height === "number" ? frame.height : undefined;
120
+ /**
121
+ * Wrap an account listener so a reconnect backfills the events missed while
122
+ * disconnected.
123
+ *
124
+ * A snapshot after the first, other than one marked `snapshot: "resent"`
125
+ * (sent because another listener joined), marks a re-subscription. The
126
+ * snapshot is passed through at once: it is current state, not part of the
127
+ * event log. Until the backfill finishes, live events are buffered. The
128
+ * backfill waits while history has not indexed up to the new snapshot's
129
+ * height, reads history newest-first down to the last delivered event (or
130
+ * the previous snapshot's height when none was delivered), delivers the
131
+ * newer rows in history order, then flushes the buffer, dropping any live
132
+ * frame history already delivered. If the socket reconnects again during a
133
+ * backfill, only the frames before that snapshot are flushed; the next
134
+ * backfill starts from the last of them and the later frames stay buffered.
135
+ */
136
+ export function recoveringAccountHandler(opts) {
137
+ const maxPages = opts.maxPages ?? 10;
138
+ const maxAttempts = opts.maxAttempts ?? 30;
139
+ const retryDelayMs = opts.retryDelayMs ?? 1000;
140
+ const abort = new AbortController();
141
+ // `undefined`: nothing delivered yet. `null`: the last delivered frame had
142
+ // no history key, so there is no event boundary to recover from.
143
+ let last;
144
+ // Height of the latest snapshot that recovery has caught up to.
145
+ let snapshotHeight;
146
+ let seenSnapshot = false;
147
+ let recovering = false;
148
+ let closed = false;
149
+ let buffer = [];
150
+ // Events a backfill delivered, kept until a live frame passes the newest
151
+ // of their heights: a slow socket can still deliver one the indexer
152
+ // already served.
153
+ let recent = null;
154
+ const deliver = (frame, key) => {
155
+ if (closed)
156
+ return;
157
+ last = key;
158
+ opts.onFrame(frame);
159
+ };
160
+ /** Deliver a live frame unless a backfill already delivered it. */
161
+ const deliverLive = (frame) => {
162
+ const key = liveKey(frame);
163
+ if (key && recent) {
164
+ if (hasEvent(recent.keys, key) || key.height < recent.floor)
165
+ return;
166
+ if (key.height > recent.height)
167
+ recent = null;
168
+ }
169
+ deliver(frame, key);
170
+ };
171
+ const scan = async (boundary) => {
172
+ const newerFirst = [];
173
+ // A height boundary is exact: the snapshot holds everything up to it.
174
+ let found = boundary.key === null;
175
+ let reached = false;
176
+ let cursor = null;
177
+ for (let page = 0; page < maxPages && !reached; page++) {
178
+ const { rows, nextCursor } = await opts.fetchPage(cursor, abort.signal);
179
+ for (const row of rows) {
180
+ const key = rowKey(row);
181
+ if (boundary.key && sameEvent(key, boundary.key)) {
182
+ found = reached = true;
183
+ break;
184
+ }
185
+ if (boundary.key
186
+ ? key.height < boundary.height
187
+ : key.height <= boundary.height) {
188
+ reached = true;
189
+ break;
190
+ }
191
+ newerFirst.push(row);
192
+ }
193
+ if (!nextCursor)
194
+ break;
195
+ cursor = nextCursor;
196
+ if (page === maxPages - 1 && !reached)
197
+ throw new Error(`account history holds more than ${maxPages} pages after the recovery boundary`);
198
+ }
199
+ const rows = newerFirst.reverse();
200
+ return {
201
+ found,
202
+ rows: found || !boundary.key
203
+ ? rows
204
+ : rows.filter((r) => Number(r.block_height) > boundary.height),
205
+ };
206
+ };
207
+ const boundaryNow = () => {
208
+ if (last === null)
209
+ return { kind: "unsupported" };
210
+ if (last)
211
+ return { key: last, height: last.height };
212
+ if (snapshotHeight !== undefined)
213
+ return { key: null, height: snapshotHeight };
214
+ return { kind: "unverified", delivered: 0 };
215
+ };
216
+ const recover = async (snapshot) => {
217
+ const target = heightOf(snapshot);
218
+ const boundary = boundaryNow();
219
+ let status;
220
+ let delivered = new Map();
221
+ let floor = -1;
222
+ if ("kind" in boundary) {
223
+ status = boundary;
224
+ recent = null;
225
+ }
226
+ else {
227
+ try {
228
+ let indexed = target === undefined
229
+ ? -1
230
+ : await opts.fetchIndexedHeight(abort.signal);
231
+ for (let attempt = 1; target !== undefined && indexed < target && attempt < maxAttempts; attempt++) {
232
+ await abortableSleep(retryDelayMs, abort.signal);
233
+ indexed = await opts.fetchIndexedHeight(abort.signal);
234
+ }
235
+ const result = await scan(boundary);
236
+ if (closed)
237
+ return undefined;
238
+ if (boundary.key)
239
+ addEvent(delivered, boundary.key);
240
+ floor = boundary.key ? boundary.height : boundary.height + 1;
241
+ let newest = -1;
242
+ for (const row of result.rows) {
243
+ const key = rowKey(row);
244
+ addEvent(delivered, key);
245
+ newest = Math.max(newest, key.height);
246
+ deliver(rowFrame(row), key);
247
+ }
248
+ const count = result.rows.length;
249
+ status = !result.found
250
+ ? { kind: "boundaryNotFound", delivered: count }
251
+ : target === undefined
252
+ ? { kind: "unverified", delivered: count }
253
+ : indexed >= target
254
+ ? { kind: "backfilled", delivered: count }
255
+ : { kind: "historyBehind", delivered: count };
256
+ recent = { keys: delivered, height: newest, floor };
257
+ }
258
+ catch (err) {
259
+ if (closed)
260
+ return undefined;
261
+ status = {
262
+ kind: "failed",
263
+ error: err instanceof Error ? err : new Error(String(err)),
264
+ };
265
+ recent = null;
266
+ }
267
+ }
268
+ snapshotHeight = target;
269
+ // Flush up to the next reconnect snapshot; it starts the next backfill,
270
+ // from the last frame flushed here, and the frames after it stay buffered.
271
+ const cut = buffer.findIndex((b) => b.kind === "snapshot");
272
+ const now = cut < 0 ? buffer : buffer.slice(0, cut);
273
+ const next = cut < 0 ? undefined : buffer[cut].frame;
274
+ buffer = cut < 0 ? [] : buffer.slice(cut + 1);
275
+ for (const b of now)
276
+ if (b.kind === "event")
277
+ deliverLive(b.frame);
278
+ if (!closed)
279
+ opts.onRecovery?.(status);
280
+ return next;
281
+ };
282
+ const run = async (snapshot) => {
283
+ recovering = true;
284
+ let current = snapshot;
285
+ while (current && !closed)
286
+ current = await recover(current);
287
+ recovering = false;
288
+ };
289
+ const handle = (frame) => {
290
+ if (closed)
291
+ return;
292
+ if (frame.type === "snapshot") {
293
+ opts.onFrame(frame);
294
+ const snap = frame;
295
+ if (!seenSnapshot) {
296
+ seenSnapshot = true;
297
+ snapshotHeight = heightOf(snap);
298
+ return;
299
+ }
300
+ // A resend for another listener is not a reconnect.
301
+ if (snap.snapshot === "resent")
302
+ return;
303
+ if (recovering)
304
+ buffer.push({ kind: "snapshot", frame: snap });
305
+ else
306
+ void run(snap);
307
+ return;
308
+ }
309
+ // An error frame (a refused subscribe, a failed authentication) is no
310
+ // account event: it passes straight through and moves no boundary.
311
+ if (frame.type === "error") {
312
+ opts.onFrame(frame);
313
+ return;
314
+ }
315
+ const event = frame;
316
+ if (recovering)
317
+ buffer.push({ kind: "event", frame: event });
318
+ else
319
+ deliverLive(event);
320
+ };
321
+ return {
322
+ handle,
323
+ close: () => {
324
+ closed = true;
325
+ buffer = [];
326
+ abort.abort();
327
+ },
328
+ };
329
+ }
330
+ //# sourceMappingURL=account-recovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-recovery.js","sourceRoot":"","sources":["../src/account-recovery.ts"],"names":[],"mappings":"AAsBA;wEACwE;AACxE,SAAS,SAAS,CAAC,CAAkB,EAAE,CAAkB;IACvD,OAAO,CACL,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QACrB,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QACrB,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC,UAAU;QAC7B,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,SAAS;QAC3B,CAAC,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,CAAC,CACtE,CAAC;AACJ,CAAC;AAED;wEACwE;AACxE,SAAS,QAAQ,CACf,IAAoC,EACpC,GAAoB;IAEpB,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;IACtB,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC5B,IAAI,MAAM;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;;QACxB,IAAI,CAAC,GAAG,CAAC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