@pod-network/trade-sdk 0.3.0 → 0.4.1

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 (89) hide show
  1. package/README.md +99 -2
  2. package/dist/client.d.ts +45 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +63 -2
  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/resolution.d.ts +4 -1
  15. package/dist/codec/resolution.d.ts.map +1 -1
  16. package/dist/codec/resolution.js +6 -3
  17. package/dist/codec/resolution.js.map +1 -1
  18. package/dist/codec/units.d.ts.map +1 -1
  19. package/dist/codec/units.js +9 -1
  20. package/dist/codec/units.js.map +1 -1
  21. package/dist/datafeed.d.ts.map +1 -1
  22. package/dist/datafeed.js +15 -9
  23. package/dist/datafeed.js.map +1 -1
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/stores/resource.d.ts +14 -1
  29. package/dist/stores/resource.d.ts.map +1 -1
  30. package/dist/stores/resource.js +7 -1
  31. package/dist/stores/resource.js.map +1 -1
  32. package/dist/sync/candles.d.ts +62 -4
  33. package/dist/sync/candles.d.ts.map +1 -1
  34. package/dist/sync/candles.js +259 -42
  35. package/dist/sync/candles.js.map +1 -1
  36. package/dist/sync/sources.d.ts +5 -1
  37. package/dist/sync/sources.d.ts.map +1 -1
  38. package/dist/sync/sources.js +16 -0
  39. package/dist/sync/sources.js.map +1 -1
  40. package/dist/sync/withdrawals.d.ts +5 -0
  41. package/dist/sync/withdrawals.d.ts.map +1 -0
  42. package/dist/sync/withdrawals.js +172 -0
  43. package/dist/sync/withdrawals.js.map +1 -0
  44. package/dist/transport/claim.d.ts +160 -0
  45. package/dist/transport/claim.d.ts.map +1 -0
  46. package/dist/transport/claim.js +341 -0
  47. package/dist/transport/claim.js.map +1 -0
  48. package/dist/transport/jsonrpc.d.ts +16 -0
  49. package/dist/transport/jsonrpc.d.ts.map +1 -0
  50. package/dist/transport/jsonrpc.js +42 -0
  51. package/dist/transport/jsonrpc.js.map +1 -0
  52. package/dist/transport/rest.d.ts +23 -1
  53. package/dist/transport/rest.d.ts.map +1 -1
  54. package/dist/transport/rest.js +33 -2
  55. package/dist/transport/rest.js.map +1 -1
  56. package/dist/transport/ws.d.ts +4 -1
  57. package/dist/transport/ws.d.ts.map +1 -1
  58. package/dist/transport/ws.js.map +1 -1
  59. package/dist/types/public.d.ts +87 -0
  60. package/dist/types/public.d.ts.map +1 -1
  61. package/dist/types/wire.d.ts +43 -1
  62. package/dist/types/wire.d.ts.map +1 -1
  63. package/dist/write/delegation.d.ts.map +1 -1
  64. package/dist/write/delegation.js +2 -12
  65. package/dist/write/delegation.js.map +1 -1
  66. package/dist/write/index.d.ts +25 -0
  67. package/dist/write/index.d.ts.map +1 -1
  68. package/dist/write/index.js +20 -13
  69. package/dist/write/index.js.map +1 -1
  70. package/package.json +1 -1
  71. package/src/client.ts +77 -5
  72. package/src/codec/bridge.ts +138 -0
  73. package/src/codec/decode.ts +47 -4
  74. package/src/codec/resolution.ts +6 -3
  75. package/src/codec/units.ts +8 -1
  76. package/src/datafeed.ts +15 -9
  77. package/src/index.ts +16 -0
  78. package/src/stores/resource.ts +14 -1
  79. package/src/sync/candles.ts +297 -45
  80. package/src/sync/sources.ts +16 -1
  81. package/src/sync/withdrawals.ts +177 -0
  82. package/src/transport/claim.ts +434 -0
  83. package/src/transport/jsonrpc.ts +54 -0
  84. package/src/transport/rest.ts +50 -8
  85. package/src/transport/ws.ts +4 -1
  86. package/src/types/public.ts +94 -0
  87. package/src/types/wire.ts +47 -1
  88. package/src/write/delegation.ts +2 -12
  89. package/src/write/index.ts +58 -12
