@pod-network/trade-sdk 0.17.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 (77) hide show
  1. package/README.md +15 -0
  2. package/dist/client.d.ts +23 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +32 -5
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec/activity.d.ts +4 -9
  7. package/dist/codec/activity.d.ts.map +1 -1
  8. package/dist/codec/activity.js +6 -23
  9. package/dist/codec/activity.js.map +1 -1
  10. package/dist/codec/bridge.d.ts +24 -0
  11. package/dist/codec/bridge.d.ts.map +1 -1
  12. package/dist/codec/bridge.js +21 -0
  13. package/dist/codec/bridge.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/stores/resource.d.ts +9 -3
  19. package/dist/stores/resource.d.ts.map +1 -1
  20. package/dist/stores/resource.js +6 -1
  21. package/dist/stores/resource.js.map +1 -1
  22. package/dist/sync/activity.d.ts +11 -2
  23. package/dist/sync/activity.d.ts.map +1 -1
  24. package/dist/sync/activity.js +74 -18
  25. package/dist/sync/activity.js.map +1 -1
  26. package/dist/sync/candles.d.ts.map +1 -1
  27. package/dist/sync/candles.js +6 -0
  28. package/dist/sync/candles.js.map +1 -1
  29. package/dist/sync/order-ledger.d.ts +42 -0
  30. package/dist/sync/order-ledger.d.ts.map +1 -0
  31. package/dist/sync/order-ledger.js +163 -0
  32. package/dist/sync/order-ledger.js.map +1 -0
  33. package/dist/sync/order-preview.d.ts.map +1 -1
  34. package/dist/sync/order-preview.js +5 -1
  35. package/dist/sync/order-preview.js.map +1 -1
  36. package/dist/sync/orders.d.ts +5 -1
  37. package/dist/sync/orders.d.ts.map +1 -1
  38. package/dist/sync/orders.js +41 -16
  39. package/dist/sync/orders.js.map +1 -1
  40. package/dist/sync/positions-live.d.ts.map +1 -1
  41. package/dist/sync/positions-live.js +33 -7
  42. package/dist/sync/positions-live.js.map +1 -1
  43. package/dist/sync/sources.d.ts +3 -1
  44. package/dist/sync/sources.d.ts.map +1 -1
  45. package/dist/sync/sources.js +21 -9
  46. package/dist/sync/sources.js.map +1 -1
  47. package/dist/sync/withdrawals.d.ts +1 -1
  48. package/dist/sync/withdrawals.d.ts.map +1 -1
  49. package/dist/sync/withdrawals.js +15 -6
  50. package/dist/sync/withdrawals.js.map +1 -1
  51. package/dist/transport/claim.d.ts +15 -0
  52. package/dist/transport/claim.d.ts.map +1 -1
  53. package/dist/transport/claim.js +39 -1
  54. package/dist/transport/claim.js.map +1 -1
  55. package/dist/transport/rest.d.ts +5 -0
  56. package/dist/transport/rest.d.ts.map +1 -1
  57. package/dist/transport/rest.js +3 -0
  58. package/dist/transport/rest.js.map +1 -1
  59. package/dist/types/public.d.ts +4 -0
  60. package/dist/types/public.d.ts.map +1 -1
  61. package/package.json +1 -1
  62. package/src/client.ts +39 -5
  63. package/src/codec/activity.ts +5 -22
  64. package/src/codec/bridge.ts +37 -0
  65. package/src/index.ts +2 -1
  66. package/src/stores/resource.ts +13 -4
  67. package/src/sync/activity.ts +78 -20
  68. package/src/sync/candles.ts +5 -0
  69. package/src/sync/order-ledger.ts +157 -0
  70. package/src/sync/order-preview.ts +5 -1
  71. package/src/sync/orders.ts +39 -14
  72. package/src/sync/positions-live.ts +32 -7
  73. package/src/sync/sources.ts +22 -8
  74. package/src/sync/withdrawals.ts +15 -6
  75. package/src/transport/claim.ts +44 -1
  76. package/src/transport/rest.ts +8 -0
  77. package/src/types/public.ts +4 -0
