@blockrun/franklin 3.36.0 → 3.38.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.
@@ -1,29 +1,67 @@
1
1
  // src/utils/polymarket/redeem.ts
2
2
  //
3
3
  // Claim winnings for a resolved market. Burns the ERC-1155 outcome tokens and
4
- // credits collateral back to the funds wallet:
4
+ // credits pUSD back to the funds wallet:
5
5
  // - POLY_1271: a gasless relayer WALLET batch executed BY the deposit wallet
6
- // (redeemPositions credits msg.sender, i.e. the deposit wallet).
6
+ // (the adapter credits msg.sender, i.e. the deposit wallet).
7
7
  // - EOA mode: a direct transaction from the EOA (needs POL gas).
8
8
  //
9
- // Target contracts:
10
- // - standard binary markets → ConditionalTokens.redeemPositions(collateral,
11
- // 0x0, conditionId, [1, 2])
12
- // - negRisk markets → NegRiskAdapter.redeemPositions(conditionId, [yesAmt,
13
- // noAmt]) (adapter must be CTF-approved — done in setup)
14
- //
15
- // Collateral note: V2-era conditions settle in pUSD; conditions prepared
16
- // before the 2026-04-28 cutover may use legacy USDC.e collateral, in which
17
- // case the standard redeem with pUSD reverts — the error message says so and
18
- // the relayer batch simply fails without side effects.
9
+ // Target contracts — ALWAYS the pUSD collateral adapters, NEVER the CTF or the
10
+ // legacy NegRiskAdapter directly. CTF positions (the CLOB token_ids) are still
11
+ // keyed to USDC.e (standard) / the legacy adapter's wrapped collateral
12
+ // (neg-risk); a direct CTF redeem with pUSD collateral computes a positionId
13
+ // nobody holds and SUCCEEDS redeeming 0 — success + tx hash, zero payout (the
14
+ // bug behind data-api "REDEEM size=0" reports). The adapters pull the caller's
15
+ // outcome tokens (one-time CTF operator approval, granted in setup), redeem
16
+ // through the right underlying path, wrap the USDC.e payout into pUSD, and
17
+ // return pUSD to the caller:
18
+ // - standard binary markets → CtfCollateralAdapter.redeemPositions(...)
19
+ // - negRisk markets → NegRiskCtfCollateralAdapter.redeemPositions(...)
20
+ // Both mirror the CTF redeemPositions(collateral, parent, conditionId,
21
+ // indexSets) signature; only conditionId is read — the adapter derives the
22
+ // position ids and amounts (full caller balance) itself.
19
23
  import { createWalletClient, encodeFunctionData, http } from "viem";
20
24
  import { polygon } from "viem/chains";
21
25
  import { getClobClient, getPolymarketAccount } from "./client.js";
22
- import { CONDITIONAL_TOKENS, ERC1155_ABI, getSigType, NEG_RISK_ADAPTER, NEG_RISK_ADAPTER_ABI, POLYGON_RPC_URLS, PUSD_COLLATERAL, PUSD_DECIMALS, } from "./constants.js";
26
+ import { CONDITIONAL_TOKENS, CTF_COLLATERAL_ADAPTER, ERC1155_ABI, getSigType, NEG_RISK_CTF_COLLATERAL_ADAPTER, POLYGON_WRITE_RPC_URL, PUSD_COLLATERAL, PUSD_DECIMALS, } from "./constants.js";
23
27
  import { mapClobError } from "./orders.js";
24
28
  import { getFundsAddress } from "./positions.js";
25
29
  import { sendWalletBatch } from "./relayer.js";
26
30
  import { getPublicClient, getPusdBalance } from "./setup.js";