package/README.md CHANGED
@@ -48,15 +48,112 @@ const ob = useSyncExternalStore(
48
48
 
49
49
  - **Layer 1 (low-level, exposed):** `client.rest.*` typed one-shot reads and
50
50
  `client.ws.subscribe(channel, params, onMessage)` raw subscriptions.
51
+ - **One-shot reads:** `client.candleHistory(id, resolution, range)` for chart
52
+ history (resolves with the whole window or rejects — a partial answer is worse
53
+ than an error, because a chart never re-asks) and `.candleTail(id, resolution,
54
+ range)` for the still-forming bucket, plus `.leaderboard(query)`,
55
+ `.transaction(hash)`.
51
56
  - **Layer 2 (resources):** `client.status`, `.markets`, `.market(id)`,
52
57
  `.orderbook(id,{depth})`, `.positions(account)`, `.triggers(account)`,
53
58
  `.backstopTransfers(account)`, `.candles(id, resolution, range)` (a
54
- `SeriesResource` with `setWindow`/`loadOlder`), `.orders(account, query)`.
59
+ `SeriesResource` with `setWindow`/`loadOlder`), `.orders(account, query)`,
60
+ `.bridgeConfig`, `.withdrawals(account)`.
55
61
  - **Charting:** `createPodDatafeed(client)` returns an `IDatafeedChartApi`-shaped
56
62
  object for the TradingView Charting Library (framework-agnostic, no React).
57
63
 
58
64
  All monetary values are `bigint` (1e18-scaled; use `formatAmount`/`toNumber`/
59
- `parseAmount`); all timestamps are millisecond `number`s.
65
+ `parseAmount`); all timestamps are millisecond `number`s — with one deliberate
66
+ exception, `Withdrawal.timeUs`, which stays in **microseconds** because it is
67
+ also the resume cursor for `pod_withdrawals` and its REST backfill, both of which
68
+ compare it in micros. The `Us` suffix is the only marker, so treating it as
69
+ milliseconds silently reads a timestamp a thousand times too large.
70
+
71
+ ## Withdrawals (ADR 0033)
72
+
73
+ `Clob.withdraw` moves a CLOB balance straight to the claim chain in **one**
74
+ transaction — nothing is credited to a pod account on the way, so there is no
75
+ second signature and no half-finished state to recover.
76
+
77
+ ```ts
78
+ import { buildClobWithdraw, NATIVE_USD_ADDRESS } from "@pod-network/trade-sdk/write";
79
+ import { bridgeTokenFor, checkWithdrawAmount, maxWithdrawable } from "@pod-network/trade-sdk";
80
+
81
+ const config = await client.bridgeConfig.ready();
82
+ const token = bridgeTokenFor(config, NATIVE_USD_ADDRESS)!;
83
+
84
+ // Size it against the token's own rules before signing.
85
+ const amount = maxWithdrawable(balances.withdrawableCash, token);
86
+ const rejection = checkWithdrawAmount(amount, token); // undefined = admissible
87
+ if (rejection) return render(rejection); // e.g. a balance below the token's minimum
88
+
89
+ await wallet.submit(buildClobWithdraw({
90
+ token: token.podToken,
91
+ recipient,
92
+ amount,
93
+ // Required: admission refuses a deadline that is not a multiple of it.
94
+ auctionIntervalUs: market.auctionIntervalMs * 1000,
95
+ }));
96
+ ```
97
+
98
+ The rejection is checked rather than merely computed, because `maxWithdrawable`
99
+ returns `0n` for a balance below the token's minimum — so an unguarded path
100
+ submits an amount the node is certain to refuse.
101
+
102
+ `checkWithdrawAmount` returns a discriminated rejection (`{ code, … }`, each
103
+ variant carrying only the numbers its message needs) rather than a sentence — the
104
+ wording belongs to whatever renders it.
105
+
106
+ **`amount` stays in pod's 18 decimals but must be a whole number of claim-chain
107
+ units.** Whatever decimals the token uses on the claim chain become the
108
+ withdrawal granularity on pod, and the config's `min`/`max` are in those decimals
109
+ too — so where native USD maps to 6-decimal USDC, every withdrawal must be a
110
+ multiple of 1e12 wei. `maxWithdrawable` handles both; the builder deliberately
111
+ does no rounding of its own, because silently changing a signed amount is worse
112
+ than a clear rejection.
113
+
114
+ Track the outcome on `client.withdrawals(account)` (live, REST-backfilled),
115
+ matching on the id derived above. `error` is the **only** place a failure reason
116
+ exists: both `insufficient_balance` and `not_included` produce no L1 event at
117
+ all, so a client watching only the claim chain waits forever.
118
+
119
+ To confirm the funds actually landed, `waitForClaim({ restUrl, claimRpcUrl,
120
+ withdrawalId, bridge })` reads the withdrawal's claim state from pod and then
121
+ watches the claim chain for the bridge's `Claim` event carrying its hash. It
122
+ settles as `claimed` (with the L1 transaction), `refused` (rejected at execution
123
+ — nothing was debited, so the user can resubmit), or `pending` (timed out or
124
+ aborted, still in flight). Pass a `signal` to stop it.
125
+
126
+ Two things it handles that are easy to get wrong alone: the claim hash is
127
+ **fetched, never recomputed** — it folds in the pod chain id and the bridge
128
+ version, so a local copy silently stops matching after a version bump — and
129
+ `pending` is not `refused`, so a certificate that is merely still assembling
130
+ never reads as a dead withdrawal. Note `refused` is named for the *burn*, not for
131
+ claimability: it means nothing left the CLOB balance.
132
+
133
+ **Following more than one, use `watchClaims`.** `waitForClaim` is one loop per
134
+ withdrawal, and a UI tracking several pays that many times over. `watchClaims`
135
+ takes the same options minus the id, hands back `{ add, size, stop }`, and
136
+ reports each outcome through `onSettled` as it happens:
137
+
138
+ ```ts
139
+ const claims = watchClaims({ restUrl, claimRpcUrl, bridge, onSettled: announce });
140
+ claims.add(withdrawalId, { lookbackBlocks: 200 });
141
+ ```
142
+
143
+ The claim-chain half then costs the same whether one withdrawal is outstanding
144
+ or twenty, because a `Claim` topic filter is an OR set at `topics[1]` and one
145
+ `eth_getLogs` covers every hash. Stage 1 is still a REST read per unresolved id,
146
+ issued concurrently, so it is the log scan that stops scaling — not every request.
147
+
148
+ Each withdrawal keeps its **own** scan floor and the shared query starts at the
149
+ oldest of them, which is the one thing worth knowing when using it. A withdrawal
150
+ still waiting for its certificate contributes no hash to the query, but the
151
+ blocks passing meanwhile are exactly where its `Claim` may land — a relayer can
152
+ claim from a certificate this node has not finished assembling. So a floor is
153
+ raised only for an id whose hash was actually in the query that covered it.
154
+ `add` is idempotent while a withdrawal is outstanding but not after it settles —
155
+ the watcher forgets settled ids, so not re-announcing an outcome you already
156
+ acted on stays with the caller.
60
157
 
