@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
@@ -8,8 +8,8 @@
8
8
  // implied_leverage = (Σ current perp notional + notional) / perps_equity
9
9
  // liquidation = mark where equity falls to Σ maintenance margin (im/2)
10
10
 
11
- import type { Market, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
12
- import { div, imRate, mul } from "../codec/fixed.js";
11
+ import type { Market, Orderbook, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
12
+ import { div, imRate, min, mul } from "../codec/fixed.js";
13
13
  import { alignSize, parseAmount, toNumber, WAD } from "../codec/units.js";
14
14
 
15
15
  export interface ReturnPriceInput {
@@ -220,3 +220,57 @@ export function closePreview(
220
220
  fee: mul(notional, input.feeRate ?? 0n),
221
221
  };
222
222
  }
223
+
224
+ export interface FillEstimate {
225
+ /** Base size the book fills within `limit` (≤ `size`). */
226
+ filled: bigint;
227
+ /** The price the whole fill clears at were this the batch's only order;
228
+ * undefined when nothing fills. A batch clears every match at one price and
229
+ * a market order never sets it, so this is at least the last level reached —
230
+ * not an average across the levels. */
231
+ price?: bigint;
232
+ /** How much worse `price` is than the best level, in percent — the cost of
233
+ * the size alone, spread excluded. */
234
+ slippagePct?: number;
235
+ /** The walk ran off the last level given while still inside `limit`. On a
236
+ * depth-truncated book `filled` is then a floor, not an estimate. */
237
+ exhausted: boolean;
238
+ }
239
+
240
+ /**
241
+ * What a taker order of `size` (base, magnitude) would fill against `book`:
242
+ * walks the opposite side best-first — asks for a long, bids for a short — and
243
+ * stops at `limit`, a market order's protective price. Grouped levels make the
244
+ * prices approximate to the grouping.
245
+ */
246
+ export function estimateFill(
247
+ book: Pick<Orderbook, "bids" | "asks">,
248
+ side: "long" | "short",
249
+ size: bigint,
250
+ limit?: bigint,
251
+ ): FillEstimate {
252
+ const levels = side === "long" ? book.asks : book.bids;
253
+ const within = (p: bigint) => limit === undefined || (side === "long" ? p <= limit : p >= limit);
254
+ let filled = 0n;
255
+ let left = 0n; // volume the last level reached still holds
256
+ let i = 0;
257
+ for (; i < levels.length && filled < size; i++) {
258
+ const l = levels[i]!;
259
+ if (!within(l.price)) break;
260
+ const take = min(l.volume, size - filled);
261
+ filled += take;
262
+ left = l.volume - take;
263
+ }
264
+ const exhausted = filled < size && i === levels.length;
265
+ if (filled === 0n) return { filled, exhausted };
266
+ // The clearing range runs from the last level matched to the first level left
267
+ // unmatched — that same level when only part of it was taken — and settles at
268
+ // its midpoint, never past the order's own limit (doc/protocol/orderbook.md, Clearing).
269
+ const last = levels[i - 1]!.price;
270
+ const unmatched = left > 0n ? last : levels[i]?.price;
271
+ let price = unmatched === undefined ? last : (last + unmatched) / 2n;
272
+ if (limit !== undefined && !within(price)) price = limit;
273
+ const best = levels[0]!.price;
274
+ const worse = side === "long" ? price - best : best - price;
275
+ return { filled, price, slippagePct: (Number(worse) / Number(best)) * 100, exhausted };
276
+ }
@@ -145,10 +145,10 @@ export class OrderHistory implements SeriesResource<Order> {
145
145
  const frame = result as WireOrdersFrame;
146
146
  if (!frame || !Array.isArray(frame.orders) || !Array.isArray(frame.events)) return;
147
147
 
148
- // Drop what we already hold. Applying a frame is not idempotent — a fill event
149
- // appends to `order.fills`, and re-creating an entity resets its totals — and
150
- // re-delivery is designed in: a resumed subscription replays from a cursor, and
151
- // the replay boundary is a whole batch.
148
+ // Drop what we already hold. Applying a frame is not idempotent — re-creating an
149
+ // entity resets its totals, and events would be reported twice — and re-delivery is
150
+ // designed in: a resumed subscription replays from a cursor, and the replay boundary
151
+ // is a whole batch.
152
152
  const at: SubParams = { since: frame.batch, sinceBook: frame.book };
153
153
  if (this.stream.delivered(at)) return;
154
154
 
@@ -13,7 +13,8 @@
13
13
 
14
14
  import type { Address, MarketId, MoneyActivity } from "../types/public.js";
15
15
  import { div, mul } from "../codec/fixed.js";
16
- import { dec } from "../codec/units.js";
16
+ import { dec, usToMs } from "../codec/units.js";
17
+ import { decodeActivityEntry } from "../codec/activity.js";
17
18
  import type { WireFillRow, WireSolutionRow } from "../types/wire.js";
18
19
  import { rpc, type RpcOptions } from "../transport/jsonrpc.js";
19
20
  import { PodHttpError, type PodRestClient } from "../transport/rest.js";
@@ -380,15 +381,20 @@ const FLOW_TYPES = ["backstop", "bridge_transfer", "transfer"] as const;
380
381
 
381
382
  /** Money movements in [fromUs, toUs) from the activity feed, or `undefined`
382
383
  * when the node does not serve it. */
383
- async function drainFlows(rest: PodRestClient, account: Address, fromUs: number, toUs: number): Promise<MoneyActivity[] | undefined> {
384
+ async function drainFlows(rest: PodRestClient, account: Address, fromUs: number, toUsExclusive: number): Promise<MoneyActivity[] | undefined> {
384
385
  const out: MoneyActivity[] = [];
385
- let cursor: string | undefined;
386
+ let toUs: number | null = toUsExclusive - 1;
386
387
  try {
387
388
  do {
388
- const page = await rest.activity(account, { types: [...FLOW_TYPES], from: fromUs / 1000, to: toUs / 1000, limit: 200, cursor });
389
- for (const e of page.activity) if (e.activityType !== "order") out.push(e);
390
- cursor = page.nextCursor ?? undefined;
391
- } while (cursor);
389
+ const page = await rest.activity(account, { types: [...FLOW_TYPES], fromUs, toUs, limit: 500 });
390
+ for (const [batchUs, entries] of page.batches) {
391
+ for (const e of entries) {
392
+ if (e.k !== "backstop" && e.k !== "bridge_transfer" && e.k !== "transfer") continue;
393
+ out.push(decodeActivityEntry(e, usToMs(batchUs)) as MoneyActivity);
394
+ }
395
+ }
396
+ toUs = page.nextUs;
397
+ } while (toUs !== null);
392
398
  } catch (e) {
393
399
  // Only a missing route means the node has no feed. Anything else (a 503,
394
400
  // a timeout) must fail the run, or the range would be cached without
@@ -4,21 +4,21 @@
4
4
 
5
5
  import type { WireFillRow, WireSolutionRow } from "../types/wire.js";
6
6
  import type {
7
- ActivityEntry, ActivityType, Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery,
7
+ ActivityType, Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery,
8
8
  Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status,
9
9
  Trigger, TxExplorer, Withdrawal, WithdrawalsQuery,
10
10
  } from "../types/public.js";
11
11
  import type {
12
- WireActivityPage, WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
12
+ WireActivityEntry, WireActivityPage, WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
13
13
  WireMarketStatic, WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot,
14
14
  WireStatus, WireTriggersPage, WireWithdrawal,
15
15
  } from "../types/wire.js";
16
16
  import {
17
- decodeActivityEntry, decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle,
17
+ decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle,
18
18
  decodeMarketDynamics, decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions,
19
19
  decodeStatus, decodeTrigger, decodeWithdrawal,
20
20
  } from "../codec/decode.js";
21
- import { msToSecs, msToUs, usToMs } from "../codec/units.js";
21
+ import { msToSecs, usToMs } from "../codec/units.js";
22
22
 
23
23
  export type MarketDynamicsPatch = Partial<Market> & { id: string };
24
24
 
@@ -33,8 +33,10 @@ export interface OrdersPage {
33
33
  solutionNow: number;
34
34
  }
35
35
  export interface ActivityPage {
36
- activity: ActivityEntry[];
37
- nextCursor: string | null;
36
+ /** Newest first, each batch's entries in the node's order. */
37
+ batches: Array<[batchUs: number, entries: WireActivityEntry[]]>;
38
+ /** Pass back as `toUs` for the next, older page; null when the window is exhausted. */
39
+ nextUs: number | null;
38
40
  solutionNow: number; // ms
39
41
  }
40
42
  export interface BackstopPage {
@@ -60,11 +62,11 @@ export interface OrdersQueryRest {
60
62
  cursor?: string;
61
63
  }
62
64
  export interface ActivityQueryRest {
63
- limit?: number;
64
- cursor?: string;
65
65
  types?: ActivityType[];
66
- from?: number; // ms
67
- to?: number; // ms
66
+ fromUs?: number; // inclusive
67
+ toUs?: number; // inclusive
68
+ /** Entries per page, 1..=2000; the newest batch is served whole even past it. */
69
+ limit?: number;
68
70
  }
69
71
  export interface TriggersQueryRest {
70
72
  orderbook?: MarketId;
@@ -190,22 +192,20 @@ export class PodRestClient {
190
192
  };
191
193
  }
192
194
 
193
- /**
194
- * One account's activity, newest first: orders at their placement tick, and the
195
- * money that moved (ADR 0057 §5). The seed behind `pod_activity`; page it
196
- * with `cursor`.
197
- */
195
+ /** One page of an account's activity by batch, newest batches first (ADR 0057 §5); page with `nextUs`. */
198
196
  async activity(account: Address, q?: ActivityQueryRest): Promise<ActivityPage> {
199
197
  const w = await this.get<WireActivityPage>(`/clob/activity/${account}`, {
200
- limit: q?.limit,
201
- cursor: q?.cursor,
202
198
  activity_types: q?.types?.length ? q.types.join(",") : undefined,
203
- from: q?.from !== undefined ? msToUs(q.from) : undefined,
204
- to: q?.to !== undefined ? msToUs(q.to) : undefined,
199
+ from: q?.fromUs !== undefined ? String(q.fromUs) : undefined,
200
+ to: q?.toUs !== undefined ? String(q.toUs) : undefined,
201
+ limit: q?.limit,
205
202
  });
203
+ const batches = Object.entries(w.activity)
204
+ .map(([batch, entries]): [number, WireActivityEntry[]] => [Number(batch), entries])
205
+ .sort((a, b) => b[0] - a[0]);
206
206
  return {
207
- activity: w.activity.map(decodeActivityEntry).filter((e): e is ActivityEntry => e !== undefined),
208
- nextCursor: w.next_cursor,
207
+ batches,
208
+ nextUs: w.next === null ? null : Number(w.next),
209
209
  solutionNow: usToMs(w.solution_now),
210
210
  };
211
211
  }
@@ -11,9 +11,7 @@ export type Channel =
11
11
  /** Terminal withdrawal outcomes; one array per tick, `account`-filtered on the
12
12
  * debited account. ADR 0033 §6. */
13
13
  | "pod_withdrawals"
14
- /** One account's whole activity: `pod_orders_v2` for every book the tick
15
- * cleared, plus the money it moved. One frame per tick, so `since` alone
16
- * resumes it. ADR 0057 §6. */
14
+ /** One `{ "<batch>": [entries] }` message per tick, so `since` alone resumes it. ADR 0057 §6. */
17
15
  | "pod_activity";
18
16
 
19
17
  export interface SubParams {
@@ -20,7 +20,7 @@ export type OrderSide = "buy" | "sell";
20
20
  export type OrderType = "limit" | "market";
21
21
  export type OrderStatus =
22
22
  | "pending" | "active" | "filled" | "expired"
23
- | "canceled" | "margin_canceled" | "invalid" | "post_only_refused";
23
+ | "canceled" | "margin_canceled" | "self_trade_canceled" | "invalid" | "post_only_refused";
24
24
  export type OrderKind =
25
25
  | "user_signed" | "liquidation" | "triggered" | "adl" | "adl_counterparty"
26
26
  /** A backstop transfer merged into the order feed as a synthetic terminal row. */
@@ -76,20 +76,21 @@ export interface AmendRejection {
76
76
  * Absent when the stream names a single account.
77
77
  */
78
78
  requestedBy?: Address;
79
- /** The batch the refusal landed in (ms). */
80
79
  batchMs: number;
81
80
  }
82
81
 
83
82
  /** What the engine did to an order, as `pod_orders_v2` reports it (ADR 0029 §3). */
84
83
  export type OrderEventKind =
85
- | "new" | "reject" | "fill" | "cancel" | "expire" | "modify" | "modify_reject";
84
+ | "new" | "reject" | "fill" | "cancel" | "expire" | "modify" | "modify_reject" | "cancel_reject";
86
85
 
87
86
  /**
88
87
  * The statuses an order can *close* with. Narrower than `OrderStatus`, which also
89
88
  * covers the states a live order passes through — so a `switch` over this one can be
90
89
  * exhaustive.
91
90
  */
92
- export type TerminalStatus = Extract<OrderStatus, "filled" | "canceled" | "margin_canceled" | "expired" | "post_only_refused">;
91
+ export type TerminalStatus = Extract<
92
+ OrderStatus, "filled" | "canceled" | "margin_canceled" | "self_trade_canceled" | "expired" | "post_only_refused"
93
+ >;
93
94
 
94
95
  /** One fill, plus the status it closed the order with when it did. */
95
96
  export interface OrderEventFill extends PartialFill {
@@ -110,6 +111,8 @@ export interface OrderEventFill extends PartialFill {
110
111
  * 0029 §6 reserves a `why` for that), so do not try to re-derive it from `status`.
111
112
  */
112
113
  closedAs?: TerminalStatus;
114
+ /** This fill's fee; absent on activity rows stored before it was recorded. */
115
+ fee?: bigint;
113
116
  }
114
117
 
115
118
  /**
@@ -149,6 +152,16 @@ export interface OrderEvent {
149
152
  * from REST.
150
153
  */
151
154
  amendRejection?: AmendRejection;
155
+ /** `cancel_reject` only. */
156
+ cancelRejection?: CancelRejection;
157
+ }
158
+
159
+ /** A cancel the engine refused; the order is untouched. */
160
+ export interface CancelRejection {
161
+ code: RejectCode;
162
+ message?: string;
163
+ /** The batch the refusal landed in (ms). */
164
+ batchMs: number;
152
165
  }
153
166
 
154
167
  export interface TokenInfo {
@@ -277,7 +290,6 @@ export interface Order {
277
290
  endMs?: number;
278
291
  /** Batch-inclusion time (ms) — when the order entered the book. */
279
292
  includedMs?: number;
280
- fills: PartialFill[];
281
293
  /** Why the engine rejected the order; set only on `status: "invalid"`. */
282
294
  rejectReason?: string;
283
295
  // perpetual-only
@@ -451,21 +463,53 @@ export interface CandleQuery {
451
463
  limit?: number;
452
464
  }
453
465
 
454
- export type ActivityType = "order" | "backstop" | "bridge_transfer" | "transfer";
466
+ export type ActivityType =
467
+ | "order" | "fill" | "modify" | "termination" | "backstop" | "bridge_transfer" | "transfer"
468
+ | "modify_reject" | "cancel_reject";
455
469
 
456
470
  /**
457
- * One row of an account's activity (ADR 0057): an order at its placement tick,
458
- * or money that moved.
459
- *
460
- * `timeMs` is what the row is ordered by. Fills, cancels and amendments are not
461
- * rows — they are events on the stream, and the order an `order` row carries
462
- * already reflects them.
463
- *
464
- * Money amounts are signed from the account's side — negative left, positive
465
- * arrived — and say nothing about the other end.
471
+ * One row of an account's activity (ADR 0057). Money amounts are signed from the
472
+ * account's side: negative left, positive arrived.
466
473
  */
467
474
  export type ActivityEntry =
475
+ /** The placement, carrying the order as every later row seen so far left it. */
468
476
  | { activityType: "order"; timeMs: number; order: Order }
477
+ | {
478
+ activityType: "fill";
479
+ timeMs: number;
480
+ orderId: Hash;
481
+ orderbookId: MarketId;
482
+ /** This fill alone. */
483
+ base: bigint;
484
+ quote: bigint;
485
+ /** Life-to-date totals; absent only on rows stored before they were recorded. */
486
+ totalBase?: bigint;
487
+ totalQuote?: bigint;
488
+ totalFee?: bigint;
489
+ /** This fill's fee; absent on rows stored before it was recorded. */
490
+ fee?: bigint;
491
+ closedAs?: TerminalStatus;
492
+ /** Perp only; signed. */
493
+ positionAfter?: bigint;
494
+ }
495
+ | {
496
+ activityType: "modify";
497
+ timeMs: number;
498
+ orderId: Hash;
499
+ orderbookId: MarketId;
500
+ price: bigint;
501
+ /** Unsigned magnitude. */
502
+ size: bigint;
503
+ oldPrice: bigint;
504
+ oldSize: bigint;
505
+ }
506
+ | {
507
+ activityType: "termination";
508
+ timeMs: number;
509
+ orderId: Hash;
510
+ orderbookId: MarketId;
511
+ status: TerminalStatus;
512
+ }
469
513
  | (BackstopTransfer & { activityType: "backstop"; timeMs: number })
470
514
  | {
471
515
  activityType: "bridge_transfer";
@@ -483,13 +527,33 @@ export type ActivityEntry =
483
527
  activityType: "transfer";
484
528
  timeMs: number;
485
529
  transferId: Hash;
530
+ /** The receiver when `amount` is negative, the sender otherwise; the account itself on a self-transfer. */
531
+ counterparty: Address;
486
532
  token: Address;
487
533
  amount: bigint;
488
534
  error?: string;
535
+ }
536
+ /** An amendment the engine refused; `message` is the engine's reason. */
537
+ | {
538
+ activityType: "modify_reject";
539
+ timeMs: number;
540
+ orderId: Hash;
541
+ orderbookId: MarketId;
542
+ requestedPrice: bigint;
543
+ requestedSize: bigint;
544
+ message: string;
545
+ }
546
+ /** A cancel the engine refused; `message` is the engine's reason. */
547
+ | {
548
+ activityType: "cancel_reject";
549
+ timeMs: number;
550
+ orderId: Hash;
551
+ orderbookId: MarketId;
552
+ message: string;
489
553
  };
490
554
 
491
- /** The activity rows that are not orders. */
492
- export type MoneyActivity = Exclude<ActivityEntry, { activityType: "order" }>;
555
+ /** The activity rows that move money. */
556
+ export type MoneyActivity = Extract<ActivityEntry, { activityType: "backstop" | "bridge_transfer" | "transfer" }>;
493
557
 
494
558
  /**
495
559
  * What the stream reported in one tick: the order transitions, and the money
@@ -501,14 +565,13 @@ export type MoneyActivity = Exclude<ActivityEntry, { activityType: "order" }>;
501
565
  export type ActivityEvent = OrderEvent | MoneyActivity;
502
566
 
503
567
  /**
504
- * `from` and `to` are milliseconds; `limit` is a row count, not a span of time.
505
- * `types` names the kinds to keep — absent or empty keeps every kind.
568
+ * `from` and `to` are milliseconds, both inclusive. `types` names the kinds to
569
+ * keep — absent or empty keeps every kind.
506
570
  */
507
571
  export interface ActivityQuery {
508
572
  types?: ActivityType[];
509
573
  from?: number;
510
574
  to?: number;
511
- limit?: number;
512
575
  }
513
576
 
514
577
  export interface OrdersQuery {
package/src/types/wire.ts CHANGED
@@ -91,13 +91,6 @@ export interface WireCandleTick {
91
91
  volume: WireDecimal;
92
92
  }
93
93
 
94
- export interface WirePartialFill {
95
- base_amount: WireDecimal;
96
- quote_amount: WireDecimal;
97
- timestamp: number; // micros
98
- price: WireDecimal;
99
- }
100
-
101
94
  export interface WireOrder {
102
95
  orderbook_id?: Hex;
103
96
  /** The order endpoints say "perpetual" where `/clob/markets` says "perp". */
@@ -118,13 +111,13 @@ export interface WireOrder {
118
111
  end: number | string; // micros
119
112
  included_batch?: number | string; // micros; batch-inclusion time (REST order history)
120
113
  effective_price?: WireDecimal | null;
121
- fills?: WirePartialFill[];
122
114
  side?: "buy" | "sell";
123
115
  reduce_only?: boolean;
124
116
  ioc?: boolean;
125
117
  direction?: string;
126
118
  grouping?: WireDecimal;
127
119
  trigger_type?: string | null;
120
+ invalid_reason?: string;
128
121
  }
129
122
 
130
123
  export interface WireOrdersPage {
@@ -269,8 +262,7 @@ export interface WireBackstopPage {
269
262
  // means something specific — noted per field.
270
263
 
271
264
  export interface WireOrdersFrame {
272
- /** The orderbook these actions happened on; constant for the frame. Absent on
273
- * `pod_activity`, which is one frame per tick and names the book per entity. */
265
+ /** The orderbook these actions happened on; constant for the frame. */
274
266
  book?: Hex;
275
267
  /** Deadline (micros) of the batch the actions **landed in**. Half of the resume cursor; `book` is the other half. */
276
268
  batch: number;
@@ -289,8 +281,6 @@ export interface WireOrderEntity {
289
281
  id: Hex;
290
282
  /** Creating transaction, or its parent `submitBatch` envelope. */
291
283
  tx: Hex;
292
- /** The order's book. Sent here by `pod_activity`, which covers a whole
293
- * account; `pod_orders_v2` names it once on the frame instead. */
294
284
  book?: Hex;
295
285
  /** Index into the frame's `accts`; present iff `accts` is. */
296
286
  a?: number;
@@ -357,13 +347,15 @@ export interface WireOrderEvent {
357
347
  tb?: WireDecimal;
358
348
  /** Total quote filled so far; travels with `tb`. */
359
349
  tq?: WireDecimal;
360
- /** Total fee charged so far; travels with `tb`. There is no per-fill counterpart. */
350
+ /** Total fee charged so far; travels with `tb`. */
361
351
  tf?: WireDecimal;
352
+ /** `fill` only: this fill's fee. */
353
+ f?: WireDecimal;
362
354
  /**
363
355
  * The terminal status an event closed the order with. On `fill`, only on the fill that
364
356
  * closed it. On `cancel`, only when the engine removed the order rather than the owner.
365
357
  */
366
- st?: "filled" | "canceled" | "margin_canceled" | "expired" | "post_only_refused";
358
+ st?: WireTerminalStatus;
367
359
  /**
368
360
  * `fill` on a perp market: the owner's position after this fill, signed and
369
361
  * 1e18-scaled. Omitted on spot, which has no position.
@@ -441,80 +433,79 @@ export interface WireWithdrawalDetail {
441
433
 
442
434
  // --- account activity (ADR 0057) ---
443
435
  //
444
- // `GET /clob/activity/{account}` serves the seed and `pod_activity` streams it.
445
- // The seed is a union tagged by `activity_type`: the order variant flattens the
446
- // orders route's `WireOrder`, and every money variant carries exactly the fields
447
- // its stream event does, so the two decode through one decoder. The channel is
448
- // `pod_orders_v2`'s frame for a whole account — one frame per tick, with the
449
- // money the tick moved as extra event kinds.
450
-
451
- export interface WireActivityPage {
452
- activity: WireActivityEntry[];
453
- next_cursor: string | null;
454
- solution_now: number; // micros
455
- }
436
+ // REST pages and `pod_activity` frames are `{ "<batch micros>": [entry, ...] }`; absent fields are absent, never null.
456
437
 
457
- /** What each money kind carries. Shared because the seed row and the stream
458
- * event differ only in how they are tagged. */
459
438
  export interface WireBackstopMoney {
460
439
  /** Absent on the terminal cash sweep, which belongs to no market. */
461
440
  book?: Hex;
462
- size: WireDecimal; // signed
441
+ sz: WireDecimal; // signed
463
442
  cash: WireDecimal; // signed
464
443
  mark: WireDecimal;
465
- equity: WireDecimal; // signed
444
+ eq: WireDecimal; // signed
466
445
  pnl: WireDecimal; // signed
467
446
  }
468
447
 
469
448
  export interface WireBridgeMoney {
470
449
  tx: Hex;
471
- /** Position within the transaction: one tx can bridge several amounts, so the
472
- * hash alone does not identify the row. */
473
450
  idx: number;
474
- token: Hex;
475
- amount: WireDecimal; // signed
476
- error?: string;
451
+ tok: Hex;
452
+ amt: WireDecimal; // signed
453
+ err?: string;
477
454
  }
478
455
 
479
456
  export interface WireTransferMoney {
480
457
  id: Hex;
481
- token: Hex;
482
- amount: WireDecimal; // signed
483
- error?: string;
458
+ /** The receiver when `amt` is negative, the sender otherwise. */
459
+ cp: Hex;
460
+ tok: Hex;
461
+ amt: WireDecimal; // signed
462
+ err?: string;
484
463
  }
485
464
 
486
- /**
487
- * One activity row. `ts` is what the node sorted the page by — for an order that
488
- * is its **signed deadline**, not the batch it landed in.
489
- *
490
- * Money amounts are signed from the account's side: negative left, positive
491
- * arrived, for the bridge and for a transfer alike.
492
- */
493
- export type WireActivityEntry =
494
- | ({ activity_type: "order"; ts: number } & WireOrder)
495
- | ({ activity_type: "backstop"; ts: number } & WireBackstopMoney)
496
- | ({ activity_type: "bridge_transfer"; ts: number } & WireBridgeMoney)
497
- | ({ activity_type: "transfer"; ts: number } & WireTransferMoney);
465
+ type WireTerminalStatus =
466
+ | "filled" | "canceled" | "margin_canceled" | "self_trade_canceled" | "expired" | "post_only_refused";
498
467
 
499
468
  /**
500
- * One tick of an account's activity. No `book` — a tick covers every book the
501
- * account traded on, so each entity names its own — and no `accts`, since the
502
- * channel takes exactly one account.
469
+ * An unknown `k` from a newer node is dropped by the decoder; it is not in this union
470
+ * because an open member would defeat narrowing on the known ones.
503
471
  */
504
- export interface WireActivityFrame {
505
- /** Deadline (micros) of the batch. One frame per tick, so this alone is the
506
- * resume cursor: a frame is already delivered exactly when `batch <= since`. */
507
- batch: number;
508
- orders: WireOrderEntity[];
509
- events: (WireOrderEvent | WireMoneyEvent)[];
510
- }
511
-
512
- /** Money the tick moved, discriminated by `k` — disjoint from the order kinds,
513
- * which is what lets the two share one untagged union on the wire. */
514
- export type WireMoneyEvent =
472
+ export type WireActivityEntry =
473
+ | ({ k: "order" } & WireOrder)
474
+ | {
475
+ k: "fill";
476
+ id: Hex;
477
+ book: Hex;
478
+ b: WireDecimal;
479
+ q: WireDecimal;
480
+ tb?: WireDecimal;
481
+ tq?: WireDecimal;
482
+ tf?: WireDecimal;
483
+ f?: WireDecimal;
484
+ st?: WireTerminalStatus;
485
+ pa?: WireDecimal;
486
+ }
487
+ | { k: "modify"; id: Hex; book: Hex; px: WireDecimal; sz: WireDecimal; old_px: WireDecimal; old_sz: WireDecimal }
488
+ | {
489
+ k: "termination";
490
+ id: Hex;
491
+ book: Hex;
492
+ st: Exclude<WireTerminalStatus, "filled">;
493
+ }
515
494
  | ({ k: "backstop" } & WireBackstopMoney)
516
495
  | ({ k: "bridge_transfer" } & WireBridgeMoney)
517
- | ({ k: "transfer" } & WireTransferMoney);
496
+ | ({ k: "transfer" } & WireTransferMoney)
497
+ | { k: "modify_reject"; id: Hex; book: Hex; px: WireDecimal; sz: WireDecimal; why: string }
498
+ | { k: "cancel_reject"; id: Hex; book: Hex; why: string };
499
+
500
+ /** Entries by batch (micros, decimal string key); the stream sends one key per message. */
501
+ export type WireActivityFrame = Record<string, WireActivityEntry[]>;
502
+
503
+ export interface WireActivityPage {
504
+ activity: WireActivityFrame;
505
+ /** Pass back as `to` for the next, older page; null when the window is exhausted. */
506
+ next: string | null;
507
+ solution_now: number; // micros
508
+ }
518
509
 
519
510
  /** One `/clob/fills/{account}` row: a fill of one order in one batch. */
520
511
  export interface WireFillRow {