@blockrun/franklin 3.37.0 → 3.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/compact.js +1 -1
  3. package/dist/agent/context.js +3 -3
  4. package/dist/agent/evaluator.js +1 -1
  5. package/dist/agent/llm.js +6 -6
  6. package/dist/agent/loop.js +25 -9
  7. package/dist/agent/tokens.js +17 -3
  8. package/dist/agent/turn-analyzer.js +6 -4
  9. package/dist/agent/verification.js +1 -1
  10. package/dist/commands/slack.js +1 -1
  11. package/dist/commands/social.js +1 -1
  12. package/dist/commands/telegram.js +1 -1
  13. package/dist/content/image-pricing.js +23 -0
  14. package/dist/content/library.d.ts +1 -1
  15. package/dist/gateway-models.d.ts +14 -4
  16. package/dist/gateway-models.js +18 -5
  17. package/dist/learnings/extractor.js +2 -2
  18. package/dist/plugin-sdk/workflow.d.ts +1 -1
  19. package/dist/plugin-sdk/workflow.js +2 -2
  20. package/dist/pricing.js +39 -19
  21. package/dist/proxy/fallback.js +1 -1
  22. package/dist/proxy/server.js +52 -5
  23. package/dist/router/index.d.ts +24 -5
  24. package/dist/router/index.js +100 -35
  25. package/dist/router/vision.js +5 -3
  26. package/dist/serve/server.js +4 -4
  27. package/dist/tools/content-execute.js +1 -1
  28. package/dist/tools/moa.js +3 -3
  29. package/dist/tools/polymarket/client.d.ts +5 -5
  30. package/dist/tools/polymarket/client.js +26 -11
  31. package/dist/tools/polymarket/constants.d.ts +25 -26
  32. package/dist/tools/polymarket/constants.js +65 -31
  33. package/dist/tools/polymarket/creds.d.ts +10 -0
  34. package/dist/tools/polymarket/creds.js +7 -1
  35. package/dist/tools/polymarket/fund.js +15 -3
  36. package/dist/tools/polymarket/orders.js +14 -7
  37. package/dist/tools/polymarket/positions.js +1 -1
  38. package/dist/tools/polymarket/redeem.d.ts +26 -0
  39. package/dist/tools/polymarket/redeem.js +180 -33
  40. package/dist/tools/polymarket/relayer.d.ts +20 -10
  41. package/dist/tools/polymarket/relayer.js +57 -37
  42. package/dist/tools/polymarket/setup.d.ts +20 -0
  43. package/dist/tools/polymarket/setup.js +135 -53
  44. package/dist/tools/polymarket/transactions.d.ts +9 -0
  45. package/dist/tools/polymarket/transactions.js +22 -0
  46. package/dist/tools/polymarket/withdraw.d.ts +15 -0
  47. package/dist/tools/polymarket/withdraw.js +173 -23
  48. package/dist/tools/prediction.d.ts +5 -2
  49. package/dist/tools/prediction.js +21 -44
  50. package/dist/tools/subagent.js +1 -1
  51. package/dist/tools/videogen.d.ts +4 -3
  52. package/dist/tools/videogen.js +9 -6
  53. package/dist/ui/model-picker.js +48 -39
  54. package/package.json +8 -5
