@pod-network/trade-sdk 0.18.0 → 0.19.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 (61) hide show
  1. package/dist/client.d.ts +5 -0
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +6 -5
  4. package/dist/client.js.map +1 -1
  5. package/dist/codec/activity.d.ts +4 -9
  6. package/dist/codec/activity.d.ts.map +1 -1
  7. package/dist/codec/activity.js +6 -23
  8. package/dist/codec/activity.js.map +1 -1
  9. package/dist/stores/resource.d.ts +9 -3
  10. package/dist/stores/resource.d.ts.map +1 -1
  11. package/dist/stores/resource.js +6 -1
  12. package/dist/stores/resource.js.map +1 -1
  13. package/dist/sync/activity.d.ts +11 -2
  14. package/dist/sync/activity.d.ts.map +1 -1
  15. package/dist/sync/activity.js +74 -18
  16. package/dist/sync/activity.js.map +1 -1
  17. package/dist/sync/candles.d.ts.map +1 -1
  18. package/dist/sync/candles.js +6 -0
  19. package/dist/sync/candles.js.map +1 -1
  20. package/dist/sync/order-ledger.d.ts +42 -0
  21. package/dist/sync/order-ledger.d.ts.map +1 -0
  22. package/dist/sync/order-ledger.js +163 -0
  23. package/dist/sync/order-ledger.js.map +1 -0
  24. package/dist/sync/order-preview.d.ts.map +1 -1
  25. package/dist/sync/order-preview.js +5 -1
  26. package/dist/sync/order-preview.js.map +1 -1
  27. package/dist/sync/orders.d.ts +5 -1
  28. package/dist/sync/orders.d.ts.map +1 -1
  29. package/dist/sync/orders.js +41 -16
  30. package/dist/sync/orders.js.map +1 -1
  31. package/dist/sync/positions-live.d.ts.map +1 -1
  32. package/dist/sync/positions-live.js +33 -7
  33. package/dist/sync/positions-live.js.map +1 -1
  34. package/dist/sync/sources.d.ts +3 -1
  35. package/dist/sync/sources.d.ts.map +1 -1
  36. package/dist/sync/sources.js +21 -9
  37. package/dist/sync/sources.js.map +1 -1
  38. package/dist/sync/withdrawals.d.ts +1 -1
  39. package/dist/sync/withdrawals.d.ts.map +1 -1
  40. package/dist/sync/withdrawals.js +15 -6
  41. package/dist/sync/withdrawals.js.map +1 -1
  42. package/dist/transport/rest.d.ts +5 -0
  43. package/dist/transport/rest.d.ts.map +1 -1
  44. package/dist/transport/rest.js +3 -0
  45. package/dist/transport/rest.js.map +1 -1
  46. package/dist/types/public.d.ts +4 -0
  47. package/dist/types/public.d.ts.map +1 -1
  48. package/package.json +1 -1
  49. package/src/client.ts +11 -5
  50. package/src/codec/activity.ts +5 -22
  51. package/src/stores/resource.ts +13 -4
  52. package/src/sync/activity.ts +78 -20
  53. package/src/sync/candles.ts +5 -0
  54. package/src/sync/order-ledger.ts +157 -0
  55. package/src/sync/order-preview.ts +5 -1
  56. package/src/sync/orders.ts +39 -14
  57. package/src/sync/positions-live.ts +32 -7
  58. package/src/sync/sources.ts +22 -8
  59. package/src/sync/withdrawals.ts +15 -6
  60. package/src/transport/rest.ts +8 -0
  61. package/src/types/public.ts +4 -0
@@ -8,7 +8,7 @@
8
8
  // basis, resting-order escrow).
9
9
  //
10
10
  // EXACT replication of pod — see the cross-reference notes in pod at:
11
- // trading/src/perps/mod.rs `cross_budgets` (withdrawable / equity)
11
+ // trading/src/perps/mod.rs `cross_budgets` (equity)
12
12
  // trading/src/perps/mod.rs `pending_funding` (funding)
13
13
  // Integer semantics match trading/src/decimal.rs:
14
14
  // mul(a,b) = (a*b)/1e18 truncated toward zero (Decimal `*`)
@@ -37,6 +37,13 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
37
37
  let im = 0n; // Σ initial-margin requirement at live notional
