@pod-network/trade-sdk 0.12.0 → 0.14.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 (64) hide show
  1. package/README.md +7 -3
  2. package/dist/client.d.ts +5 -5
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +3 -16
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec/activity.d.ts +15 -10
  7. package/dist/codec/activity.d.ts.map +1 -1
  8. package/dist/codec/activity.js +166 -31
  9. package/dist/codec/activity.js.map +1 -1
  10. package/dist/codec/decode.d.ts +2 -14
  11. package/dist/codec/decode.d.ts.map +1 -1
  12. package/dist/codec/decode.js +1 -66
  13. package/dist/codec/decode.js.map +1 -1
  14. package/dist/codec/fixed.d.ts +2 -0
  15. package/dist/codec/fixed.d.ts.map +1 -1
  16. package/dist/codec/fixed.js +2 -0
  17. package/dist/codec/fixed.js.map +1 -1
  18. package/dist/codec/orders-v2.d.ts +16 -9
  19. package/dist/codec/orders-v2.d.ts.map +1 -1
  20. package/dist/codec/orders-v2.js +6 -16
  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 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/sync/activity.d.ts +19 -28
  27. package/dist/sync/activity.d.ts.map +1 -1
  28. package/dist/sync/activity.js +141 -167
  29. package/dist/sync/activity.js.map +1 -1
  30. package/dist/sync/order-preview.d.ts +23 -1
  31. package/dist/sync/order-preview.d.ts.map +1 -1
  32. package/dist/sync/order-preview.js +36 -1
  33. package/dist/sync/order-preview.js.map +1 -1
  34. package/dist/sync/orders.js +4 -4
  35. package/dist/sync/orders.js.map +1 -1
  36. package/dist/sync/pnl-history.d.ts.map +1 -1
  37. package/dist/sync/pnl-history.js +14 -9
  38. package/dist/sync/pnl-history.js.map +1 -1
  39. package/dist/transport/rest.d.ts +11 -12
  40. package/dist/transport/rest.d.ts.map +1 -1
  41. package/dist/transport/rest.js +11 -13
  42. package/dist/transport/rest.js.map +1 -1
  43. package/dist/transport/ws.d.ts +1 -3
  44. package/dist/transport/ws.d.ts.map +1 -1
  45. package/dist/transport/ws.js.map +1 -1
  46. package/dist/types/public.d.ts +78 -22
  47. package/dist/types/public.d.ts.map +1 -1
  48. package/dist/types/wire.d.ts +68 -63
  49. package/dist/types/wire.d.ts.map +1 -1
  50. package/package.json +1 -1
  51. package/src/client.ts +8 -11
  52. package/src/codec/activity.ts +167 -41
  53. package/src/codec/decode.ts +6 -74
  54. package/src/codec/fixed.ts +3 -0
  55. package/src/codec/orders-v2.ts +11 -26
  56. package/src/index.ts +3 -1
  57. package/src/sync/activity.ts +141 -167
  58. package/src/sync/order-preview.ts +56 -2
  59. package/src/sync/orders.ts +4 -4
  60. package/src/sync/pnl-history.ts +13 -7
  61. package/src/transport/rest.ts +21 -21
  62. package/src/transport/ws.ts +1 -3
  63. package/src/types/public.ts +83 -20
  64. package/src/types/wire.ts +56 -65
@@ -2,14 +2,14 @@
2
2
  // representations are normalized into bigint + millisecond numbers.
3
3
 
4
4
  import type {
5
- ActivityEntry, Bar, BackstopTransfer, Balances, BridgeConfig, Market, Order,
6
- Orderbook, PartialFill, PerpPosition, Position, PositionsSnapshot, SpotHolding,
7
- SpotPosition, Status, Trigger, MarketType, MoneyActivity, OrderDirection, OrderKind,
5
+ Bar, BackstopTransfer, Balances, BridgeConfig, Market, Order,
6
+ Orderbook, PerpPosition, Position, PositionsSnapshot, SpotHolding,
7
+ SpotPosition, Status, Trigger, MarketType, OrderDirection, OrderKind,
8
8
  OrderStatus, TriggerType, Withdrawal,
9
9
  } from "../types/public.js";
