@pod-network/trade-sdk 0.10.0 → 0.12.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 (86) hide show
  1. package/README.md +6 -4
  2. package/dist/client.d.ts +30 -11
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +37 -17
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec/activity.d.ts +11 -0
  7. package/dist/codec/activity.d.ts.map +1 -0
  8. package/dist/codec/activity.js +33 -0
  9. package/dist/codec/activity.js.map +1 -0
  10. package/dist/codec/decode.d.ts +14 -6
  11. package/dist/codec/decode.d.ts.map +1 -1
  12. package/dist/codec/decode.js +58 -24
  13. package/dist/codec/decode.js.map +1 -1
  14. package/dist/codec/json.d.ts +3 -0
  15. package/dist/codec/json.d.ts.map +1 -0
  16. package/dist/codec/json.js +14 -0
  17. package/dist/codec/json.js.map +1 -0
  18. package/dist/codec/orders-v2.d.ts +9 -3
  19. package/dist/codec/orders-v2.d.ts.map +1 -1
  20. package/dist/codec/orders-v2.js +12 -9
  21. package/dist/codec/orders-v2.js.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/stores/resource.d.ts +48 -2
  27. package/dist/stores/resource.d.ts.map +1 -1
  28. package/dist/stores/resource.js +75 -6
  29. package/dist/stores/resource.js.map +1 -1
  30. package/dist/sync/activity.d.ts +58 -0
  31. package/dist/sync/activity.d.ts.map +1 -0
  32. package/dist/sync/activity.js +259 -0
  33. package/dist/sync/activity.js.map +1 -0
  34. package/dist/sync/orders.d.ts +8 -65
  35. package/dist/sync/orders.d.ts.map +1 -1
  36. package/dist/sync/orders.js +44 -192
  37. package/dist/sync/orders.js.map +1 -1
  38. package/dist/sync/pnl-history.d.ts +33 -14
  39. package/dist/sync/pnl-history.d.ts.map +1 -1
  40. package/dist/sync/pnl-history.js +255 -65
  41. package/dist/sync/pnl-history.js.map +1 -1
  42. package/dist/sync/sources.d.ts.map +1 -1
  43. package/dist/sync/sources.js +12 -5
  44. package/dist/sync/sources.js.map +1 -1
  45. package/dist/sync/stream.d.ts +101 -0
  46. package/dist/sync/stream.d.ts.map +1 -0
  47. package/dist/sync/stream.js +243 -0
  48. package/dist/sync/stream.js.map +1 -0
  49. package/dist/transport/jsonrpc.d.ts +0 -5
  50. package/dist/transport/jsonrpc.d.ts.map +1 -1
  51. package/dist/transport/jsonrpc.js +0 -20
  52. package/dist/transport/jsonrpc.js.map +1 -1
  53. package/dist/transport/rest.d.ts +36 -4
  54. package/dist/transport/rest.d.ts.map +1 -1
  55. package/dist/transport/rest.js +43 -10
  56. package/dist/transport/rest.js.map +1 -1
  57. package/dist/transport/ws.d.ts +5 -1
  58. package/dist/transport/ws.d.ts.map +1 -1
  59. package/dist/transport/ws.js.map +1 -1
  60. package/dist/types/public.d.ts +62 -23
  61. package/dist/types/public.d.ts.map +1 -1
  62. package/dist/types/wire.d.ts +98 -16
  63. package/dist/types/wire.d.ts.map +1 -1
  64. package/dist/write/index.d.ts +3 -3
  65. package/dist/write/index.d.ts.map +1 -1
  66. package/dist/write/index.js +0 -3
  67. package/dist/write/index.js.map +1 -1
  68. package/package.json +1 -1
  69. package/src/client.ts +49 -19
  70. package/src/codec/activity.ts +46 -0
  71. package/src/codec/decode.ts +65 -30
  72. package/src/codec/json.ts +18 -0
  73. package/src/codec/orders-v2.ts +24 -11
  74. package/src/index.ts +4 -2
  75. package/src/stores/resource.ts +111 -5
  76. package/src/sync/activity.ts +266 -0
  77. package/src/sync/orders.ts +46 -189
  78. package/src/sync/pnl-history.ts +244 -75
  79. package/src/sync/sources.ts +12 -6
  80. package/src/sync/stream.ts +270 -0
  81. package/src/transport/jsonrpc.ts +0 -23
  82. package/src/transport/rest.ts +62 -14
  83. package/src/transport/ws.ts +5 -1
  84. package/src/types/public.ts +62 -26
  85. package/src/types/wire.ts +105 -18
  86. package/src/write/index.ts +3 -6
