@pod-network/trade-sdk 0.2.0 → 0.3.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 (43) hide show
  1. package/dist/client.d.ts.map +1 -1
  2. package/dist/client.js +1 -12
  3. package/dist/client.js.map +1 -1
  4. package/dist/codec/decode.d.ts.map +1 -1
  5. package/dist/codec/decode.js +7 -6
  6. package/dist/codec/decode.js.map +1 -1
  7. package/dist/codec/direction.d.ts +10 -0
  8. package/dist/codec/direction.d.ts.map +1 -0
  9. package/dist/codec/direction.js +46 -0
  10. package/dist/codec/direction.js.map +1 -0
  11. package/dist/codec/orders-v2.d.ts +19 -0
  12. package/dist/codec/orders-v2.d.ts.map +1 -0
  13. package/dist/codec/orders-v2.js +200 -0
  14. package/dist/codec/orders-v2.js.map +1 -0
  15. package/dist/codec/units.d.ts +10 -0
  16. package/dist/codec/units.d.ts.map +1 -1
  17. package/dist/codec/units.js +16 -0
  18. package/dist/codec/units.js.map +1 -1
  19. package/dist/sync/orders.d.ts +71 -16
  20. package/dist/sync/orders.d.ts.map +1 -1
  21. package/dist/sync/orders.js +202 -83
  22. package/dist/sync/orders.js.map +1 -1
  23. package/dist/transport/ws.d.ts +19 -2
  24. package/dist/transport/ws.d.ts.map +1 -1
  25. package/dist/transport/ws.js +14 -2
  26. package/dist/transport/ws.js.map +1 -1
  27. package/dist/types/public.d.ts +125 -9
  28. package/dist/types/public.d.ts.map +1 -1
  29. package/dist/types/wire.d.ts +104 -40
  30. package/dist/types/wire.d.ts.map +1 -1
  31. package/dist/write/index.d.ts +1 -1
  32. package/dist/write/index.js +1 -1
  33. package/package.json +1 -1
  34. package/src/client.ts +1 -14
  35. package/src/codec/decode.ts +7 -6
  36. package/src/codec/direction.ts +36 -0
  37. package/src/codec/orders-v2.ts +222 -0
  38. package/src/codec/units.ts +16 -0
  39. package/src/sync/orders.ts +203 -83
  40. package/src/transport/ws.ts +26 -3
  41. package/src/types/public.ts +139 -7
  42. package/src/types/wire.ts +114 -28
  43. package/src/write/index.ts +1 -1
@@ -6,7 +6,7 @@
6
6
  import type { Address, MarketId } from "../types/public.js";
7
7
 
8
8
  export type Channel =
9
- | "pod_orderbook" | "pod_orders" | "pod_candles"
9
+ | "pod_orderbook" | "pod_orders_v2" | "pod_candles"
10
10
  | "pod_markets" | "pod_positions" | "pod_triggers";
11
11
 