31
+ import { assertTransactionSucceeded } from "./transactions.js";
32
+ /**
33
+ * Redeem call for the pUSD collateral adapter (standard or neg-risk). Exported
34
+ * for unit tests — the target/calldata pair is the money-critical part of this
35
+ * file. The CTF-mirror arguments besides conditionId are ignored by the
36
+ * adapter; we pass the canonical values anyway so the calldata reads sanely on
37
+ * a block explorer.
38
+ */
39
+ export function buildRedeemCall(negRisk, conditionId) {
40
+ return {
41
+ target: (negRisk ? NEG_RISK_CTF_COLLATERAL_ADAPTER : CTF_COLLATERAL_ADAPTER),
42
+ data: encodeFunctionData({
43
+ abi: ERC1155_ABI,
44
+ functionName: "redeemPositions",
45
+ args: [PUSD_COLLATERAL, "0x0000000000000000000000000000000000000000000000000000000000000000", conditionId, [1n, 2n]],
46
+ }),
47
+ };
48
+ }
49
+ /**
50
+ * Did the redeem actually consume something we held?
51
+ *
52
+ * A transaction hash is not proof: redeeming through the wrong collateral path
53
+ * burns a positionId nobody holds, which SUCCEEDS on-chain having done nothing
54
+ * (CTF redeemPositions never reverts on a zero balance). Only a DECREASE in a
55
+ * balance that was non-zero before proves the position was consumed.
56
+ *
57
+ * Conservative on length mismatch: a missing `after` entry reads as unchanged,
58
+ * i.e. "not redeemed", so a truncated read can never fake success.
59
+ *
60
+ * Pure and exported for tests. Design from @KillerQueen-Z's #66.
61
+ */
62
+ export function didRedeemAnyHeldPosition(before, after) {
63
+ return before.some((balance, index) => balance > 0n && (after[index] ?? balance) < balance);
64
+ }
27
65
  export async function redeemPosition(input) {
28
66
  if (!input.condition_id) {
29
67
  return { text: `Pass condition_id:"0x…" (see action:"positions" for redeemable markets).`, isError: true };
@@ -57,7 +95,26 @@ export async function redeemPosition(input) {
57
95
  if (balances.every((b) => b === 0n)) {
58
96
  return { text: `Nothing to redeem: ${owner} holds no outcome tokens for "${market?.question ?? conditionId}".`, isError: true };
59
97
  }
60
- const negRisk = Boolean(market?.neg_risk);
98
+ // negRisk picks WHICH adapter redeems — the wrong one is the silent
99
+ // no-op this module was rewritten to kill. A missing field is not "false":
100
+ // if the market payload omits it (API shape drift), cross-check the order
101
+ // book, and refuse rather than guess if that's missing too. Guessing wrong
102
+ // is caught post-hoc by no_effect_detected, but only after burning a
103
+ // relayer transaction and confusing the caller (issue #72 finding 3).
104
+ let negRiskRaw = market?.neg_risk;
105
+ if (negRiskRaw === undefined) {
106
+ const book = (await clob.getOrderBook(tokens[0].token_id).catch(() => null));
107
+ negRiskRaw = book?.neg_risk;
108
+ }
109
+ if (typeof negRiskRaw !== "boolean") {
110
+ return {
111
+ text: `Cannot determine whether "${market?.question ?? conditionId}" is a neg-risk market (neither the ` +
112
+ `market metadata nor the order book carries neg_risk) — refusing to guess, because the wrong collateral ` +
113
+ `adapter redeems 0. Retry shortly; if this persists, report it.`,
114
+ isError: true,
115
+ };
116
+ }
117
+ const negRisk = negRiskRaw;
61
118
  const held = tokens
62
119
  .map((t, i) => ({ outcome: t.outcome, winner: t.winner, shares: Number(balances[i]) / 10 ** PUSD_DECIMALS }))
63
120
  .filter((h) => h.shares > 0);
@@ -78,44 +135,134 @@ export async function redeemPosition(input) {
78
135
  structured: { dryRun: true, conditionId, negRisk, holdings: held },
79
136
  };
80
137
  }
81
- const data = negRisk
82
- ? encodeFunctionData({
83
- abi: NEG_RISK_ADAPTER_ABI,
84
- functionName: "redeemPositions",
85
- args: [conditionId, balances],
86
- })
87
- : encodeFunctionData({
88
- abi: ERC1155_ABI,
89
- functionName: "redeemPositions",
90
- args: [PUSD_COLLATERAL, "0x0000000000000000000000000000000000000000000000000000000000000000", conditionId, [1n, 2n]],
91
- });
92
- const target = (negRisk ? NEG_RISK_ADAPTER : CONDITIONAL_TOKENS);
138
+ // The dry-run only WARNED about an unresolved market; the confirm path
139
+ // then happily submitted a batch that reverts on-chain (CTF requires
140
+ // payoutDenominator > 0). No fund risk, but a wasted relayer transaction
141
+ // and a confusing failure — refuse up front instead (issue #72 finding 6).
142
+ if (market?.closed === false) {
143
+ return {
144
+ text: `"${market?.question ?? conditionId}" is not closed/resolved yet — redeeming now would revert ` +
145
+ `on-chain. Wait for resolution, then re-run action:"redeem".`,
146
+ isError: true,
147
+ };
148
+ }
149
+ const { target, data } = buildRedeemCall(negRisk, conditionId);
150
+ // Balance BEFORE the tx so the success message can report the actual
151
+ // payout delta — "tx succeeded" alone is NOT proof anything was paid
152
+ // (that deception is the exact bug class this path was rewritten to fix).
153
+ const balanceBefore = await getPusdBalance(owner).catch(() => null);
93
154
  let txHash;
94
155
  if (getSigType() === 3) {
95
- const res = await sendWalletBatch([{ target, value: "0", data }], owner, "Redeem");
156
+ const res = await sendWalletBatch([{ target, value: "0", data }], owner, "Redeem", {
157
+ guidance: 're-run action:"positions" to see whether the position was consumed before retrying',
158
+ });
96
159
  txHash = res.transactionHash;
97
160
  }
98
161
  else {
99
162
  const account = getPolymarketAccount();
100
- const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
163
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
101
164
  txHash = await wallet.sendTransaction({ to: target, data, chain: polygon, account });
102
- await pc.waitForTransactionReceipt({ hash: txHash });
165
+ assertTransactionSucceeded(await pc.waitForTransactionReceipt({ hash: txHash }), "redeem transaction", txHash);
166
+ }
167
+ // Two INDEPENDENT questions, and a redeem is only proven by answering both:
168
+ // 1. did my outcome tokens actually burn? (ERC-1155 balances, below)
169
+ // 2. did I actually get paid? (pUSD delta, further down)
170
+ // Until 0.32.6 only (2) was checked. A receipt plus a pUSD balance that
171
+ // happens to look right is not proof the position was consumed — the
172
+ // wrong-collateral no-op that started all of this burns nothing and
173
+ // reverts nothing. Token-effect verification per @KillerQueen-Z's #66.
174
+ //
175
+ // Retry the read: a receipt can land before every public RPC reflects its
176
+ // state, and reporting "your tokens did not burn" off a lagging node is a
177
+ // false alarm on a money operation.
178
+ let balancesAfter = null;
179
+ for (let attempt = 0; attempt < 3 && balancesAfter === null; attempt++) {
180
+ if (attempt > 0)
181
+ await new Promise((r) => setTimeout(r, 750));
182
+ balancesAfter = await Promise.all(tokens.map((t) => pc.readContract({
183
+ address: CONDITIONAL_TOKENS,
184
+ abi: ERC1155_ABI,
185
+ functionName: "balanceOf",
186
+ args: [owner, BigInt(t.token_id)],
187
+ }))).catch(() => null);
103
188
  }
104
189
  const balanceAfter = await getPusdBalance(owner).catch(() => null);
190
+ const paidOut = balanceBefore !== null && balanceAfter !== null ? balanceAfter - balanceBefore : null;
191
+ const heldWinner = held.some((h) => h.winner);
192
+ // "We could not check" and "we checked and nothing burned" are different
193
+ // facts that need different actions from the caller, so they get different
194
+ // statuses. Collapsing them is what made the original bug invisible.
195
+ if (balancesAfter === null) {
196
+ return {
197
+ text: [
198
+ `⚠️ Redeem transaction confirmed, but its token effect could NOT be verified — the Polygon RPC read failed after 3 attempts.`,
199
+ `This is "the transaction landed", not "you were paid". Do not retry blindly:`,
200
+ `inspect the transaction, then re-run action:"positions" once the RPC recovers.`,
201
+ ...(txHash ? [` tx: https://polygonscan.com/tx/${txHash}`] : []),
202
+ ].join("\n"),
203
+ structured: {
204
+ status: "confirmed_but_unverified", conditionId, negRisk, transactionHash: txHash,
205
+ paidOutUsd: paidOut, pusdBalance: balanceAfter, tokensBurned: null, payoutVerified: paidOut !== null,
206
+ },
207
+ isError: true,
208
+ };
209
+ }
210
+ if (!didRedeemAnyHeldPosition(balances, balancesAfter)) {
211
+ return {
212
+ text: [
213
+ `⚠️ Redeem transaction confirmed, but NO held outcome tokens were consumed.`,
214
+ `Nothing was redeemed. Your outcome tokens are NOT lost — this points at an`,
215
+ `unexpected collateral route or a missing CTF operator approval for the`,
216
+ `collateral adapter. Re-run action:"setup" to check approvals, then retry.`,
217
+ ...(txHash ? [` tx: https://polygonscan.com/tx/${txHash}`] : []),
218
+ ].join("\n"),
219
+ structured: {
220
+ status: "no_effect_detected", conditionId, negRisk, transactionHash: txHash,
221
+ paidOutUsd: paidOut, pusdBalance: balanceAfter, tokensBurned: false, payoutVerified: paidOut !== null,
222
+ },
223
+ isError: true,
224
+ };
225
+ }
226
+ if (paidOut !== null && paidOut <= 0 && heldWinner) {
227
+ return {
228
+ text: [
229
+ `⚠️ Redeem transaction succeeded but paid out $0 while winning tokens were held.`,
230
+ `This should not happen — the market may be routed to the wrong adapter or not fully`,
231
+ `resolved on-chain yet. Your outcome tokens are NOT lost; re-run action:"positions"`,
232
+ `to check, wait a few minutes, then retry. If it persists, report it.`,
233
+ ...(txHash ? [` tx: https://polygonscan.com/tx/${txHash}`] : []),
234
+ ].join("\n"),
235
+ structured: { conditionId, negRisk, transactionHash: txHash, paidOutUsd: 0, pusdBalance: balanceAfter },
236
+ isError: true,
237
+ };
238
+ }
105
239
  return {
106
240
  text: [
107
241
  `✅ Redeemed "${market?.question ?? conditionId}".`,
108
242
  heldText,
243
+ // paidOut === null means a balance read failed, which ALSO makes the
244
+ // "paid $0 while holding a winner" guard above unreachable. Silently
245
+ // omitting the payout line then rendered identically to a verified
246
+ // payout — the exact size=0 silent-loss shape this module was rewritten
247
+ // to kill. Say which one it is.
248
+ ...(paidOut !== null
249
+ ? [` Paid out: $${paidOut.toFixed(2)} pUSD`]
250
+ : [` ⚠️ Payout UNVERIFIED — the pUSD balance read failed, so this is "the tx landed", not "you were paid". Re-run action:"positions" to confirm.`]),
109
251
  ...(txHash ? [` tx: https://polygonscan.com/tx/${txHash}`] : []),
110
252
  ...(balanceAfter !== null ? [` Funds wallet pUSD balance: $${balanceAfter.toFixed(2)}`] : []),
111
253
  ].join("\n"),
112
- structured: { conditionId, negRisk, transactionHash: txHash, pusdBalance: balanceAfter },
254
+ structured: {
255
+ status: "redeemed", conditionId, negRisk, transactionHash: txHash,
256
+ paidOutUsd: paidOut, pusdBalance: balanceAfter, tokensBurned: true, payoutVerified: paidOut !== null,
257
+ },
113
258
  };
114
259
  }
115
260
  catch (err) {
116
261
  const base = await mapClobError(err);
117
- const legacyHint = ` If this market predates the 2026-04-28 V2 cutover it may settle in legacy ` +
118
- `USDC.e collateral, which this tool does not auto-detect yet — redeem it once via the Polymarket UI.`;
119
- return { text: `${base}${/revert|execution reverted|failed/i.test(base) ? legacyHint : ""}`, isError: true };
262
+ // The adapter pulls tokens via safeBatchTransferFrom — a vault set up
263
+ // before the collateral-adapter approvals were added reverts here.
264
+ const approvalHint = ` If the transaction reverted, the wallet may be missing the collateral-adapter ` +
265
+ `approval (added 2026-07) — run action:"setup" confirm:true once to grant it, then retry.`;
266
+ return { text: `${base}${/revert|execution reverted|failed/i.test(base) ? approvalHint : ""}`, isError: true };
120
267
  }
121
268
  }