61
158
  ## How caching / low traffic works
62
159
 
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Address, BackstopTransfer, Balances, LeaderboardPage, LeaderboardQuery, Market, MarketId, PositionsSnapshot, Resolution, Status, TimeRange, Trigger, TriggersQuery, TxExplorer, OrdersQuery } from "./types/public.js";
1
+ import type { Address, BackstopTransfer, Balances, Bar, BridgeConfig, LeaderboardPage, LeaderboardQuery, Market, MarketId, PositionsSnapshot, Resolution, Status, TimeRange, Trigger, TriggersQuery, TxExplorer, OrdersQuery, Withdrawal } from "./types/public.js";
2
2
  import { PodRestClient } from "./transport/rest.js";
3
3
  import { PodWsClient, type WebSocketCtor } from "./transport/ws.js";
4
4
  import { type Resource } from "./stores/resource.js";
@@ -81,6 +81,24 @@ export declare class PodTradeClient {
81
81
  triggers(account: Address, _query?: TriggersQuery): Resource<Trigger[]>;
82
82
  /** Live spot holdings + native cash. */
83
83
  balances(account: Address): Resource<Balances>;
84
+ /**
85
+ * Static bridge config: the claim chain, and each bridged token's L1 address,
86
+ * decimals and withdraw window (ADR 0033 §5). Everything a client needs to
87
+ * build an admissible withdrawal — see `maxWithdrawable` / `checkWithdrawAmount`.
88
+ *
89
+ * Re-seeded on reconnect rather than fetched once: an operator can change the
90
+ * token set or the limits under a long-lived tab, and a stale window would
91
+ * quietly offer amounts the node now refuses.
92
+ */
93
+ get bridgeConfig(): Resource<BridgeConfig>;
94
+ /**
95
+ * This account's terminal withdrawal outcomes, newest first — live off
96
+ * `pod_withdrawals`, gap-filled over REST on every reconnect.
97
+ *
98
+ * Scoped to the **debited** account, which is the master for a delegated
99
+ * withdrawal, so pass the master address rather than the session key.
100
+ */
101
+ withdrawals(account: Address): Resource<Withdrawal[]>;
84
102
  /** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
85
103
  * `{ limit, offset }`. Not a stream — call again to refresh. */
86
104
  leaderboard(query?: LeaderboardQuery): Promise<LeaderboardPage>;
@@ -88,6 +106,32 @@ export declare class PodTradeClient {
88
106
  transaction(hash: string): Promise<TxExplorer>;
89
107
  backstopTransfers(account: Address): Resource<BackstopTransfer[]>;
90
108
  candles(id: MarketId, resolution: Resolution, range?: TimeRange): CandleSeries;
109
+ /**
110
+ * Closed bars for a window — a one-shot read, not a live resource.
111
+ *
112
+ * Chart history belongs here rather than on a `CandleSeries`: series are
113
+ * memoised per (market, resolution) and shared with whatever else is watching
114
+ * that market, so a history read that waited on the series' loading state
115
+ * could be resolved by an unrelated load finishing and report "no bars" for a
116
+ * window whose own pages were still in flight. This read owns its request:
117
+ * it resolves with the window's bars or rejects.
118
+ */
119
+ candleHistory(id: MarketId, resolution: Resolution, range: TimeRange): Promise<Bar[]>;
120
+ /**
121
+ * The bars the live tick fold currently holds inside `range`, the forming
122
+ * bucket included — the other half of `candleHistory`, which can only ever
123
+ * return closed bars because REST withholds the open bucket.
124
+ *
125
+ * A chart asking for a window that reaches "now" on a market whose only
126
+ * activity is in that bucket has no closed history at all, and answering it
127
+ * "no bars" makes the chart latch the range as empty. Both datafeeds fall
128
+ * back to this instead.
129
+ *
130
+ * Subscribes for the wait rather than calling `ready()`, which both starts the
131
+ * resource without registering a listener (nothing would ever stop its WS fold
132
+ * again) and resolves on the empty seed — see `candleTailFrom`.
133
+ */
134
+ candleTail(id: MarketId, resolution: Resolution, range: TimeRange, timeoutMs?: number): Promise<Bar[]>;
91
135
  orders(account: Address, query?: OrdersQuery): OrderHistory;
92
136
  }
93
137
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,EAAE,QAAQ,EACxF,iBAAiB,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAClG,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAmD,KAAK,QAAQ,EAAE,MAAM,sBAAsB,C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AAC,EAAE,WAAW,GAAG,YAAY;CAI5D"}
package/dist/client.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { PodRestClient } from "./transport/rest.js";
2
2
  import { PodWsClient } from "./transport/ws.js";
3
3
  import { BaseResource, combineResources, derivedResource } from "./stores/resource.js";
4
- import { balancesSource, marketsSource, orderbookSource, positionsSource, statusSource, triggersSource, } from "./sync/sources.js";
5
- import { CandleSeries } from "./sync/candles.js";
4
+ import { balancesSource, bridgeConfigSource, marketsSource, orderbookSource, positionsSource, statusSource, triggersSource, } from "./sync/sources.js";
5
+ import { withdrawalsSource } from "./sync/withdrawals.js";
6
+ import { CandleSeries, candleTailFrom, fetchCandleHistory } from "./sync/candles.js";
6
7
  import { OrderHistory } from "./sync/orders.js";
7
8
  import { enrichPositions } from "./sync/positions-live.js";
8
9
  export class PodTradeClient {
@@ -124,6 +125,28 @@ export class PodTradeClient {
124
125
  balances(account) {
125
126
  return this.memo(`balances:${account}`, () => new BaseResource(balancesSource(this.ctx, account)));
126
127
  }
128
+ /**
129
+ * Static bridge config: the claim chain, and each bridged token's L1 address,
130
+ * decimals and withdraw window (ADR 0033 §5). Everything a client needs to
131
+ * build an admissible withdrawal — see `maxWithdrawable` / `checkWithdrawAmount`.
132
+ *
133
+ * Re-seeded on reconnect rather than fetched once: an operator can change the
134
+ * token set or the limits under a long-lived tab, and a stale window would
135
+ * quietly offer amounts the node now refuses.
136
+ */
137
+ get bridgeConfig() {
138
+ return this.memo("bridgeConfig", () => new BaseResource(bridgeConfigSource(this.ctx)));
139
+ }
140
+ /**
141
+ * This account's terminal withdrawal outcomes, newest first — live off
142
+ * `pod_withdrawals`, gap-filled over REST on every reconnect.
143
+ *
144
+ * Scoped to the **debited** account, which is the master for a delegated
145
+ * withdrawal, so pass the master address rather than the session key.
146
+ */
147
+ withdrawals(account) {
148
+ return this.memo(`withdrawals:${account}`, () => new BaseResource(withdrawalsSource(this.ctx, account)));
149
+ }
127
150
  /** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
128
151
  * `{ limit, offset }`. Not a stream — call again to refresh. */
129
152
  leaderboard(query) {
@@ -149,6 +172,44 @@ export class PodTradeClient {
149
172
  series.setWindow(range);
150
173
  return series;
151
174
  }
175
+ /**
176
+ * Closed bars for a window — a one-shot read, not a live resource.
177
+ *
178
+ * Chart history belongs here rather than on a `CandleSeries`: series are
179
+ * memoised per (market, resolution) and shared with whatever else is watching
180
+ * that market, so a history read that waited on the series' loading state
181
+ * could be resolved by an unrelated load finishing and report "no bars" for a
182
+ * window whose own pages were still in flight. This read owns its request:
183
+ * it resolves with the window's bars or rejects.
184
+ */
185
+ candleHistory(id, resolution, range) {
186
+ return fetchCandleHistory(this.ctx.rest, id, resolution, range);
187
+ }
188
+ /**
189
+ * The bars the live tick fold currently holds inside `range`, the forming
190
+ * bucket included — the other half of `candleHistory`, which can only ever
191
+ * return closed bars because REST withholds the open bucket.
192
+ *
193
+ * A chart asking for a window that reaches "now" on a market whose only
194
+ * activity is in that bucket has no closed history at all, and answering it
195
+ * "no bars" makes the chart latch the range as empty. Both datafeeds fall
196
+ * back to this instead.
197
+ *
198
+ * Subscribes for the wait rather than calling `ready()`, which both starts the
199
+ * resource without registering a listener (nothing would ever stop its WS fold
200
+ * again) and resolves on the empty seed — see `candleTailFrom`.
201
+ */
202
+ async candleTail(id, resolution, range, timeoutMs = 1_500) {
203
+ // No range: this must not call setWindow on a series someone else is live on.
204
+ const series = this.candles(id, resolution);
205
+ const release = series.subscribe(() => { });
206
+ try {
207
+ return await candleTailFrom(series, range, timeoutMs);
208
+ }
209
+ finally {
210
+ release();
211
+ }
212
+ }
152
213
  orders(account, query) {
153
214
  const key = `orders:${account}:${query ? JSON.stringify(query) : ""}`;
154
215
  return this.memo(key, () => new OrderHistory(this.ctx, account, query));
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;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EAAE,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,KAAK,CAAC,UAAU,CACd,EAAY,EACZ,UAAsB,EACtB,KAAgB,EAChB,SAAS,GAAG,KAAK;QAEjB,8EAA8E;QAC9E,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;QAC5C,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC3C,IAAI,CAAC;YACH,OAAO,MAAM,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;QACxD,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;IAED,MAAM,CAAC,OAAgB,EAAE,KAAmB;QAC1C,MAAM,GAAG,GAAG,UAAU,OAAO,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QACtE,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;IAC1E,CAAC;CACF"}
@@ -0,0 +1,82 @@
1
+ import type { Address, BridgeConfig, BridgeToken } from "../types/public.js";
2
+ /**
3
+ * The 18-decimal step a withdrawal of this token must be a multiple of:
4
+ * `10^(18 − decimals)`, or 1 for a token at least as fine as pod (which can
5
+ * represent every 18-decimal amount, so nothing is quantized away).
6
+ */
7
+ export declare function withdrawStep(decimals: number): bigint;
8
+ /** Floor an 18-decimal amount to a whole number of claim-chain units. Never negative. */
9
+ export declare function quantizeWithdrawAmount(amount: bigint, decimals: number): bigint;
10
+ /**
11
+ * Pod's 18 decimals → the token's claim-chain decimals: what the L1 `claim` call
12
+ * carries and what the claim hash commits to.
13
+ *
14
+ * Throws on a remainder rather than truncating, matching the node's admission
15
+ * check — silently flooring here is exactly the dust this design avoids. Use
16
+ * {@link quantizeWithdrawAmount} when rounding down is what you want.
17
+ */
18
+ export declare function toClaimAmount(amount: bigint, decimals: number): bigint;
19
+ /**
20
+ * The claim chain's decimals → pod's 18. Exact by construction: only amounts
21
+ * that were a whole number of claim-chain units are ever admitted, so scaling
22
+ * back up recovers the original.
23
+ */
24
+ export declare function toPodAmount(claimAmount: bigint, decimals: number): bigint;
25
+ /**
26
+ * The largest amount of `balance` that this token's rules actually admit, in
27
+ * pod's 18 decimals: quantized down to a whole claim-chain unit, then clamped
28
+ * into `[min, max]` — which are in claim decimals, so the clamp has to happen
29
+ * after the conversion, not before.
30
+ *
31
+ * `0n` when the balance cannot clear `min`, which is the honest answer: there is
32
+ * no admissible withdrawal at all, and MAX should be disabled rather than
33
+ * offering an amount the node refuses.
34
+ */
35
+ export declare function maxWithdrawable(balance: bigint, token: BridgeToken): bigint;
36
+ /**
37
+ * Why the node would refuse a withdrawal, as a code plus the numbers behind it.
38
+ *
39
+ * A code rather than a sentence: this is a published, framework-agnostic
40
+ * package, so the wording belongs to the consumer that renders it — the same
41
+ * way `WithdrawalError` is a code the app turns into words. Each variant carries
42
+ * exactly the numbers its message needs, so a renderer quotes the real bound
43
+ * without re-deriving it and without defaulting fields that cannot be absent.
44
+ */
45
+ export type WithdrawRejection =
46
+ /** The token is not in the bridge's set, so it has no claim chain at all. */
47
+ {
48
+ code: "not_bridged";
49
+ } | {
50
+ code: "non_positive";
51
+ decimals: number;
52
+ }
53
+ /** `step` is the 18-decimal multiple the amount must be of. */
54
+ | {
55
+ code: "not_representable";
56
+ decimals: number;
57
+ step: bigint;
58
+ }
59
+ /** `bound` is the limit that was crossed, in claim-chain decimals. */
60
+ | {
61
+ code: "below_min" | "above_max";
62
+ decimals: number;
63
+ bound: bigint;
64
+ };
65
+ /**
66
+ * Why the node would refuse this 18-decimal withdrawal, or `undefined` when it
67
+ * is admissible — the same checks `WithdrawRules::check_clob_withdraw` runs, so
68
+ * a client can disable the button and say why instead of discovering it from a
69
+ * revert.
70
+ *
71
+ * Mirroring the node's rules is deliberate and unlike the claim hash, which the
72
+ * ADR insists on fetching: the values here (`decimals`, `min`, `max`) all come
73
+ * from `/v1/bridge/config`, so only the rule *shape* could drift, and a client
74
+ * has to predict admissibility anyway to render MAX and enable the button.
75
+ *
76
+ * A missing `token` is itself a refusal: with no bridge configured for it there
77
+ * is no chain for the withdrawal to be claimed on.
78
+ */
79
+ export declare function checkWithdrawAmount(amount: bigint, token: BridgeToken | undefined): WithdrawRejection | undefined;
80
+ /** The bridge rules for a pod-side token, or undefined when it isn't bridged. */
81
+ export declare function bridgeTokenFor(config: BridgeConfig | undefined, podToken: Address): BridgeToken | undefined;
82
+ //# sourceMappingURL=bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../../src/codec/bridge.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAG7E;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,yFAAyF;AACzF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAI/E;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAWtE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGzE;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,MAAM,CAK3E;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,iBAAiB;AAC3B,6EAA6E;AAC3E;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE;AAC5C,+DAA+D;GAC7D;IAAE,IAAI,EAAE,mBAAmB,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AAC/D,sEAAsE;GACpE;IAAE,IAAI,EAAE,WAAW,GAAG,WAAW,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,WAAW,GAAG,SAAS,GAC7B,iBAAiB,GAAG,SAAS,CAY/B;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAC5B,MAAM,EAAE,YAAY,GAAG,SAAS,EAChC,QAAQ,EAAE,OAAO,GAChB,WAAW,GAAG,SAAS,CAGzB"}
@@ -0,0 +1,114 @@
1
+ // Withdrawal amount arithmetic (ADR 0033 §2), mirroring the node's
2
+ // `WithdrawRules::check_clob_withdraw`.
3
+ //
4
+ // A CLOB withdrawal's `amount` is in pod's 18 decimals, but it settles on the
5
+ // claim chain in that token's decimals — so it has to be a WHOLE number of
6
+ // claim-chain units. The node rejects a remainder at admission rather than
7
+ // truncating it, which removes dust by construction; these helpers exist so a
8
+ // client never offers an amount that will be refused.
9
+ //
10
+ // The case that bites: pod's native USD maps to 6-decimal L1 USDC on devnet, so
11
+ // every native withdrawal must be a multiple of 1e12 wei and the per-token
12
+ // `min`/`max` from `/v1/bridge/config` are in those 6 decimals, not 18. A MAX
13
+ // button that keeps 18 decimals of precision produces amounts the node refuses.
14
+ import { WAD_DECIMALS } from "./units.js";
15
+ /**
16
+ * The 18-decimal step a withdrawal of this token must be a multiple of:
17
+ * `10^(18 − decimals)`, or 1 for a token at least as fine as pod (which can
18
+ * represent every 18-decimal amount, so nothing is quantized away).
19
+ */
20
+ export function withdrawStep(decimals) {
21
+ return decimals >= WAD_DECIMALS ? 1n : 10n ** BigInt(WAD_DECIMALS - decimals);
22
+ }
23
+ /** Floor an 18-decimal amount to a whole number of claim-chain units. Never negative. */
24
+ export function quantizeWithdrawAmount(amount, decimals) {
25
+ if (amount <= 0n)
26
+ return 0n;
27
+ const step = withdrawStep(decimals);
28
+ return (amount / step) * step;
29
+ }
30
+ /**
31
+ * Pod's 18 decimals → the token's claim-chain decimals: what the L1 `claim` call
32
+ * carries and what the claim hash commits to.
33
+ *
34
+ * Throws on a remainder rather than truncating, matching the node's admission
35
+ * check — silently flooring here is exactly the dust this design avoids. Use
36
+ * {@link quantizeWithdrawAmount} when rounding down is what you want.
37
+ */
38
+ export function toClaimAmount(amount, decimals) {
39
+ if (decimals > WAD_DECIMALS)
40
+ return amount * 10n ** BigInt(decimals - WAD_DECIMALS);
41
+ const step = withdrawStep(decimals);
42
+ const remainder = amount % step;
43
+ if (remainder !== 0n) {
44
+ throw new Error(`withdraw amount ${amount} is not exactly representable in ${decimals} decimals ` +
45
+ `(remainder ${remainder}); use a multiple of ${step}`);
46
+ }
47
+ return amount / step;
48
+ }
49
+ /**
50
+ * The claim chain's decimals → pod's 18. Exact by construction: only amounts
51
+ * that were a whole number of claim-chain units are ever admitted, so scaling
52
+ * back up recovers the original.
53
+ */
54
+ export function toPodAmount(claimAmount, decimals) {
55
+ if (decimals > WAD_DECIMALS)
56
+ return claimAmount / 10n ** BigInt(decimals - WAD_DECIMALS);
57
+ return claimAmount * withdrawStep(decimals);
58
+ }
59
+ /**
60
+ * The largest amount of `balance` that this token's rules actually admit, in
61
+ * pod's 18 decimals: quantized down to a whole claim-chain unit, then clamped
62
+ * into `[min, max]` — which are in claim decimals, so the clamp has to happen
63
+ * after the conversion, not before.
64
+ *
65
+ * `0n` when the balance cannot clear `min`, which is the honest answer: there is
66
+ * no admissible withdrawal at all, and MAX should be disabled rather than
67
+ * offering an amount the node refuses.
68
+ */
69
+ export function maxWithdrawable(balance, token) {
70
+ if (balance <= 0n)
71
+ return 0n;
72
+ const claim = toClaimAmount(quantizeWithdrawAmount(balance, token.decimals), token.decimals);
73
+ if (claim < token.min)
74
+ return 0n;
75
+ return toPodAmount(claim > token.max ? token.max : claim, token.decimals);
76
+ }
77
+ /**
78
+ * Why the node would refuse this 18-decimal withdrawal, or `undefined` when it
79
+ * is admissible — the same checks `WithdrawRules::check_clob_withdraw` runs, so
80
+ * a client can disable the button and say why instead of discovering it from a
81
+ * revert.
82
+ *
83
+ * Mirroring the node's rules is deliberate and unlike the claim hash, which the
84
+ * ADR insists on fetching: the values here (`decimals`, `min`, `max`) all come
85
+ * from `/v1/bridge/config`, so only the rule *shape* could drift, and a client
86
+ * has to predict admissibility anyway to render MAX and enable the button.
87
+ *
88
+ * A missing `token` is itself a refusal: with no bridge configured for it there
89
+ * is no chain for the withdrawal to be claimed on.
90
+ */
91
+ export function checkWithdrawAmount(amount, token) {
92
+ if (!token)
93
+ return { code: "not_bridged" };
94
+ const { decimals } = token;
95
+ if (amount <= 0n)
96
+ return { code: "non_positive", decimals };
97
+ const step = withdrawStep(decimals);
98
+ if (amount % step !== 0n)
99
+ return { code: "not_representable", decimals, step };
100
+ // Not `amount / step`: a token finer than pod's 18 scales *up*, so the step
101
+ // is 1 and the division would compare the wrong number against the bounds.
102
+ const claim = toClaimAmount(amount, decimals);
103
+ if (claim < token.min)
104
+ return { code: "below_min", decimals, bound: token.min };
105
+ if (claim > token.max)
106
+ return { code: "above_max", decimals, bound: token.max };
107
+ return undefined;
108
+ }
109
+ /** The bridge rules for a pod-side token, or undefined when it isn't bridged. */
110
+ export function bridgeTokenFor(config, podToken) {
111
+ const want = podToken.toLowerCase();
112
+ return config?.tokens.find((t) => t.podToken.toLowerCase() === want);
113
+ }
114
+ //# sourceMappingURL=bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file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,MAAM,KAAK,GAAG,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC9C,IAAI,KAAK,GAAG,KAAK,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC;IAChF,IAAI,KAAK,GAAG,KAAK,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC;IAChF,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,cAAc,CAC5B,MAAgC,EAChC,QAAiB;IAEjB,MAAM,IAAI,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IACpC,OAAO,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,CAAC;AACvE,CAAC"}
@@ -1,5 +1,5 @@
1
- import type { Bar, BackstopTransfer, Balances, LeaderboardPage, Market, Order, Orderbook, PositionsSnapshot, SpotHolding, Status, Trigger } from "../types/public.js";
2
- import type { WireBackstopTransfer, WireBalances, WireCandle, WireLeaderboard, WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePositionsSnapshot, WireSpotHolding, WireStatus, WireTrigger } from "../types/wire.js";
1
+ import type { Bar, BackstopTransfer, Balances, BridgeConfig, LeaderboardPage, Market, Order, Orderbook, PositionsSnapshot, SpotHolding, Status, Trigger, Withdrawal } from "../types/public.js";
2
+ import type { WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle, WireLeaderboard, WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePositionsSnapshot, WireSpotHolding, WireStatus, WireTrigger, WireWithdrawal } from "../types/wire.js";
3
3
  export declare function decodeStatus(w: WireStatus): Status;
4
4
  /** Static market identity. Dynamics are merged in later by the market store. */
5
5
  export declare function decodeMarketStatic(w: WireMarketStatic): Market;
@@ -19,4 +19,17 @@ export declare function decodeBalances(w: WireBalances): Balances;
19
19
  export declare function decodeLeaderboard(w: WireLeaderboard, offset?: number): LeaderboardPage;
20
20
  export declare function decodeTrigger(w: WireTrigger): Trigger;
21
21
  export declare function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfer;
22
+ export declare function decodeBridgeConfig(w: WireBridgeConfig): BridgeConfig;
23
+ /**
24
+ * One withdrawal outcome.
25
+ *
26
+ * An unrecognised `error` spelling is carried through **verbatim**, never
27
+ * dropped. The node's reason enum is extensible and this app ships ahead of the
28
+ * fleet, so filtering to the spellings this build knows would turn a *failed*
29
+ * withdrawal into a claimable-looking one: the caller announces that the money
30
+ * is on its way and then waits for an L1 event that can never fire. Presence is
31
+ * what carries the meaning here — any reason at all means no claim — so only
32
+ * presence is decoded, and naming the reason is left to whatever renders it.
33
+ */
34
+ export declare function decodeWithdrawal(w: WireWithdrawal): Withdrawal;
22
35
  //# sourceMappingURL=decode.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../../src/codec/decode.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,GAAG,EAAE,gBAAgB,EAAE,QAAQ,EAAoB,eAAe,EAAE,MAAM,EAAE,KAAK,EACjF,SAAS,EAAuC,iBAAiB,EAAE,WAAW,EAChE,MAAM,EAAE,OAAO,EAC9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,oBAAoB,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,kBAAkB,EACnF,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAC1C,qBAAqB,EAAE,eAAe,EAAoB,UAAU,EAAE,WAAW,EAClF,MAAM,kBAAkB,CAAC;AAG1B,wBAAgB,YAAY,CAAC,CAAC,EAAE,UAAU,GAAG,MAAM,CAElD;AAED,gFAAgF;AAChF,wB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250
250
  };
251
251
  }
252
+ export function decodeBridgeConfig(w) {
253
+ return {
254
+ claimChainId: w.claim_chain_id,
255
+ sourceContract: w.source_contract,
256
+ version: w.version,
257
+ tokens: w.tokens.map((t) => ({
258
+ podToken: t.pod_token,
259
+ l1Token: t.l1_token,
260
+ decimals: t.decimals,
261
+ min: dec(t.min),
262
+ max: dec(t.max),
263
+ })),
264
+ };
265
+ }
266
+ /**
267
+ * One withdrawal outcome.
268
+ *
269
+ * An unrecognised `error` spelling is carried through **verbatim**, never
270
+ * dropped. The node's reason enum is extensible and this app ships ahead of the
271
+ * fleet, so filtering to the spellings this build knows would turn a *failed*
272
+ * withdrawal into a claimable-looking one: the caller announces that the money
273
+ * is on its way and then waits for an L1 event that can never fire. Presence is
274
+ * what carries the meaning here — any reason at all means no claim — so only
275
+ * presence is decoded, and naming the reason is left to whatever renders it.
276
+ */
277
+ export function decodeWithdrawal(w) {
278
+ return {
279
+ id: w.withdrawal_id,
280
+ withdrawer: w.withdrawer,
281
+ to: w.to,
282
+ token: w.token,
283
+ amount: dec(w.amount),
284
+ // `||`, not `??`: an empty string is the wire saying "no reason", and it
285
+ // would otherwise be a present-but-falsy value that every `if (w.error)`
286
+ // reads as success while `error !== undefined` reads as failure.
287
+ error: w.error || undefined,
288
+ timeUs: w.timestamp_us,
289
+ };
290
+ }
252
291
  //# sourceMappingURL=decode.js.map