12
12
  export interface SubParams {
@@ -14,6 +14,17 @@ export interface SubParams {
14
14
  account?: Address;
15
15
  depth?: number;
16
16
  since?: number; // micros (solution time)
17
+ /**
18
+ * `pod_orders_v2` only: the `book` of the last frame accepted at `since`,
19
+ * completing the resume cursor.
20
+ *
21
+ * One batch settles many orderbooks and is delivered as one frame each, so a
22
+ * client can hold part of a batch, and `since` alone cannot express that
23
+ * position. With this set, replay skips every book at or below it within
24
+ * `since`, then delivers later batches whole. Omitted means the whole of
25
+ * `since` arrived — what `since` means on every other channel.
26
+ */
27
+ sinceBook?: MarketId;
17
28
  }
18
29
 
19
30
  export interface Subscription {
@@ -45,6 +56,7 @@ interface WireCloseError {
45
56
  data?: {
46
57
  resumable?: unknown;
47
58
  resume_since?: unknown;
59
+ resume_since_book?: unknown;
48
60
  missed?: unknown;
49
61
  };
50
62
  }
@@ -61,7 +73,7 @@ const asString = (v: unknown) => (typeof v === "string" ? v : undefined);
61
73
  * subscription's `since` to `resumeSince`, so restarting it is one call:
62
74
  *
63
75
  * ```ts
64
- * const sub = ws.subscribe("pod_orders", { account }, onUpdate, (err) => {
76
+ * const sub = ws.subscribe("pod_orders_v2", { account }, onFrame, (err) => {
65
77
  * if (err instanceof PodSubscriptionClosedError && err.resumable) sub.resubscribe();
66
78
  * });
67
79
  * ```
@@ -80,6 +92,11 @@ export class PodSubscriptionClosedError extends Error {
80
92
  * had not yet taken a whole tick.
81
93
  */
82
94
  readonly resumeSince?: number;
95
+ /**
96
+ * `pod_orders_v2` only: the last book of `resumeSince` that was delivered, when
97
+ * that batch was only partly delivered. Absent means the batch landed whole.
98
+ */
99
+ readonly resumeSinceBook?: MarketId;
83
100
  /** `-32020` only: how many ticks the broadcast dropped. */
84
101
  readonly missed?: number;
85
102
  /** The raw `params.error`, for fields this version does not map. */
@@ -94,6 +111,7 @@ export class PodSubscriptionClosedError extends Error {
94
111
  // close we failed to understand can hot-loop, which is the worse failure.
95
112
  this.resumable = data.resumable === true;
96
113
  this.resumeSince = asNumber(data.resume_since);
114
+ this.resumeSinceBook = asString(data.resume_since_book) as MarketId | undefined;
97
115
  this.missed = asNumber(data.missed);
98
116
  this.raw = raw;
99
117
  }
@@ -265,6 +283,7 @@ export class PodWsClient {
265
283
  if (p.account) out.account = p.account; // server aliases to `bidder`
266
284
  if (p.depth !== undefined) out.depth = p.depth;
267
285
  if (p.since !== undefined) out.since = p.since;
286
+ if (p.sinceBook !== undefined) out.since_book = p.sinceBook;
268
287
  return out;
269
288
  }
270
289
 
@@ -318,7 +337,11 @@ export class PodWsClient {
318
337
  // is the gap the close frame exists to prevent. Doing it here also
319
338
  // means `resubscribe()` alone resumes correctly.
320
339
  if (closed.resumable && closed.resumeSince !== undefined) {
321
- sub.params = { ...sub.params, since: closed.resumeSince };
340
+ // Both halves, together. A close with no `resume_since_book` says the
341
+ // batch landed whole, so the stored book must be cleared rather than
342
+ // carried over: it belongs to an older batch, and leaving it would
343
+ // ask the server to skip books inside the new one.
344
+ sub.params = { ...sub.params, since: closed.resumeSince, sinceBook: closed.resumeSinceBook };
322
345
  }
323
346
  if (sub.onError) sub.onError(closed);
324
347
  else this.emit("error", closed);
@@ -32,6 +32,125 @@ export type OrderDirection =
32
32
  | "open_short" | "add_short" | "reduce_short" | "close_short"
33
33
  | "long_to_short" | "short_to_long" | "liquidation";
34
34
 
35
+ /**
36
+ * Why the engine refused something, as a stable identifier to branch on.
37
+ *
38
+ * Open by design: a newer node may report a code this version does not list, so
39
+ * treat an unrecognised one like `"unspecified"` — the accompanying `message` is
40
+ * then all there is. `"unspecified"` itself means the engine has not given that
41
+ * reason a name yet.
42
+ */
43
+ export type RejectCode =
44
+ | "insufficient_balance" | "invalid_price" | "zero_size" | "notional_below_minimum"
45
+ | "unknown_market" | "order_not_found" | "not_order_owner" | "stale_nonce"
46
+ | "wrong_pair" | "engine_managed_order" | "price_above_maximum" | "price_off_tick"
47
+ | "market_order_must_be_ioc" | "size_above_maximum" | "size_off_lot"
48
+ | "notional_overflow" | "notional_above_cap" | "unspecified"
49
+ | (string & {});
50
+
51
+ /**
52
+ * An amendment the engine refused. The order itself is untouched — this is the
53
+ * answer to a price/size change that did not happen.
54
+ *
55
+ * The requested price and size are echoed back because a client may have several
56
+ * amendments outstanding on one order, and they are how it tells which one this
57
+ * answers.
58
+ */
59
+ export interface AmendRejection {
60
+ /** The price that was asked for. */
61
+ requestedPrice: bigint;
62
+ /** The size that was asked for, as an unsigned magnitude. */
63
+ requestedSize: bigint;
64
+ /** Branch on this rather than on `message`. */
65
+ code: RejectCode;
66
+ /**
67
+ * Present only when the reason carries detail the code cannot — the amounts on
68
+ * `insufficient_balance`, `invalid_price` and `notional_below_minimum`, the pair on
69
+ * `unknown_market`, and the whole reason on `unspecified`. For every other code the
70
+ * message would just restate the code.
71
+ */
72
+ message?: string;
73
+ /**
74
+ * Who asked. Deliberately not the order's owner: a refusal says nothing about who
75
+ * owns the order, and on `not_order_owner` the requester is precisely who does not.
76
+ * Absent when the stream names a single account.
77
+ */
78
+ requestedBy?: Address;
79
+ /** The batch the refusal landed in (ms). */
80
+ batchMs: number;
81
+ }
82
+
83
+ /** What the engine did to an order, as `pod_orders_v2` reports it (ADR 0029 §3). */
84
+ export type OrderEventKind =
85
+ | "new" | "reject" | "fill" | "cancel" | "expire" | "modify" | "modify_reject";
86
+
87
+ /**
88
+ * The statuses an order can *close* with. Narrower than `OrderStatus`, which also
89
+ * covers the states a live order passes through — so a `switch` over this one can be
90
+ * exhaustive.
91
+ */
92
+ export type TerminalStatus = Extract<OrderStatus, "filled" | "canceled" | "margin_canceled" | "expired">;
93
+
94
+ /** One fill, plus the status it closed the order with when it did. */
95
+ export interface OrderEventFill extends PartialFill {
96
+ /**
97
+ * Base filled over the order's life **as of this fill**.
98
+ *
99
+ * Not the same as `order.filledBase`, which is where the *whole frame* left the order:
100
+ * two fills of one order in one batch would otherwise both report the final total,
101
+ * so neither matches the fill it is attached to.
102
+ */
103
+ totalBase: bigint;
104
+ /**
105
+ * Absent while the order is still working.
106
+ *
107
+ * `margin_canceled` here is the engine evicting the order for margin, reported on the
108
+ * fill that closed it. An eviction that closes an order *without* a fill arrives as a
109
+ * plain `cancel` instead: the wire cannot yet distinguish it from a user cancel (ADR
110
+ * 0029 §6 reserves a `why` for that), so do not try to re-derive it from `status`.
111
+ */
112
+ closedAs?: TerminalStatus;
113
+ }
114
+
115
+ /**
116
+ * One transition the stream reported.
117
+ *
118
+ * The alternative is diffing consecutive snapshots, which can only see net state: two
119
+ * fills in one batch collapse into one change, a fill that closes an order hides the
120
+ * partial, and a transition that changes nothing about the order — a refused amendment
121
+ * — is invisible without a synthetic marker to spot it by.
122
+ *
123
+ * Deliberately lean. `order` is the row as the whole frame left it, so durable state a
124
+ * transition leaves behind is read from there — a `reject`'s `rejectReason` annotates the
125
+ * `invalid` status it set. Detail that belongs to the transition itself, and describes
126
+ * nothing about the order afterwards, is on the event: `fill`, and `amendRejection`.
127
+ */
128
+ export interface OrderEvent {
129
+ kind: OrderEventKind;
130
+ /**
131
+ * The order it happened to, as the whole frame left it.
132
+ *
133
+ * A live row, not a copy: the stream mutates it in place as later frames arrive. Read
134
+ * it in the callback, and copy it if you keep it — a buffered event would otherwise
135
+ * show the order's present state rather than its state at the time.
136
+ */
137
+ order: Order;
138
+ /** The batch it landed in (ms). */
139
+ batchMs: number;
140
+ /** `fill` only: this fill alone, not a running total. */
141
+ fill?: OrderEventFill;
142
+ /**
143
+ * `modify_reject` only: the amendment the engine refused.
144
+ *
145
+ * On the event rather than on `order`, because the order is exactly what it is not
146
+ * about — a refusal changes nothing about it. Parked on the entity it would be
147
+ * write-once and never cleared, so an order would keep reporting a refusal it had
148
+ * long since amended past, and only when the row came from this stream rather than
149
+ * from REST.
150
+ */
151
+ amendRejection?: AmendRejection;
152
+ }
153
+
35
154
  export interface TokenInfo {
36
155
  address: Address;
37
156
  symbol: string;
@@ -117,10 +236,13 @@ export interface PartialFill {
117
236
  export interface Order {
118
237
  id: Hash;
119
238
  txHash: Hash;
120
- orderbookId?: MarketId; // REST orders; WS stream orders carry `pair` instead
239
+ orderbookId?: MarketId;
240
+ /**
241
+ * Whether the book is spot or perp, when the source said so — REST rows carry it,
242
+ * streamed ones do not. It is static market metadata rather than a fact about the
243
+ * order, so the reliable read is a join: `markets.find((m) => m.id === o.orderbookId)?.type`.
244
+ */
121
245
  marketType?: MarketType;
122
- /** Token-address pair (base/quote); present on WS stream orders. */
123
- pair?: { base: Address; quote: Address };
124
246
  side: OrderSide;
125
247
  orderType: OrderType;
126
248
  status: OrderStatus;
@@ -133,11 +255,20 @@ export interface Order {
133
255
  filledQuote: bigint;
134
256
  fee: bigint;
135
257
  effectivePrice?: bigint;
136
- deadlineMs: number;
137
- endMs: number;
138
- /** Batch-inclusion time (ms) — when the order entered the book. REST history only. */
258
+ /**
259
+ * The auction deadline the order was signed for (ms). REST only: it is a fact
260
+ * about the intent, not about when the order became real, and the
261
+ * `pod_orders_v2` frame does not carry it. To order orders, use `includedMs` —
262
+ * both sources report that.
263
+ */
264
+ deadlineMs?: number;
265
+ /** TTL expiry (ms). Undefined when the order never expires. */
266
+ endMs?: number;
267
+ /** Batch-inclusion time (ms) — when the order entered the book. */
139
268
  includedMs?: number;
140
269
  fills: PartialFill[];
270
+ /** Why the engine rejected the order; set only on `status: "invalid"`. */
271
+ rejectReason?: string;
141
272
  // perpetual-only
142
273
  reduceOnly?: boolean;
143
274
  ioc?: boolean;
@@ -201,7 +332,8 @@ export interface Trigger {
201
332
  reduceOnly: boolean;
202
333
  ioc: boolean;
203
334
  deadlineMs: number;
204
- endMs: number;
335
+ /** TTL expiry (ms). Undefined when the trigger never expires. */
336
+ endMs?: number;
205
337
  }
206
338
 
207
339
  export interface BackstopTransfer {
package/src/types/wire.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // strings; timestamps are microseconds (in `*_us` fields, or bare on candle/
4
4
  // orderbook). Decoders in ../codec/decode.ts convert these to ../types/public.
5
5
 
6
- import type { Hex } from "./public.js";
6
+ import type { Hex, OrderEventKind } from "./public.js";
7
7
 
8
8
  export type WireDecimal = string; // 1e18-scaled integer as a decimal string
9
9
 
@@ -89,8 +89,9 @@ export interface WirePartialFill {
89
89
  }
90
90
 
91
91
  export interface WireOrder {
92
- orderbook_id?: Hex; // REST only; WS raw Order carries `pair` instead
93
- market_type?: "spot" | "perp"; // REST only
92
+ orderbook_id?: Hex;
93
+ /** The order endpoints say "perpetual" where `/clob/markets` says "perp". */
94
+ market_type?: "spot" | "perp" | "perpetual";
94
95
  kind: string;
95
96
  order_id: Hex;
96
97
  tx_hash: Hex;
@@ -108,9 +109,6 @@ export interface WireOrder {
108
109
  included_batch?: number | string; // micros; batch-inclusion time (REST order history)
109
110
  effective_price?: WireDecimal | null;
110
111
  fills?: WirePartialFill[];
111
- /** Present on WS stream orders (raw engine Order) instead of orderbook_id. */
112
- pair?: { base: Hex; quote: Hex };
113
- /** Present on REST orders; absent on the WS raw Order (derive from `initial_size`). */
114
112
  side?: "buy" | "sell";
115
113
  reduce_only?: boolean;
116
114
  ioc?: boolean;
@@ -263,29 +261,117 @@ export interface WireBackstopPage {
263
261
  solution_now: number;
264
262
  }
265
263
 
266
- // pod_orders push: tagged union on `type`.
267
- export type WireOrderUpdate =
268
- | ({ type: "new" } & WireOrder)
269
- | ({ type: "invalid" } & WireOrder)
270
- | ({ type: "fill" } & WireOrderFill)
271
- | { type: "expired"; order_id: Hex }
272
- | { type: "canceled"; order_id: Hex }
273
- | { type: "modified"; order_id: Hex; new_price: WireDecimal; new_size: WireDecimal };
264
+ // --- pod_orders_v2 push (ADR 0029) ---
265
+ //
266
+ // One notification is one frame: everything that happened to one orderbook in one
267
+ // auction batch. The book and the batch are named once, orders created in the
268
+ // batch appear once in `orders`, and `events` are transitions referencing them.
269
+ // Optional fields are omitted at their default rather than sent, so each absence
270
+ // means something specific — noted per field.
274
271
 
275
- export interface WireOrderFill {
276
- orderbook_id: Hex;
277
- order_id: Hex;
278
- tx_hash: Hex;
279
- bidder: Hex;
280
- status: string;
281
- base_amount: WireDecimal;
282
- quote_amount: WireDecimal;
283
- filled_base_amount: WireDecimal;
284
- filled_quote_amount: WireDecimal;
285
- effective_price?: WireDecimal | null;
286
- fee: WireDecimal;
287
- position_before?: WireDecimal | null;
288
- position_after?: WireDecimal | null;
272
+ export interface WireOrdersFrame {
273
+ /** The orderbook these actions happened on; constant for the frame. */
274
+ book: Hex;
275
+ /** Deadline (micros) of the batch the actions **landed in**. Half of the resume cursor; `book` is the other half. */
276
+ batch: number;
277
+ /**
278
+ * Owner addresses, indexed by `orders[].a` and by events that name an order by
279
+ * `id`. Omitted when the subscription names exactly one account — decode on
280
+ * this field, not on the filter that was sent.
281
+ */
282
+ accts?: Hex[];
283
+ orders: WireOrderEntity[];
284
+ events: WireOrderEvent[];
285
+ }
286
+
287
+ /** An order as admitted: the facts that do not change. Its status is implied by the events. */
288
+ export interface WireOrderEntity {
289
+ id: Hex;
290
+ /** Creating transaction, or its parent `submitBatch` envelope. */
291
+ tx: Hex;
292
+ /** Index into the frame's `accts`; present iff `accts` is. */
293
+ a?: number;
294
+ n: number;
295
+ px: WireDecimal;
296
+ /** Signed size: the sign carries the side, so there is no side field. */
297
+ sz: WireDecimal;
298
+ /** TTL expiry (micros). **Omitted means the order never expires.** */
299
+ end?: number;
300
+ /** **Omitted means user-signed.** */
301
+ kind?: string;
302
+ /** **Omitted means a limit order.** */
303
+ type?: "market";
304
+ /** Omitted means false. */
305
+ reduce_only?: boolean;
306
+ /** Omitted means false. */
307
+ ioc?: boolean;
308
+ /** Omitted unless the order is a fired trigger's synthetic. */
309
+ trigger?: string;
310
+ /** Omitted when ungrouped. */
311
+ grouping?: string;
312
+ }
313
+
314
+ /**
315
+ * One transition, discriminated by `k`. Every event names its order by exactly
316
+ * one of `o` (an index into this frame's `orders`) or `id` (resting from an
317
+ * earlier batch, owned by `accts[a]`).
318
+ *
319
+ * Kinds are open: unknown values of `k` must be ignored rather than rejected, so
320
+ * this is a plain shape with per-kind optional fields rather than a union that
321
+ * would make an unrecognised kind unrepresentable.
322
+ */
323
+ export interface WireOrderEvent {
324
+ k: OrderEventKind | (string & {});
325
+ o?: number;
326
+ id?: Hex;
327
+ a?: number;
328
+ /** `reject`: why the engine dropped the order. `modify_reject`: detail the `code` cannot carry. */
329
+ why?: string;
330
+ /**
331
+ * `modify_reject`: index into `accts` for the account that *asked*, which is not
332
+ * necessarily the order's owner — hence not `a`. On `not_order_owner` the requester
333
+ * is precisely who does not own it.
334
+ */
335
+ by?: number;
336
+ /** `modify_reject`: the price that was asked for. */
337
+ req_px?: WireDecimal;
338
+ /** `modify_reject`: the size that was asked for, unsigned. */
339
+ req_sz?: WireDecimal;
340
+ /** `modify_reject`: the stable reason identifier — branch on this, not on `why`. */
341
+ code?: string;
342
+ /** `fill`: base filled by **this** fill. */
343
+ b?: WireDecimal;
344
+ /** `fill`: quote filled by this fill. */
345
+ q?: WireDecimal;
346
+ /**
347
+ * Total base filled over the order's life so far.
348
+ *
349
+ * Carried by `fill`, `cancel` and `expire` alike (ADR 0029 §4.1): a terminated
350
+ * order reports what it had filled, as an explicit zero rather than an omission,
351
+ * so absence never has to be read as zero. Optional only because this one shape
352
+ * covers every kind — `new`, `reject` and `modify` have no totals to report.
353
+ */
354
+ tb?: WireDecimal;
355
+ /** Total quote filled so far; travels with `tb`. */
356
+ tq?: WireDecimal;
357
+ /** Total fee charged so far; travels with `tb`. There is no per-fill counterpart. */
358
+ tf?: WireDecimal;
359
+ /** `fill`: present only on the fill that closed the order, carrying its terminal status. */
360
+ st?: "filled" | "canceled" | "margin_canceled" | "expired";
361
+ /**
362
+ * `fill` on a perp market: the owner's position after this fill, signed and
363
+ * 1e18-scaled. Omitted on spot, which has no position.
364
+ *
365
+ * The position *before* is not sent because it is derivable — `pa - sign(sz) * b`,
366
+ * the same arithmetic the engine used to produce the pair — and the transition
367
+ * between the two is what says whether the fill opened, added to, reduced, closed
368
+ * or flipped the position.
369
+ */
370
+ pa?: WireDecimal;
371
+ /** `modify`: the price after the change. */
372
+ px?: WireDecimal;
373
+ /** `modify`: the size after the change, as an **unsigned magnitude**. */
374
+ sz?: WireDecimal;
289
375
  }
290
376
 
291
377
  export interface WirePositionsPush {
@@ -689,7 +689,7 @@ export function buildWaitlistDeposit(p: WaitlistDepositParams): SourceChainCall
689
689
  * matching the engine (`trading/src/lib.rs`). `sequence` is the 0-based index
690
690
  * of the intent within a `submitBatch` (0 for a single-intent tx). Needs the
691
691
  * nonce, so it's only known up-front in managed mode; in advisory mode reconcile
692
- * by `tx_hash` from the `pod_orders` stream instead.
692
+ * by `tx` from the `pod_orders_v2` stream instead.
693
693
  */
694
694
  export function deriveOrderId(signer: Address, nonce: number, sequence = 0): Hash {
695
695
  return keccak256(