10
10
  import type {
11
- WireActivityEntry, WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle,
12
- WireMarketDynamics, WireMarketStatic, WireMoneyEvent, WireOrder, WireOrderbook, WirePartialFill,
11
+ WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle,
12
+ WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook,
13
13
  WirePerpPosition, WirePosition, WirePositionsSnapshot, WireSpotHolding, WireSpotPosition,
14
14
  WireStatus, WireTrigger, WireWithdrawal,
15
15
  } from "../types/wire.js";
@@ -78,15 +78,6 @@ export function decodeCandle(w: WireCandle): Bar {
78
78
  };
79
79
  }
80
80
 
81
- function decodePartialFill(w: WirePartialFill): PartialFill {
82
- return {
83
- base: dec(w.base_amount),
84
- quote: dec(w.quote_amount),
85
- price: dec(w.price),
86
- time: usToMs(w.timestamp),
87
- };
88
- }
89
-
90
81
  export function decodeOrder(w: WireOrder): Order {
91
82
  const initialSize = dec(w.initial_size);
92
83
  return {
@@ -112,7 +103,7 @@ export function decodeOrder(w: WireOrder): Order {
112
103
  deadlineMs: usToMs(w.deadline),
113
104
  endMs: endMsFromUs(w.end),
114
105
  includedMs: usToMsOpt(w.included_batch),
115
- fills: (w.fills ?? []).map(decodePartialFill),
106
+ rejectReason: w.invalid_reason,
116
107
  reduceOnly: w.reduce_only,
117
108
  ioc: w.ioc,
118
109
  direction: w.direction as OrderDirection | undefined,
@@ -268,65 +259,6 @@ export function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfe
268
259
  };
269
260
  }
270
261
 
271
- /** One money row (ADR 0057), from a seed entry or a stream event alike — the two
272
- * carry the same fields under different tags. */
273
- export function decodeMoneyEvent(event: WireMoneyEvent, timeMs: number): MoneyActivity {
274
- switch (event.k) {
275
- case "backstop":
276
- return {
277
- activityType: "backstop",
278
- timeMs,
279
- time: timeMs,
280
- orderbookId: event.book,
281
- size: dec(event.size),
282
- cash: dec(event.cash),
283
- markPrice: dec(event.mark),
284
- equity: dec(event.equity),
285
- realizedPnl: dec(event.pnl),
286
- };
287
- case "bridge_transfer":
288
- return {
289
- activityType: "bridge_transfer",
290
- timeMs,
291
- txHash: event.tx,
292
- idx: event.idx,
293
- token: event.token,
294
- amount: dec(event.amount),
295
- // `||`, as `decodeWithdrawal` does: an empty string is the wire saying
296
- // "no reason", and it would otherwise read as a failure.
297
- error: event.error || undefined,
298
- };
299
- case "transfer":
300
- return {
301
- activityType: "transfer",
302
- timeMs,
303
- transferId: event.id,
304
- token: event.token,
305
- amount: dec(event.amount),
306
- error: event.error || undefined,
307
- };
308
- }
309
- }
310
-
311
- /**
312
- * One activity row (ADR 0057), reusing the decoder its kind already had, or
313
- * `undefined` for a kind this version does not know — the same silence the frame
314
- * path keeps, rather than a row with no tag a consumer could act on.
315
- *
316
- * `timeMs` is the node's own sort key, which for an order is its **signed
317
- * deadline** rather than the batch it landed in — `order.includedMs` is that.
318
- */
319
- export function decodeActivityEntry(w: WireActivityEntry): ActivityEntry | undefined {
320
- const timeMs = usToMs(w.ts);
321
- switch (w.activity_type) {
322
- case "order": return { activityType: "order", timeMs, order: decodeOrder(w) };
323
- case "backstop": return decodeMoneyEvent({ ...w, k: "backstop" }, timeMs);
324
- case "bridge_transfer": return decodeMoneyEvent({ ...w, k: "bridge_transfer" }, timeMs);
325
- case "transfer": return decodeMoneyEvent({ ...w, k: "transfer" }, timeMs);
326
- default: return undefined;
327
- }
328
- }
329
-
330
262
  export function decodeBridgeConfig(w: WireBridgeConfig): BridgeConfig {
331
263
  return {
332
264
  claimChainId: w.claim_chain_id,
@@ -5,6 +5,9 @@ import { WAD } from "./units.js";
5
5
 
6
6
  const absB = (x: bigint) => (x < 0n ? -x : x);
7
7
 
8
+ /** `Math.min` for bigints, which it rejects. */
9
+ export const min = (a: bigint, b: bigint) => (a < b ? a : b);
10
+
8
11
  /** Decimal `*`: (a*b)/1e18 truncated toward zero. */
9
12
  export function mul(a: bigint, b: bigint): bigint {
10
13
  const n = a * b;
@@ -11,23 +11,17 @@ import type {
11
11
  PartialFill, RejectCode, TerminalStatus,
12
12
  } from "../types/public.js";
13
13
  import type { WireOrderEntity, WireOrderEvent, WireOrdersFrame } from "../types/wire.js";
14
- import { dec, endMsFromUs, usToMs } from "./units.js";
14
+ import { dec, decOpt, endMsFromUs, usToMs } from "./units.js";
15
15
  import { div } from "./fixed.js";
16
16
  import { classifyPerpDirection } from "./direction.js";
17
17
 
18
- export interface OrdersFrameContext<X = never> {
18
+ export interface OrdersFrameContext {
19
19
  /** The account the subscription is filtered to, used when the frame omits `accts`. */
20
20
  account: Address;
21
- /**
22
- * Events this codec applied nothing for, offered back in wire order — how a
23
- * superset channel (`pod_activity`) folds its own kinds without a second pass
24
- * that would report the tick's money after all of its order flow.
25
- */
26
- foreign?(event: WireOrderEvent): X | undefined;
27
21
  }
28
22
 
29
23
  /** Per-frame facts the events need. */
30
- interface FrameFacts {
24
+ export interface FrameFacts {
31
25
  batchMs: number;
32
26
  accts?: WireOrdersFrame["accts"];
33
27
  }
@@ -43,17 +37,17 @@ interface FrameFacts {
43
37
  * mid-frame: they are collected while applying but the rows are mutated in place, so a
44
38
  * consumer never sees a half-applied order.
45
39
  */
46
- export function applyOrdersFrame<X = never>(
40
+ export function applyOrdersFrame(
47
41
  frame: WireOrdersFrame,
48
42
  byId: Map<string, Order>,
49
- ctx: OrdersFrameContext<X>,
50
- ): (OrderEvent | X)[] {
43
+ ctx: OrdersFrameContext,
44
+ ): OrderEvent[] {
51
45
  // The book and the batch are frame constants: resolved once, not per entity.
52
46
  const batchMs = usToMs(frame.batch);
53
47
  const facts: FrameFacts = { batchMs, accts: frame.accts };
54
48
  const created = frame.orders.map((e) => decodeEntity(e, frame, batchMs, ctx.account));
55
49
 
56
- const applied: (OrderEvent | X)[] = [];
50
+ const applied: OrderEvent[] = [];
57
51
  for (const event of frame.events) {
58
52
  // `o` indexes this frame's entities and `id` names one resting from an earlier
59
53
  // batch — but an event kind added later (ADR 0029 §6 reserves several) may name
@@ -75,10 +69,7 @@ export function applyOrdersFrame<X = never>(
75
69
  fill: outcome.fill,
76
70
  amendRejection: outcome.amendRejection,
77
71
  });
78
- continue;
79
72
  }
80
- const foreign = ctx.foreign?.(event);
81
- if (foreign !== undefined) applied.push(foreign);
82
73
  }
83
74
 
84
75
  // After the events, not before: an entity's own `new`/`reject` decides the
@@ -122,7 +113,6 @@ function decodeEntity(e: WireOrderEntity, frame: WireOrdersFrame, batchMs: numbe
122
113
  // inclusion time is the one thing every source agrees on and the only honest
123
114
  // key to order by.
124
115
  includedMs: batchMs,
125
- fills: [],
126
116
  reduceOnly: e.reduce_only ?? false,
127
117
  ioc: e.ioc ?? false,
128
118
  triggerType: e.trigger as Order["triggerType"],
@@ -138,6 +128,8 @@ function decodeEntity(e: WireOrderEntity, frame: WireOrdersFrame, batchMs: numbe
138
128
  * accumulated, so a client that missed a fill cannot drift.
139
129
  */
140
130
  function applyTotals(event: WireOrderEvent, order: Order): void {
131
+ // Activity terminations, and activity fills stored before totals were recorded, carry none; `pod_orders_v2` always does.
132
+ if (event.tb === undefined) return;
141
133
  order.filledBase = dec(event.tb);
142
134
  order.filledQuote = dec(event.tq);
143
135
  order.fee = dec(event.tf);
@@ -150,7 +142,7 @@ function applyTotals(event: WireOrderEvent, order: Order): void {
150
142
  * Apply one event. `undefined` when the kind is not one this version knows; otherwise what
151
143
  * the event contributed beyond the order's own state — the fill, or the refused amendment.
152
144
  */
153
- function applyEvent(
145
+ export function applyEvent(
154
146
  event: WireOrderEvent,
155
147
  order: Order,
156
148
  facts: FrameFacts,
@@ -186,11 +178,6 @@ function applyEvent(
186
178
  const base = dec(event.b);
187
179
  const quote = dec(event.q);
188
180
  const fill: PartialFill = { base, quote, price: div(quote, base), time: facts.batchMs };
189
- // A real fill always has size. A zero-size one is the engine flipping status: the
190
- // cap-to-filled amendment fabricates it so `st: filled` reaches the indexer, which
191
- // reads status from fills alone. Its totals and status count; adding a
192
- // `0.0000 @ $0.00` row to the order's fill history would only invent a trade.
193
- if (base !== 0n) order.fills = [...order.fills, fill];
194
181
  // A perp fill reports the position it left. The position it started from is
195
182
  // that minus what this fill moved it — a buy raises it, a sell lowers it — and
196
183
  // the transition is what says whether the order opened, added to, reduced,
@@ -208,10 +195,8 @@ function applyEvent(
208
195
  }
209
196
  // Present only on the fill that closed the order.
210
197
  if (event.st) order.status = event.st as OrderStatus;
211
- // Copied rather than shared: the same object is in `order.fills`, and attaching a
212
- // per-event field to it would leak the event into the order's fill history.
213
198
  return {
214
- fill: { ...fill, totalBase: dec(event.tb), closedAs: event.st as TerminalStatus | undefined },
199
+ fill: { ...fill, totalBase: order.filledBase, closedAs: event.st as TerminalStatus | undefined, fee: decOpt(event.f) },
215
200
  };
216
201
  }
217
202
  case "modify_reject":
package/src/index.ts CHANGED
@@ -30,11 +30,12 @@ export {
30
30
  closePreview, type ClosePreview,
31
31
  priceForReturn, type ReturnPriceInput,
32
32
  closestTriggers,
33
+ estimateFill, type FillEstimate,
33
34
  } from "./sync/order-preview.js";
34
35
  export type { SeriesResource } from "./sync/candles.js";
35
36
  export { CandleSeries } from "./sync/candles.js";
36
37
  export { OrderHistory } from "./sync/orders.js";
37
- export { ActivityHistory } from "./sync/activity.js";
38
+ export { ActivityHistory, type ActivityView } from "./sync/activity.js";
38
39
  export {
39
40
  fetchPnlHistory, streamPnlHistory, PnlHistoryCache,
40
41
  type PnlHistory, type PnlHistoryChunk, type PnlHistoryDeps, type PnlHistoryQuery, type PnlPoint,
@@ -45,6 +46,7 @@ export { createPodDatafeed } from "./datafeed.js";
45
46
 
46
47
  // Public data types
47
48
  export * from "./types/public.js";
49
+ export type { WireActivityEntry, WireActivityFrame } from "./types/wire.js";
48
50
 
49
51
  // Codec helpers
50
52
  export {
@@ -1,95 +1,47 @@
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.
1
+ // `pod_activity` sends one batch per tick, so the batch alone is the resume cursor (ADR 0057).
8
2
 
9
3
  import type {
10
- ActivityEntry, ActivityEvent, ActivityQuery, Address, MoneyActivity, Order,
4
+ ActivityEntry, ActivityEvent, ActivityQuery, ActivityType, Address, Order, OrderEventKind,
11
5
  } 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";
6
+ import type { WireActivityEntry } from "../types/wire.js";
7
+ import { foldActivityBatch } from "../codec/activity.js";
8
+ import { msToUs } from "../codec/units.js";
15
9
  import { BaseResource, type ResourceHandle } from "../stores/resource.js";
10
+ import type { ActivityPage } from "../transport/rest.js";
16
11
  import type { SubParams } from "../transport/ws.js";
17
12
  import type { SeriesResource } from "./candles.js";
18
13
  import type { SyncContext } from "./sources.js";
19
- import { compareCursor, ResumableStream } from "./stream.js";
14
+ import { ResumableStream } from "./stream.js";
20
15
 
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 };
16
+ export interface ActivityView extends SeriesResource<ActivityEntry> {
17
+ onEvent(listener: (events: ActivityEvent[]) => void): () => void;
27
18
  }
28
19
 
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> {
20
+ /** One account's whole feed: the one subscription, batch map and paging state its views share. */
21
+ export class ActivityHistory implements ActivityView {
61
22
  private readonly base: BaseResource<ActivityEntry[]>;
62
23
  private handle: ResourceHandle<ActivityEntry[]> | undefined;
24
+ /** Every batch's rows, from either source; what dedupes one against the other. */
25
+ private readonly batches = new Map<number, ActivityEntry[]>();
63
26
  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;
27
+ private rows: ActivityEntry[] = [];
28
+ private nextUs: number | null = null;
74
29
  private seedGen = 0;
75
30
  private _hasMore = true;
76
31
  private _loading = false;
77
32
  private readonly eventListeners = new Set<(events: ActivityEvent[]) => void>();
78
33
  private readonly stream: ResumableStream;
79
-
80
- private readonly query: ActivityQuery;
34
+ private readonly views = new Map<string, FilteredActivity>();
81
35
 
82
36
  constructor(
83
37
  private readonly ctx: SyncContext,
84
38
  private readonly account: Address,
85
- query: ActivityQuery = {},
86
39
  ) {
87
- this.query = normalizeActivityQuery(query);
88
40
  this.stream = new ResumableStream({
89
41
  ws: ctx.ws,
90
42
  channel: "pod_activity",
91
43
  params: { account },
92
- reseed: () => this.fetchFirstPage(),
44
+ reseed: () => this.seed(),
93
45
  onFrame: (r) => this.onFrame(r),
94
46
  });
95
47
  this.base = new BaseResource<ActivityEntry[]>((h) => {
@@ -110,67 +62,73 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
110
62
  loading(): boolean { return this._loading; }
111
63
  destroy(): void { this.base.destroy(); }
112
64
 
65
+ /** The rows of `types` whose `timeMs` is within inclusive `from`/`to`. */
66
+ view(query: ActivityQuery): ActivityView {
67
+ // An empty `types` is no filter; sorted, since key order is an argument's accident.
68
+ const q = query.types?.length ? query : { ...query, types: undefined };
69
+ const key = JSON.stringify(q, Object.keys(q).sort());
70
+ let view = this.views.get(key);
71
+ if (!view) this.views.set(key, view = new FilteredActivity(this, q));
72
+ return view;
73
+ }
74
+
113
75
  /**
114
76
  * 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.
77
+ * the money that moved. Nothing is emitted for REST pages.
116
78
  */
117
79
  onEvent(listener: (events: ActivityEvent[]) => void): () => void {
118
80
  this.eventListeners.add(listener);
119
- // Listening starts the stream, like subscribing does — the resource is
120
- // ref-counted from `subscribe`/`ready` alone.
81
+ // Listening starts the stream, like subscribing does.
121
82
  const release = this.base.subscribe(() => {});
122
83
  return () => { this.eventListeners.delete(listener); release(); };
123
84
  }
124
85
 
125
- setWindow(): void { /* activity pages by cursor, not by time window */ }
86
+ setWindow(): void { /* activity pages by batch, not by time window */ }
126
87
 
127
88
  async loadOlder(): Promise<void> {
128
- if (!this.handle || !this.nextCursor || this._loading) return;
89
+ if (!this.handle || this.nextUs === null || this._loading) return;
129
90
  this._loading = true;
130
91
  this.rebuild();
131
92
  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;
93
+ const page = await this.ctx.rest.activity(this.account, { toUs: this.nextUs });
94
+ this.store([page]);
95
+ this.nextUs = page.nextUs;
96
+ this._hasMore = page.nextUs !== null;
97
+ this.restack();
139
98
  } finally {
140
99
  this._loading = false;
141
100
  this.rebuild();
142
101
  }
143
102
  }
144
103
 
145
- // --- internals ---
146
-
147
- private restQuery() {
148
- return { ...this.query, limit: this.query.limit ?? 100 };
149
- }
150
-
151
- private async fetchFirstPage(): Promise<boolean> {
104
+ private async seed(): Promise<boolean> {
152
105
  const gen = ++this.seedGen;
153
- const before = this.stream.cursor;
106
+ const since = this.stream.cursor.since;
107
+ const stale = () => !this.stream.running || gen !== this.seedGen;
154
108
  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;
109
+ if (since === undefined) {
110
+ const page = await this.ctx.rest.activity(this.account);
111
+ if (stale()) return false;
112
+ this.store([page]);
113
+ this.nextUs = page.nextUs;
114
+ this._hasMore = page.nextUs !== null;
115
+ this.restack();
116
+ this.stream.raise({ since: msToUs(page.solutionNow) });
117
+ return true;
171
118
  }
172
- this.stream.raise({ since: msToUs(page.solutionNow) });
173
- this.rebuild();
119
+ // A reconnect: fill the gap above the cursor, and keep the consumer's paging position.
120
+ const fromUs = since + 1;
121
+ let toUs: number | undefined;
122
+ const pages: ActivityPage[] = [];
123
+ do {
124
+ const page = await this.ctx.rest.activity(this.account, { fromUs, toUs });
125
+ if (stale()) return false;
126
+ pages.push(page);
127
+ toUs = page.nextUs ?? undefined;
128
+ } while (toUs !== undefined);
129
+ this.store(pages);
130
+ this.restack();
131
+ for (const page of pages) this.stream.raise({ since: msToUs(page.solutionNow) });
174
132
  return true;
175
133
  } catch (e) {
176
134
  // Only before the first paint: an account whose history is genuinely empty has
@@ -180,46 +138,33 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
180
138
  }
181
139
  }
182
140
 
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);
141
+ /** Oldest batch first, so transitions to held orders land in order; a batch already held is skipped. */
142
+ private store(pages: ActivityPage[]): void {
143
+ const fresh = pages.flatMap((p) => p.batches).filter(([batchUs]) => !this.batches.has(batchUs));
144
+ const pageOrders = new Set(fresh.flatMap(([, entries]) => entries.flatMap((e) => (e.k === "order" ? [e.order_id] : []))));
145
+ for (const [batchUs, entries] of fresh.sort((a, b) => a[0] - b[0])) {
146
+ this.batches.set(batchUs, foldActivityBatch(batchUs, entries, this.orders, { pageOrders }).rows);
196
147
  }
197
148
  }
198
149
 
199
- /** One frame: everything that happened to the account in one auction batch. */
200
150
  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 };
151
+ if (!result || typeof result !== "object") return;
152
+ const keys = Object.keys(result);
153
+ if (keys.length !== 1) return;
154
+ const key = keys[0]!;
155
+ const entries = (result as Record<string, unknown>)[key];
156
+ const batchUs = Number(key);
157
+ if (!Array.isArray(entries) || !Number.isSafeInteger(batchUs)) return;
158
+ // Folding is not idempotent (events would be reported twice) and a resume replays from the cursor.
159
+ const at: SubParams = { since: batchUs };
206
160
  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
161
  this.stream.advance(at);
162
+ if (!entries.length || this.batches.has(batchUs)) return;
163
+ const { rows, events } = foldActivityBatch(batchUs, entries as WireActivityEntry[], this.orders, "stream");
164
+ this.batches.set(batchUs, rows);
165
+ this.rows = [...rows, ...this.rows];
166
+ // Listeners run after rebuild() so one that reads the resource sees what the event produced.
220
167
  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
168
  if (events.length) {
224
169
  for (const listener of this.eventListeners) {
225
170
  try { listener(events); } catch { /* a listener's failure is not the stream's */ }
@@ -227,40 +172,69 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
227
172
  }
228
173
  }
229
174
 
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
- };
175
+ /** Rows newest batch first, wire order within a batch. */
176
+ private restack(): void {
177
+ this.rows = [...this.batches.keys()].sort((a, b) => b - a).flatMap((b) => this.batches.get(b)!);
178
+ this.rebuild();
246
179
  }
247
180
 
248
181
  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
- };
182
+ this.handle?.set(this.rows.slice());
183
+ }
184
+ }
185
+
186
+ const EVENT_TYPE: Record<OrderEventKind, ActivityType> = {
187
+ new: "order", reject: "order", modify_reject: "modify_reject", cancel_reject: "cancel_reject",
188
+ fill: "fill", modify: "modify", cancel: "termination", expire: "termination",
189
+ };
190
+
191
+ class FilteredActivity implements ActivityView {
192
+ private readonly want: Set<ActivityType> | undefined;
193
+ private held: ActivityEntry[] | undefined;
194
+ private shown: ActivityEntry[] | undefined;
195
+
196
+ constructor(private readonly parent: ActivityHistory, private readonly query: ActivityQuery) {
197
+ this.want = query.types && new Set(query.types);
198
+ }
199
+
200
+ get(): ActivityEntry[] | undefined {
201
+ const rows = this.parent.get();
202
+ if (rows !== this.held) {
203
+ this.held = rows;
204
+ this.shown = rows?.filter((r) => this.keeps(r));
258
205
  }
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);
206
+ return this.shown;
207
+ }
208
+
209
+ subscribe(listener: () => void): () => void { return this.parent.subscribe(listener); }
210
+ async ready(): Promise<ActivityEntry[]> { return (await this.parent.ready()).filter((r) => this.keeps(r)); }
211
+ get error(): Error | undefined { return this.parent.error; }
212
+ loading(): boolean { return this.parent.loading(); }
213
+ setWindow(): void { /* a view's window is its query */ }
214
+
215
+ hasMore(): boolean {
216
+ const oldest = this.parent.get()?.at(-1)?.timeMs;
217
+ const floor = this.query.from;
218
+ return this.parent.hasMore() && (floor === undefined || oldest === undefined || oldest > floor);
219
+ }
220
+
221
+ async loadOlder(): Promise<void> {
222
+ if (this.hasMore()) await this.parent.loadOlder();
223
+ }
224
+
225
+ onEvent(listener: (events: ActivityEvent[]) => void): () => void {
226
+ const want = this.want;
227
+ if (!want) return this.parent.onEvent(listener);
228
+ return this.parent.onEvent((events) => {
229
+ const kept = events.filter((e) => want.has("activityType" in e ? e.activityType : EVENT_TYPE[e.kind]));
230
+ if (kept.length) listener(kept);
231
+ });
232
+ }
233
+
234
+ private keeps(r: ActivityEntry): boolean {
235
+ const { from, to } = this.query;
236
+ if (from !== undefined && r.timeMs < from) return false;
237
+ if (to !== undefined && r.timeMs > to) return false;
238
+ return !this.want || this.want.has(r.activityType);
265
239
  }
266
240
  }