@@ -1,8 +1,6 @@
1
1
  import { RelayClient, type DepositWalletCall } from "@polymarket/builder-relayer-client";
2
2
  import { type Hex } from "viem";
3
3
  export type { DepositWalletCall };
4
- export declare function relayerCredsMissing(): boolean;
5
- export declare function relayerCredsMissingMessage(): string;
6
4
  /**
7
5
  * RelayClient bound to the REAL account address (the deposit-wallet owner), with
8
6
  * builder-HMAC auth from bootstrapped Builder API creds. Async because the first
@@ -11,13 +9,6 @@ export declare function relayerCredsMissingMessage(): string;
11
9
  export declare function getRelayClient(): Promise<RelayClient>;
12
10
  /** CREATE2-derived deposit wallet address for the local key (pre-deploy safe). */
13
11
  export declare function deriveDepositWallet(): Promise<Hex>;
14
- /**
15
- * Derive the deposit wallet address WITHOUT relayer API creds. Derivation is
16
- * pure CREATE2 math over the signer address plus a public-RPC factory read — no
17
- * authenticated relayer call — so it works before the user has creds, letting
18
- * them pre-fund the address. (Deploy/approve/trade still need creds.)
19
- */
20
- export declare function deriveDepositWalletNoCreds(): Promise<Hex>;
21
12
  export declare function isDepositWalletDeployed(address: string): Promise<boolean>;
