@pod-network/trade-sdk 0.3.0 → 0.4.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 (70) hide show
  1. package/README.md +94 -2
  2. package/dist/client.d.ts +19 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +24 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec/bridge.d.ts +82 -0
  7. package/dist/codec/bridge.d.ts.map +1 -0
  8. package/dist/codec/bridge.js +114 -0
  9. package/dist/codec/bridge.js.map +1 -0
  10. package/dist/codec/decode.d.ts +15 -2
  11. package/dist/codec/decode.d.ts.map +1 -1
  12. package/dist/codec/decode.js +39 -0
  13. package/dist/codec/decode.js.map +1 -1
  14. package/dist/codec/units.d.ts.map +1 -1
  15. package/dist/codec/units.js +9 -1
  16. package/dist/codec/units.js.map +1 -1
  17. package/dist/index.d.ts +3 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +5 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/sync/sources.d.ts +5 -1
  22. package/dist/sync/sources.d.ts.map +1 -1
  23. package/dist/sync/sources.js +16 -0
  24. package/dist/sync/sources.js.map +1 -1
  25. package/dist/sync/withdrawals.d.ts +5 -0
  26. package/dist/sync/withdrawals.d.ts.map +1 -0
  27. package/dist/sync/withdrawals.js +172 -0
  28. package/dist/sync/withdrawals.js.map +1 -0
  29. package/dist/transport/claim.d.ts +160 -0
  30. package/dist/transport/claim.d.ts.map +1 -0
  31. package/dist/transport/claim.js +341 -0
  32. package/dist/transport/claim.js.map +1 -0
  33. package/dist/transport/jsonrpc.d.ts +16 -0
  34. package/dist/transport/jsonrpc.d.ts.map +1 -0
  35. package/dist/transport/jsonrpc.js +42 -0
  36. package/dist/transport/jsonrpc.js.map +1 -0
  37. package/dist/transport/rest.d.ts +15 -1
  38. package/dist/transport/rest.d.ts.map +1 -1
  39. package/dist/transport/rest.js +25 -1
  40. package/dist/transport/rest.js.map +1 -1
  41. package/dist/transport/ws.d.ts +4 -1
  42. package/dist/transport/ws.d.ts.map +1 -1
  43. package/dist/transport/ws.js.map +1 -1
  44. package/dist/types/public.d.ts +87 -0
  45. package/dist/types/public.d.ts.map +1 -1
  46. package/dist/types/wire.d.ts +43 -1
  47. package/dist/types/wire.d.ts.map +1 -1
  48. package/dist/write/delegation.d.ts.map +1 -1
  49. package/dist/write/delegation.js +2 -12
  50. package/dist/write/delegation.js.map +1 -1
  51. package/dist/write/index.d.ts +25 -0
  52. package/dist/write/index.d.ts.map +1 -1
  53. package/dist/write/index.js +20 -13
  54. package/dist/write/index.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/client.ts +32 -4
  57. package/src/codec/bridge.ts +138 -0
  58. package/src/codec/decode.ts +47 -4
  59. package/src/codec/units.ts +8 -1
  60. package/src/index.ts +16 -0
  61. package/src/sync/sources.ts +16 -1
  62. package/src/sync/withdrawals.ts +177 -0
  63. package/src/transport/claim.ts +434 -0
  64. package/src/transport/jsonrpc.ts +54 -0
  65. package/src/transport/rest.ts +35 -7
  66. package/src/transport/ws.ts +4 -1
  67. package/src/types/public.ts +94 -0
  68. package/src/types/wire.ts +47 -1
  69. package/src/write/delegation.ts +2 -12
  70. package/src/write/index.ts +58 -12
