@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.
- package/README.md +94 -2
- package/dist/client.d.ts +19 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +24 -1
- package/dist/client.js.map +1 -1
- package/dist/codec/bridge.d.ts +82 -0
- package/dist/codec/bridge.d.ts.map +1 -0
- package/dist/codec/bridge.js +114 -0
- package/dist/codec/bridge.js.map +1 -0
- package/dist/codec/decode.d.ts +15 -2
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +39 -0
- package/dist/codec/decode.js.map +1 -1
- package/dist/codec/units.d.ts.map +1 -1
- package/dist/codec/units.js +9 -1
- package/dist/codec/units.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/sync/sources.d.ts +5 -1
- package/dist/sync/sources.d.ts.map +1 -1
- package/dist/sync/sources.js +16 -0
- package/dist/sync/sources.js.map +1 -1
- package/dist/sync/withdrawals.d.ts +5 -0
- package/dist/sync/withdrawals.d.ts.map +1 -0
- package/dist/sync/withdrawals.js +172 -0
- package/dist/sync/withdrawals.js.map +1 -0
- package/dist/transport/claim.d.ts +160 -0
- package/dist/transport/claim.d.ts.map +1 -0
- package/dist/transport/claim.js +341 -0
- package/dist/transport/claim.js.map +1 -0
- package/dist/transport/jsonrpc.d.ts +16 -0
- package/dist/transport/jsonrpc.d.ts.map +1 -0
- package/dist/transport/jsonrpc.js +42 -0
- package/dist/transport/jsonrpc.js.map +1 -0
- package/dist/transport/rest.d.ts +15 -1
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +25 -1
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/ws.d.ts +4 -1
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +87 -0
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +43 -1
- package/dist/types/wire.d.ts.map +1 -1
- package/dist/write/delegation.d.ts.map +1 -1
- package/dist/write/delegation.js +2 -12
- package/dist/write/delegation.js.map +1 -1
- package/dist/write/index.d.ts +25 -0
- package/dist/write/index.d.ts.map +1 -1
- package/dist/write/index.js +20 -13
- package/dist/write/index.js.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +32 -4
- package/src/codec/bridge.ts +138 -0
- package/src/codec/decode.ts +47 -4
- package/src/codec/units.ts +8 -1
- package/src/index.ts +16 -0
- package/src/sync/sources.ts +16 -1
- package/src/sync/withdrawals.ts +177 -0
- package/src/transport/claim.ts +434 -0
- package/src/transport/jsonrpc.ts +54 -0
- package/src/transport/rest.ts +35 -7
- package/src/transport/ws.ts +4 -1
- package/src/types/public.ts +94 -0
- package/src/types/wire.ts +47 -1
- package/src/write/delegation.ts +2 -12
- package/src/write/index.ts +58 -12
|
@@ -0,0 +1,138 @@
|
|
|
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
|
+
|
|
15
|
+
import type { Address, BridgeConfig, BridgeToken } from "../types/public.js";
|
|
16
|
+
import { WAD_DECIMALS } from "./units.js";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The 18-decimal step a withdrawal of this token must be a multiple of:
|
|
20
|
+
* `10^(18 − decimals)`, or 1 for a token at least as fine as pod (which can
|
|
21
|
+
* represent every 18-decimal amount, so nothing is quantized away).
|
|
22
|
+
*/
|
|
23
|
+
export function withdrawStep(decimals: number): bigint {
|
|
24
|
+
return decimals >= WAD_DECIMALS ? 1n : 10n ** BigInt(WAD_DECIMALS - decimals);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Floor an 18-decimal amount to a whole number of claim-chain units. Never negative. */
|
|
28
|
+
export function quantizeWithdrawAmount(amount: bigint, decimals: number): bigint {
|
|
29
|
+
if (amount <= 0n) return 0n;
|
|
30
|
+
const step = withdrawStep(decimals);
|
|
31
|
+
return (amount / step) * step;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Pod's 18 decimals → the token's claim-chain decimals: what the L1 `claim` call
|
|
36
|
+
* carries and what the claim hash commits to.
|
|
37
|
+
*
|
|
38
|
+
* Throws on a remainder rather than truncating, matching the node's admission
|
|
39
|
+
* check — silently flooring here is exactly the dust this design avoids. Use
|
|
40
|
+
* {@link quantizeWithdrawAmount} when rounding down is what you want.
|
|
41
|
+
*/
|
|
42
|
+
export function toClaimAmount(amount: bigint, decimals: number): bigint {
|
|
43
|
+
if (decimals > WAD_DECIMALS) return amount * 10n ** BigInt(decimals - WAD_DECIMALS);
|
|
44
|
+
const step = withdrawStep(decimals);
|
|
45
|
+
const remainder = amount % step;
|
|
46
|
+
if (remainder !== 0n) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`withdraw amount ${amount} is not exactly representable in ${decimals} decimals ` +
|
|
49
|
+
`(remainder ${remainder}); use a multiple of ${step}`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return amount / step;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The claim chain's decimals → pod's 18. Exact by construction: only amounts
|
|
57
|
+
* that were a whole number of claim-chain units are ever admitted, so scaling
|
|
58
|
+
* back up recovers the original.
|
|
59
|
+
*/
|
|
60
|
+
export function toPodAmount(claimAmount: bigint, decimals: number): bigint {
|
|
61
|
+
if (decimals > WAD_DECIMALS) return claimAmount / 10n ** BigInt(decimals - WAD_DECIMALS);
|
|
62
|
+
return claimAmount * withdrawStep(decimals);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The largest amount of `balance` that this token's rules actually admit, in
|
|
67
|
+
* pod's 18 decimals: quantized down to a whole claim-chain unit, then clamped
|
|
68
|
+
* into `[min, max]` — which are in claim decimals, so the clamp has to happen
|
|
69
|
+
* after the conversion, not before.
|
|
70
|
+
*
|
|
71
|
+
* `0n` when the balance cannot clear `min`, which is the honest answer: there is
|
|
72
|
+
* no admissible withdrawal at all, and MAX should be disabled rather than
|
|
73
|
+
* offering an amount the node refuses.
|
|
74
|
+
*/
|
|
75
|
+
export function maxWithdrawable(balance: bigint, token: BridgeToken): bigint {
|
|
76
|
+
if (balance <= 0n) return 0n;
|
|
77
|
+
const claim = toClaimAmount(quantizeWithdrawAmount(balance, token.decimals), token.decimals);
|
|
78
|
+
if (claim < token.min) return 0n;
|
|
79
|
+
return toPodAmount(claim > token.max ? token.max : claim, token.decimals);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Why the node would refuse a withdrawal, as a code plus the numbers behind it.
|
|
84
|
+
*
|
|
85
|
+
* A code rather than a sentence: this is a published, framework-agnostic
|
|
86
|
+
* package, so the wording belongs to the consumer that renders it — the same
|
|
87
|
+
* way `WithdrawalError` is a code the app turns into words. Each variant carries
|
|
88
|
+
* exactly the numbers its message needs, so a renderer quotes the real bound
|
|
89
|
+
* without re-deriving it and without defaulting fields that cannot be absent.
|
|
90
|
+
*/
|
|
91
|
+
export type WithdrawRejection =
|
|
92
|
+
/** The token is not in the bridge's set, so it has no claim chain at all. */
|
|
93
|
+
| { code: "not_bridged" }
|
|
94
|
+
| { code: "non_positive"; decimals: number }
|
|
95
|
+
/** `step` is the 18-decimal multiple the amount must be of. */
|
|
96
|
+
| { code: "not_representable"; decimals: number; step: bigint }
|
|
97
|
+
/** `bound` is the limit that was crossed, in claim-chain decimals. */
|
|
98
|
+
| { code: "below_min" | "above_max"; decimals: number; bound: bigint };
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Why the node would refuse this 18-decimal withdrawal, or `undefined` when it
|
|
102
|
+
* is admissible — the same checks `WithdrawRules::check_clob_withdraw` runs, so
|
|
103
|
+
* a client can disable the button and say why instead of discovering it from a
|
|
104
|
+
* revert.
|
|
105
|
+
*
|
|
106
|
+
* Mirroring the node's rules is deliberate and unlike the claim hash, which the
|
|
107
|
+
* ADR insists on fetching: the values here (`decimals`, `min`, `max`) all come
|
|
108
|
+
* from `/v1/bridge/config`, so only the rule *shape* could drift, and a client
|
|
109
|
+
* has to predict admissibility anyway to render MAX and enable the button.
|
|
110
|
+
*
|
|
111
|
+
* A missing `token` is itself a refusal: with no bridge configured for it there
|
|
112
|
+
* is no chain for the withdrawal to be claimed on.
|
|
113
|
+
*/
|
|
114
|
+
export function checkWithdrawAmount(
|
|
115
|
+
amount: bigint,
|
|
116
|
+
token: BridgeToken | undefined,
|
|
117
|
+
): WithdrawRejection | undefined {
|
|
118
|
+
if (!token) return { code: "not_bridged" };
|
|
119
|
+
const { decimals } = token;
|
|
120
|
+
if (amount <= 0n) return { code: "non_positive", decimals };
|
|
121
|
+
const step = withdrawStep(decimals);
|
|
122
|
+
if (amount % step !== 0n) return { code: "not_representable", decimals, step };
|
|
123
|
+
// Not `amount / step`: a token finer than pod's 18 scales *up*, so the step
|
|
124
|
+
// is 1 and the division would compare the wrong number against the bounds.
|
|
125
|
+
const claim = toClaimAmount(amount, decimals);
|
|
126
|
+
if (claim < token.min) return { code: "below_min", decimals, bound: token.min };
|
|
127
|
+
if (claim > token.max) return { code: "above_max", decimals, bound: token.max };
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The bridge rules for a pod-side token, or undefined when it isn't bridged. */
|
|
132
|
+
export function bridgeTokenFor(
|
|
133
|
+
config: BridgeConfig | undefined,
|
|
134
|
+
podToken: Address,
|
|
135
|
+
): BridgeToken | undefined {
|
|
136
|
+
const want = podToken.toLowerCase();
|
|
137
|
+
return config?.tokens.find((t) => t.podToken.toLowerCase() === want);
|
|
138
|
+
}
|
package/src/codec/decode.ts
CHANGED
|
@@ -2,14 +2,16 @@
|
|
|
2
2
|
// representations are normalized into bigint + millisecond numbers.
|
|
3
3
|
|
|
4
4
|
import type {
|
|
5
|
-
Bar, BackstopTransfer, Balances, LeaderboardEntry, LeaderboardPage, Market, Order,
|
|
5
|
+
Bar, BackstopTransfer, Balances, BridgeConfig, LeaderboardEntry, LeaderboardPage, Market, Order,
|
|
6
6
|
Orderbook, PartialFill, PerpPosition, Position, PositionsSnapshot, SpotHolding,
|
|
7
7
|
SpotPosition, Status, Trigger, MarketType, OrderDirection, OrderKind, OrderStatus, TriggerType,
|
|
8
|
+
Withdrawal,
|
|
8
9
|
} from "../types/public.js";
|
|
9
10
|
import type {
|
|
10
|
-
WireBackstopTransfer, WireBalances, WireCandle, WireLeaderboard,
|
|
11
|
-
WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill,
|
|
12
|
-
|
|
11
|
+
WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle, WireLeaderboard,
|
|
12
|
+
WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill,
|
|
13
|
+
WirePerpPosition, WirePosition, WirePositionsSnapshot, WireSpotHolding, WireSpotPosition,
|
|
14
|
+
WireStatus, WireTrigger, WireWithdrawal,
|
|
13
15
|
} from "../types/wire.js";
|
|
14
16
|
import { dec, decOpt, endMsFromUs, toNumber, usToMs, usToMsOpt } from "./units.js";
|
|
15
17
|
|
|
@@ -276,3 +278,44 @@ export function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfe
|
|
|
276
278
|
time: usToMs(w.timestamp_us),
|
|
277
279
|
};
|
|
278
280
|
}
|
|
281
|
+
|
|
282
|
+
export function decodeBridgeConfig(w: WireBridgeConfig): BridgeConfig {
|
|
283
|
+
return {
|
|
284
|
+
claimChainId: w.claim_chain_id,
|
|
285
|
+
sourceContract: w.source_contract,
|
|
286
|
+
version: w.version,
|
|
287
|
+
tokens: w.tokens.map((t) => ({
|
|
288
|
+
podToken: t.pod_token,
|
|
289
|
+
l1Token: t.l1_token,
|
|
290
|
+
decimals: t.decimals,
|
|
291
|
+
min: dec(t.min),
|
|
292
|
+
max: dec(t.max),
|
|
293
|
+
})),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* One withdrawal outcome.
|
|
299
|
+
*
|
|
300
|
+
* An unrecognised `error` spelling is carried through **verbatim**, never
|
|
301
|
+
* dropped. The node's reason enum is extensible and this app ships ahead of the
|
|
302
|
+
* fleet, so filtering to the spellings this build knows would turn a *failed*
|
|
303
|
+
* withdrawal into a claimable-looking one: the caller announces that the money
|
|
304
|
+
* is on its way and then waits for an L1 event that can never fire. Presence is
|
|
305
|
+
* what carries the meaning here — any reason at all means no claim — so only
|
|
306
|
+
* presence is decoded, and naming the reason is left to whatever renders it.
|
|
307
|
+
*/
|
|
308
|
+
export function decodeWithdrawal(w: WireWithdrawal): Withdrawal {
|
|
309
|
+
return {
|
|
310
|
+
id: w.withdrawal_id,
|
|
311
|
+
withdrawer: w.withdrawer,
|
|
312
|
+
to: w.to,
|
|
313
|
+
token: w.token,
|
|
314
|
+
amount: dec(w.amount),
|
|
315
|
+
// `||`, not `??`: an empty string is the wire saying "no reason", and it
|
|
316
|
+
// would otherwise be a present-but-falsy value that every `if (w.error)`
|
|
317
|
+
// reads as success while `error !== undefined` reads as failure.
|
|
318
|
+
error: w.error || undefined,
|
|
319
|
+
timeUs: w.timestamp_us,
|
|
320
|
+
};
|
|
321
|
+
}
|
package/src/codec/units.ts
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
// strings; wire timestamps are microseconds. Public surface uses `bigint`
|
|
3
3
|
// (1e18-scaled) and millisecond `number` timestamps.
|
|
4
4
|
|
|
5
|
+
// "wad" is the DappHub/MakerDAO name for a fixed-point number carrying 18
|
|
6
|
+
// digits of precision, which is the scale every pod amount is in. Spelled out
|
|
7
|
+
// because the term is only obvious if you have met it before, and code that
|
|
8
|
+
// mixes scales — bridge withdrawals settle in the claim-chain token's decimals,
|
|
9
|
+
// not pod's — reads very differently depending on whether you know that.
|
|
5
10
|
export const WAD = 1_000_000_000_000_000_000n; // 1e18
|
|
6
11
|
export const WAD_DECIMALS = 18;
|
|
7
12
|
|
|
@@ -110,7 +115,9 @@ export function parseAmount(value: string, decimals: number = WAD_DECIMALS): big
|
|
|
110
115
|
const neg = value.trim().startsWith("-");
|
|
111
116
|
const clean = neg ? value.trim().slice(1) : value.trim();
|
|
112
117
|
const [whole = "0", frac = ""] = clean.split(".");
|
|
118
|
+
if (whole === "" && frac === "") throw new SyntaxError("Cannot convert empty amount to a BigInt");
|
|
113
119
|
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
114
|
-
const
|
|
120
|
+
const wholePart = whole === "" && frac !== "" ? "0" : whole;
|
|
121
|
+
const scaled = BigInt(wholePart) * 10n ** BigInt(decimals) + BigInt(fracPadded || "0");
|
|
115
122
|
return neg ? -scaled : scaled;
|
|
116
123
|
}
|
package/src/index.ts
CHANGED
|
@@ -47,3 +47,19 @@ export {
|
|
|
47
47
|
export {
|
|
48
48
|
RESOLUTION_SECONDS, RESOLUTION_PAGE_BUCKETS, RESOLUTIONS, isResolution,
|
|
49
49
|
} from "./codec/resolution.js";
|
|
50
|
+
|
|
51
|
+
// Withdrawal amount arithmetic (ADR 0033). Read-side, so a UI can size and
|
|
52
|
+
// validate a withdrawal without pulling the signing entry.
|
|
53
|
+
export {
|
|
54
|
+
withdrawStep, quantizeWithdrawAmount, toClaimAmount, toPodAmount,
|
|
55
|
+
maxWithdrawable, checkWithdrawAmount, type WithdrawRejection, bridgeTokenFor,
|
|
56
|
+
} from "./codec/bridge.js";
|
|
57
|
+
// Following a withdrawal onto the claim chain.
|
|
58
|
+
export {
|
|
59
|
+
fetchClaimStatus, waitForClaim, watchClaims, CLAIM_TOPIC,
|
|
60
|
+
type ClaimStatus, type ClaimOutcome, type WaitForClaimOptions,
|
|
61
|
+
type ClaimWatcher, type WatchClaimsOptions,
|
|
62
|
+
} from "./transport/claim.js";
|
|
63
|
+
// Only the options type: `WaitForClaimOptions` extends it, so declaration emit
|
|
64
|
+
// needs it public. The functions themselves stay internal.
|
|
65
|
+
export type { RpcOptions } from "./transport/jsonrpc.js";
|
package/src/sync/sources.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// REST re-seed via `onError` when `since` is too old (down too long).
|
|
15
15
|
|
|
16
16
|
import type {
|
|
17
|
-
Address, Balances, Market, MarketId, Orderbook, PositionsSnapshot, Status, Trigger,
|
|
17
|
+
Address, Balances, BridgeConfig, Market, MarketId, Orderbook, PositionsSnapshot, Status, Trigger,
|
|
18
18
|
} from "../types/public.js";
|
|
19
19
|
import type {
|
|
20
20
|
WireMarketDynamics, WireOrderbook, WirePositionsPush, WireTriggersPush,
|
|
@@ -84,6 +84,21 @@ export function statusSource({ rest, ws }: SyncContext): ResourceSource<Status>
|
|
|
84
84
|
};
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Static bridge config (ADR 0033 §5). Re-seeded on reconnect because an
|
|
88
|
+
* operator can change the token set or the withdraw limits under a long-lived
|
|
89
|
+
* tab, and a stale window would offer amounts the node now refuses. */
|
|
90
|
+
export function bridgeConfigSource({ rest, ws }: SyncContext): ResourceSource<BridgeConfig> {
|
|
91
|
+
return (h) => {
|
|
92
|
+
let alive = true;
|
|
93
|
+
const off = seedNowAndOnReconnect(ws, () => {
|
|
94
|
+
rest.bridgeConfig()
|
|
95
|
+
.then((c) => { if (alive) h.set(c); })
|
|
96
|
+
.catch((e) => { if (!h.current()) h.fail(e as Error); });
|
|
97
|
+
});
|
|
98
|
+
return () => { alive = false; off(); };
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
87
102
|
export function marketsSource(
|
|
88
103
|
{ rest, ws, marketResyncMs, marketsCache }: SyncContext,
|
|
89
104
|
): ResourceSource<Market[]> {
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Terminal withdrawal outcomes for one account (ADR 0033 §6): seeded and
|
|
2
|
+
// gap-filled over `GET /v1/bridge/withdrawals/{account}`, kept live by the
|
|
3
|
+
// `pod_withdrawals` subscription.
|
|
4
|
+
//
|
|
5
|
+
// The two surfaces serve the identical shape, so a backfilled outcome is
|
|
6
|
+
// indistinguishable from one that arrived live — which is what lets a reconnect
|
|
7
|
+
// be a plain "fetch the gap" rather than a separate code path.
|
|
8
|
+
//
|
|
9
|
+
// Outcomes are terminal and immutable: an id appears once and never changes, so
|
|
10
|
+
// merging is last-write-wins on the id with no reconciliation.
|
|
11
|
+
|
|
12
|
+
import type { Address, Withdrawal } from "../types/public.js";
|
|
13
|
+
import type { WireWithdrawal } from "../types/wire.js";
|
|
14
|
+
import { decodeWithdrawal } from "../codec/decode.js";
|
|
15
|
+
import type { ResourceSource } from "../stores/resource.js";
|
|
16
|
+
import { seedNowAndOnReconnect, type SyncContext } from "./sources.js";
|
|
17
|
+
|
|
18
|
+
/** Page size for the backfill. The server caps at 1000 and defaults to 500. */
|
|
19
|
+
const PAGE_LIMIT = 500;
|
|
20
|
+
|
|
21
|
+
/** Pages to walk in one backfill before giving up, so a bad cursor can't spin
|
|
22
|
+
* forever. 50 pages × 500 covers 25k outcomes — far past any real account. */
|
|
23
|
+
const MAX_PAGES = 50;
|
|
24
|
+
|
|
25
|
+
/** Resubscribe attempts after a rejection before leaving the channel alone.
|
|
26
|
+
* Reached only when the rejection is permanent — see the `onError` comment. */
|
|
27
|
+
const MAX_SUB_RETRIES = 5;
|
|
28
|
+
|
|
29
|
+
export function withdrawalsSource(
|
|
30
|
+
{ rest, ws }: SyncContext,
|
|
31
|
+
account: Address,
|
|
32
|
+
): ResourceSource<Withdrawal[]> {
|
|
33
|
+
return (h) => {
|
|
34
|
+
let alive = true;
|
|
35
|
+
const byId = new Map<string, Withdrawal>();
|
|
36
|
+
// Cursor into the outcome log: the newest tick fully absorbed, plus the last
|
|
37
|
+
// id seen inside it. Both are needed because one tick can span a page — the
|
|
38
|
+
// deadline alone can only re-serve the tick's earlier rows or skip its later
|
|
39
|
+
// ones.
|
|
40
|
+
let sinceUs = 0;
|
|
41
|
+
let sinceId: Withdrawal["id"] | undefined;
|
|
42
|
+
let retries = 0;
|
|
43
|
+
let retryTimer: ReturnType<typeof setTimeout> | undefined;
|
|
44
|
+
|
|
45
|
+
const publish = () => {
|
|
46
|
+
// Newest first: a user reads their most recent withdrawal at the top, and
|
|
47
|
+
// the id tiebreak keeps a same-tick pair from reordering between renders.
|
|
48
|
+
h.set([...byId.values()].sort((a, b) => b.timeUs - a.timeUs || b.id.localeCompare(a.id)));
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const absorb = (items: Withdrawal[]) => {
|
|
52
|
+
for (const w of items) {
|
|
53
|
+
byId.set(w.id, w);
|
|
54
|
+
// Never move the cursor backwards: an out-of-order arrival would
|
|
55
|
+
// otherwise re-serve ticks we already hold.
|
|
56
|
+
if (w.timeUs >= sinceUs) { sinceUs = w.timeUs; sinceId = w.id; }
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Walk forward from the cursor until the log is exhausted.
|
|
62
|
+
*
|
|
63
|
+
* Serialised on `inflight` because two callers race by construction: the
|
|
64
|
+
* immediate seed and the socket's `open` overlap on a cold start, and a
|
|
65
|
+
* reconnect can fire while a retry's backfill is still paging. Both share
|
|
66
|
+
* the cursor, so concurrent loops would re-request each other's pages.
|
|
67
|
+
*/
|
|
68
|
+
let inflight: Promise<void> | undefined;
|
|
69
|
+
const backfill = (): Promise<void> => (inflight ??= run().finally(() => { inflight = undefined; }));
|
|
70
|
+
|
|
71
|
+
const run = async () => {
|
|
72
|
+
try {
|
|
73
|
+
// Page against a cursor local to this run. The shared one is also moved
|
|
74
|
+
// by live pushes, and a push landing mid-backfill would jump the next
|
|
75
|
+
// page past the rest of an older tick — rows the forward-only cursor
|
|
76
|
+
// could then never come back for.
|
|
77
|
+
let pageSince = sinceUs;
|
|
78
|
+
let pageSinceId = sinceId;
|
|
79
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
80
|
+
const rows = await rest.bridgeWithdrawals(account, {
|
|
81
|
+
since: pageSince,
|
|
82
|
+
sinceId: pageSinceId,
|
|
83
|
+
limit: PAGE_LIMIT,
|
|
84
|
+
});
|
|
85
|
+
if (!alive) return;
|
|
86
|
+
if (rows.length === 0) break;
|
|
87
|
+
absorb(rows);
|
|
88
|
+
// Rows come back ascending, so the last one is this page's high-water
|
|
89
|
+
// mark — regardless of what the stream did to the shared cursor.
|
|
90
|
+
// Non-empty by the check above.
|
|
91
|
+
const last = rows[rows.length - 1]!;
|
|
92
|
+
pageSince = last.timeUs;
|
|
93
|
+
pageSinceId = last.id;
|
|
94
|
+
if (rows.length < PAGE_LIMIT) break;
|
|
95
|
+
}
|
|
96
|
+
// Once, after paging: publishing per page re-copies and re-sorts
|
|
97
|
+
// everything accumulated so far for a list the user sees for
|
|
98
|
+
// milliseconds — O(pages²) on exactly the accounts paging exists for.
|
|
99
|
+
//
|
|
100
|
+
// Unconditional, including when nothing was found. An account with no
|
|
101
|
+
// withdrawals must still reach a defined `[]`, or every consumer stays
|
|
102
|
+
// on "not loaded yet" and treats the first live outcome as its initial
|
|
103
|
+
// snapshot — silently swallowing a user's first-ever withdrawal.
|
|
104
|
+
publish();
|
|
105
|
+
} catch (e) {
|
|
106
|
+
// Publish on the failure path too, for exactly the reason the success
|
|
107
|
+
// path publishes unconditionally: a consumer left on "not loaded yet"
|
|
108
|
+
// treats the first live outcome as its initial snapshot and swallows it.
|
|
109
|
+
// A failed backfill is a reason to have no history — not a reason to
|
|
110
|
+
// misread the next thing that happens. `fail` records the error beside
|
|
111
|
+
// the value rather than replacing it, so a caller can read both.
|
|
112
|
+
publish();
|
|
113
|
+
// Only surface the failure when there is nothing to show; otherwise the
|
|
114
|
+
// stream is still feeding a usable list and a toast would be noise.
|
|
115
|
+
if (byId.size === 0) h.fail(e as Error);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const sub = ws.subscribe(
|
|
120
|
+
"pod_withdrawals",
|
|
121
|
+
// Live-only until a cursor exists. This is a replay channel, so the server
|
|
122
|
+
// accepts `since` only when its buffer still reaches back that far — and
|
|
123
|
+
// `since: 0` never does, so sending it would fail the subscribe every time
|
|
124
|
+
// and burn the retry budget below on a self-inflicted rejection. (The
|
|
125
|
+
// `since: 0` idiom belongs to the *state* channels, which answer it with a
|
|
126
|
+
// snapshot.) REST backfill covers history either way.
|
|
127
|
+
{ account },
|
|
128
|
+
(result) => {
|
|
129
|
+
retries = 0;
|
|
130
|
+
// A frame means the subscription is healthy, so a retry armed by an
|
|
131
|
+
// earlier rejection has nothing left to fix. Letting it fire would call
|
|
132
|
+
// `resubscribe()` on a live subscription, which drops the server's id
|
|
133
|
+
// without an `eth_unsubscribe` and leaks one subscription per occurrence.
|
|
134
|
+
if (retryTimer) { clearTimeout(retryTimer); retryTimer = undefined; }
|
|
135
|
+
// One message per tick carrying that tick's outcomes for this account.
|
|
136
|
+
absorb((result as WireWithdrawal[]).map(decodeWithdrawal));
|
|
137
|
+
publish();
|
|
138
|
+
sub.update({ since: sinceUs }); // keep the resume point fresh for a reconnect
|
|
139
|
+
},
|
|
140
|
+
() => {
|
|
141
|
+
// Rejected — usually a `since` older than the replay buffer. Back off,
|
|
142
|
+
// re-seed over REST (which has no such horizon), and resubscribe; after
|
|
143
|
+
// a couple of failures drop `since` and settle for live-only.
|
|
144
|
+
//
|
|
145
|
+
// Bounded, because the other reason for a rejection is a node that
|
|
146
|
+
// doesn't serve this channel at all — an older build, since the app
|
|
147
|
+
// ships ahead of the fleet. Retrying that forever is a request every
|
|
148
|
+
// 30s for the lifetime of the tab, so give up and leave the REST-seeded
|
|
149
|
+
// list in place rather than polling a node that will never answer.
|
|
150
|
+
if (!alive || retries >= MAX_SUB_RETRIES) return;
|
|
151
|
+
retries++;
|
|
152
|
+
if (retryTimer) clearTimeout(retryTimer);
|
|
153
|
+
retryTimer = setTimeout(() => {
|
|
154
|
+
void backfill().then(() => {
|
|
155
|
+
if (!alive) return;
|
|
156
|
+
// Live-only until a real cursor exists (see the subscribe above), and
|
|
157
|
+
// dropped again after a couple of failures in case the replay buffer
|
|
158
|
+
// has outrun it.
|
|
159
|
+
sub.update({ since: retries > 2 || sinceUs === 0 ? undefined : sinceUs });
|
|
160
|
+
sub.resubscribe();
|
|
161
|
+
});
|
|
162
|
+
}, Math.min(30_000, 500 * 2 ** (retries - 1)));
|
|
163
|
+
},
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
// Seed immediately — REST needs no socket, so history paints without waiting
|
|
167
|
+
// on the handshake — and fill the gap again on every reconnect.
|
|
168
|
+
const offOpen = seedNowAndOnReconnect(ws, () => { if (alive) void backfill(); });
|
|
169
|
+
|
|
170
|
+
return () => {
|
|
171
|
+
alive = false;
|
|
172
|
+
offOpen();
|
|
173
|
+
if (retryTimer) clearTimeout(retryTimer);
|
|
174
|
+
sub.unsubscribe();
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
}
|