@@ -12,15 +12,16 @@ import { createPublicClient, createWalletClient, encodeFunctionData, fallback, f
12
12
  import { polygon } from "viem/chains";
13
13
  import { AssetType } from "@polymarket/clob-client-v2";
14
14
  import { checkGeoblock, getClobClient, getPolymarketAccount } from "./client.js";
15
- import { assertContractConfig, CONDITIONAL_TOKENS, CTF_EXCHANGE_V2, ERC1155_ABI, ERC20_ABI, getBoundedApprovalsUsd, getSigType, NEG_RISK_ADAPTER, NEG_RISK_CTF_EXCHANGE_V2, POLYGON_RPC_URLS, PUSD_COLLATERAL, PUSD_DECIMALS, } from "./constants.js";
15
+ import { assertContractConfig, CONDITIONAL_TOKENS, CTF_COLLATERAL_ADAPTER, CTF_EXCHANGE_V2, ERC1155_ABI, ERC20_ABI, getBoundedApprovalsUsd, getSigType, NEG_RISK_ADAPTER, NEG_RISK_CTF_COLLATERAL_ADAPTER, NEG_RISK_CTF_EXCHANGE_V2, POLYGON_READ_RPC_URLS, POLYGON_WRITE_RPC_URL, PUSD_COLLATERAL, PUSD_DECIMALS, } from "./constants.js";
16
16
  import { loadDepositWalletForSigner, loadState, saveState } from "./creds.js";
17
- import { deployDepositWallet, deriveDepositWallet, deriveDepositWalletNoCreds, isDepositWalletDeployed, relayerCredsMissing, relayerCredsMissingMessage, sendWalletBatch, } from "./relayer.js";
17
+ import { deployDepositWallet, deriveDepositWallet, isDepositWalletDeployed, sendWalletBatch, } from "./relayer.js";
18
+ import { assertTransactionSucceeded } from "./transactions.js";
18
19
  let _publicClient = null;
19
20
  export function getPublicClient() {
20
21
  if (!_publicClient) {
21
22
  _publicClient = createPublicClient({
22
23
  chain: polygon,
23
- transport: fallback(POLYGON_RPC_URLS.map((u) => http(u, { retryCount: 2, timeout: 8_000 })), { retryCount: 2 }),
24
+ transport: fallback(POLYGON_READ_RPC_URLS.map((u) => http(u, { retryCount: 2, timeout: 8_000 })), { retryCount: 2 }),
24
25
  });
25
26
  }
26
27
  return _publicClient;
@@ -47,6 +48,35 @@ async function withRpcRetry(fn, attempts = 4) {
47
48
  }
48
49
  throw lastErr;
49
50
  }
51
+ /**
52
+ * An approval transaction landing is not the same as the approvals being on
53
+ * the books — re-read the chain (retrying across RPC propagation lag, the same
54
+ * 3×750ms shape as redeem's post-transaction reads) and believe ONLY what it
55
+ * says. An empty read can never count as granted, so a truncated RPC response
56
+ * cannot fake success. Throws if every read attempt fails; the caller decides
57
+ * how to report "chain state unknown". `readFn` is injected so tests can pin
58
+ * the retry/verdict logic without an RPC.
59
+ */
60
+ export async function verifyApprovalsLanded(readFn, attempts = 3, delayMs = 750) {
61
+ let latest = null;
62
+ let lastErr;
63
+ for (let i = 0; i < attempts; i++) {
64
+ try {
65
+ latest = await readFn();
66
+ if (latest.length > 0 && latest.every((a) => a.granted)) {
67
+ return { approvals: latest, allGranted: true };
68
+ }
69
+ }
70
+ catch (err) {
71
+ lastErr = err;
72
+ }
73
+ if (i < attempts - 1)
74
+ await new Promise((r) => setTimeout(r, delayMs));
75
+ }
76
+ if (latest === null)
77
+ throw lastErr;
78
+ return { approvals: latest, allGranted: false };
79
+ }
50
80
  /**
51
81
  * The pUSD allowance we grant per exchange: the bounded amount if
52
82
  * POLYMARKET_BOUNDED_APPROVALS is set, else unlimited. Shared by the approval
@@ -58,12 +88,16 @@ function pusdApprovalTarget() {
58
88
  return bounded === null ? maxUint256 : parseUnits(String(bounded), PUSD_DECIMALS);
59
89
  }
60
90
  /**
61
- * The approval set Polymarket V2 trading needs from the funds-holding wallet,
62
- * mirroring Polymarket's own canonical approveTokensForTrading.ts (proxy/safe
63
- * wallet): pUSD spend for ALL FOUR collateral spenders — both exchanges, the
64
- * Conditional Tokens contract (direct split/merge), AND the NegRisk Adapter
65
- * (negRisk order settlement / convert / redeem pulls collateral through it) —
66
- * plus the CTF operator for both exchanges and the adapter.
91
+ * The approval set Polymarket V2 trading needs from the funds-holding wallet:
92
+ * Polymarket's own canonical approveTokensForTrading.ts (proxy/safe wallet) —
93
+ * pUSD spend for ALL FOUR collateral spenders (both exchanges, the Conditional
94
+ * Tokens contract for direct split/merge, AND the NegRisk Adapter, whose
95
+ * negRisk order settlement / convert pulls collateral through it) plus the CTF
96
+ * operator for both exchanges and the NegRisk Adapter — PLUS, beyond the
97
+ * canonical script, CTF operator for the two pUSD collateral adapters, which
98
+ * pull the outcome tokens during action:"redeem" (five ERC-1155 operators in
99
+ * total). Removing the adapter operators silently reintroduces the
100
+ * redeem-pays-$0 bug.
67
101
  *
68
102
  * The NegRisk Adapter pUSD approval is REQUIRED to trade neg-risk markets (e.g.
69
103
  * multi-outcome "winner" markets): without it the CLOB accepts the order but
@@ -79,10 +113,16 @@ async function readApprovals(owner) {
79
113
  ["pUSD → NegRisk Adapter", NEG_RISK_ADAPTER],
80
114
  ["pUSD → Conditional Tokens", CONDITIONAL_TOKENS],
81
115
  ];
116
+ // The two collateral adapters are the redeem path (they pull the caller's
117
+ // outcome tokens via safeBatchTransferFrom, so they need operator approval).
118
+ // Wallets set up before 2026-07 lack these; readApprovals runs on-chain
119
+ // every setup, so they self-heal with one action:"setup" confirm:true.
82
120
  const erc1155Operators = [
83
121
  ["CTF → CTF Exchange V2", CTF_EXCHANGE_V2],
84
122
  ["CTF → NegRisk Exchange V2", NEG_RISK_CTF_EXCHANGE_V2],
85
123
  ["CTF → NegRisk Adapter", NEG_RISK_ADAPTER],
124
+ ["CTF → CtfCollateral Adapter (redeem)", CTF_COLLATERAL_ADAPTER],
125
+ ["CTF → NegRisk CtfCollateral Adapter (redeem)", NEG_RISK_CTF_COLLATERAL_ADAPTER],
86
126
  ];
87
127
  // "granted" = allowance meets the amount we'd approve (bounded or unlimited),
88
128
  // so a configured bound of any size converges instead of re-approving forever.
@@ -137,13 +177,16 @@ async function geoblockLine() {
137
177
  return `✅ Region: order placement permitted from this egress${where}`;
138
178
  if (geo.orderPlacement === "blocked") {
139
179
  return `❌ Region: order placement BLOCKED from this egress${where}. ` +
140
- "Route through an unrestricted egress: set POLYMARKET_CLOB_PROXY / HTTPS_PROXY, or point " +
141
- "POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL at a Tokyo relay (see deploy/tokyo-egress).";
180
+ "Point POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL at a permitted-region relay " +
181
+ "(see deploy/finland-egress) or restore the default. A proxy alone (POLYMARKET_CLOB_PROXY / " +
182
+ "HTTPS_PROXY) only changes how the current egress is reached, not the Polymarket-facing IP.";
142
183
  }
143
184
  return "ℹ️ Region: could not determine order-placement status (check re-runs on demand)";
144
185
  }
145
- const KEY_BACKUP_NOTE = "🔑 The Polymarket signer is your BlockRun wallet key (~/.blockrun/.session). " +
146
- "It is the ONLY key to these funds — back it up; never share or print it.";
186
+ const KEY_BACKUP_NOTE = "🔑 The Polymarket signer is your BlockRun wallet key (~/.blockrun/.session by default; " +
187
+ "a BLOCKRUN_WALLET_KEY env var or an existing agent wallet.json takes precedence). It is " +
188
+ "the ONLY key to these funds — back up the key behind the signer address shown above, " +
189
+ "wherever it lives (key file, or the env-var value itself); never share or print it.";
147
190
  export async function runSetup(opts) {
148
191
  // Verify our exchange/collateral addresses still match the SDK's BEFORE any
149
192
  // funds-affecting signature (approval batch / EOA approvals) — otherwise an
@@ -154,37 +197,6 @@ export async function runSetup(opts) {
154
197
  }
155
198
  async function runSetupDepositWallet(opts) {
156
199
  const account = getPolymarketAccount();
157
- if (relayerCredsMissing()) {
158
- // Even without relayer creds we can DERIVE (not deploy) the deposit wallet
159
- // address, so the user can pre-fund it while they get creds.
160
- let depositWallet;
161
- try {
162
- depositWallet = loadDepositWalletForSigner(account.address)
163
- ?? (await deriveDepositWalletNoCreds());
164
- saveState({ depositWallet, signer: account.address });
165
- }
166
- catch { /* derivation is best-effort here */ }
167
- const geo = await geoblockLine();
168
- const balance = depositWallet ? await getPusdBalance(depositWallet).catch(() => 0) : 0;
169
- return {
170
- text: [
171
- `Polymarket setup — deposit-wallet mode (signer ${account.address})`,
172
- ...(depositWallet
173
- ? [
174
- ``,
175
- `Your deposit wallet (holds betting funds): ${depositWallet}`,
176
- ` https://polygonscan.com/address/${depositWallet}`,
177
- ` ${balance > 0 ? `✅ pUSD balance: $${balance.toFixed(2)}` : "❌ Not funded yet"} — you can fund it NOW`,
178
- ` (send ~$5 pUSD, or USDC via the Polymarket bridge which auto-wraps) while you get relayer creds.`,
179
- ]
180
- : []),
181
- geo,
182
- ``,
183
- relayerCredsMissingMessage(),
184
- ].join("\n"),
185
- structured: { mode: "POLY_1271", signer: account.address, depositWallet, ready: false, missing: "relayer_credentials" },
186
- };
187
- }
188
200
  // 1. Derive (pure CREATE2 math) + persist, keyed to the current signer.
