@pod-network/trade-sdk 0.10.0 → 0.11.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 (72) hide show
  1. package/README.md +6 -4
  2. package/dist/client.d.ts +20 -10
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +26 -11
  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/orders-v2.d.ts +9 -3
  15. package/dist/codec/orders-v2.d.ts.map +1 -1
  16. package/dist/codec/orders-v2.js +12 -9
  17. package/dist/codec/orders-v2.js.map +1 -1
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/sync/activity.d.ts +58 -0
  23. package/dist/sync/activity.d.ts.map +1 -0
  24. package/dist/sync/activity.js +259 -0
  25. package/dist/sync/activity.js.map +1 -0
  26. package/dist/sync/orders.d.ts +4 -64
  27. package/dist/sync/orders.d.ts.map +1 -1
  28. package/dist/sync/orders.js +40 -190
  29. package/dist/sync/orders.js.map +1 -1
  30. package/dist/sync/pnl-history.d.ts +33 -14
  31. package/dist/sync/pnl-history.d.ts.map +1 -1
  32. package/dist/sync/pnl-history.js +255 -65
  33. package/dist/sync/pnl-history.js.map +1 -1
  34. package/dist/sync/stream.d.ts +101 -0
  35. package/dist/sync/stream.d.ts.map +1 -0
  36. package/dist/sync/stream.js +243 -0
  37. package/dist/sync/stream.js.map +1 -0
  38. package/dist/transport/jsonrpc.d.ts +0 -5
  39. package/dist/transport/jsonrpc.d.ts.map +1 -1
  40. package/dist/transport/jsonrpc.js +0 -20
  41. package/dist/transport/jsonrpc.js.map +1 -1
  42. package/dist/transport/rest.d.ts +36 -4
  43. package/dist/transport/rest.d.ts.map +1 -1
  44. package/dist/transport/rest.js +43 -10
  45. package/dist/transport/rest.js.map +1 -1
  46. package/dist/transport/ws.d.ts +5 -1
  47. package/dist/transport/ws.d.ts.map +1 -1
  48. package/dist/transport/ws.js.map +1 -1
  49. package/dist/types/public.d.ts +62 -23
  50. package/dist/types/public.d.ts.map +1 -1
  51. package/dist/types/wire.d.ts +98 -16
  52. package/dist/types/wire.d.ts.map +1 -1
  53. package/dist/write/index.d.ts +3 -3
  54. package/dist/write/index.d.ts.map +1 -1
  55. package/dist/write/index.js +0 -3
  56. package/dist/write/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/src/client.ts +28 -13
  59. package/src/codec/activity.ts +46 -0
  60. package/src/codec/decode.ts +65 -30
  61. package/src/codec/orders-v2.ts +24 -11
  62. package/src/index.ts +3 -1
  63. package/src/sync/activity.ts +266 -0
  64. package/src/sync/orders.ts +41 -187
  65. package/src/sync/pnl-history.ts +244 -75
  66. package/src/sync/stream.ts +270 -0
  67. package/src/transport/jsonrpc.ts +0 -23
  68. package/src/transport/rest.ts +62 -14
  69. package/src/transport/ws.ts +5 -1
  70. package/src/types/public.ts +62 -26
  71. package/src/types/wire.ts +105 -18
  72. package/src/write/index.ts +3 -6
package/src/client.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type {
2
- Address, BackstopTransfer, Balances, Bar, BridgeConfig, LeaderboardPage, LeaderboardQuery, Market,
2
+ ActivityQuery, Address, BackstopTransfer, Balances, Bar, BridgeConfig, Market,
3
3
  MarketId, PositionsSnapshot, Resolution, Status, TimeRange, Trigger, TriggersQuery, TxExplorer,
4
4
  OrdersQuery, Withdrawal,
5
5
  } from "./types/public.js";