38
38
  let mm = 0n; // Σ maintenance-margin requirement at live notional
39
39
  let dSpot = 0n; // change in spot mark value vs snapshot (slope = balance)
40
+ // Withdrawable is the node's figure moved by the equity and reserve change since
41
+ // it was read. Market data older than the snapshot (another node behind a load
42
+ // balancer) moves nothing.
43
+ let dEquity = 0n;
44
+ let imMoved = 0n;
45
+ let notionalMoved = 0n;
46
+ let notionalSnap = 0n;
40
47
 
41
48
  const positions: Position[] = snap.positions.map((p) => {
42
49
  const market = p.orderbookId ? byId.get(p.orderbookId) : undefined;
@@ -48,9 +55,10 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
48
55
  const liveMark = market?.markPrice && market.markPrice > 0n ? market.markPrice : p.markPrice;
49
56
  const mark = liveMark > 0n ? liveMark : p.entryPrice;
50
57
  // The entry-price fallback rounds against the holder.
51
- const upnl = p.costBasis !== undefined
52
- ? mul(mark, p.size) - p.costBasis
53
- : mulFloor(mark - p.entryPrice, p.size); // pure price drift (signed)
58
+ const pnlAt = (m: bigint) => p.costBasis !== undefined
59
+ ? mul(m, p.size) - p.costBasis
60
+ : mulFloor(m - p.entryPrice, p.size); // pure price drift (signed)
61
+ const upnl = pnlAt(mark);
54
62
  const sizeQuote = mul(absB(p.size), mark); // = notional
55
63
  const imr = market?.initialMargin ?? imRate(market?.maxLeverage ?? 0);
56
64
  im += mul(sizeQuote, imr);
@@ -66,6 +74,15 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
66
74
  }
67
75
  fundingLiveTotal += funding;
68
76
  fundingSnapTotal += p.fundingAccrued;
77
+ const marketFresh = snap.timestampUs === undefined
78
+ || (market?.dynamicsUs !== undefined && market.dynamicsUs >= snap.timestampUs);
79
+ const snapMark = p.markPrice > 0n ? p.markPrice : p.entryPrice;
80
+ const movedMark = marketFresh ? mark : snapMark;
81
+ if (marketFresh) dEquity += upnl - pnlAt(snapMark) - (funding - p.fundingAccrued);
82
+ const movedNotional = mul(absB(p.size), movedMark);
83
+ imMoved += mul(movedNotional, imr);
84
+ notionalMoved += movedNotional;
85
+ notionalSnap += mul(absB(p.size), snapMark);
69
86
 
70
87
  return { ...p, markPrice: mark, unrealizedPnl: upnl, notional: sizeQuote, fundingAccrued: funding };
71
88
  }
@@ -80,10 +97,16 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
80
97
  const nativeCash = snap.cash + fundingSnapTotal;
81
98
  const cashWithFunding = nativeCash - fundingLiveTotal;
82
99
 
83
- // EXACT (perp-only, integer-faithful): equity = cash_with_funding + Σ price PnL;
84
- // withdrawable = max(0, equity - Σ IM), forced to 0 below maintenance margin.
100
+ // EXACT (perp-only, integer-faithful): equity = cash_with_funding + Σ price PnL.
85
101
  const perpsEquity = cashWithFunding + priceUpnl;
86
- const withdrawableCash = perpsEquity < mm ? 0n : maxB(0n, perpsEquity - im);
102
+ // The node reserves max(IM, ratio × notional) plus frozen profit; the ratio is not
103
+ // served, so the snapshot's reserve is scaled with notional, floored at live IM.
104
+ // A zero base hides the reserve, so it moves with equity alone.
105
+ const reserveSnap = snap.perpsEquity - snap.withdrawableCash;
106
+ const dReserve = snap.withdrawableCash > 0n && notionalSnap > 0n
107
+ ? maxB(imMoved, (reserveSnap * notionalMoved) / notionalSnap) - reserveSnap
108
+ : 0n;
109
+ const withdrawableCash = maxB(0n, snap.withdrawableCash + dEquity - dReserve);
87
110
 
88
111
  // account_value moves with perp equity (incl. funding) AND spot mark; total