22
13
  /**
23
14
  * Deploy the deposit wallet (idempotence guarded by the caller via
@@ -27,11 +18,30 @@ export declare function isDepositWalletDeployed(address: string): Promise<boolea
27
18
  export declare function deployDepositWallet(): Promise<{
28
19
  transactionHash?: string;
29
20
  }>;
21
+ /** How long a signed batch stays executable by the relayer, in seconds. */
22
+ export declare const BATCH_DEADLINE_SECS = 300;
23
+ /** Current relayer-side state of a submitted batch, or undefined if unreachable. */
24
+ export declare function getRelayerTransactionState(transactionID: string): Promise<string | undefined>;
30
25
  /**
31
26
  * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
32
27
  * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
33
28
  * submits; we wait for confirmation.
29
+ *
30
+ * `wait()` returns undefined for BOTH an on-chain failure and a poll timeout
31
+ * (100×2s < the 300s signature deadline), and those need OPPOSITE advice: a
32
+ * failed batch is safe to retry, a timed-out one is NOT — its signature stays
33
+ * executable until the deadline, so re-signing a money movement can
34
+ * double-execute (the withdraw double-spend window from issue #72). On
35
+ * undefined we ask the relayer which case it is and say so explicitly.
36
+ *
37
+ * opts.guidance replaces the generic "re-run setup" advice with per-operation
38
+ * instructions. opts.trackPendingWithdraw persists the in-flight batch to the
39
+ * state file so withdraw can refuse to sign a second transfer while the first
40
+ * may still land (cleared on confirmation or terminal failure).
34
41
  */