@@ -13,6 +13,7 @@ import {
13
13
  import { withdrawalsSource } from "./sync/withdrawals.js";
14
14
  import { CandleSeries, candleTailFrom, fetchCandleHistory } from "./sync/candles.js";
15
15
  import { OrderHistory } from "./sync/orders.js";
16
+ import { ActivityHistory, normalizeActivityQuery } from "./sync/activity.js";
16
17
  import { enrichPositions } from "./sync/positions-live.js";
17
18
  import { fetchPnlHistory, streamPnlHistory, PnlHistoryCache, type PnlHistory, type PnlHistoryChunk, type PnlHistoryQuery } from "./sync/pnl-history.js";
18
19
 
@@ -207,12 +208,6 @@ export class PodTradeClient {
207
208
  );
208
209
  }
209
210
 
210
- /** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
211
- * `{ limit, offset }`. Not a stream — call again to refresh. */
212
- leaderboard(query?: LeaderboardQuery): Promise<LeaderboardPage> {
213
- return this.rest.leaderboard(query);
214
- }
215
-
216
211
  /** Explorer view of a transaction by hash. One-shot. */
217
212
  transaction(hash: string): Promise<TxExplorer> {
218
213
  return this.rest.transaction(hash);
@@ -232,18 +227,20 @@ export class PodTradeClient {
232
227
 
233
228
  /**
234
229
  * PnL change over a past window, sampled at up to `points` (default and
235
- * maximum 500) evenly spaced batch ticks, starting at 0 at `from`. Folded
236
- * backwards from the live snapshot over the account's fills, backstop sweeps
237
- * and spot withdrawals. Requires `rpcUrl`.
230
+ * maximum 500) evenly spaced batch ticks, starting at 0 at `from`, with the
231
+ * absolute account value at each point where the node serves the activity
232
+ * feed. Folded backwards from the live snapshot over the account's fills,
233
+ * backstop sweeps and money movements. Requires `rpcUrl`.
238
234
  */
239
235
  pnlHistory(account: Address, query: PnlHistoryQuery): Promise<PnlHistory> {
240
236
  return fetchPnlHistory(this.pnlDeps("pnlHistory", account), account, query);
241
237
  }
242
238
 
243
239
  /**
244
- * {@link pnlHistory} delivered as it is built: chunks of up to 50 points,
245
- * newest first, each yielded once its fills are in. Points are relative to
246
- * the current tick; the oldest chunk arrives last with `done`.
240
+ * {@link pnlHistory} delivered as it is built: chunks newest first, the
241
+ * first ones small (10, 20, 40 points) and then 50, each yielded once its
242
+ * fills are in. Points are relative to the current tick; the oldest chunk
243
+ * arrives last with `done`.
247
244
  */
248
245
  pnlHistoryStream(account: Address, query: PnlHistoryQuery): AsyncGenerator<PnlHistoryChunk> {
249
246
  return streamPnlHistory(this.pnlDeps("pnlHistoryStream", account), account, query);
@@ -312,6 +309,24 @@ export class PodTradeClient {
312
309
  }
313
310
  }
314
311
 
312
+ /**
313
+ * One account's whole activity, newest first (ADR 0057): its orders, the
314
+ * backstop legs it was swept into, and every bridge transfer and transfer that
315
+ * moved its money.
316
+ *
317
+ * `orders` is a separate stream (`pod_orders_v2`), with its own cursor and its
318
+ * own row shape — not this feed narrowed to orders. It is to be retired in
319
+ * favour of this one, so new code should start here.
320
+ */
321
+ activity(account: Address, query?: ActivityQuery): ActivityHistory {
322
+ // The constructor normalises too, so the key must — otherwise `{}` and
323
+ // `{ types: [] }` ask for the same feed and get two of them, each with its own
324
+ // socket subscription. Sorted, since key order is an argument's accident.
325
+ const q = normalizeActivityQuery(query);
326
+ const key = `activity:${account.toLowerCase()}:${JSON.stringify(q, Object.keys(q).sort())}`;
327
+ return this.memo(key, () => new ActivityHistory(this.ctx, account, query));
328
+ }
329
+
315
330
  orders(account: Address, query?: OrdersQuery): OrderHistory {
316
331
  const key = `orders:${account}:${query ? JSON.stringify(query) : ""}`;
317
332
  return this.memo(key, () => new OrderHistory(this.ctx, account, query));
@@ -0,0 +1,46 @@
1
+ // `pod_activity` frames -> the order map plus the account's money rows (ADR 0057).
2
+ //
3
+ // A frame is `pod_orders_v2` for one whole account: the order half folds through
4
+ // `applyOrdersFrame` unchanged, and the money half is a set of extra event kinds
5
+ // whose `k` tags are disjoint from the order ones. Money has no entity to
6
+ // reference and no state to mutate, so each event is decoded straight into the
7
+ // entry the REST seed would have served for it — in one pass over `frame.events`,
8
+ // so what a consumer sees is the node's own interleaving of the tick.
9
+
10
+ import type { ActivityEntry, ActivityEvent, Address, MoneyActivity, Order } from "../types/public.js";
11
+ import type { WireActivityFrame, WireMoneyEvent, WireOrderEvent, WireOrdersFrame } from "../types/wire.js";
12
+ import { decodeMoneyEvent } from "./decode.js";
13
+ import { applyOrdersFrame } from "./orders-v2.js";
14
+ import { usToMs } from "./units.js";
15
+
16
+ const MONEY_KINDS: Record<WireMoneyEvent["k"], true> = {
17
+ backstop: true,
18
+ bridge_transfer: true,
19
+ transfer: true,
20
+ };
21
+
22
+ export const isMoney = (k: string): k is WireMoneyEvent["k"] => Object.hasOwn(MONEY_KINDS, k);
23
+
24
+ export interface ActivityState {
25
+ orders: Map<string, Order>;
26
+ entries: ActivityEntry[];
27
+ }
28
+
29
+ export function applyActivityFrame(
30
+ frame: WireActivityFrame,
31
+ state: ActivityState,
32
+ ctx: { account: Address },
33
+ ): ActivityEvent[] {
34
+ const timeMs = usToMs(frame.batch);
35
+ return applyOrdersFrame<MoneyActivity>(frame as WireOrdersFrame, state.orders, {
36
+ account: ctx.account,
37
+ // Order kinds, and money kinds this version does not know, are ignored rather
38
+ // than handed on — exactly as `applyOrdersFrame` does.
39
+ foreign: (event: WireOrderEvent) => {
40
+ if (!isMoney(event.k)) return undefined;
41
+ const entry = decodeMoneyEvent(event as unknown as WireMoneyEvent, timeMs);
42
+ state.entries.push(entry);
43
+ return entry;
44
+ },
45
+ });
46
+ }
@@ -2,14 +2,14 @@
2
2
  // representations are normalized into bigint + millisecond numbers.
3
3
 
4
4
  import type {
5
- Bar, BackstopTransfer, Balances, BridgeConfig, LeaderboardEntry, LeaderboardPage, Market, Order,
5
+ ActivityEntry, Bar, BackstopTransfer, Balances, BridgeConfig, Market, Order,
6
6
  Orderbook, PartialFill, PerpPosition, Position, PositionsSnapshot, SpotHolding,
7
- SpotPosition, Status, Trigger, MarketType, OrderDirection, OrderKind, OrderStatus, TriggerType,
8
- Withdrawal,
7
+ SpotPosition, Status, Trigger, MarketType, MoneyActivity, OrderDirection, OrderKind,
8
+ OrderStatus, TriggerType, Withdrawal,
9
9
  } from "../types/public.js";
10
10
  import type {
11
- WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle, WireLeaderboard,
12
- WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill,
11
+ WireActivityEntry, WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle,
12
+ WireMarketDynamics, WireMarketStatic, WireMoneyEvent, WireOrder, WireOrderbook, WirePartialFill,
13
13
  WirePerpPosition, WirePosition, WirePositionsSnapshot, WireSpotHolding, WireSpotPosition,
14
14
  WireStatus, WireTrigger, WireWithdrawal,
15
15
  } from "../types/wire.js";
@@ -238,31 +238,6 @@ export function decodeBalances(w: WireBalances): Balances {
238
238
  };
239
239
  }
240
240
 
241
- /** Decode a ranked-accounts page (REST `/clob/leaderboard`). `offset` makes the
242
- * ranks 1-based over the full ordering. PnL = unrealized + realized (the rank
243
- * key); `%` is suppressed to 0 when the basis (accountValue − unrealized) is dust. */
244
- export function decodeLeaderboard(w: WireLeaderboard, offset = 0): LeaderboardPage {
245
- const entries: LeaderboardEntry[] = (w.ranked ?? []).map((r, i) => {
246
- const unrealizedPnl = dec(r.positions.total_unrealized_pnl);
247
- const realizedPnl = dec(r.positions.total_realized_pnl);
248
- const accountValue = dec(r.positions.account_value);
249
- const pnl = unrealizedPnl + realizedPnl;
250
- const basis = accountValue - unrealizedPnl;
251
- const absAv = accountValue < 0n ? -accountValue : accountValue;
252
- const safe = basis > 0n && absAv > 0n && basis * 1000n >= absAv * 5n; // basis ≥ 0.5% of |av|
253
- return {
254
- rank: offset + i + 1,
255
- account: r.account,
256
- accountValue,
257
- unrealizedPnl,
258
- realizedPnl,
259
- pnl,
260
- pnlPercent: safe ? (Number(pnl) / Number(basis)) * 100 : 0,
261
- };
262
- });
263
- return { entries, total: w.total ?? 0 };
264
- }
265
-
266
241
  export function decodeTrigger(w: WireTrigger): Trigger {
267
242
  return {
268
243
  orderbookId: w.orderbook_id,
@@ -288,10 +263,70 @@ export function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfe
288
263
  cash: dec(w.cash),
289
264
  markPrice: dec(w.mark_price),
290
265
  equity: dec(w.equity),
266
+ realizedPnl: dec(w.realized_pnl),
291
267
  time: usToMs(w.timestamp_us),
292
268
  };
293
269
  }
294
270
 
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
+
295
330
  export function decodeBridgeConfig(w: WireBridgeConfig): BridgeConfig {
296
331
  return {
297
332
  claimChainId: w.claim_chain_id,
@@ -15,9 +15,15 @@ import { dec, 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 {
18
+ export interface OrdersFrameContext<X = never> {
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;
21
27
  }
22
28
 
23
29
  /** Per-frame facts the events need. */
@@ -37,13 +43,17 @@ interface FrameFacts {
37
43
  * mid-frame: they are collected while applying but the rows are mutated in place, so a
38
44
  * consumer never sees a half-applied order.
39
45
  */
40
- export function applyOrdersFrame(frame: WireOrdersFrame, byId: Map<string, Order>, ctx: OrdersFrameContext): OrderEvent[] {
46
+ export function applyOrdersFrame<X = never>(
47
+ frame: WireOrdersFrame,
48
+ byId: Map<string, Order>,
49
+ ctx: OrdersFrameContext<X>,
50
+ ): (OrderEvent | X)[] {
41
51
  // The book and the batch are frame constants: resolved once, not per entity.
42
52
  const batchMs = usToMs(frame.batch);
43
53
  const facts: FrameFacts = { batchMs, accts: frame.accts };
44
54
  const created = frame.orders.map((e) => decodeEntity(e, frame, batchMs, ctx.account));
45
55
 
46
- const applied: OrderEvent[] = [];
56
+ const applied: (OrderEvent | X)[] = [];
47
57
  for (const event of frame.events) {
48
58
  // `o` indexes this frame's entities and `id` names one resting from an earlier
49
59
  // batch — but an event kind added later (ADR 0029 §6 reserves several) may name
@@ -53,12 +63,11 @@ export function applyOrdersFrame(frame: WireOrdersFrame, byId: Map<string, Order
53
63
  const target = event.o !== undefined
54
64
  ? created[event.o]
55
65
  : byId.get(event.id ?? "") ?? created.find((o) => o.id === event.id);
56
- if (!target) continue;
57
66
  // `undefined` means a kind this version does not know, which is ignored rather than
58
67
  // handed on as an event a consumer cannot act on (ADR 0029 §6). The switch is the
59
68
  // only list of what is recognised — a separate one could disagree with it.
60
- const outcome = applyEvent(event, target, facts);
61
- if (outcome) {
69
+ const outcome = target ? applyEvent(event, target, facts) : undefined;
70
+ if (outcome && target) {
62
71
  applied.push({
63
72
  kind: event.k as OrderEventKind,
64
73
  order: target,
@@ -66,7 +75,10 @@ export function applyOrdersFrame(frame: WireOrdersFrame, byId: Map<string, Order
66
75
  fill: outcome.fill,
67
76
  amendRejection: outcome.amendRejection,
68
77
  });
78
+ continue;
69
79
  }
80
+ const foreign = ctx.foreign?.(event);
81
+ if (foreign !== undefined) applied.push(foreign);
70
82
  }
71
83
 
72
84
  // After the events, not before: an entity's own `new`/`reject` decides the
@@ -82,11 +94,12 @@ function decodeEntity(e: WireOrderEntity, frame: WireOrdersFrame, batchMs: numbe
82
94
  return {
83
95
  id: e.id,
84
96
  txHash: e.tx,
85
- // The frame names the book, so this is exact rather than inferred. Whether
86
- // that book is spot or perp is static market metadata, joined at read time by
87
- // whoever needs it — freezing it here would strand every order decoded before
88
- // the markets list loaded.
89
- orderbookId: frame.book,
97
+ // Named by the entity on `pod_activity` and by the frame on
98
+ // `pod_orders_v2`, so this is exact rather than inferred. Whether that book is
99
+ // spot or perp is static market metadata, joined at read time by whoever needs
100
+ // it — freezing it here would strand every order decoded before the markets
101
+ // list loaded.
102
+ orderbookId: e.book ?? frame.book,
90
103
  side: initialSize < 0n ? "sell" : "buy",
91
104
  orderType: e.type === "market" ? "market" : "limit",
92
105
  // Not on the entity: an order that rests is `active`, and the events below
package/src/index.ts CHANGED
@@ -8,7 +8,8 @@ export type { MarketsCache } from "./sync/sources.js";
8
8
  export { PodRestClient, PodHttpError } from "./transport/rest.js";
9
9
  export type {
10
10
  MarketDynamicsPatch, MarketStatsPage, OrdersPage, BackstopPage, TriggersPage,
11
- CandlesPage, OrdersQueryRest, TriggersQueryRest, RestClientOptions,
11
+ CandlesPage, ActivityPage, OrdersQueryRest, ActivityQueryRest, TriggersQueryRest,
12
+ RestClientOptions,
12
13
  } from "./transport/rest.js";
13
14
  export { PodWsClient, PodSubscriptionClosedError } from "./transport/ws.js";
14
15
  export type {
@@ -33,6 +34,7 @@ export {
33
34
  export type { SeriesResource } from "./sync/candles.js";
34
35
  export { CandleSeries } from "./sync/candles.js";
35
36
  export { OrderHistory } from "./sync/orders.js";
37
+ export { ActivityHistory } from "./sync/activity.js";
36
38
  export {
37
39
  fetchPnlHistory, streamPnlHistory, PnlHistoryCache,
38
40
  type PnlHistory, type PnlHistoryChunk, type PnlHistoryDeps, type PnlHistoryQuery, type PnlPoint,
@@ -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
+ }