@@ -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
  };
@@ -16,7 +16,8 @@
16
16
  // this module is a consequence of that: it is why stage 1 exists at all.
17
17
 
18
18
  import type { Address, Hash } from "../types/public.js";
19
- import { tryRpc, type RpcOptions } from "./jsonrpc.js";
19
+ import { PodRpcError, rpc, tryRpc, type RpcOptions } from "./jsonrpc.js";
20
+ import type { BridgeUsage } from "../codec/bridge.js";
20
21
  import type { WireWithdrawalDetail } from "../types/wire.js";
21
22
 
22
23
  /**
@@ -432,3 +433,45 @@ export function watchClaims(opts: WatchClaimsOptions): ClaimWatcher {
432
433
  },
433
434
  };
434
435
  }
436
+
437
+ // `tokenData(address)` on the claim-chain bridge: eight words — minAmount, depositLimit,
438
+ // claimLimit, depositUsage {consumed, lastUpdated}, claimUsage {consumed, lastUpdated}, mirrorToken.
439
+ const TOKEN_DATA_SELECTOR = "0x27e45c2c";
440
+
441
+ /** Reads the bridge's daily allowances for `l1Token` from the claim chain: `deposit` for money
442
+ * coming in, `claim` for withdrawals paying out, the token's `minAmount`, and `blockTime`, the
443
+ * time of the block that answered (the contract's own clock, for {@link bridgeCapacity}).
444
+ * With `chainId`, refuses an endpoint on another chain rather than reading a look-alike there.
445
+ * Throws a {@link PodRpcError} for anything it cannot read: a missing limit must not read as
446
+ * "nothing left". */
447
+ export async function fetchBridgeUsage(
448
+ claimRpcUrl: string,
449
+ bridge: Address,
450
+ l1Token: Address,
451
+ opts?: RpcOptions & { chainId?: number },
452
+ ): Promise<{ minAmount: bigint; deposit: BridgeUsage; claim: BridgeUsage; blockTime: number }> {
453
+ const hex = (v: unknown, what: string): string => {
454
+ if (typeof v !== "string" || !/^0x[0-9a-fA-F]*$/.test(v)) throw new PodRpcError(undefined, `${what} is not hex`);
455
+ return v;
456
+ };
457
+ if (!/^0x[0-9a-fA-F]{40}$/.test(bridge) || !/^0x[0-9a-fA-F]{40}$/.test(l1Token)) {
458
+ throw new PodRpcError(undefined, "bridge and l1Token must be addresses");
459
+ }
460
+ if (opts?.chainId !== undefined) {
461
+ const id = Number(hex(await rpc<string>(claimRpcUrl, "eth_chainId", [], opts), "eth_chainId"));
462
+ if (id !== opts.chainId) throw new PodRpcError(undefined, `claim RPC is on chain ${id}, not ${opts.chainId}`);
463
+ }
464
+ // The call is made at the block whose time is read, so the two can't disagree.
465
+ const block = await rpc<{ number?: unknown; timestamp?: unknown }>(claimRpcUrl, "eth_getBlockByNumber", ["latest", false], opts);
466
+ const number = hex(block?.number, "block number"), timestamp = hex(block?.timestamp, "block timestamp");
467
+ const data = TOKEN_DATA_SELECTOR + l1Token.slice(2).toLowerCase().padStart(64, "0");
468
+ const raw = hex(await rpc<unknown>(claimRpcUrl, "eth_call", [{ to: bridge, data }, number], opts), "tokenData");
469
+ if (raw.length < 2 + 64 * 8) throw new PodRpcError(undefined, "tokenData returned too little");
470
+ const word = (i: number) => BigInt(`0x${raw.slice(2 + 64 * i, 2 + 64 * (i + 1))}`);
471
+ return {
472
+ minAmount: word(0),
473
+ deposit: { limit: word(1), consumed: word(3), lastUpdated: Number(word(4)) },
474
+ claim: { limit: word(2), consumed: word(5), lastUpdated: Number(word(6)) },
475
+ blockTime: Number(timestamp),
476
+ };
477
+ }
@@ -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;