@blockrun/franklin 3.29.16 → 3.30.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.
@@ -0,0 +1,360 @@
1
+ // src/utils/polymarket/setup.ts
2
+ //
3
+ // action:"setup" — idempotent state machine that walks the account from "bare
4
+ // key" to "ready to trade", reporting done/todo at every step. Safe to re-run
5
+ // any time (after funding, after a failed batch, after switching sig types).
6
+ //
7
+ // POLY_1271 (default): derive → deploy (gasless) → fund (user) → approve
8
+ // (gasless WALLET batch, confirm-gated) → derive L2 creds → refresh CLOB cache.
9
+ // EOA mode (POLYMARKET_SIG_TYPE=0): the EOA holds pUSD itself and sends its own
10
+ // approval transactions (requires POL for gas).
11
+ import { createPublicClient, createWalletClient, encodeFunctionData, fallback, formatUnits, http, maxUint256, parseUnits, } from "viem";
12
+ import { polygon } from "viem/chains";
13
+ import { AssetType } from "@polymarket/clob-client-v2";
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";
16
+ import { loadDepositWalletForSigner, loadState, saveState } from "./creds.js";
17
+ import { deployDepositWallet, deriveDepositWallet, deriveDepositWalletNoCreds, isDepositWalletDeployed, relayerCredsMissing, relayerCredsMissingMessage, sendWalletBatch, } from "./relayer.js";
18
+ let _publicClient = null;
19
+ export function getPublicClient() {
20
+ if (!_publicClient) {
21
+ _publicClient = createPublicClient({
22
+ chain: polygon,
23
+ transport: fallback(POLYGON_RPC_URLS.map((u) => http(u, { retryCount: 2, timeout: 8_000 })), { retryCount: 2 }),
24
+ });
25
+ }
26
+ return _publicClient;
27
+ }
28
+ /**
29
+ * Retry a Polygon read across transient RPC failures. viem's fallback rotates
30
+ * transports on transport-level errors, but a flaky public RPC can still return
31
+ * a bad/stale body that surfaces as a decode error (which fallback does NOT
32
+ * retry) — enough to fail an entire setup on the approvals/balance reads. Re-
33
+ * running the whole read gives the fallback a fresh shot; a few attempts make
34
+ * setup robust to a single RPC hiccup instead of erroring the whole flow.
35
+ */
36
+ async function withRpcRetry(fn, attempts = 4) {
37
+ let lastErr;
38
+ for (let i = 0; i < attempts; i++) {
39
+ try {
40
+ return await fn();
41
+ }
42
+ catch (err) {
43
+ lastErr = err;
44
+ if (i < attempts - 1)
45
+ await new Promise((r) => setTimeout(r, 350 * (i + 1)));
46
+ }
47
+ }
48
+ throw lastErr;
49
+ }
50
+ /**
51
+ * The pUSD allowance we grant per exchange: the bounded amount if
52
+ * POLYMARKET_BOUNDED_APPROVALS is set, else unlimited. Shared by the approval
53
+ * builder AND the "granted?" check so a bounded value below the old $1000
54
+ * threshold still converges (an allowance exactly meeting the target counts).
55
+ */
56
+ function pusdApprovalTarget() {
57
+ const bounded = getBoundedApprovalsUsd();
58
+ return bounded === null ? maxUint256 : parseUnits(String(bounded), PUSD_DECIMALS);
59
+ }
60
+ /**
61
+ * The approval set Polymarket V2 trading needs from the funds-holding wallet:
62
+ * pUSD spend for buys (both exchanges), CTF operator for sells (both exchanges)
63
+ * plus the NegRisk adapter (negRisk redeem/convert path).
64
+ */
65
+ async function readApprovals(owner) {
66
+ const pc = getPublicClient();
67
+ const erc20Spenders = [
68
+ ["pUSD → CTF Exchange V2", CTF_EXCHANGE_V2],
69
+ ["pUSD → NegRisk Exchange V2", NEG_RISK_CTF_EXCHANGE_V2],
70
+ ];
71
+ const erc1155Operators = [
72
+ ["CTF → CTF Exchange V2", CTF_EXCHANGE_V2],
73
+ ["CTF → NegRisk Exchange V2", NEG_RISK_CTF_EXCHANGE_V2],
74
+ ["CTF → NegRisk Adapter", NEG_RISK_ADAPTER],
75
+ ];
76
+ // "granted" = allowance meets the amount we'd approve (bounded or unlimited),
77
+ // so a configured bound of any size converges instead of re-approving forever.
78
+ const target = pusdApprovalTarget();
79
+ const items = [];
80
+ for (const [label, spender] of erc20Spenders) {
81
+ const allowance = await withRpcRetry(() => pc.readContract({
82
+ address: PUSD_COLLATERAL,
83
+ abi: ERC20_ABI,
84
+ functionName: "allowance",
85
+ args: [owner, spender],
86
+ }));
87
+ items.push({ label, token: PUSD_COLLATERAL, spender, kind: "erc20", granted: allowance >= target });
88
+ }
89
+ for (const [label, operator] of erc1155Operators) {
90
+ const approved = await withRpcRetry(() => pc.readContract({
91
+ address: CONDITIONAL_TOKENS,
92
+ abi: ERC1155_ABI,
93
+ functionName: "isApprovedForAll",
94
+ args: [owner, operator],
95
+ }));
96
+ items.push({ label, token: CONDITIONAL_TOKENS, spender: operator, kind: "erc1155", granted: approved });
97
+ }
98
+ return items;
99
+ }
100
+ function buildApprovalCalls(missing) {
101
+ const erc20Amount = pusdApprovalTarget();
102
+ return missing.map((item) => ({
103
+ target: item.token,
104
+ value: "0",
105
+ data: item.kind === "erc20"
106
+ ? encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [item.spender, erc20Amount] })
107
+ : encodeFunctionData({ abi: ERC1155_ABI, functionName: "setApprovalForAll", args: [item.spender, true] }),
108
+ }));
109
+ }
110
+ export async function getPusdBalance(owner) {
111
+ const raw = await withRpcRetry(() => getPublicClient().readContract({
112
+ address: PUSD_COLLATERAL,
113
+ abi: ERC20_ABI,
114
+ functionName: "balanceOf",
115
+ args: [owner],
116
+ }));
117
+ return Number(formatUnits(raw, PUSD_DECIMALS));
118
+ }
119
+ function approvalChecklist(items) {
120
+ return items.map((i) => ` ${i.granted ? "✅" : "❌"} ${i.label}`).join("\n");
121
+ }
122
+ async function geoblockLine() {
123
+ const geo = await checkGeoblock();
124
+ const where = geo.country ? ` (egress country: ${geo.country})` : "";
125
+ if (geo.orderPlacement === "permitted")
126
+ return `✅ Region: order placement permitted from this egress${where}`;
127
+ if (geo.orderPlacement === "blocked") {
128
+ return `❌ Region: order placement BLOCKED from this egress${where}. ` +
129
+ "Route through an unrestricted egress: set POLYMARKET_CLOB_PROXY / HTTPS_PROXY, or point " +
130
+ "POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL at a Tokyo relay (see deploy/tokyo-egress).";
131
+ }
132
+ return "ℹ️ Region: could not determine order-placement status (check re-runs on demand)";
133
+ }
134
+ const KEY_BACKUP_NOTE = "🔑 The Polymarket signer is your BlockRun wallet key (~/.blockrun/.session). " +
135
+ "It is the ONLY key to these funds — back it up; never share or print it.";
136
+ export async function runSetup(opts) {
137
+ // Verify our exchange/collateral addresses still match the SDK's BEFORE any
138
+ // funds-affecting signature (approval batch / EOA approvals) — otherwise an
139
+ // upstream address rotation could have us approving a dead contract.
140
+ assertContractConfig();
141
+ const sigType = getSigType();
142
+ return sigType === 0 ? runSetupEoa(opts) : runSetupDepositWallet(opts);
143
+ }
144
+ async function runSetupDepositWallet(opts) {
145
+ const account = getPolymarketAccount();
146
+ if (relayerCredsMissing()) {
147
+ // Even without relayer creds we can DERIVE (not deploy) the deposit wallet
148
+ // address, so the user can pre-fund it while they get creds.
149
+ let depositWallet;
150
+ try {
151
+ depositWallet = loadDepositWalletForSigner(account.address)
152
+ ?? (await deriveDepositWalletNoCreds());
153
+ saveState({ depositWallet, signer: account.address });
154
+ }
155
+ catch { /* derivation is best-effort here */ }
156
+ const geo = await geoblockLine();
157
+ const balance = depositWallet ? await getPusdBalance(depositWallet).catch(() => 0) : 0;
158
+ return {
159
+ text: [
160
+ `Polymarket setup — deposit-wallet mode (signer ${account.address})`,
161
+ ...(depositWallet
162
+ ? [
163
+ ``,
164
+ `Your deposit wallet (holds betting funds): ${depositWallet}`,
165
+ ` https://polygonscan.com/address/${depositWallet}`,
166
+ ` ${balance > 0 ? `✅ pUSD balance: $${balance.toFixed(2)}` : "❌ Not funded yet"} — you can fund it NOW`,
167
+ ` (send ~$5 pUSD, or USDC via the Polymarket bridge which auto-wraps) while you get relayer creds.`,
168
+ ]
169
+ : []),
170
+ geo,
171
+ ``,
172
+ relayerCredsMissingMessage(),
173
+ ].join("\n"),
174
+ structured: { mode: "POLY_1271", signer: account.address, depositWallet, ready: false, missing: "relayer_credentials" },
175
+ };
176
+ }
177
+ // 1. Derive (pure CREATE2 math) + persist, keyed to the current signer.
178
+ const depositWallet = loadDepositWalletForSigner(account.address) ?? (await deriveDepositWallet());
179
+ saveState({ depositWallet, signer: account.address });
180
+ // 2. Deploy if missing — gasless, moves no funds, ownership is baked into
181
+ // the CREATE2 address, so no confirm gate is needed here.
182
+ let deployed = loadState().deployed === true || (await isDepositWalletDeployed(depositWallet));
183
+ let deployTxHash;
184
+ if (!deployed) {
185
+ const res = await deployDepositWallet();
186
+ deployTxHash = res.transactionHash;
187
+ deployed = true;
188
+ }
189
+ saveState({ deployed: true });
190
+ // 3. Funds + approvals state.
191
+ const balance = await getPusdBalance(depositWallet);
192
+ const approvals = await readApprovals(depositWallet);
193
+ const missing = approvals.filter((a) => !a.granted);
194
+ // 4. Approvals batch — the first real signature; confirm-gated with preview.
195
+ let approvalsTxHash;
196
+ let approvalsPending = missing.length > 0;
197
+ if (missing.length > 0 && opts.confirm) {
198
+ const calls = buildApprovalCalls(missing);
199
+ const res = await sendWalletBatch(calls, depositWallet, "Approval batch");
200
+ approvalsTxHash = res.transactionHash;
201
+ approvalsPending = false;
202
+ saveState({ approvalsDone: true });
203
+ }
204
+ else if (missing.length === 0) {
205
+ saveState({ approvalsDone: true });
206
+ }
207
+ // 5. L2 creds + CLOB balance-cache refresh (needs deposit wallet on disk,
208
+ // which is guaranteed above). Non-fatal: report instead of failing setup.
209
+ let credsReady = false;
210
+ let credsNote = "";
211
+ try {
212
+ const clob = await getClobClient();
213
+ credsReady = true;
214
+ await clob.updateBalanceAllowance({ asset_type: AssetType.COLLATERAL }).catch(() => undefined);
215
+ }
216
+ catch (err) {
217
+ credsNote = ` (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
218
+ }
219
+ const geo = await geoblockLine();
220
+ const ready = deployed && balance > 0 && !approvalsPending && credsReady;
221
+ const lines = [
222
+ `Polymarket setup — deposit-wallet mode (POLY_1271)`,
223
+ ``,
224
+ `Signer (BlockRun wallet): ${account.address}`,
225
+ `Deposit wallet (holds betting funds): ${depositWallet}`,
226
+ ` https://polygonscan.com/address/${depositWallet}`,
227
+ ``,
228
+ `${deployed ? "✅" : "❌"} Deposit wallet deployed${deployTxHash ? ` (tx ${deployTxHash})` : ""}`,
229
+ `${balance > 0 ? "✅" : "❌"} pUSD balance: $${balance.toFixed(2)}`,
230
+ ...(balance <= 0
231
+ ? [
232
+ ` Fund it: send pUSD (or USDC via the Polymarket bridge/app, which`,
233
+ ` auto-wraps to pUSD) to the DEPOSIT WALLET address above. Only pUSD`,
234
+ ` held in the deposit wallet counts as buying power. ~$5 is plenty for a demo.`,
235
+ ]
236
+ : []),
237
+ `${approvalsPending ? "❌" : "✅"} Exchange approvals${approvalsTxHash ? ` (batch tx ${approvalsTxHash})` : ""}`,
238
+ approvalChecklist(approvals),
239
+ ...(approvalsPending && !opts.confirm
240
+ ? [
241
+ ``,
242
+ ` ${missing.length} approval(s) needed. This authorizes Polymarket's exchange`,
243
+ ` contracts to settle YOUR signed orders from the deposit wallet (gasless`,
244
+ ` batch via the relayer). Re-run action:"setup" with confirm:true to sign.`,
245
+ ]
246
+ : []),
247
+ `${credsReady ? "✅" : "❌"} CLOB API credentials${credsNote}`,
248
+ geo,
249
+ ``,
250
+ ready ? `🎯 Ready to trade. Discover markets with blockrun_markets, then action:"buy".` : `Re-run action:"setup" after completing the ❌ items.`,
251
+ ``,
252
+ KEY_BACKUP_NOTE,
253
+ ];
254
+ return {
255
+ text: lines.join("\n"),
256
+ structured: {
257
+ mode: "POLY_1271",
258
+ signer: account.address,
259
+ depositWallet,
260
+ deployed,
261
+ pusdBalance: balance,
262
+ approvals: approvals.map((a) => ({ label: a.label, granted: a.granted })),
263
+ approvalsPending,
264
+ credsReady,
265
+ ready,
266
+ },
267
+ };
268
+ }
269
+ async function runSetupEoa(opts) {
270
+ const account = getPolymarketAccount();
271
+ const pc = getPublicClient();
272
+ const [balance, polWei, approvals] = await Promise.all([
273
+ getPusdBalance(account.address),
274
+ pc.getBalance({ address: account.address }),
275
+ readApprovals(account.address),
276
+ ]);
277
+ const pol = Number(formatUnits(polWei, 18));
278
+ const missing = approvals.filter((a) => !a.granted);
279
+ // EOA mode sends its own approval transactions — needs POL for gas.
280
+ let approvalsPending = missing.length > 0;
281
+ const approvalTxHashes = [];
282
+ if (missing.length > 0 && opts.confirm) {
283
+ if (pol <= 0) {
284
+ approvalsPending = true;
285
+ }
286
+ else {
287
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
288
+ const erc20Amount = pusdApprovalTarget(); // honor POLYMARKET_BOUNDED_APPROVALS in EOA mode too
289
+ for (const item of missing) {
290
+ const hash = item.kind === "erc20"
291
+ ? await wallet.writeContract({
292
+ address: item.token,
293
+ abi: ERC20_ABI,
294
+ functionName: "approve",
295
+ args: [item.spender, erc20Amount],
296
+ chain: polygon,
297
+ account,
298
+ })
299
+ : await wallet.writeContract({
300
+ address: item.token,
301
+ abi: ERC1155_ABI,
302
+ functionName: "setApprovalForAll",
303
+ args: [item.spender, true],
304
+ chain: polygon,
305
+ account,
306
+ });
307
+ await pc.waitForTransactionReceipt({ hash });
308
+ approvalTxHashes.push(hash);
309
+ }
310
+ approvalsPending = false;
311
+ }
312
+ }
313
+ let credsReady = false;
314
+ let credsNote = "";
315
+ try {
316
+ const clob = await getClobClient();
317
+ credsReady = true;
318
+ await clob.updateBalanceAllowance({ asset_type: AssetType.COLLATERAL }).catch(() => undefined);
319
+ }
320
+ catch (err) {
321
+ credsNote = ` (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
322
+ }
323
+ const geo = await geoblockLine();
324
+ const ready = balance > 0 && !approvalsPending && credsReady;
325
+ const lines = [
326
+ `Polymarket setup — plain EOA mode (POLYMARKET_SIG_TYPE=0)`,
327
+ ``,
328
+ `Trading wallet (BlockRun key, holds funds directly): ${account.address}`,
329
+ ` https://polygonscan.com/address/${account.address}`,
330
+ ``,
331
+ `${balance > 0 ? "✅" : "❌"} pUSD balance: $${balance.toFixed(2)}`,
332
+ `${pol > 0 ? "✅" : "❌"} POL for gas: ${pol.toFixed(4)} POL`,
333
+ `${approvalsPending ? "❌" : "✅"} Exchange approvals${approvalTxHashes.length ? ` (${approvalTxHashes.length} tx sent)` : ""}`,
334
+ approvalChecklist(approvals),
335
+ ...(approvalsPending && !opts.confirm
336
+ ? [``, ` Re-run action:"setup" with confirm:true to send the approval transactions.`]
337
+ : approvalsPending && pol <= 0
338
+ ? [``, ` Cannot send approvals: the EOA has no POL for gas. Send a little POL first.`]
339
+ : []),
340
+ `${credsReady ? "✅" : "❌"} CLOB API credentials${credsNote}`,
341
+ geo,
342
+ ``,
343
+ ready ? `🎯 Ready to trade.` : `Re-run action:"setup" after completing the ❌ items.`,
344
+ ``,
345
+ KEY_BACKUP_NOTE,
346
+ ];
347
+ return {
348
+ text: lines.join("\n"),
349
+ structured: {
350
+ mode: "EOA",
351
+ signer: account.address,
352
+ pusdBalance: balance,
353
+ polBalance: pol,
354
+ approvals: approvals.map((a) => ({ label: a.label, granted: a.granted })),
355
+ approvalsPending,
356
+ credsReady,
357
+ ready,
358
+ },
359
+ };
360
+ }
@@ -0,0 +1,14 @@
1
+ import { type Hex } from "viem";
2
+ /**
3
+ * Load-or-create the EVM session key and cache it so the synchronous
4
+ * getOrCreateWalletKey() below can serve it. Call once at capability entry.
5
+ */
6
+ export declare function ensurePolymarketWallet(): Promise<void>;
7
+ /** The local EVM private key (0x…), cached. Mirrors blockrun-mcp's sync helper. */
8
+ export declare function getOrCreateWalletKey(): Hex;
9
+ /**
10
+ * USDC balance in whole dollars for `address` on the given chain. Only "base" is
11
+ * supported (the agent's x402 wallet); Solana returns null since Polymarket
12
+ * funding always sources Base USDC. Read-only viem call, best-effort.
13
+ */
14
+ export declare function getChainBalance(chain: "base" | "solana", address: string): Promise<number | null>;
@@ -0,0 +1,69 @@
1
+ // src/tools/polymarket/wallet-key.ts
2
+ //
3
+ // Franklin shim for the two wallet helpers the ported Polymarket module expects
4
+ // from blockrun-mcp's `../wallet.js`. Franklin keeps its EVM session key via
5
+ // @blockrun/llm (`~/.blockrun/.session` — the SAME key that pays x402 fees on
6
+ // Base), so a bet on Polygon and an API payment on Base are one identity. The
7
+ // key never leaves this machine.
8
+ //
9
+ // getOrCreateWalletKey() must stay SYNCHRONOUS because the ported client.ts calls
10
+ // it inside getPolymarketAccount() without awaiting. We satisfy that by caching
11
+ // the key: the PolymarketBet capability calls ensurePolymarketWallet() (async,
12
+ // creates the wallet if missing) before dispatching any action, after which the
13
+ // sync getter returns the cached key. loadWallet() (sync) is the fallback when
14
+ // the cache is cold but a wallet already exists on disk.
15
+ import { createPublicClient, http, erc20Abi } from "viem";
16
+ import { base } from "viem/chains";
17
+ import { getOrCreateWallet, loadWallet } from "@blockrun/llm";
18
+ import { BASE_USDC } from "./constants.js";
19
+ let _cachedKey = null;
20
+ /**
21
+ * Load-or-create the EVM session key and cache it so the synchronous
22
+ * getOrCreateWalletKey() below can serve it. Call once at capability entry.
23
+ */
24
+ export async function ensurePolymarketWallet() {
25
+ const wallet = await getOrCreateWallet();
26
+ _cachedKey = wallet.privateKey;
27
+ }
28
+ /** The local EVM private key (0x…), cached. Mirrors blockrun-mcp's sync helper. */
29
+ export function getOrCreateWalletKey() {
30
+ if (_cachedKey)
31
+ return _cachedKey;
32
+ // Cold cache but a wallet may already exist: loadWallet() returns the key
33
+ // string synchronously (or throws/empty if none exists yet).
34
+ try {
35
+ const raw = loadWallet();
36
+ if (typeof raw === "string" && raw.startsWith("0x") && raw.length === 66) {
37
+ _cachedKey = raw;
38
+ return _cachedKey;
39
+ }
40
+ }
41
+ catch {
42
+ /* fall through to the explicit error */
43
+ }
44
+ throw new Error("Polymarket wallet not initialized. This is an internal error — the " +
45
+ "capability must call ensurePolymarketWallet() before signing.");
46
+ }
47
+ const BASE_RPC = process.env.BASE_RPC_URL || process.env.RUNCODE_BASE_RPC || "https://mainnet.base.org";
48
+ /**
49
+ * USDC balance in whole dollars for `address` on the given chain. Only "base" is
50
+ * supported (the agent's x402 wallet); Solana returns null since Polymarket
51
+ * funding always sources Base USDC. Read-only viem call, best-effort.
52
+ */
53
+ export async function getChainBalance(chain, address) {
54
+ if (chain !== "base")
55
+ return null;
56
+ try {
57
+ const client = createPublicClient({ chain: base, transport: http(BASE_RPC) });
58
+ const bal = (await client.readContract({
59
+ address: BASE_USDC,
60
+ abi: erc20Abi,
61
+ functionName: "balanceOf",
62
+ args: [address],
63
+ }));
64
+ return Number(bal) / 1e6;
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
@@ -0,0 +1,8 @@
1
+ import type { ToolResult } from "./orders.js";
2
+ interface WithdrawInput {
3
+ amount_usd?: number;
4
+ to_address?: string;
5
+ confirm?: boolean;
6
+ }
7
+ export declare function withdrawFunds(input: WithdrawInput): Promise<ToolResult>;
8
+ export {};
@@ -0,0 +1,108 @@
1
+ // src/utils/polymarket/withdraw.ts
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):
6
+ // 1. POST /withdraw {address, toChainId, toTokenAddress, recipientAddr} → a
7
+ // one-time EVM bridge address.
8
+ // 2. Transfer pUSD FROM the deposit wallet TO that bridge address (gasless
9
+ // relayer WALLET batch; or a direct tx in EOA mode). The amount sent IS the
10
+ // withdrawal amount.
11
+ // 3. The bridge unwraps pUSD → USDC (Collateral Offramp + Uniswap v3) and
12
+ // sends it to recipientAddr on Base. Instant, no Polymarket fee (minor
13
+ // swap slippage may apply).
14
+ import axios from "axios";
15
+ import { encodeFunctionData, formatUnits, http, createWalletClient } from "viem";
16
+ 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";
18
+ import { getPolymarketAccount } from "./client.js";
19
+ import { mapClobError } from "./orders.js";
20
+ import { getFundsAddress } from "./positions.js";
21
+ import { sendWalletBatch } from "./relayer.js";
22
+ import { getPublicClient } from "./setup.js";
23
+ async function rawPusdBalance(owner) {
24
+ return getPublicClient().readContract({
25
+ address: PUSD_COLLATERAL,
26
+ abi: ERC20_ABI,
27
+ functionName: "balanceOf",
28
+ args: [owner],
29
+ });
30
+ }
31
+ export async function withdrawFunds(input) {
32
+ let owner;
33
+ try {
34
+ owner = getFundsAddress();
35
+ }
36
+ catch (err) {
37
+ return { text: err instanceof Error ? err.message : String(err), isError: true };
38
+ }
39
+ const recipient = input.to_address || getPolymarketAccount().address;
40
+ 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 };
46
+ }
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 };
52
+ }
53
+ const amountUsd = Number(formatUnits(amountRaw, PUSD_DECIMALS));
54
+ if (input.confirm !== true) {
55
+ return {
56
+ text: [
57
+ `DRY RUN — nothing withdrawn.`,
58
+ `Withdraw $${amountUsd.toFixed(2)} pUSD → native USDC on Base`,
59
+ ` from deposit wallet: ${owner}`,
60
+ ` to (agent wallet): ${recipient}`,
61
+ ``,
62
+ `pUSD is unwrapped to USDC (Uniswap v3 — minor slippage may apply); instant, no Polymarket fee.`,
63
+ `Re-call with confirm:true to execute.`,
64
+ ].join("\n"),
65
+ structured: { dryRun: true, amountUsd, from: owner, to: recipient, toChainId: BASE_CHAIN_ID, toToken: BASE_USDC },
66
+ };
67
+ }
68
+ // 1. Ask the bridge for a one-time deposit address for this withdrawal.
69
+ const headers = { "content-type": "application/json" };
70
+ const builderCode = getBuilderCode();
71
+ if (builderCode)
72
+ headers["X-Builder-Code"] = builderCode;
73
+ const wres = await axios.post(`${BRIDGE_API_HOST}/withdraw`, { address: owner, toChainId: String(BASE_CHAIN_ID), toTokenAddress: BASE_USDC, recipientAddr: recipient }, { headers, timeout: 20_000 });
74
+ const bridgeEvm = wres.data?.address?.evm;
75
+ if (!bridgeEvm) {
76
+ return { text: `Bridge did not return a withdrawal address (got: ${JSON.stringify(wres.data)}).`, isError: true };
77
+ }
78
+ // 2. Transfer pUSD from the deposit wallet to the bridge address.
79
+ const data = encodeFunctionData({ abi: ERC20_ABI, functionName: "transfer", args: [bridgeEvm, amountRaw] });
80
+ let txHash;
81
+ if (getSigType() === 3) {
82
+ const res = await sendWalletBatch([{ target: PUSD_COLLATERAL, value: "0", data }], owner, "Withdraw");
83
+ txHash = res.transactionHash;
84
+ }
85
+ else {
86
+ const account = getPolymarketAccount();
87
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
88
+ txHash = await wallet.sendTransaction({ to: PUSD_COLLATERAL, data, chain: polygon, account });
89
+ await getPublicClient().waitForTransactionReceipt({ hash: txHash });
90
+ }
91
+ return {
92
+ text: [
93
+ `✅ Withdrawal submitted: $${amountUsd.toFixed(2)} pUSD → USDC on Base`,
94
+ ` to your agent wallet: ${recipient}`,
95
+ ...(txHash ? [` pUSD transfer tx: https://polygonscan.com/tx/${txHash}`] : []),
96
+ ` The bridge unwraps + delivers USDC to Base (usually within a minute).`,
97
+ ` Track: GET ${BRIDGE_API_HOST}/status/${owner}`,
98
+ ].join("\n"),
99
+ structured: {
100
+ amountUsd, from: owner, to: recipient, toChainId: BASE_CHAIN_ID, toToken: BASE_USDC,
101
+ bridgeAddress: bridgeEvm, transactionHash: txHash,
102
+ },
103
+ };
104
+ }
105
+ catch (err) {
106
+ return { text: await mapClobError(err), isError: true };
107
+ }
108
+ }
@@ -0,0 +1,4 @@
1
+ import type { CapabilityHandler } from '../agent/types.js';
2
+ import { getSessionLedger } from './polymarket/orders.js';
3
+ export declare const polymarketBetCapability: CapabilityHandler;
4
+ export { getSessionLedger };