35
- export declare function sendWalletBatch(calls: DepositWalletCall[], depositWallet: string, description: string): Promise<{
42
+ export declare function sendWalletBatch(calls: DepositWalletCall[], depositWallet: string, description: string, opts?: {
43
+ guidance?: string;
44
+ trackPendingWithdraw?: boolean;
45
+ }): Promise<{
36
46
  transactionHash?: string;
37
47
  }>;
@@ -7,28 +7,19 @@
7
7
  // EIP-712 payloads signed by the local key, which it can neither alter (the
8
8
  // signature covers every byte) nor replay (nonce + deadline).
9
9
  //
10
- // The relayer requires API credentials (polymarket.com → Settings → API Keys)
11
- // purely to authenticate use of its gas-sponsoring service. Phase 2 moves
12
- // these behind the BlockRun gateway so end users need no Polymarket account.
10
+ // The relayer authenticates via a Builder API key the MCP bootstraps from the
11
+ // wallet key itself (getOrCreateBuilderCreds below) — no Polymarket account or
12
+ // manually-obtained credentials needed.
13
13
  import { RelayClient } from "@polymarket/builder-relayer-client";
14
14
  import { BuilderConfig } from "@polymarket/builder-signing-sdk";
15
15
  import { ClobClient } from "@polymarket/clob-client-v2";
16
16
  import { createWalletClient, http } from "viem";
17
17
  import { polygon } from "viem/chains";
18
18
  import { getPolymarketAccount } from "./client.js";
19
- import { CLOB_HOST, POLYGON_CHAIN_ID, POLYGON_RPC_URLS, RELAYER_URL } from "./constants.js";
20
- import { loadBuilderCreds, loadL2Creds, saveBuilderCreds, saveL2Creds } from "./creds.js";
19
+ import { CLOB_HOST, POLYGON_CHAIN_ID, POLYGON_WRITE_RPC_URL, RELAYER_URL } from "./constants.js";
20
+ import { loadBuilderCreds, loadL2Creds, saveBuilderCreds, saveL2Creds, saveState } from "./creds.js";
21
21
  import { deriveApiCreds } from "./l1-auth-1271.js";
22
22
  let _relayClient = null;
23
- // The deposit-wallet flow no longer needs manually-obtained relayer credentials:
24
- // the MCP bootstraps a Builder API key from the wallet key itself (see
25
- // getOrCreateBuilderCreds). These functions are retained as always-available.
26
- export function relayerCredsMissing() {
27
- return false;
28
- }
29
- export function relayerCredsMissingMessage() {
30
- return "";
31
- }
32
23
  /**
33
24
  * Programmatically obtain Builder API credentials (key/secret/passphrase) for
34
25
  * the local wallet — created via the CLOB createBuilderApiKey() (L2-authed),
@@ -52,7 +43,7 @@ async function getOrCreateBuilderCreds() {
52
43
  if (!l2)
53
44
  throw new Error("failed to derive CLOB credentials for builder-key creation");
54
45
  }
55
- const wc = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
46
+ const wc = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
56
47
  const clob = new ClobClient({
57
48
  host: CLOB_HOST,
58
49
  chain: POLYGON_CHAIN_ID,
@@ -78,7 +69,7 @@ export async function getRelayClient() {
78
69
  const walletClient = createWalletClient({
79
70
  account: getPolymarketAccount(),
80
71
  chain: polygon,
81
- transport: http(POLYGON_RPC_URLS[0]),
72
+ transport: http(POLYGON_WRITE_RPC_URL),
82
73
  });
83
74
  const builderCreds = await getOrCreateBuilderCreds();
84
75
  const builderConfig = new BuilderConfig({ localBuilderCreds: builderCreds });
@@ -90,22 +81,6 @@ export async function deriveDepositWallet() {
90
81
  const addr = await (await getRelayClient()).deriveDepositWalletAddress();
91
82
  return addr;
92
83
  }
93
- /**
94
- * Derive the deposit wallet address WITHOUT relayer API creds. Derivation is
95
- * pure CREATE2 math over the signer address plus a public-RPC factory read — no
96
- * authenticated relayer call — so it works before the user has creds, letting
97
- * them pre-fund the address. (Deploy/approve/trade still need creds.)
98
- */
99
- export async function deriveDepositWalletNoCreds() {
100
- const walletClient = createWalletClient({
101
- account: getPolymarketAccount(),
102
- chain: polygon,
103
- transport: http(POLYGON_RPC_URLS[0]),
104
- });
105
- const client = new RelayClient(RELAYER_URL, POLYGON_CHAIN_ID, walletClient);
106
- const addr = await client.deriveDepositWalletAddress();
107
- return addr;
108
- }
109
84
  export async function isDepositWalletDeployed(address) {
110
85
  return (await getRelayClient()).getDeployed(address, "WALLET");
111
86
  }
@@ -123,18 +98,63 @@ export async function deployDepositWallet() {
123
98
  }
124
99
  return { transactionHash: confirmed.transactionHash };
125
100
  }