@@ -0,0 +1,434 @@
1
+ // Following a withdrawal from pod onto the claim chain (ADR 0033).
2
+ //
3
+ // Two stages, because the claim hash is not known when the withdrawal resolves:
4
+ // ask the pod node for it, then watch the claim chain for the bridge's `Claim`
5
+ // event carrying it. Both live here rather than in a consumer because the event
6
+ // ABI, the topic filter and the log-range policy are protocol knowledge that
7
+ // has to track the bridge contract, not application code.
8
+ //
9
+ // Stage 1 is REST (`GET /v1/bridge/withdrawals/by-id/{id}`), stage 2 is JSON-RPC
10
+ // against the claim chain — the asymmetry is just where each fact lives.
11
+ //
12
+ // **The claim hash is fetched, never recomputed.** It folds in the pod chain id
13
+ // and the bridge version, so a local derivation is a second copy of a
14
+ // consensus-critical hash that silently stops matching after a version bump —
15
+ // the node serves it so that callers don't (ADR 0033 §4.6). Everything else in
16
+ // this module is a consequence of that: it is why stage 1 exists at all.
17
+
18
+ import type { Address, Hash } from "../types/public.js";
19
+ import { tryRpc, type RpcOptions } from "./jsonrpc.js";
20
+ import type { WireWithdrawalDetail } from "../types/wire.js";
21
+
22
+ /**
23
+ * topic0 of `Claim(bytes32 indexed txHash, address token, address mirrorToken,
24
+ * uint256 amount, address indexed to)` — protocol/src/Bridge.sol.
25
+ *
26
+ * A literal rather than a derivation so the read path doesn't pull in an ABI
27
+ * encoder; `claim.test.ts` pins it against viem's `toEventSelector`, so it
28
+ * cannot drift from the signature above without failing a test.
29
+ */
30
+ export const CLAIM_TOPIC: Hash =
31
+ "0xa0b99c0fdfc395724d7b81a88a6d74852461f7691371afe2839bb8688475788c";
32
+
33
+ /** Where a withdrawal has got to on its way to the claim chain. */
34
+ export type ClaimStatus =
35
+ /** The certificate is still assembling (below the signature threshold). */
36
+ | { state: "pending" }
37
+ /** Claimable. `claimHash` is the `Claim` event's indexed `txHash`. */
38
+ | { state: "claimable"; claimHash: Hash }
39
+ /** Refused at execution: nothing was debited, so no `Claim` event can ever
40
+ * fire and the user can resubmit under a new id. Terminal. */
41
+ | { state: "refused" };
42
+
43
+ /**
44
+ * Resolve one withdrawal's claim state from the pod node.
45
+ *
46
+ * **The precedence is deliberate and is the forward-compatibility contract — do
47
+ * not "simplify" it into a switch on `status`:**
48
+ *
49
+ * 1. A present `proof.claim_hash` wins, whatever `status` says. The money is in
50
+ * the certificate, not in the word beside it, and a status this build has
51
+ * never heard of must not veto one sitting in the same response.
52
+ * 2. Only then may `status` be terminal, and only `refused` is — meaning the
53
+ * withdrawal was rejected at execution with nothing debited.
54
+ * 3. Everything else is `pending`, i.e. "ask again": an unfamiliar status, a
55
+ * 404 (this node has no outcome row yet, normal right after submitting), any
56
+ * other HTTP failure, and a transport error. None of them is information
57
+ * about the withdrawal, and guessing `refused` would tell a user their funds
58
+ * were never taken when they may well have been.
59
+ *
60
+ * This mirrors the two properties the node's own `WithdrawalDetail` documents
61
+ * for consumers (node/src/rpc/bridge_rest.rs), which its producer type
62
+ * deliberately does not provide.
63
+ */
64
+ export async function fetchClaimStatus(
65
+ restUrl: string,
66
+ withdrawalId: Hash,
67
+ opts?: RpcOptions,
68
+ ): Promise<ClaimStatus> {
69
+ const doFetch = opts?.fetch ?? fetch;
70
+ try {
71
+ // Trailing slashes are stripped because `PodRestClient` accepts a base with
72
+ // one and this helper is handed the same value. `https://host/v1/` would
73
+ // otherwise request `/v1//bridge/...`, and a 404 from that is indistinguishable
74
+ // here from a certificate that has not assembled yet — so the watch would
75
+ // poll a misspelled URL forever without surfacing anything.
76
+ const base = restUrl.replace(/\/+$/, "");
77
+ const res = await doFetch(`${base}/bridge/withdrawals/by-id/${withdrawalId}`, {
78
+ headers: { accept: "application/json" },
79
+ signal: opts?.signal,
80
+ });
81
+ // Anything non-OK, 404 included, is "ask again": the row may not be written
82
+ // yet, and no HTTP status carries terminality — only `status` does.
83
+ if (!res.ok) return { state: "pending" };
84
+ const body = (await res.json()) as WireWithdrawalDetail;
85
+ // The proof is read FIRST and believed on its presence alone, whatever
86
+ // `status` says. That ordering is the node's own consumer contract
87
+ // (`WithdrawalDetail`, node/src/rpc/bridge_rest.rs): a node that adds a
88
+ // fourth status while still attaching a certificate must not have that
89
+ // certificate vetoed by a label this client has never heard of. The money
90
+ // is in the proof, not in the word next to it.
91
+ const claimHash = body.proof?.claim_hash;
92
+ if (claimHash) return { state: "claimable", claimHash };
93
+ // Only now may a status be terminal, and only this one. Anything unfamiliar
94
+ // falls through to `pending` — "ask again", never terminal.
95
+ if (body.status === "refused") return { state: "refused" };
96
+ return { state: "pending" };
97
+ } catch {
98
+ // A transport failure is not information about the withdrawal. Guessing
99
+ // `refused` here would tell a user their funds were never taken when they may
100
+ // well have been.
101
+ return { state: "pending" };
102
+ }
103
+ }
104
+
105
+ export interface WaitForClaimOptions extends RpcOptions {
106
+ /** pod REST base, as `PodTradeClient` takes it — `""` for a same-origin
107
+ * browser deployment. Stage 1 lives entirely on this surface; no JSON-RPC. */
108
+ restUrl: string;
109
+ /** Claim-chain JSON-RPC — where the `Claim` event is emitted. */
110
+ claimRpcUrl: string;
111
+ withdrawalId: Hash;
112
+ /** The bridge on the claim chain (`BridgeConfig.sourceContract`). Narrows the
113
+ * log query to one contract; omit only if it isn't known. */
114
+ bridge?: Address;
115
+ /** Give up after this long. Default 10 minutes. */
116
+ timeoutMs?: number;
117
+ /** Default 5s. */
118
+ pollMs?: number;
119
+ /** How far before the current block the log scan starts, covering a relayer
120
+ * that claimed before the watch began. Default 5000.
121
+ *
122
+ * Worth lowering for a watch started as the withdrawal resolves: the claim
123
+ * cannot predate the outcome, so the window is known-empty, and this is both
124
+ * the largest query of the watch and the one public providers cap by range. */
125
+ lookbackBlocks?: number;
126
+ }
127
+
128
+ export type ClaimOutcome =
129
+ /** The funds landed. */
130
+ | { state: "claimed"; claimHash: Hash; transactionHash: Hash }
131
+ /** Refused at execution; nothing was debited and nothing will arrive. */
132
+ | { state: "refused" }
133
+ /** Still outstanding when the timeout or the abort signal hit. Carries the
134
+ * claim hash if stage 1 got that far, so a caller can resume the watch. */
135
+ | { state: "pending"; claimHash?: Hash };
136
+
137
+ /**
138
+ * Follow one withdrawal to the claim chain: resolve its claim hash, then watch
139
+ * for the `Claim` event carrying it.
140
+ *
141
+ * Matching on the hash rather than the recipient is what makes this exact —
142
+ * `Claim` indexes `to` as well, but that identifies the *user*, so two
143
+ * withdrawals of the same amount to the same address would be indistinguishable.
144
+ *
145
+ * Returns rather than throws on every expected ending, so a caller renders an
146
+ * outcome instead of catching. Pass `signal` to stop the polling when whatever
147
+ * asked for it goes away.
148
+ */
149
+ export async function waitForClaim(opts: WaitForClaimOptions): Promise<ClaimOutcome> {
150
+ const { restUrl, claimRpcUrl, withdrawalId, bridge, signal } = opts;
151
+ const pollMs = opts.pollMs ?? 5_000;
152
+ const lookback = opts.lookbackBlocks ?? 5_000;
153
+ const deadline = Date.now() + (opts.timeoutMs ?? 10 * 60_000);
154
+ const rest = { fetch: opts.fetch, signal };
155
+
156
+ const live = () => !signal?.aborted && Date.now() < deadline;
157
+ const sleep = () => new Promise<void>((resolve) => {
158
+ const timer = setTimeout(done, pollMs);
159
+ function done() { signal?.removeEventListener("abort", done); clearTimeout(timer); resolve(); }
160
+ signal?.addEventListener("abort", done, { once: true });
161
+ });
162
+
163
+ // Anchor the scan window before stage 1, so the range stays bounded however
164
+ // long the certificate takes to assemble. This same reading is the first
165
+ // scan's upper bound, so stage 2 costs no extra round trip to start.
166
+ const tip = await tryRpc<string>(claimRpcUrl, "eth_blockNumber", [], rest);
167
+ if (tip === undefined) return { state: "pending" };
168
+ let head: bigint | undefined = BigInt(tip);
169
+ let fromBlock = head > BigInt(lookback) ? head - BigInt(lookback) : 0n;
170
+
171
+ let claimHash: Hash | undefined;
172
+ while (!claimHash && live()) {
173
+ const status = await fetchClaimStatus(restUrl, withdrawalId, rest);
174
+ if (status.state === "refused") return { state: "refused" };
175
+ if (status.state === "claimable") claimHash = status.claimHash;
176
+ else await sleep();
177
+ }
178
+ if (!claimHash) return { state: "pending" };
179
+
180
+ while (live()) {
181
+ // The upper bound is pinned BEFORE the scan and named explicitly. With
182
+ // `toBlock: "latest"` the node picks the end itself, and any block mined
183
+ // between that choice and a later head read would be stepped over by the
184
+ // advance below — permanently, since the window only moves forward. On a
185
+ // 250ms-block chain that silently loses the claim a few percent of the time.
186
+ if (head === undefined) {
187
+ const latest = await tryRpc<string>(claimRpcUrl, "eth_blockNumber", [], rest);
188
+ if (latest === undefined) { await sleep(); continue; }
189
+ head = BigInt(latest);
190
+ }
191
+ const toBlock = head;
192
+ head = undefined; // re-read on the next pass; this one is now spent
193
+
194
+ if (toBlock >= fromBlock) {
195
+ const filter: Record<string, unknown> = {
196
+ fromBlock: `0x${fromBlock.toString(16)}`,
197
+ toBlock: `0x${toBlock.toString(16)}`,
198
+ topics: [CLAIM_TOPIC, claimHash],
199
+ };
200
+ if (bridge) filter.address = bridge;
201
+ const logs = await tryRpc<Array<{ transactionHash: Hash }>>(
202
+ claimRpcUrl, "eth_getLogs", [filter], rest,
203
+ );
204
+ const hit = logs?.[0];
205
+ if (hit) return { state: "claimed", claimHash, transactionHash: hit.transactionHash };
206
+
207
+ // Only advance on a scan that actually completed. `tryRpc` maps a 429, a
208
+ // 5xx or "query returned more than 10000 results" to undefined, which is
209
+ // indistinguishable from an empty result — advancing there would skip the
210
+ // range unread, and the lookback window is the one covering a relayer that
211
+ // claimed before this watch began.
212
+ if (logs !== undefined) fromBlock = toBlock + 1n;
213
+ }
214
+ await sleep();
215
+ }
216
+ return { state: "pending", claimHash };
217
+ }
218
+
219
+ export interface WatchClaimsOptions extends RpcOptions {
220
+ /** pod REST base, as `PodTradeClient` takes it. */
221
+ restUrl: string;
222
+ /** Claim-chain JSON-RPC — where the `Claim` event is emitted. */
223
+ claimRpcUrl: string;
224
+ /** The bridge on the claim chain (`BridgeConfig.sourceContract`). */
225
+ bridge?: Address;
226
+ /** Default 5s. */
227
+ pollMs?: number;
228
+ /** Called once per withdrawal, when it reaches a terminal state. Never called
229
+ * for one still outstanding when the watcher stops. */
230
+ onSettled: (withdrawalId: Hash, outcome: ClaimOutcome) => void;
231
+ }
232
+
233
+ export interface ClaimWatcher {
234
+ /**
235
+ * Follow one withdrawal. Ignored if it is already followed, so a caller may
236
+ * re-offer the same id freely. It is NOT ignored for an id that has already
237
+ * settled, because the watcher forgets those — deduplicating across
238
+ * settlement belongs to the caller, which is the only side that knows whether
239
+ * it acted on the outcome.
240
+ *
241
+ * `lookbackBlocks` covers a claim emitted before this id joined. It sets this
242
+ * id's OWN scan floor, and the shared query starts at the oldest floor among
243
+ * outstanding ids — so a range already scanned for others is re-scanned for
244
+ * this one, and no id's window is ever skipped on another's behalf.
245
+ */
246
+ add(withdrawalId: Hash, opts?: { lookbackBlocks?: number }): void;
247
+ /** How many withdrawals are still outstanding. */
248
+ readonly size: number;
249
+ stop(): void;
250
+ }
251
+
252
+ /**
253
+ * Follow many withdrawals on one pair of loops instead of one pair each.
254
+ *
255
+ * The saving is on the claim chain, which is the half that costs: a `Claim`
256
+ * topic filter is an OR set at `topics[1]`, so a single `eth_getLogs` covers
257
+ * every outstanding hash and that query's count stops scaling with the number of
258
+ * withdrawals. Stage 1 still costs one REST read per unresolved id, issued
259
+ * concurrently rather than in series — those go to pod's own node, not to a
260
+ * metered provider, so the thing worth collapsing is the log scan.
261
+ *
262
+ * **Each id carries its own scan floor, and the shared query starts at the
263
+ * oldest of them.** This is the part that is easy to get wrong: a withdrawal
264
+ * still waiting for its certificate has no hash to search for yet, so it
265
+ * contributes nothing to the topic set — but the blocks passing meanwhile are
266
+ * exactly where its `Claim` may land, because a relayer can claim from a
267
+ * certificate this node has not finished assembling. Advancing the floor on the
268
+ * strength of the ids that *do* have hashes would step over that window for
269
+ * good. So a floor is only raised for an id whose hash was actually in the query
270
+ * that covered it.
271
+ *
272
+ * Settlement arrives through `onSettled` rather than a promise per id, so a
273
+ * caller hears about each outcome when it happens rather than when the slowest
274
+ * one does.
275
+ */
276
+ export function watchClaims(opts: WatchClaimsOptions): ClaimWatcher {
277
+ const { restUrl, claimRpcUrl, bridge, signal, onSettled } = opts;
278
+ const pollMs = opts.pollMs ?? 5_000;
279
+ const rest = { fetch: opts.fetch, signal };
280
+
281
+ interface Entry {
282
+ /** Set once the certificate exists. Lower-cased: it is compared against a
283
+ * topic from a different source, and hex casing is not guaranteed to agree. */
284
+ claimHash?: Hash;
285
+ /** Oldest block this id still needs searched. Pinned on the first tick after
286
+ * `add`, then raised only by a query that actually carried its hash. */
287
+ floor?: bigint;
288
+ lookback: number;
289
+ }
290
+
291
+ const pending = new Map<Hash, Entry>();
292
+ let stopped = false;
293
+ let wake: (() => void) | undefined;
294
+ /**
295
+ * The newest head this watcher has seen. Kept so `add` can anchor immediately
296
+ * rather than waiting for the next tick to do it: an id added while a scan is
297
+ * in flight is not covered by `wake` (the watcher is not sleeping) and would
298
+ * otherwise be anchored at the FOLLOWING head, silently skipping every block
299
+ * between the call and that read — the exact window a per-id floor exists to
300
+ * preserve. Undefined only before the first head read, where nothing has been
301
+ * scanned yet and the first tick anchors it correctly.
302
+ */
303
+ let lastHead: bigint | undefined;
304
+
305
+ const live = () => !stopped && !signal?.aborted;
306
+
307
+ /** The oldest block an id joining at `head` still needs searched. */
308
+ const anchorFrom = (head: bigint, lookback: number) => {
309
+ const back = BigInt(lookback);
310
+ return head > back ? head - back : 0n;
311
+ };
312
+
313
+ const sleep = () => new Promise<void>((resolve) => {
314
+ const timer = setTimeout(done, pollMs);
315
+ wake = done;
316
+ function done() {
317
+ signal?.removeEventListener("abort", done);
318
+ clearTimeout(timer);
319
+ wake = undefined;
320
+ resolve();
321
+ }
322
+ signal?.addEventListener("abort", done, { once: true });
323
+ });
324
+
325
+ /** Terminal for one id. Silent once stopped: `stop()` cannot cancel an
326
+ * in-flight request, and a caller that has torn down its state must not be
327
+ * told about an outcome afterwards — it would announce a claim for an account
328
+ * the user has left, and un-mark an id its own cleanup had just released. */
329
+ const settle = (id: Hash, outcome: ClaimOutcome) => {
330
+ if (!live()) return;
331
+ pending.delete(id);
332
+ onSettled(id, outcome);
333
+ };
334
+
335
+ async function tick(): Promise<void> {
336
+ // Stage 1, concurrently: the reads share no state until their results are
337
+ // written back, so in series they would simply add up one RTT at a time.
338
+ const unresolved = [...pending].filter(([, e]) => !e.claimHash);
339
+ const statuses = await Promise.all(
340
+ unresolved.map(([id]) => fetchClaimStatus(restUrl, id, rest)),
341
+ );
342
+ unresolved.forEach(([id, entry], i) => {
343
+ const status = statuses[i]!;
344
+ if (status.state === "refused") settle(id, { state: "refused" });
345
+ else if (status.state === "claimable") entry.claimHash = status.claimHash.toLowerCase() as Hash;
346
+ });
347
+ if (!live() || pending.size === 0) return;
348
+
349
+ // The tip is read every tick, even with nothing to search for yet, because
350
+ // it is what pins a newcomer's floor. Deferring that until a hash exists
351
+ // would anchor it at a later block than the one it joined at, losing the
352
+ // window in between — the same mistake as advancing past an unresolved id.
353
+ const head = await tryRpc<string>(claimRpcUrl, "eth_blockNumber", [], rest);
354
+ if (head === undefined) return;
355
+ const toBlock = BigInt(head);
356
+ lastHead = toBlock;
357
+ for (const entry of pending.values()) {
358
+ if (entry.floor === undefined) entry.floor = anchorFrom(toBlock, entry.lookback);
359
+ }
360
+
361
+ const hashes = [...pending.values()].map((e) => e.claimHash).filter((h): h is Hash => !!h);
362
+ if (hashes.length === 0) return; // nothing to look for; floors are pinned
363
+
364
+ let fromBlock = toBlock;
365
+ for (const entry of pending.values()) {
366
+ if (entry.floor !== undefined && entry.floor < fromBlock) fromBlock = entry.floor;
367
+ }
368
+ if (toBlock < fromBlock) return;
369
+
370
+ const filter: Record<string, unknown> = {
371
+ fromBlock: `0x${fromBlock.toString(16)}`,
372
+ toBlock: `0x${toBlock.toString(16)}`,
373
+ // An array at `topics[1]` is an OR over claim hashes — the whole reason
374
+ // one query can serve every outstanding withdrawal.
375
+ topics: [CLAIM_TOPIC, hashes],
376
+ };
377
+ if (bridge) filter.address = bridge;
378
+
379
+ const logs = await tryRpc<Array<{ transactionHash: Hash; topics: Hash[] }>>(
380
+ claimRpcUrl, "eth_getLogs", [filter], rest,
381
+ );
382
+ // Undefined is a failed query, not an empty range, so no floor may move.
383
+ if (logs === undefined) return;
384
+
385
+ for (const log of logs) {
386
+ const claimHash = log.topics[1]?.toLowerCase() as Hash | undefined;
387
+ if (!claimHash) continue;
388
+ for (const [id, entry] of [...pending]) {
389
+ if (entry.claimHash === claimHash) {
390
+ settle(id, { state: "claimed", claimHash, transactionHash: log.transactionHash });
391
+ }
392
+ }
393
+ }
394
+ // Raise the floor ONLY for ids whose hash this query carried. One that is
395
+ // still waiting on its certificate keeps its original floor, so the blocks
396
+ // that passed while it waited are searched once its hash appears.
397
+ const searched = new Set(hashes);
398
+ for (const entry of pending.values()) {
399
+ if (entry.claimHash && searched.has(entry.claimHash)) entry.floor = toBlock + 1n;
400
+ }
401
+ }
402
+
403
+ async function run(): Promise<void> {
404
+ while (live()) {
405
+ if (pending.size > 0) await tick();
406
+ await sleep();
407
+ }
408
+ }
409
+
410
+ void run();
411
+
412
+ return {
413
+ add(withdrawalId, addOpts) {
414
+ if (stopped || pending.has(withdrawalId)) return;
415
+ const lookback = addOpts?.lookbackBlocks ?? 0;
416
+ // Anchor from the last head seen, NOT from whatever the next tick reads.
417
+ // `wake` only helps while the watcher is sleeping; an id added during an
418
+ // in-flight scan would otherwise be pinned at a later head and lose every
419
+ // block in between.
420
+ pending.set(withdrawalId, {
421
+ lookback,
422
+ floor: lastHead === undefined ? undefined : anchorFrom(lastHead, lookback),
423
+ });
424
+ wake?.(); // and start looking now rather than after the current sleep
425
+ },
426
+ get size() {
427
+ return pending.size;
428
+ },
429
+ stop() {
430
+ stopped = true;
431
+ wake?.();
432
+ },
433
+ };
434
+ }
@@ -0,0 +1,54 @@
1
+ // One JSON-RPC POST, shared by every raw-RPC caller in the SDK.
2
+ //
3
+ // Deliberately not viem: this is reachable from the main entry, and read-only
4
+ // consumers should not pull a signing library in to read a block number. The
5
+ // `/write` entry uses viem because it must.
6
+
7
+ export interface RpcOptions {
8
+ fetch?: typeof fetch;
9
+ signal?: AbortSignal;
10
+ }
11
+
12
+ export class PodRpcError extends Error {
13
+ constructor(public code: number | undefined, message: string) {
14
+ super(message);
15
+ this.name = "PodRpcError";
16
+ }
17
+ }
18
+
19
+ /** Call `method` and return its result, throwing {@link PodRpcError} on an
20
+ * error response. Use {@link tryRpc} where an error is an expected state. */
21
+ export async function rpc<T>(
22
+ rpcUrl: string,
23
+ method: string,
24
+ params: unknown[] = [],
25
+ opts?: RpcOptions,
26
+ ): Promise<T> {
27
+ const doFetch = opts?.fetch ?? fetch;
28
+ const res = await doFetch(rpcUrl, {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json" },
31
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
32
+ signal: opts?.signal,
33
+ });
34
+ const json = (await res.json()) as { result?: T; error?: { code?: number; message?: string } };
35
+ if (json.error) throw new PodRpcError(json.error.code, json.error.message ?? `${method} failed`);
36
+ if (json.result === undefined) throw new PodRpcError(undefined, `${method} returned no result`);
37
+ return json.result;
38
+ }
39
+
40
+ /** {@link rpc}, but an error response (or a transport failure) yields
41
+ * `undefined` instead of throwing — for methods whose failure is a state the
42
+ * caller expects and handles, not an exception. */
43
+ export async function tryRpc<T>(
44
+ rpcUrl: string,
45
+ method: string,
46
+ params: unknown[] = [],
47
+ opts?: RpcOptions,
48
+ ): Promise<T | undefined> {
49
+ try {
50
+ return await rpc<T>(rpcUrl, method, params, opts);
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ }
@@ -3,17 +3,19 @@
3
3
  // ms in, decoded (bigint / ms) out.
4
4
 
5
5
  import type {
6
- Address, BackstopTransfer, Balances, Bar, CandleQuery, LeaderboardPage, LeaderboardQuery,
7
- Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status, Trigger, TxExplorer,
6
+ Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery, LeaderboardPage,
7
+ LeaderboardQuery, Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status,
8
+ Trigger, TxExplorer, Withdrawal, WithdrawalsQuery,
8
9
  } from "../types/public.js";
9
10
  import type {
10
- WireBackstopPage, WireBalances, WireCandlesEnvelope, WireLeaderboard, WireMarketStatic,
11
- WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot, WireStatus,
12
- WireTriggersPage,
11
+ WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope, WireLeaderboard,
12
+ WireMarketStatic, WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot,
13
+ WireStatus, WireTriggersPage, WireWithdrawal,
13
14
  } from "../types/wire.js";
14
15
  import {
15
- decodeBackstopTransfer, decodeBalances, decodeCandle, decodeLeaderboard, decodeMarketDynamics,
16
- decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions, decodeStatus, decodeTrigger,
16
+ decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle, decodeLeaderboard,
17
+ decodeMarketDynamics, decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions,
18
+ decodeStatus, decodeTrigger, decodeWithdrawal,
17
19
  } from "../codec/decode.js";
18
20
  import { msToSecs, usToMs } from "../codec/units.js";
19
21
 
@@ -199,6 +201,32 @@ export class PodRestClient {
199
201
  return decodeLeaderboard(w, q?.offset ?? 0);
200
202
  }
201
203
 
204
+ /** Static bridge config: the claim chain, the bridge contract, and every
205
+ * bridged token's L1 address, decimals and withdraw window (ADR 0033 §5).
206
+ * Served unconditionally — it is not behind the CLOB indexer's gate. */
207
+ async bridgeConfig(): Promise<BridgeConfig> {
208
+ return decodeBridgeConfig(await this.get<WireBridgeConfig>("/bridge/config"));
209
+ }
210
+
211
+ /**
212
+ * Terminal withdrawal outcomes, newest cursor last. Omit `account` for every
213
+ * account (what a relayer wants); pass one to scope it to a single user.
214
+ *
215
+ * This is the reconnect backfill behind the `pod_withdrawals` subscription:
216
+ * the rows decode to exactly the same shape the stream pushes, so a client
217
+ * cannot tell which one an outcome arrived on. Page with `since` (the tick
218
+ * cursor) plus `sinceId` to resume *inside* a tick that spanned a page.
219
+ */
220
+ async bridgeWithdrawals(account?: Address, q?: WithdrawalsQuery): Promise<Withdrawal[]> {
221
+ const path = account ? `/bridge/withdrawals/${account}` : "/bridge/withdrawals";
222
+ const w = await this.get<WireWithdrawal[]>(path, {
223
+ since: q?.since,
224
+ since_id: q?.sinceId,
225
+ limit: q?.limit,
226
+ });
227
+ return w.map(decodeWithdrawal);
228
+ }
229
+
202
230
  async triggers(account: Address, q?: TriggersQueryRest): Promise<TriggersPage> {
203
231
  const w = await this.get<WireTriggersPage>(`/clob/triggers/${account}`, {
204
232
  orderbook: q?.orderbook,
@@ -7,7 +7,10 @@ import type { Address, MarketId } from "../types/public.js";
7
7
 
8
8
  export type Channel =
9
9
  | "pod_orderbook" | "pod_orders_v2" | "pod_candles"
10
- | "pod_markets" | "pod_positions" | "pod_triggers";
10
+ | "pod_markets" | "pod_positions" | "pod_triggers"
11
+ /** Terminal withdrawal outcomes; one array per tick, `account`-filtered on the
12
+ * debited account (the master, under delegation). ADR 0033 §6. */
13
+ | "pod_withdrawals";
11
14
 
12
15
  export interface SubParams {
13
16
  clobIds?: MarketId[];
@@ -465,3 +465,97 @@ export interface TriggersQuery {
465
465
  orderbookId?: MarketId;
466
466
  limit?: number;
467
467
  }
468
+
469
+ // --- bridge / withdrawals (ADR 0033) ---
470
+
471
+ /**
472
+ * One bridged token, as `GET /v1/bridge/config` serves it.
473
+ *
474
+ * `min`, `max` and `decimals` are all on the **claim chain's** terms, not pod's
475
+ * 18 — see `codec/bridge.ts`, which owns that conversion.
476
+ */
477
+ export interface BridgeToken {
478
+ podToken: Address;
479
+ l1Token: Address;
480
+ /** Decimals on the claim chain, and so the withdrawal granularity on pod. */
481
+ decimals: number;
482
+ /** Smallest admissible withdrawal, in claim-chain decimals. */
483
+ min: bigint;
484
+ /** Largest admissible withdrawal, in claim-chain decimals. */
485
+ max: bigint;
486
+ }
487
+
488
+ /** Static bridge configuration — the one chain pod withdrawals settle on. */
489
+ export interface BridgeConfig {
490
+ /** `0` when the node has no bridge configured, in which case `tokens` is
491
+ * empty and no withdrawal is admissible at all. */
492
+ claimChainId: number;
493
+ /** The bridge contract on the claim chain, where `Claim` is emitted. */
494
+ sourceContract: Address;
495
+ /** Bridge version; feeds the claim-hash domain separator. */
496
+ version: number;
497
+ tokens: BridgeToken[];
498
+ }
499
+
500
+ /**
501
+ * Why a withdrawal produced no L1 claim. Any value here means **no L1 event will
502
+ * ever fire**, so a client watching only the claim chain would wait forever —
503
+ * this is the only place a reason exists.
504
+ */
505
+ export type WithdrawalError =
506
+ /** The CLOB balance did not cover it at execution. Admission deliberately
507
+ * doesn't check the balance (pending fills can raise it), so this races that. */
508
+ | "insufficient_balance"
509
+ /** The solver never included the intent before its deadline. Funds are
510
+ * untouched and the withdrawal can simply be resubmitted. */
511
+ | "not_included"
512
+ /**
513
+ * Any other reason a node reports. This set is **open by construction**: the
514
+ * node's reason enum is explicitly extensible and an app ships ahead of the
515
+ * fleet, so a spelling this build predates has to arrive verbatim rather than
516
+ * be dropped. Dropping it makes a *failed* withdrawal read as claimable —
517
+ * the one direction it is unsafe to be lossy in, because the caller then
518
+ * reports success and waits for a claim that can never land.
519
+ *
520
+ * `(string & {})` keeps the two known values in editor completion while still
521
+ * admitting the rest. Treat an unknown reason exactly like a known one, and
522
+ * show it verbatim rather than guessing which known reason it resembles.
523
+ */
524
+ | (string & {});
525
+
526
+ /** One terminal withdrawal outcome, from `pod_withdrawals` or its REST backfill. */
527
+ export interface Withdrawal {
528
+ /** `keccak(abi.encode(signer, nonce, sequence))` — derivable client-side
529
+ * before submitting, which is what lets a client match its own withdrawal. */
530
+ id: Hash;
531
+ /** The debited account: the master, for a delegated withdrawal. */
532
+ withdrawer: Address;
533
+ /** Recipient on the **claim chain**. Nothing is credited on pod. */
534
+ to: Address;
535
+ /** Pod-side token address. */
536
+ token: Address;
537
+ /** Pod's 18 decimals, as signed. The L1 claim carries this converted to the
538
+ * token's claim-chain decimals — never pass this value to `claim`. */
539
+ amount: bigint;
540
+ /** Absent when the withdrawal is claimable on L1. */
541
+ error?: WithdrawalError;
542
+ /**
543
+ * The tick's batch deadline, in **microseconds** — not the millisecond
544
+ * convention the rest of this surface uses.
545
+ *
546
+ * Deliberate: this value is also the resume cursor for `pod_withdrawals` and
547
+ * for the REST backfill, both of which compare it in micros. Narrowing it to
548
+ * ms and back would round a tick boundary and silently re-serve or skip a
549
+ * tick, so it stays in the unit the server compares.
550
+ */
551
+ timeUs: number;
552
+ }
553
+
554
+ export interface WithdrawalsQuery {
555
+ /** Batch deadline in microseconds; strictly greater. */
556
+ since?: number;
557
+ /** Last id already seen *within* the `since` tick, to resume mid-tick. */
558
+ sinceId?: Hash;
559
+ /** Server default 500, capped at 1000. */
560
+ limit?: number;
561
+ }