89
112
  // uPnL is pure price drift only (funding is reported separately). Re-baseline
@@ -95,8 +118,10 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
95
118
  totalRealizedPnl: snap.totalRealizedPnl,
96
119
  perpsEquity,
97
120
  withdrawableCash,
121
+ initialMargin: im,
98
122
  maintenanceMargin: mm,
99
123
  totalUnrealizedPnl: snap.totalUnrealizedPnl + dPriceUpnl + dSpot,
100
124
  accountValue: snap.accountValue + (perpsEquity - snap.perpsEquity) + dSpot,
125
+ timestampUs: snap.timestampUs,
101
126
  };
102
127
  }
@@ -34,6 +34,8 @@ export interface SyncContext {
34
34
  positionResyncMs: number;
35
35
  /** Periodic REST re-poll (ms) of market 24h stats; 0 disables. */
36
36
  marketResyncMs: number;
37
+ /** Periodic REST reconcile (ms) of orders, activity, withdrawals, candles and triggers; 0 disables. */
38
+ historyResyncMs: number;
37
39
  /** Optional persistence for the static markets list (see marketsSource). */
38
40
  marketsCache?: MarketsCache;
39
41
  }
@@ -226,7 +228,7 @@ export function marketsSource(
226
228
  const seedStats = () => readAtLeast((min) => rest.marketStats(undefined, min), heldUs).then((page) => {
227
229
  if (!alive) return;
228
230
  heldUs = Math.max(heldUs, page.solutionNow * 1000);
229
- page.markets.forEach((m) => { if (fresh(page.solutionNow, m.id)) mergePatch(m); });
231
+ page.markets.forEach((m) => { if (fresh(page.solutionNow, m.id)) mergePatch({ ...m, dynamicsUs: page.solutionNow * 1000 }); });
230
232
  publish();
231
233
  }).catch(() => { /* live dynamics also arrive on the stream */ });
232
234
 
@@ -241,7 +243,10 @@ export function marketsSource(
241
243
  const id = (w.orderbook_id ?? w.orderbook) as string;
242
244
  if (typeof w.timestamp === "number") heldUs = Math.max(heldUs, w.timestamp);
243
245
  if (!fresh(typeof w.timestamp === "number" ? usToMs(w.timestamp) : undefined, id)) continue;
244
- mergePatch(decodeMarketDynamics({ ...w, orderbook_id: id } as WireMarketDynamics));
246
+ mergePatch({
247
+ ...decodeMarketDynamics({ ...w, orderbook_id: id } as WireMarketDynamics),
248
+ dynamicsUs: typeof w.timestamp === "number" ? w.timestamp : undefined,
249
+ });
245
250
  }
246
251
  publish();
247
252
  });