101
+ /** How long a signed batch stays executable by the relayer, in seconds. */
102
+ export const BATCH_DEADLINE_SECS = 300;
103
+ /** Terminal relayer states — the batch can no longer land after these. */
104
+ const TERMINAL_FAILURE_STATES = ["STATE_FAILED", "STATE_INVALID"];
105
+ /** Current relayer-side state of a submitted batch, or undefined if unreachable. */
106
+ export async function getRelayerTransactionState(transactionID) {
107
+ try {
108
+ const txns = await (await getRelayClient()).getTransaction(transactionID);
109
+ return txns?.[0]?.state;
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
126
115
  /**
127
116
  * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
128
117
  * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
129
118
  * submits; we wait for confirmation.
119
+ *
120
+ * `wait()` returns undefined for BOTH an on-chain failure and a poll timeout
121
+ * (100×2s < the 300s signature deadline), and those need OPPOSITE advice: a
122
+ * failed batch is safe to retry, a timed-out one is NOT — its signature stays
123
+ * executable until the deadline, so re-signing a money movement can
124
+ * double-execute (the withdraw double-spend window from issue #72). On
125
+ * undefined we ask the relayer which case it is and say so explicitly.
126
+ *
127
+ * opts.guidance replaces the generic "re-run setup" advice with per-operation
128
+ * instructions. opts.trackPendingWithdraw persists the in-flight batch to the
129
+ * state file so withdraw can refuse to sign a second transfer while the first
130
+ * may still land (cleared on confirmation or terminal failure).
130
131
  */
131
- export async function sendWalletBatch(calls, depositWallet, description) {
132
- const deadline = String(Math.floor(Date.now() / 1000) + 300);
133
- const response = await (await getRelayClient()).executeDepositWalletBatch(calls, depositWallet, deadline);
132
+ export async function sendWalletBatch(calls, depositWallet, description, opts) {
133
+ const deadlineSec = Math.floor(Date.now() / 1000) + BATCH_DEADLINE_SECS;
134
+ const response = await (await getRelayClient()).executeDepositWalletBatch(calls, depositWallet, String(deadlineSec));
135
+ if (opts?.trackPendingWithdraw) {
136
+ saveState({ pendingWithdraw: { transactionID: response.transactionID, deadline: deadlineSec } });
137
+ }
134
138
  const confirmed = await response.wait();
135
139
  if (!confirmed) {
136
- throw new Error(`${description}: relayer batch did not confirm (tx ${response.transactionID}). ` +
137
- `Re-run action:"setup" to check state and retry.`);
140
+ const state = await getRelayerTransactionState(response.transactionID);
141
+ if (state && TERMINAL_FAILURE_STATES.includes(state)) {
142
+ if (opts?.trackPendingWithdraw)
143
+ saveState({ pendingWithdraw: undefined });
144
+ // "failed" must appear here so callers' revert-hint regexes (e.g.
145
+ // redeem's missing-approval hint) fire on it. Safe to retry.
146
+ throw new Error(`${description}: relayer batch failed on-chain (tx ${response.transactionID}). ` +
147
+ `${opts?.guidance ?? 'Re-run action:"setup" to check state and retry.'}`);
148
+ }
149
+ // Unknown or still-pending: the signed batch may STILL land. Deliberately
150
+ // no "failed"/"revert" wording (this is not a revert), and deliberately
151
+ // anti-retry advice — pendingWithdraw stays persisted when tracked.
152
+ throw new Error(`${description}: relayer batch did not confirm within the polling window ` +
153
+ `(tx ${response.transactionID}, relayer state: ${state ?? "unreachable"}). It may still land — the signed ` +
154
+ `batch stays executable until its ${BATCH_DEADLINE_SECS / 60}-minute deadline. Do NOT retry yet: wait for ` +
155
+ `the deadline to pass, then ${opts?.guidance ?? 're-run action:"setup" to re-check state'}.`);
138
156
  }
157
+ if (opts?.trackPendingWithdraw)
158
+ saveState({ pendingWithdraw: undefined });
139
159
  return { transactionHash: confirmed.transactionHash };
140
160
  }
@@ -1,5 +1,25 @@
1
1
  import { type Hex, type PublicClient } from "viem";
2
2
  export declare function getPublicClient(): PublicClient;
3
+ export interface ApprovalItem {
4
+ label: string;
5
+ token: Hex;
6
+ spender: Hex;
7
+ kind: "erc20" | "erc1155";
8
+ granted: boolean;
9
+ }
10
+ /**
11
+ * An approval transaction landing is not the same as the approvals being on
12
+ * the books — re-read the chain (retrying across RPC propagation lag, the same
13
+ * 3×750ms shape as redeem's post-transaction reads) and believe ONLY what it
14
+ * says. An empty read can never count as granted, so a truncated RPC response
15
+ * cannot fake success. Throws if every read attempt fails; the caller decides
16
+ * how to report "chain state unknown". `readFn` is injected so tests can pin
17
+ * the retry/verdict logic without an RPC.
18
+ */
19
+ export declare function verifyApprovalsLanded(readFn: () => Promise<ApprovalItem[]>, attempts?: number, delayMs?: number): Promise<{
20
+ approvals: ApprovalItem[];
21
+ allGranted: boolean;
22
+ }>;
3
23
  export declare function getPusdBalance(owner: Hex): Promise<number>;
4
24
  export declare function runSetup(opts: {
5
25
  confirm: boolean;