189
201
  const depositWallet = loadDepositWalletForSigner(account.address) ?? (await deriveDepositWallet());
190
202
  saveState({ depositWallet, signer: account.address });
@@ -195,22 +207,56 @@ async function runSetupDepositWallet(opts) {
195
207
  if (!deployed) {
196
208
  const res = await deployDepositWallet();
197
209
  deployTxHash = res.transactionHash;
198
- deployed = true;
210
+ // The relayer deployed *something*; only contract code at the CREATE2
211
+ // address WE derived proves it deployed THIS wallet. If factory/salt ever
212
+ // diverge between derive and deploy, recording deployed:true here would
213
+ // point approvals and funding at an address that doesn't exist — stranding
214
+ // real money (issue #72 finding 4). Retry the read across RPC lag.
215
+ for (let attempt = 0; attempt < 3 && !deployed; attempt++) {
216
+ if (attempt > 0)
217
+ await new Promise((r) => setTimeout(r, 750));
218
+ const code = await getPublicClient().getCode({ address: depositWallet }).catch(() => undefined);
219
+ deployed = typeof code === "string" && code !== "0x";
220
+ }
221
+ if (!deployed) {
222
+ throw new Error(`Deposit wallet deploy confirmed (tx ${deployTxHash}) but no contract code is visible at the derived ` +
223
+ `address ${depositWallet} after 3 reads. Either the RPCs are lagging (re-run action:"setup" in a minute — ` +
224
+ `it re-checks) or the relayer deployed a different address than we derived, in which case do NOT fund ` +
225
+ `this wallet until that is resolved.`);
226
+ }
199
227
  }
200
228
  saveState({ deployed: true });
201
229
  // 3. Funds + approvals state.
202
230
  const balance = await getPusdBalance(depositWallet);
203
- const approvals = await readApprovals(depositWallet);
231
+ let approvals = await readApprovals(depositWallet);
204
232
  const missing = approvals.filter((a) => !a.granted);
205
233
  // 4. Approvals batch — the first real signature; confirm-gated with preview.
206
234
  let approvalsTxHash;
207
235
  let approvalsPending = missing.length > 0;
236
+ let approvalsUnverified = false;
208
237
  if (missing.length > 0 && opts.confirm) {
209
238
  const calls = buildApprovalCalls(missing);
210
239
  const res = await sendWalletBatch(calls, depositWallet, "Approval batch");
211
240
  approvalsTxHash = res.transactionHash;
212
- approvalsPending = false;
213
- saveState({ approvalsDone: true });
241
+ // The batch landing proves it was MINED, not that the approvals are on the
242
+ // books. The response used to carry the pre-batch snapshot here, so every
243
+ // item the batch had just granted still read granted:false — and the
244
+ // inverse failure (relayer claims success, chain disagrees) was invisible.
245
+ try {
246
+ const verified = await verifyApprovalsLanded(() => readApprovals(depositWallet));
247
+ if (verified.approvals.length > 0)
248
+ approvals = verified.approvals;
249
+ approvalsPending = !verified.allGranted;
250
+ approvalsUnverified = !verified.allGranted;
251
+ }
252
+ catch {
253
+ // Chain state unknown after the tx landed — keep the pre-batch snapshot
254
+ // and report unverified rather than claiming success.
255
+ approvalsPending = true;
256
+ approvalsUnverified = true;
257
+ }
258
+ if (!approvalsPending)
259
+ saveState({ approvalsDone: true });
214
260
  }
215
261
  else if (missing.length === 0) {
216
262
  saveState({ approvalsDone: true });
@@ -266,6 +312,14 @@ async function runSetupDepositWallet(opts) {
266
312
  ` batch via the relayer). Re-run action:"setup" with confirm:true to sign.`,
267
313
  ]
268
314
  : []),
315
+ ...(approvalsUnverified
316
+ ? [
317
+ ``,
318
+ ` ⚠️ The approval batch landed but the chain does not (yet) show every`,
319
+ ` approval granted — treat them as NOT granted. Re-run action:"setup"`,
320
+ ` to re-check before trading or redeeming.`,
321
+ ]
322
+ : []),
269
323
  `${credsReady ? "✅" : "❌"} CLOB API credentials${credsNote}`,
270
324
  ...(balanceCacheWarned
271
325
  ? [` ⚠️ Balance cache not pre-warmed (${balanceCacheWarned}) — your first buy refreshes it automatically.`]
@@ -286,6 +340,8 @@ async function runSetupDepositWallet(opts) {
286
340
  pusdBalance: balance,
287
341
  approvals: approvals.map((a) => ({ label: a.label, granted: a.granted })),
288
342
  approvalsPending,
343
+ ...(approvalsTxHash ? { approvalsTxHash } : {}),
344
+ ...(approvalsUnverified ? { approvalsUnverified: true } : {}),
289
345
  credsReady,
290
346
  ready,
291
347
  },
@@ -294,22 +350,24 @@ async function runSetupDepositWallet(opts) {
294
350
  async function runSetupEoa(opts) {
295
351
  const account = getPolymarketAccount();
296
352
  const pc = getPublicClient();
297
- const [balance, polWei, approvals] = await Promise.all([
353
+ const [balance, polWei, initialApprovals] = await Promise.all([
298
354
  getPusdBalance(account.address),
299
355
  pc.getBalance({ address: account.address }),
300
356
  readApprovals(account.address),
301
357
  ]);
358
+ let approvals = initialApprovals;
302
359
  const pol = Number(formatUnits(polWei, 18));
303
360
  const missing = approvals.filter((a) => !a.granted);
304
361
  // EOA mode sends its own approval transactions — needs POL for gas.
305
362
  let approvalsPending = missing.length > 0;
363
+ let approvalsUnverified = false;
306
364
  const approvalTxHashes = [];
307
365
  if (missing.length > 0 && opts.confirm) {
308
366
  if (pol <= 0) {
309
367
  approvalsPending = true;
310
368
  }
311
369
  else {
312
- const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
370
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
313
371
  const erc20Amount = pusdApprovalTarget(); // honor POLYMARKET_BOUNDED_APPROVALS in EOA mode too
314
372
  for (const item of missing) {
315
373
  const hash = item.kind === "erc20"
@@ -329,10 +387,22 @@ async function runSetupEoa(opts) {
329
387
  chain: polygon,
330
388
  account,
331
389
  });
332
- await pc.waitForTransactionReceipt({ hash });
390
+ assertTransactionSucceeded(await pc.waitForTransactionReceipt({ hash }), `approval transaction (${item.label})`, hash);
333
391
  approvalTxHashes.push(hash);
334
392
  }
335
- approvalsPending = false;
393
+ // Same rule as the deposit-wallet batch: report the post-transaction
394
+ // chain state, not the pre-transaction snapshot the report was built on.
395
+ try {
396
+ const verified = await verifyApprovalsLanded(() => readApprovals(account.address));
397
+ if (verified.approvals.length > 0)
398
+ approvals = verified.approvals;
399
+ approvalsPending = !verified.allGranted;
400
+ approvalsUnverified = !verified.allGranted;
401
+ }
402
+ catch {
403
+ approvalsPending = true;
404
+ approvalsUnverified = true;
405
+ }
336
406
  }
337
407
  }
338
408
  let credsReady = false;
@@ -362,10 +432,20 @@ async function runSetupEoa(opts) {
362
432
  : approvalsPending && pol <= 0
363
433
  ? [``, ` Cannot send approvals: the EOA has no POL for gas. Send a little POL first.`]
364
434
  : []),
435
+ ...(approvalsUnverified
436
+ ? [
437
+ ``,
438
+ ` ⚠️ The approval transactions landed but the chain does not (yet) show every`,
439
+ ` approval granted — treat them as NOT granted. Re-run action:"setup" to re-check.`,
440
+ ]
441
+ : []),
365
442
  `${credsReady ? "✅" : "❌"} CLOB API credentials${credsNote}`,
366
443
  geo,
367
444
  ``,
368
- ready ? `🎯 Ready to trade.` : `Re-run action:"setup" after completing the ❌ items.`,
445
+ ready
446
+ ? `🎯 Ready to trade. Note: the CLOB may reject plain-EOA makers on order placement — ` +
447
+ `the deposit wallet (unset POLYMARKET_SIG_TYPE) is the supported trading path.`
448
+ : `Re-run action:"setup" after completing the ❌ items.`,
369
449
  ``,
370
450
  KEY_BACKUP_NOTE,
371
451
  ];
@@ -378,6 +458,8 @@ async function runSetupEoa(opts) {
378
458
  polBalance: pol,
379
459
  approvals: approvals.map((a) => ({ label: a.label, granted: a.granted })),
380
460
  approvalsPending,
461
+ ...(approvalTxHashes.length ? { approvalTxHashes } : {}),
462
+ ...(approvalsUnverified ? { approvalsUnverified: true } : {}),
381
463
  credsReady,
382
464
  ready,
383
465
  },
@@ -0,0 +1,9 @@
1
+ /** Minimal shape so callers can pass a viem receipt without importing its type. */
2
+ export interface TransactionStatusLike {
3
+ status?: string;
4
+ }
5
+ /**
6
+ * Throw unless the receipt says the transaction actually succeeded.
7
+ * `description` names the operation for the error message ("Redeem transaction").
8
+ */
9
+ export declare function assertTransactionSucceeded(receipt: TransactionStatusLike, description: string, txHash?: string): void;
@@ -0,0 +1,22 @@
1
+ // src/utils/polymarket/transactions.ts
2
+ //
3
+ // viem's waitForTransactionReceipt resolves for BOTH successful and reverted
4
+ // transactions — it only throws when the receipt cannot be fetched. So awaiting
5
+ // it proves the transaction was mined, not that it did anything. Every money
6
+ // path here must assert the status explicitly.
7
+ //
8
+ // This was open-coded in three places (redeem, setup, withdraw) with three
9
+ // slightly different error strings, and withdraw's copy was missing entirely
10
+ // until 0.32.3 — a reverted pUSD transfer printed "✅ Withdrawal submitted".
11
+ // One helper, so the next money path cannot forget.
12
+ //
13
+ // Extracted per @KillerQueen-Z's design in #66.
14
+ /**
15
+ * Throw unless the receipt says the transaction actually succeeded.
16
+ * `description` names the operation for the error message ("Redeem transaction").
17
+ */
18
+ export function assertTransactionSucceeded(receipt, description, txHash) {
19
+ if (receipt.status !== "success") {
20
+ throw new Error(`execution reverted: ${description}${txHash ? ` ${txHash}` : ""} reverted on-chain — no state change was applied.`);
21
+ }
22
+ }
@@ -1,4 +1,19 @@
1
+ import { type Hex } from "viem";
1
2
  import type { ToolResult } from "./orders.js";
3
+ /** Approve-then-wrap calls for sweeping legacy USDC.e into pUSD. Exported for tests. */
4
+ export declare function buildLegacyWrapCalls(owner: Hex, amount: bigint): Array<{
5
+ target: Hex;
6
+ value: "0";
7
+ data: Hex;
8
+ }>;
9
+ /**
10
+ * Parse a dollar amount into micro-pUSD without silently changing what the
11
+ * caller asked for. The old `BigInt(Math.floor(usd * 1e6))` truncated float
12
+ * noise downward — `19.99 * 1e6` is 19_989_999.999…, i.e. a cent less than
13
+ * requested. Round to the nearest micro-dollar and reject anything that isn't
14
+ * representable (over-precision, negatives, NaN). Exported for tests.
15
+ */
16
+ export declare function parseUsdAmount(amount: number): bigint | null;
2
17
  interface WithdrawInput {
3
18
  amount_usd?: number;
4
19
  to_address?: string;
@@ -1,8 +1,8 @@
1
1
  // src/utils/polymarket/withdraw.ts
2
2
  //
3
- // Cash out: pUSD in the deposit wallet → native USDC on Base, delivered to the
4
- // BlockRun agent wallet (the same key/address that pays x402 AI fees) — closing
5
- // the loop. Flow (Polymarket bridge):
3
+ // Cash out: collateral in the deposit wallet → native USDC on Base, delivered
4
+ // to the BlockRun agent wallet (the same key/address that pays x402 AI fees) —
5
+ // closing the loop. Flow (Polymarket bridge):
6
6
  // 1. POST /withdraw {address, toChainId, toTokenAddress, recipientAddr} → a
7
7
  // one-time EVM bridge address.
8
8
  // 2. Transfer pUSD FROM the deposit wallet TO that bridge address (gasless
@@ -11,23 +11,98 @@
11
11
  // 3. The bridge unwraps pUSD → USDC (Collateral Offramp + Uniswap v3) and
12
12
  // sends it to recipientAddr on Base. Instant, no Polymarket fee (minor
13
13
  // swap slippage may apply).
14
+ //
15
+ // Legacy USDC.e: adapter redemptions pay pUSD, but historic direct-CTF
16
+ // redemptions left USDC.e in the wallet, which the bridge does not accept and
17
+ // which action:"withdraw" previously could not see at all. Withdrawable
18
+ // balance is now pUSD + USDC.e; any shortfall beyond the pUSD on hand is
19
+ // wrapped to pUSD through the collateral onramp first (sweep design from
20
+ // @KillerQueen-Z's #59/#66, tracked in #71).
14
21
  import axios from "axios";
15
22
  import { encodeFunctionData, formatUnits, http, createWalletClient } from "viem";
16
23
  import { polygon } from "viem/chains";
17
- import { BASE_CHAIN_ID, BASE_USDC, BRIDGE_API_HOST, ERC20_ABI, getBuilderCode, getSigType, POLYGON_RPC_URLS, PUSD_COLLATERAL, PUSD_DECIMALS, } from "./constants.js";
24
+ import { BASE_CHAIN_ID, BASE_USDC, BRIDGE_API_HOST, COLLATERAL_ONRAMP, ERC20_ABI, getBuilderCode, getSigType, POLYGON_WRITE_RPC_URL, PUSD_COLLATERAL, PUSD_DECIMALS, USDCE_COLLATERAL, } from "./constants.js";
18
25
  import { getPolymarketAccount } from "./client.js";
26
+ import { assertTransactionSucceeded } from "./transactions.js";
19
27
  import { mapClobError } from "./orders.js";
20
28
  import { getFundsAddress } from "./positions.js";
21
- import { sendWalletBatch } from "./relayer.js";
29
+ import { loadState, saveState } from "./creds.js";
30
+ import { getRelayerTransactionState, sendWalletBatch } from "./relayer.js";
22
31
  import { getPublicClient } from "./setup.js";
23
- async function rawPusdBalance(owner) {
32
+ async function rawTokenBalance(token, owner) {
24
33
  return getPublicClient().readContract({
25
- address: PUSD_COLLATERAL,
34
+ address: token,
26
35
  abi: ERC20_ABI,
27
36
  functionName: "balanceOf",
28
37
  args: [owner],
29
38
  });
30
39
  }
40
+ // wrap(_asset, _to, _amount) — verified against the Sourcify exact-match
41
+ // source of COLLATERAL_ONRAMP (2026-07-21). Pulls `_amount` of `_asset` from
42
+ // the caller (needs the ERC-20 approval batched before it) and mints pUSD to
43
+ // `_to`.
44
+ const COLLATERAL_ONRAMP_ABI = [{
45
+ type: "function",
46
+ name: "wrap",
47
+ stateMutability: "nonpayable",
48
+ inputs: [
49
+ { name: "_asset", type: "address" },
50
+ { name: "_to", type: "address" },
51
+ { name: "_amount", type: "uint256" },
52
+ ],
53
+ outputs: [],
54
+ }];
55
+ /** Approve-then-wrap calls for sweeping legacy USDC.e into pUSD. Exported for tests. */
56
+ export function buildLegacyWrapCalls(owner, amount) {
57
+ return [
58
+ {
59
+ target: USDCE_COLLATERAL,
60
+ value: "0",
61
+ data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [COLLATERAL_ONRAMP, amount] }),
62
+ },
63
+ {
64
+ target: COLLATERAL_ONRAMP,
65
+ value: "0",
66
+ data: encodeFunctionData({ abi: COLLATERAL_ONRAMP_ABI, functionName: "wrap", args: [USDCE_COLLATERAL, owner, amount] }),
67
+ },
68
+ ];
69
+ }
70
+ /**
71
+ * Parse a dollar amount into micro-pUSD without silently changing what the
72
+ * caller asked for. The old `BigInt(Math.floor(usd * 1e6))` truncated float
73
+ * noise downward — `19.99 * 1e6` is 19_989_999.999…, i.e. a cent less than
74
+ * requested. Round to the nearest micro-dollar and reject anything that isn't
75
+ * representable (over-precision, negatives, NaN). Exported for tests.
76
+ */
77
+ export function parseUsdAmount(amount) {
78
+ if (!Number.isFinite(amount) || amount <= 0)
79
+ return null;
80
+ const scaled = amount * 10 ** PUSD_DECIMALS;
81
+ const rounded = Math.round(scaled);
82
+ // 0.01 micro-dollars separates the two populations cleanly: float noise on a
83
+ // representable amount is ≤ ~1e-4 micro even at $1M (ulp-scale), while a
84
+ // genuine 7th-decimal digit is ≥ 0.1 micro. An absolute 1e-7 bound (the
85
+ // first draft) sat BELOW the noise floor and rejected honest amounts like
86
+ // $1234.56 (noise 2.4e-7); a relative bound sat above real violations.
87
+ if (!Number.isSafeInteger(rounded) || rounded <= 0 || Math.abs(scaled - rounded) > 0.01) {
88
+ return null;
89
+ }
90
+ return BigInt(rounded);
91
+ }
92
+ /** Re-read pUSD until it reaches `minimum` (post-wrap RPC lag), 3×750ms. */
93
+ async function readPusdUntil(owner, minimum) {
94
+ let observed = 0n;
95
+ for (let attempt = 0; attempt < 3; attempt++) {
96
+ if (attempt > 0)
97
+ await new Promise((resolve) => setTimeout(resolve, 750));
98
+ observed = await rawTokenBalance(PUSD_COLLATERAL, owner);
99
+ if (observed >= minimum)
100
+ return observed;
101
+ }
102
+ return observed;
103
+ }
104
+ const WITHDRAW_GUIDANCE = 'check the pUSD balance with action:"setup" and the bridge status endpoint before ANY retry — ' +
105
+ "a resubmitted withdrawal signs a SECOND transfer and can double-send";
31
106
  export async function withdrawFunds(input) {
32
107
  let owner;
33
108
  try {
@@ -38,33 +113,97 @@ export async function withdrawFunds(input) {
38
113
  }
39
114
  const recipient = input.to_address || getPolymarketAccount().address;
40
115
  try {
41
- // Amount: explicit amount_usd, else the full pUSD balance.
42
- const balanceRaw = await rawPusdBalance(owner);
43
- const balanceUsd = Number(formatUnits(balanceRaw, PUSD_DECIMALS));
44
- if (balanceRaw === 0n) {
45
- return { text: `No pUSD to withdraw — the deposit wallet ${owner} holds $0. (Redeem/sell a position first.)`, isError: true };
116
+ // Refuse to sign while an earlier withdrawal batch may still land: its
117
+ // signature stays executable until its deadline, and a second signed
118
+ // transfer on top of it double-sends (issue #72 finding 1). Resolved
119
+ // states clear the guard; the balance reads below then reflect reality.
120
+ const pending = loadState().pendingWithdraw;
121
+ if (pending && input.confirm === true) {
122
+ const graceSec = 60; // relayer can mine right at the deadline; don't race it
123
+ if (Math.floor(Date.now() / 1000) < pending.deadline + graceSec) {
124
+ const state = await getRelayerTransactionState(pending.transactionID);
125
+ if (state === "STATE_MINED" || state === "STATE_CONFIRMED" || state === "STATE_FAILED" || state === "STATE_INVALID") {
126
+ saveState({ pendingWithdraw: undefined });
127
+ }
128
+ else {
129
+ const waitSecs = pending.deadline + graceSec - Math.floor(Date.now() / 1000);
130
+ return {
131
+ text: `A previous withdrawal (relayer tx ${pending.transactionID}, state: ${state ?? "unreachable"}) ` +
132
+ `may still execute — its signed transfer stays valid for up to ~${waitSecs}s more. Signing another ` +
133
+ `one now could double-send. Re-run after that window, when the balance reads will show what happened.`,
134
+ isError: true,
135
+ };
136
+ }
137
+ }
138
+ else {
139
+ saveState({ pendingWithdraw: undefined }); // deadline long past — expired, safe
140
+ }
141
+ }
142
+ // Withdrawable = pUSD + legacy USDC.e (wrapped on demand below).
143
+ const [pusdRaw, usdceRaw] = await Promise.all([
144
+ rawTokenBalance(PUSD_COLLATERAL, owner),
145
+ rawTokenBalance(USDCE_COLLATERAL, owner),
146
+ ]);
147
+ const totalRaw = pusdRaw + usdceRaw;
148
+ const totalUsd = Number(formatUnits(totalRaw, PUSD_DECIMALS));
149
+ if (totalRaw === 0n) {
150
+ return { text: `No pUSD or USDC.e to withdraw — the deposit wallet ${owner} holds $0. (Redeem/sell a position first.)`, isError: true };
46
151
  }
47
- const amountRaw = input.amount_usd !== undefined
48
- ? BigInt(Math.floor(input.amount_usd * 10 ** PUSD_DECIMALS))
49
- : balanceRaw;
50
- if (amountRaw > balanceRaw) {
51
- return { text: `Requested $${input.amount_usd} exceeds the pUSD balance of $${balanceUsd.toFixed(2)}.`, isError: true };
152
+ const amountRaw = input.amount_usd !== undefined ? parseUsdAmount(input.amount_usd) : totalRaw;
153
+ if (amountRaw === null) {
154
+ return { text: `amount_usd must be a positive USD amount with at most ${PUSD_DECIMALS} decimal places.`, isError: true };
155
+ }
156
+ if (amountRaw > totalRaw) {
157
+ return { text: `Requested $${input.amount_usd} exceeds the withdrawable collateral balance of $${totalUsd.toFixed(2)}.`, isError: true };
52
158
  }
53
159
  const amountUsd = Number(formatUnits(amountRaw, PUSD_DECIMALS));
160
+ const wrapRaw = amountRaw > pusdRaw ? amountRaw - pusdRaw : 0n;
54
161
  if (input.confirm !== true) {
55
162
  return {
56
163
  text: [
57
164
  `DRY RUN — nothing withdrawn.`,
58
- `Withdraw $${amountUsd.toFixed(2)} pUSD → native USDC on Base`,
165
+ `Withdraw $${amountUsd.toFixed(2)} → native USDC on Base`,
59
166
  ` from deposit wallet: ${owner}`,
60
167
  ` to (agent wallet): ${recipient}`,
168
+ ...(wrapRaw > 0n
169
+ ? [``, ` First wrap: $${Number(formatUnits(wrapRaw, PUSD_DECIMALS)).toFixed(2)} legacy USDC.e → pUSD (collateral onramp, same wallet)`]
170
+ : []),
61
171
  ``,
62
172
  `pUSD is unwrapped to USDC (Uniswap v3 — minor slippage may apply); instant, no Polymarket fee.`,
63
173
  `Re-call with confirm:true to execute.`,
64
174
  ].join("\n"),
65
- structured: { dryRun: true, amountUsd, from: owner, to: recipient, toChainId: BASE_CHAIN_ID, toToken: BASE_USDC },
175
+ structured: {
176
+ dryRun: true, amountUsd, from: owner, to: recipient, toChainId: BASE_CHAIN_ID, toToken: BASE_USDC,
177
+ pusdUsd: Number(formatUnits(pusdRaw, PUSD_DECIMALS)),
178
+ usdceUsd: Number(formatUnits(usdceRaw, PUSD_DECIMALS)),
179
+ wrapUsd: Number(formatUnits(wrapRaw, PUSD_DECIMALS)),
180
+ },
66
181
  };
67
182
  }
183
+ // 0. Sweep legacy USDC.e → pUSD when the pUSD on hand can't cover the
184
+ // amount. Wrapping keeps funds in the SAME wallet (a re-run after a
185
+ // partial failure is safe), so this batch is not double-spend-tracked.
186
+ if (wrapRaw > 0n) {
187
+ const [approveCall, wrapCall] = buildLegacyWrapCalls(owner, wrapRaw);
188
+ if (getSigType() === 3) {
189
+ await sendWalletBatch([approveCall, wrapCall], owner, "Wrap legacy USDC.e", {
190
+ guidance: 're-run action:"withdraw" — wrapping keeps funds in your wallet, so retrying is safe',
191
+ });
192
+ }
193
+ else {
194
+ const account = getPolymarketAccount();
195
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
196
+ const approveHash = await wallet.sendTransaction({ to: approveCall.target, data: approveCall.data, chain: polygon, account });
197
+ assertTransactionSucceeded(await getPublicClient().waitForTransactionReceipt({ hash: approveHash }), "USDC.e approval", approveHash);
198
+ const wrapHash = await wallet.sendTransaction({ to: wrapCall.target, data: wrapCall.data, chain: polygon, account });
199
+ assertTransactionSucceeded(await getPublicClient().waitForTransactionReceipt({ hash: wrapHash }), "USDC.e wrap", wrapHash);
200
+ }
201
+ const normalizedPusd = await readPusdUntil(owner, amountRaw);
202
+ if (normalizedPusd < amountRaw) {
203
+ throw new Error("The USDC.e wrap confirmed but the required pUSD balance is not yet visible after 3 reads. " +
204
+ "Your funds are in your wallet (wrapping moves nothing out) — re-run action:\"withdraw\" in a minute.");
205
+ }
206
+ }
68
207
  // 1. Ask the bridge for a one-time deposit address for this withdrawal.
69
208
  const headers = { "content-type": "application/json" };
70
209
  const builderCode = getBuilderCode();
@@ -79,18 +218,28 @@ export async function withdrawFunds(input) {
79
218
  const data = encodeFunctionData({ abi: ERC20_ABI, functionName: "transfer", args: [bridgeEvm, amountRaw] });
80
219
  let txHash;
81
220
  if (getSigType() === 3) {
82
- const res = await sendWalletBatch([{ target: PUSD_COLLATERAL, value: "0", data }], owner, "Withdraw");
221
+ const res = await sendWalletBatch([{ target: PUSD_COLLATERAL, value: "0", data }], owner, "Withdraw", {
222
+ guidance: WITHDRAW_GUIDANCE,
223
+ trackPendingWithdraw: true,
224
+ });
83
225
  txHash = res.transactionHash;
84
226
  }
85
227
  else {
86
228
  const account = getPolymarketAccount();
87
- const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
229
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
88
230
  txHash = await wallet.sendTransaction({ to: PUSD_COLLATERAL, data, chain: polygon, account });
89
- await getPublicClient().waitForTransactionReceipt({ hash: txHash });
231
+ // viem does NOT throw on a reverted tx — it resolves with status:"reverted".
232
+ // Discarding the receipt meant a REVERTED pUSD transfer still printed
233
+ // "✅ Withdrawal submitted … the bridge delivers USDC to Base" with a link
234
+ // to the failed tx and no isError, so the user waited for money that was
235
+ // never sent and blamed the bridge. redeem.ts and setup.ts both assert
236
+ // status; this path was the one that did not.
237
+ assertTransactionSucceeded(await getPublicClient().waitForTransactionReceipt({ hash: txHash }), "pUSD transfer", txHash);
90
238
  }
91
239
  return {
92
240
  text: [
93
- `✅ Withdrawal submitted: $${amountUsd.toFixed(2)} pUSD → USDC on Base`,
241
+ `✅ Withdrawal submitted: $${amountUsd.toFixed(2)} → USDC on Base`,
242
+ ...(wrapRaw > 0n ? [` (included wrapping $${Number(formatUnits(wrapRaw, PUSD_DECIMALS)).toFixed(2)} legacy USDC.e → pUSD first)`] : []),
94
243
  ` to your agent wallet: ${recipient}`,
95
244
  ...(txHash ? [` pUSD transfer tx: https://polygonscan.com/tx/${txHash}`] : []),
96
245
  ` The bridge unwraps + delivers USDC to Base (usually within a minute).`,
@@ -99,6 +248,7 @@ export async function withdrawFunds(input) {
99
248
  structured: {
100
249
  amountUsd, from: owner, to: recipient, toChainId: BASE_CHAIN_ID, toToken: BASE_USDC,
101
250
  bridgeAddress: bridgeEvm, transactionHash: txHash,
251
+ ...(wrapRaw > 0n ? { wrappedUsdceUsd: Number(formatUnits(wrapRaw, PUSD_DECIMALS)) } : {}),
102
252
  },
103
253
  };
104
254
  }