@@ -2,6 +2,8 @@
2
2
  // ref-counted (its source starts on the first subscriber and tears down after
3
3
  // the last leaves), and exposes the useSyncExternalStore-shaped contract.
4
4
 
5
+ import { parseBig, stringifyBig } from "../codec/json.js";
6
+
5
7
  export interface Resource<T> {
6
8
  get(): T | undefined;
7
9
  subscribe(listener: () => void): () => void;
@@ -15,11 +17,55 @@ export interface Resource<T> {
15
17
  ready(): Promise<T>;
16
18
  /** Restart the source for a fresh seed (optional — see BaseResource). */
17
19
  refresh?(): void;
20
+ /**
21
+ * The newest real value this resource has held, live or persisted from an
22
+ * earlier visit, and when it was committed — never a provisional `seed`. For display while the backend is away —
23
+ * never for sizing, pricing or signing, which must read `get()`.
24
+ */
25
+ lastKnown(): Snapshot<T> | undefined;
26
+ /**
27
+ * True while the current value is a provisional `seed` (e.g. a cached list
28
+ * not yet confirmed by the backend). Derived resources inherit it.
29
+ */
30
+ isProvisional(): boolean;
18
31
  readonly error?: Error;
19
32
  }
20
33
 
34
+ /** A value and the wall-clock ms it was committed at. */
35
+ export interface Snapshot<T> {
36
+ value: T;
37
+ at: number;
38
+ }
39
+
40
+ /**
41
+ * Host-supplied storage for last-known snapshots (localStorage in a browser).
42
+ * Key it per backend environment. Implementations may throw (storage denied,
43
+ * quota); callers ignore failures.
44
+ */
45
+ export interface SnapshotStore {
46
+ get(key: string): string | null;
47
+ set(key: string, value: string): void;
48
+ }
49
+
50
+ /** Where one resource persists its snapshot. */
51
+ export interface SnapshotSlot {
52
+ store: SnapshotStore;
53
+ key: string;
54
+ }
55
+
56
+ // Bump when a persisted type changes shape: a mismatch reads as no snapshot.
57
+ const SNAPSHOT_VERSION = 1;
58
+ // Account state recomputes on every market tick; storage sees at most one write per window.
59
+ const SNAPSHOT_WRITE_MS = 5_000;
60
+
21
61
  export interface ResourceHandle<T> {
22
62
  set(value: T): void;
63
+ /**
64
+ * Commit a provisional value from the host's own cache (e.g. last session's
65
+ * static markets list): readable through `get()`, but neither persisted nor
66
+ * preferred by `lastKnown()` over a snapshot of real data.
67
+ */
68
+ seed(value: T): void;
23
69
  update(fn: (prev: T | undefined) => T): void;
24
70
  current(): T | undefined;
25
71
  fail(err: Error): void;
@@ -30,6 +76,13 @@ export type ResourceSource<T> = (handle: ResourceHandle<T>) => () => void;
30
76
 
31
77
  export class BaseResource<T> implements Resource<T> {
32
78
  private value: T | undefined;
79
+ private provisional = false;
80
+ // The newest real value, kept apart from `value` so a later provisional seed
81
+ // can neither hide it from lastKnown() nor stop it being written.
82
+ private confirmed: Snapshot<T> | undefined;
83
+ private dirty = false;
84
+ private persisted: Snapshot<T> | null | undefined;
85
+ private writeTimer: ReturnType<typeof setTimeout> | undefined;
33
86
  private _error: Error | undefined;
34
87
  private readonly listeners = new Set<() => void>();
35
88
  private teardown: (() => void) | undefined;
@@ -38,12 +91,25 @@ export class BaseResource<T> implements Resource<T> {
38
91
  private readyResolve: ((v: T) => void) | undefined;
39
92
  private readyReject: ((e: Error) => void) | undefined;
40
93
 
41
- constructor(private readonly source: ResourceSource<T>) {}
94
+ constructor(
95
+ private readonly source: ResourceSource<T>,
96
+ private readonly slot?: SnapshotSlot,
97
+ ) {}
42
98
 
43
99
  get(): T | undefined {
44
100
  return this.value;
45
101
  }
46
102
 
103
+ isProvisional(): boolean {
104
+ return this.provisional;
105
+ }
106
+
107
+ lastKnown(): Snapshot<T> | undefined {
108
+ if (this.confirmed) return this.confirmed;
109
+ if (this.persisted === undefined) this.persisted = this.readSlot();
110
+ return this.persisted ?? undefined;
111
+ }
112
+
47
113
  get error(): Error | undefined {
48
114
  return this._error;
49
115
  }
@@ -97,6 +163,7 @@ export class BaseResource<T> implements Resource<T> {
97
163
  this.started = true;
98
164
  const handle: ResourceHandle<T> = {
99
165
  set: (v) => this.commit(v),
166
+ seed: (v) => this.commit(v, true),
100
167
  update: (fn) => this.commit(fn(this.value)),
101
168
  current: () => this.value,
102
169
  fail: (err) => {
@@ -122,13 +189,20 @@ export class BaseResource<T> implements Resource<T> {
122
189
  private stop(): void {
123
190
  if (!this.started) return;
124
191
  this.started = false;
192
+ this.writeSlot();
125
193
  const t = this.teardown;
126
194
  this.teardown = undefined;
127
195
  if (t) try { t(); } catch { /* ignore */ }
128
196
  }
129
197
 
130
- private commit(v: T): void {
198
+ private commit(v: T, provisional = false): void {
131
199
  this.value = v;
200
+ this.provisional = provisional;
201
+ if (!provisional) {
202
+ this.confirmed = { value: v, at: Date.now() };
203
+ this.dirty = true;
204
+ if (this.slot) this.writeTimer ??= setTimeout(() => this.writeSlot(), SNAPSHOT_WRITE_MS);
205
+ }
132
206
  this._error = undefined;
133
207
  if (this.readyResolve) {
134
208
  this.readyResolve(v);
@@ -138,6 +212,27 @@ export class BaseResource<T> implements Resource<T> {
138
212
  this.emit();
139
213
  }
140
214
 
215
+ private readSlot(): Snapshot<T> | null {
216
+ if (!this.slot) return null;
217
+ try {
218
+ const raw = this.slot.store.get(this.slot.key);
219
+ const s = raw ? parseBig<{ v: number; at: number; value: T }>(raw) : undefined;
220
+ return s?.v === SNAPSHOT_VERSION ? { value: s.value, at: s.at } : null;
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ private writeSlot(): void {
227
+ clearTimeout(this.writeTimer);
228
+ this.writeTimer = undefined;
229
+ if (!this.slot || !this.confirmed || !this.dirty) return;
230
+ this.dirty = false;
231
+ try {
232
+ this.slot.store.set(this.slot.key, stringifyBig({ v: SNAPSHOT_VERSION, ...this.confirmed }));
233
+ } catch { /* storage denied or full */ }
234
+ }
235
+
141
236
  private emit(): void {
142
237
  this.listeners.forEach((l) => {
143
238
  try { l(); } catch { /* ignore */ }
@@ -145,22 +240,31 @@ export class BaseResource<T> implements Resource<T> {
145
240
  }
146
241
  }
147
242
 
243
+ /**
244
+ * A value computed from a parent that has nothing yet, or only a provisional
245
+ * seed, is itself provisional: never persisted or preferred by `lastKnown()`.
246
+ */
247
+ const unconfirmed = (p: Resource<unknown>): boolean => p.get() === undefined || p.isProvisional();
248
+
148
249
  /** A read-only view derived from several resources; recomputes on any change. */
149
250
  export function combineResources<T>(
150
251
  parents: Resource<unknown>[],
151
252
  compute: () => T | undefined,
253
+ slot?: SnapshotSlot,
152
254
  ): Resource<T> {
153
255
  return new BaseResource<T>((handle) => {
154
256
  let alive = true;
155
257
  const apply = () => {
156
258
  if (!alive) return;
157
259
  const next = compute();
158
- if (next !== undefined) handle.set(next);
260
+ if (next === undefined) return;
261
+ if (parents.some(unconfirmed)) handle.seed(next);
262
+ else handle.set(next);
159
263
  };
160
264
  const unsubs = parents.map((p) => p.subscribe(apply));
161
265
  queueMicrotask(apply);
162
266
  return () => { alive = false; unsubs.forEach((u) => u()); };
163
- });
267
+ }, slot);
164
268
  }
165
269
 
166
270
  /** A read-only view derived from another resource. */
@@ -173,7 +277,9 @@ export function derivedResource<S, T>(
173
277
  const apply = () => {
174
278
  if (!alive) return;
175
279
  const next = select(parent.get());
176
- if (next !== undefined) handle.set(next);
280
+ if (next === undefined) return;
281
+ if (unconfirmed(parent)) handle.seed(next);
282
+ else handle.set(next);
177
283
  };
178
284
  const unsub = parent.subscribe(apply);
179
285
  // Defer the initial emit: never call handle.set synchronously inside
@@ -0,0 +1,266 @@
1
+ // ActivityHistory: one account's whole activity (ADR 0057) — `OrderHistory`
2
+ // widened to the money the account moved. Seeded from the first REST page, kept
3
+ // live by `pod_activity`, paged backwards by cursor.
4
+ //
5
+ // The cursor is the batch alone. `pod_activity` sends one frame per tick,
6
+ // covering every book, so a frame is already delivered exactly when its batch is
7
+ // at or below `since` — there is no `sinceBook` to resume inside a tick with.
8
+
9
+ import type {
10
+ ActivityEntry, ActivityEvent, ActivityQuery, Address, MoneyActivity, Order,
11
+ } from "../types/public.js";
12
+ import type { WireActivityFrame } from "../types/wire.js";
13
+ import { applyActivityFrame, isMoney } from "../codec/activity.js";
14
+ import { msToUs, usToMs } from "../codec/units.js";
15
+ import { BaseResource, type ResourceHandle } from "../stores/resource.js";
16
+ import type { SubParams } from "../transport/ws.js";
17
+ import type { SeriesResource } from "./candles.js";
18
+ import type { SyncContext } from "./sources.js";
19
+ import { compareCursor, ResumableStream } from "./stream.js";
20
+
21
+ /**
22
+ * No types is no filter, and an empty list says the same thing. One form, so REST,
23
+ * `keep()` and the client's memo key cannot read the same query three ways.
24
+ */
25
+ export function normalizeActivityQuery(query: ActivityQuery = {}): ActivityQuery {
26
+ return query.types?.length ? query : { ...query, types: undefined };
27
+ }
28
+
29
+ /** The node's page order within a tick: `(timestamp, ordinal, key)` descending. */
30
+ const ORDINAL = { order: 1, backstop: 2, bridge_transfer: 3, transfer: 4 } as const;
31
+
32
+ /**
33
+ * A money row's identity, read off the row itself — so the same row keys the same
34
+ * whichever page it arrives on and however many of its kind share its tick. A
35
+ * backstop leg has no id of its own, but a sweep touches each market once.
36
+ */
37
+ function moneyKey(entry: MoneyActivity): string {
38
+ switch (entry.activityType) {
39
+ case "transfer": return `transfer:${entry.transferId}`;
40
+ case "bridge_transfer": return `bridge:${entry.txHash}:${entry.idx}`;
41
+ case "backstop": return `backstop:${entry.timeMs}:${entry.orderbookId ?? "cash"}`;
42
+ }
43
+ }
44
+
45
+ const cmp = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;
46
+
47
+ /**
48
+ * Separate two rows the tick and the ordinal cannot. Insertion order would do it
49
+ * for one source alone, but a tick that arrives as a frame and a tick that arrives
50
+ * as a page are built in different orders, and a reload must not reshuffle the list.
51
+ */
52
+ function tiebreak(a: ActivityEntry, b: ActivityEntry): number {
53
+ if (a.activityType === "order" && b.activityType === "order") {
54
+ return b.order.nonce - a.order.nonce || cmp(a.order.id, b.order.id);
55
+ }
56
+ // Equal ordinals, so neither is an order.
57
+ return cmp(moneyKey(a as MoneyActivity), moneyKey(b as MoneyActivity));
58
+ }
59
+
60
+ export class ActivityHistory implements SeriesResource<ActivityEntry> {
61
+ private readonly base: BaseResource<ActivityEntry[]>;
62
+ private handle: ResourceHandle<ActivityEntry[]> | undefined;
63
+ private readonly orders = new Map<string, Order>();
64
+ /**
65
+ * When each order was reported, by order id. Kept beside the row rather than on
66
+ * it: the node times an order by its signed deadline, which no frame carries, so
67
+ * neither a later frame nor a re-seed must be able to retime a row already placed.
68
+ */
69
+ private readonly orderTimeMs = new Map<string, number>();
70
+ /** The money rows, by {@link moneyKey}. */
71
+ private readonly money = new Map<string, ActivityEntry>();
72
+ private nextCursor: string | null = null;
73
+ private painted = false;
74
+ private seedGen = 0;
75
+ private _hasMore = true;
76
+ private _loading = false;
77
+ private readonly eventListeners = new Set<(events: ActivityEvent[]) => void>();
78
+ private readonly stream: ResumableStream;
79
+
80
+ private readonly query: ActivityQuery;
81
+
82
+ constructor(
83
+ private readonly ctx: SyncContext,
84
+ private readonly account: Address,
85
+ query: ActivityQuery = {},
86
+ ) {
87
+ this.query = normalizeActivityQuery(query);
88
+ this.stream = new ResumableStream({
89
+ ws: ctx.ws,
90
+ channel: "pod_activity",
91
+ params: { account },
92
+ reseed: () => this.fetchFirstPage(),
93
+ onFrame: (r) => this.onFrame(r),
94
+ });
95
+ this.base = new BaseResource<ActivityEntry[]>((h) => {
96
+ this.handle = h;
97
+ this.stream.start();
98
+ return () => {
99
+ this.stream.stop();
100
+ this.handle = undefined;
101
+ };
102
+ });
103
+ }
104
+
105
+ get(): ActivityEntry[] | undefined { return this.base.get(); }
106
+ subscribe(listener: () => void): () => void { return this.base.subscribe(listener); }
107
+ ready(): Promise<ActivityEntry[]> { return this.base.ready(); }
108
+ get error(): Error | undefined { return this.base.error; }
109
+ hasMore(): boolean { return this._hasMore; }
110
+ loading(): boolean { return this._loading; }
111
+ destroy(): void { this.base.destroy(); }
112
+
113
+ /**
114
+ * Observe what the stream reported, a tick at a time: the order transitions and
115
+ * the money that moved. Nothing is emitted for the REST seed.
116
+ */
117
+ onEvent(listener: (events: ActivityEvent[]) => void): () => void {
118
+ this.eventListeners.add(listener);
119
+ // Listening starts the stream, like subscribing does — the resource is
120
+ // ref-counted from `subscribe`/`ready` alone.
121
+ const release = this.base.subscribe(() => {});
122
+ return () => { this.eventListeners.delete(listener); release(); };
123
+ }
124
+
125
+ setWindow(): void { /* activity pages by cursor, not by time window */ }
126
+
127
+ async loadOlder(): Promise<void> {
128
+ if (!this.handle || !this.nextCursor || this._loading) return;
129
+ this._loading = true;
130
+ this.rebuild();
131
+ try {
132
+ const page = await this.ctx.rest.activity(this.account, {
133
+ ...this.restQuery(),
134
+ cursor: this.nextCursor,
135
+ });
136
+ this.absorb(page.activity, false);
137
+ this.nextCursor = page.nextCursor;
138
+ this._hasMore = page.nextCursor !== null;
139
+ } finally {
140
+ this._loading = false;
141
+ this.rebuild();
142
+ }
143
+ }
144
+
145
+ // --- internals ---
146
+
147
+ private restQuery() {
148
+ return { ...this.query, limit: this.query.limit ?? 100 };
149
+ }
150
+
151
+ private async fetchFirstPage(): Promise<boolean> {
152
+ const gen = ++this.seedGen;
153
+ const before = this.stream.cursor;
154
+ try {
155
+ const page = await this.ctx.rest.activity(this.account, this.restQuery());
156
+ // A seed overtaken by a fresher one is dropped whole: it would absorb rows the
157
+ // newer page has already corrected, and raise the cursor to an older watermark.
158
+ if (!this.stream.running || gen !== this.seedGen) return false;
159
+ // Replayed frames can land while this is in flight, and the indexer trails the
160
+ // stream by design. Overwriting a row the stream has already advanced would
161
+ // revert it permanently: the cursor refuses to rewind and `onFrame` drops a
162
+ // re-delivery, so nothing would repair it.
163
+ this.absorb(page.activity, compareCursor(this.stream.cursor, before) <= 0);
164
+ // Paging is the consumer's position in history, not the seed's: a reconnect
165
+ // re-paints the first page, and taking its cursor again would hand back pages
166
+ // `loadOlder` has already walked past.
167
+ if (!this.painted) {
168
+ this.painted = true;
169
+ this.nextCursor = page.nextCursor;
170
+ this._hasMore = page.nextCursor !== null;
171
+ }
172
+ this.stream.raise({ since: msToUs(page.solutionNow) });
173
+ this.rebuild();
174
+ return true;
175
+ } catch (e) {
176
+ // Only before the first paint: an account whose history is genuinely empty has
177
+ // a resource, and reporting a later transient failure on it would blank the view.
178
+ if (this.handle && this.handle.current() === undefined) this.handle.fail(e as Error);
179
+ throw e;
180
+ }
181
+ }
182
+
183
+ private absorb(entries: ActivityEntry[], overwriteOrders: boolean): void {
184
+ for (const entry of entries) {
185
+ if (entry.activityType === "order") {
186
+ if (!overwriteOrders && this.orders.has(entry.order.id)) continue;
187
+ this.orders.set(entry.order.id, entry.order);
188
+ // Only the source that first reported the order gets to time it. A re-seed
189
+ // carries the node's row time for an order the stream already placed by its
190
+ // batch, and taking it would move the row on every reconnect.
191
+ if (!this.orderTimeMs.has(entry.order.id)) this.orderTimeMs.set(entry.order.id, entry.timeMs);
192
+ continue;
193
+ }
194
+ const key = moneyKey(entry);
195
+ if (!this.money.has(key)) this.money.set(key, entry);
196
+ }
197
+ }
198
+
199
+ /** One frame: everything that happened to the account in one auction batch. */
200
+ private onFrame(result: unknown): void {
201
+ const frame = result as WireActivityFrame;
202
+ if (!frame || !Array.isArray(frame.orders) || !Array.isArray(frame.events)) return;
203
+ // Applying a frame is not idempotent — a fill appends to `order.fills` — and
204
+ // re-delivery is designed in: a resumed subscription replays from the cursor.
205
+ const at: SubParams = { since: frame.batch };
206
+ if (this.stream.delivered(at)) return;
207
+ const kept = this.keep(frame);
208
+ if (!kept) return;
209
+
210
+ const entries: ActivityEntry[] = [];
211
+ const events = applyActivityFrame(kept, { orders: this.orders, entries }, {
212
+ account: this.account,
213
+ });
214
+ // An order the stream is the first to report is timed by its batch; one the
215
+ // seed already placed keeps the time the node gave it.
216
+ const batchMs = usToMs(kept.batch);
217
+ for (const o of kept.orders) if (!this.orderTimeMs.has(o.id)) this.orderTimeMs.set(o.id, batchMs);
218
+ this.absorb(entries, false);
219
+ this.stream.advance(at);
220
+ this.rebuild();
221
+ // Strictly after `rebuild()`: a listener that reads the resource in response to an
222
+ // event must see the state that event produced.
223
+ if (events.length) {
224
+ for (const listener of this.eventListeners) {
225
+ try { listener(events); } catch { /* a listener's failure is not the stream's */ }
226
+ }
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Narrow a frame to what the query asked for, or drop it. REST filters both the
232
+ * kinds and the window server-side; the stream filters neither.
233
+ */
234
+ private keep(frame: WireActivityFrame): WireActivityFrame | undefined {
235
+ const { types, from, to } = this.query;
236
+ if (from !== undefined && frame.batch < msToUs(from)) return undefined;
237
+ if (to !== undefined && frame.batch >= msToUs(to)) return undefined;
238
+ if (!types) return frame;
239
+ const want = new Set<string>(types);
240
+ return {
241
+ ...frame,
242
+ // The order events index `orders`, so the two are kept or dropped together.
243
+ orders: want.has("order") ? frame.orders : [],
244
+ events: frame.events.filter((e) => want.has(isMoney(e.k) ? e.k : "order")),
245
+ };
246
+ }
247
+
248
+ private rebuild(): void {
249
+ if (!this.handle) return;
250
+ const arr: ActivityEntry[] = new Array(this.orders.size + this.money.size);
251
+ let i = 0;
252
+ for (const [id, order] of this.orders) {
253
+ arr[i++] = {
254
+ activityType: "order",
255
+ timeMs: this.orderTimeMs.get(id) ?? Number.MAX_SAFE_INTEGER,
256
+ order,
257
+ };
258
+ }
259
+ for (const entry of this.money.values()) arr[i++] = entry;
260
+ arr.sort((a, b) =>
261
+ b.timeMs - a.timeMs
262
+ || ORDINAL[b.activityType] - ORDINAL[a.activityType]
263
+ || tiebreak(a, b));
264
+ this.handle.set(arr);
265
+ }
266
+ }