@@ -284,12 +289,13 @@ export function positionsSource(
284
289
  // - a periodic REST poll that re-aligns to the backend's exact accounting
285
290
  // (corrects mark-extrapolation drift even when the account isn't touched).
286
291
  const fresh = watermarks();
292
+ fresh(h.lastKnown()?.value.timestampUs);
287
293
  const accept = (s: PositionsSnapshot) => { if (alive && fresh(s.timestampUs)) h.set(s); };
288
294
  const reseed = () =>
289
- readAtLeast((min) => rest.positions(account, min), h.current()?.timestampUs).then(accept).catch(() => {});
295
+ readAtLeast((min) => rest.positions(account, min), h.lastKnown()?.value.timestampUs).then(accept).catch(() => {});
290
296
  reseed();
291
297
  const timer = positionResyncMs > 0 ? setInterval(reseed, positionResyncMs) : undefined;
292
- const sub = subscribeRetrying(ws, "pod_positions", () => ({ account, since: h.current()?.timestampUs ?? 0 }), (result) => {
298
+ const sub = subscribeRetrying(ws, "pod_positions", () => ({ account, since: h.lastKnown()?.value.timestampUs ?? 0 }), (result) => {
293
299
  accept(decodePositions((result as WirePositionsPush).data));
294
300
  });
295
301
  return () => { alive = false; if (timer) clearInterval(timer); sub.unsubscribe(); };
@@ -331,17 +337,25 @@ export function balancesSource(
331
337
  }
332
338
 
333
339
  export function triggersSource(
334
- { ws }: SyncContext,
340
+ { rest, ws, historyResyncMs }: SyncContext,
335
341
  account: Address,
336
342
  ): ResourceSource<Trigger[]> {
337
343
  const fresh = watermarks();
338
344
  let heldUs = 0;
339
345
  return (h) => {
346
+ let alive = true;
347
+ const accept = (triggers: Trigger[], timestampUs: number | undefined) => {
348
+ heldUs = Math.max(heldUs, timestampUs ?? 0);
349
+ if (alive && fresh(timestampUs)) h.set(triggers);
350
+ };
351
+ // 200 is the page `pod_triggers` pushes.
352
+ const reconcile = () => readAtLeast((min) => rest.triggers(account, { limit: 200 }, min), heldUs)
353
+ .then((page) => accept(page.triggers, page.timestampUs)).catch(() => {});
354
+ const timer = historyResyncMs > 0 ? setInterval(reconcile, historyResyncMs) : undefined;
340
355
  const sub = subscribeRetrying(ws, "pod_triggers", () => ({ account, since: heldUs }), (result) => {
341
356
  const w = result as WireTriggersPush;
342
- heldUs = Math.max(heldUs, w.timestamp ?? 0);
343
- if (fresh(w.timestamp)) h.set(w.triggers.map(decodeTrigger));
357
+ accept(w.triggers.map(decodeTrigger), w.timestamp);
344
358
  });
345
- return () => sub.unsubscribe();
359
+ return () => { alive = false; clearInterval(timer); sub.unsubscribe(); };
346
360
  };
347
361
  }
@@ -24,7 +24,7 @@ const PAGE_LIMIT = 500;
24
24
  const MAX_PAGES = 50;
25
25
 
26
26
  export function withdrawalsSource(
27
- { rest, ws }: SyncContext,
27
+ { rest, ws, historyResyncMs }: SyncContext,
28
28
  account: Address,
29
29
  ): ResourceSource<Withdrawal[]> {
30
30
  return (h) => {
@@ -66,16 +66,23 @@ export function withdrawalsSource(
66
66
  * the cursor, so concurrent loops would re-request each other's pages.
67
67
  */
68
68
  let inflight: Promise<boolean> | undefined;
69
- const backfill = (): Promise<boolean> => (inflight ??= run().finally(() => { inflight = undefined; }));
69
+ const walk = (fromUs: number, fromId: Withdrawal["txHash"] | undefined): Promise<boolean> =>
70
+ (inflight ??= run(fromUs, fromId).finally(() => { inflight = undefined; }));
71
+ const backfill = () => walk(sinceUs, sinceId);
72
+ // From the end of the log REST last served rather than the shared cursor, which
73
+ // pushes move: an outcome the stream lost below a later push is read again.
74
+ const reconcile = () => { void walk(servedUs, undefined); };
70
75
 
71
- const run = async () => {
76
+ const run = async (fromUs: number, fromId: Withdrawal["txHash"] | undefined) => {
72
77
  try {
73
78
  // Page against a cursor local to this run. The shared one is also moved
74
79
  // by live pushes, and a push landing mid-backfill would jump the next
75
80
  // page past the rest of an older tick — rows the forward-only cursor
76
81
  // could then never come back for.
77
- let pageSince = sinceUs;
78
- let pageSinceId = sinceId;
82
+ // A walk from above `servedUs` skipped whatever lies between, so it cannot vouch for the log.
83
+ const vouches = fromUs <= servedUs;
84
+ let pageSince = fromUs;
85
+ let pageSinceId = fromId;
79
86
  for (let page = 0; page < MAX_PAGES; page++) {
80
87
  const query = { since: pageSince, sinceId: pageSinceId, limit: PAGE_LIMIT };
81
88
  const res = await readAtLeast(
@@ -86,7 +93,7 @@ export function withdrawalsSource(
86
93
  const rows = res.withdrawals;
87
94
  absorb(rows);
88
95
  // Pages may come from different nodes: only the one that served the end of the log vouches for it.
89
- if (rows.length < PAGE_LIMIT) { servedUs = Math.max(servedUs, res.timestampUs); break; }
96
+ if (rows.length < PAGE_LIMIT) { if (vouches) servedUs = Math.max(servedUs, res.timestampUs); break; }
90
97
  // Rows come back ascending, so the last one is this page's high-water
91
98
  // mark — regardless of what the stream did to the shared cursor.
92
99
  const last = rows[rows.length - 1]!;
@@ -169,6 +176,7 @@ export function withdrawalsSource(
169
176
  // Seed immediately — REST needs no socket, so history paints without waiting
170
177
  // on the handshake — and fill the gap again on every reconnect.
171
178
  const offOpen = ws.on("open", () => { if (alive) void backfill(); });
179
+ const timer = historyResyncMs > 0 ? setInterval(reconcile, historyResyncMs) : undefined;
172
180
  // Subscribing after the first backfill lets `since` cover the gap between a
173
181
  // lagging REST node and the head of the node the socket landed on.
174
182
  void backfill().then((ok) => {
@@ -180,6 +188,7 @@ export function withdrawalsSource(
180
188
  return () => {
181
189
  alive = false;
182
190
  offOpen();
191
+ clearInterval(timer);
183
192
  if (retryTimer) clearTimeout(retryTimer);
184
193
  sub?.unsubscribe();
185
194
  };
@@ -31,6 +31,8 @@ export interface OrdersPage {
31
31
  nextCursor: string | null;
32
32
  totalCount: number;
33
33
  solutionNow: number;
34
+ /** The read's indexer round, exact; `solutionNow` is truncated to ms. */
35
+ solutionNowUs: number;
34
36
  }
35
37
  export interface ActivityPage {
36
38
  /** Newest first, each batch's entries in the node's order. */
@@ -38,6 +40,8 @@ export interface ActivityPage {
38
40
  /** Pass back as `toUs` for the next, older page; null when the window is exhausted. */
39
41
  nextUs: number | null;
40
42
  solutionNow: number; // ms
43
+ /** The read's indexer round, exact; `solutionNow` is truncated to ms. */
44
+ solutionNowUs: number;
41
45
  }
42
46
  export interface BackstopPage {
43
47
  transfers: BackstopTransfer[];
@@ -48,6 +52,7 @@ export interface TriggersPage {
48
52
  triggers: Trigger[];
49
53
  totalCount: number;
50
54
  nextCursor: string | null;
55
+ timestampUs?: number;
51
56
  }
52
57
  export interface WithdrawalsPage {
53
58
  withdrawals: Withdrawal[];
@@ -210,6 +215,7 @@ export class PodRestClient {
210
215
  nextCursor: w.next_cursor,
211
216
  totalCount: w.total_count,
212
217
  solutionNow: Math.trunc(w.solution_now / 1000),
218
+ solutionNowUs: w.solution_now,
213
219
  };
214
220
  }
215
221
 
@@ -229,6 +235,7 @@ export class PodRestClient {
229
235
  batches,
230
236
  nextUs: w.next === null ? null : Number(w.next),
231
237
  solutionNow: usToMs(w.solution_now),
238
+ solutionNowUs: w.solution_now,
232
239
  };
233
240
  }
234
241
 
@@ -319,6 +326,7 @@ export class PodRestClient {
319
326
  triggers: w.triggers.map(decodeTrigger),
320
327
  totalCount: w.total_count,
321
328
  nextCursor: w.next_cursor,
329
+ timestampUs: w.timestamp,
322
330
  };
323
331
  }
324
332
  }
@@ -212,6 +212,8 @@ export interface Market {
212
212
  fundingSettlingIndex?: bigint;
213
213
  fundingLastUpdatedMs?: number;
214
214
  openInterest?: bigint;
215
+ /** Solution time (µs) of the node state the dynamics above were read from. */
216
+ dynamicsUs?: number;
215
217
  }
216
218
 
217
219
  export interface Bar {
@@ -347,6 +349,8 @@ export interface PositionsSnapshot {
347
349
  accountValue: bigint;
348
350
  cash: bigint;
349
351
  withdrawableCash: bigint;
352
+ /** Live snapshots only: Σ initial margin at live notional. */
353
+ initialMargin?: bigint;
350
354
  maintenanceMargin?: bigint;
351
355
  /** Deadline (µs) of the last tick the answering node executed. */
352
356
  timestampUs?: number;