@blockrun/franklin 3.29.15 → 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.
Files changed (33) hide show
  1. package/dist/commands/start.js +4 -10
  2. package/dist/stats/insights.js +1 -3
  3. package/dist/tools/index.js +3 -1
  4. package/dist/tools/polymarket/client.d.ts +61 -0
  5. package/dist/tools/polymarket/client.js +236 -0
  6. package/dist/tools/polymarket/constants.d.ts +192 -0
  7. package/dist/tools/polymarket/constants.js +205 -0
  8. package/dist/tools/polymarket/creds.d.ts +33 -0
  9. package/dist/tools/polymarket/creds.js +96 -0
  10. package/dist/tools/polymarket/fund.d.ts +5 -0
  11. package/dist/tools/polymarket/fund.js +141 -0
  12. package/dist/tools/polymarket/l1-auth-1271.d.ts +29 -0
  13. package/dist/tools/polymarket/l1-auth-1271.js +198 -0
  14. package/dist/tools/polymarket/orders.d.ts +44 -0
  15. package/dist/tools/polymarket/orders.js +420 -0
  16. package/dist/tools/polymarket/positions.d.ts +26 -0
  17. package/dist/tools/polymarket/positions.js +88 -0
  18. package/dist/tools/polymarket/redeem.d.ts +5 -0
  19. package/dist/tools/polymarket/redeem.js +121 -0
  20. package/dist/tools/polymarket/relayer.d.ts +37 -0
  21. package/dist/tools/polymarket/relayer.js +140 -0
  22. package/dist/tools/polymarket/setup.d.ts +9 -0
  23. package/dist/tools/polymarket/setup.js +360 -0
  24. package/dist/tools/polymarket/wallet-key.d.ts +14 -0
  25. package/dist/tools/polymarket/wallet-key.js +69 -0
  26. package/dist/tools/polymarket/withdraw.d.ts +8 -0
  27. package/dist/tools/polymarket/withdraw.js +108 -0
  28. package/dist/tools/polymarket-bet.d.ts +4 -0
  29. package/dist/tools/polymarket-bet.js +164 -0
  30. package/dist/tools/tool-categories.js +4 -0
  31. package/package.json +7 -2
  32. package/dist/agent/media-router.d.ts +0 -98
  33. package/dist/agent/media-router.js +0 -328
@@ -0,0 +1,205 @@
1
+ // src/utils/polymarket/constants.ts
2
+ //
3
+ // Polymarket CLOB V2 trading constants (Polygon mainnet, chainId 137).
4
+ //
5
+ // VERIFY addresses against https://docs.polymarket.com/resources/contracts
6
+ // before changing — and note the runtime cross-check below: if our copies ever
7
+ // disagree with the installed @polymarket/clob-client-v2's own contract config,
8
+ // assertContractConfig() throws at first use so an upstream address rotation is
9
+ // caught loudly instead of sending approvals to a dead contract.
10
+ import { getContractConfig } from "@polymarket/clob-client-v2";
11
+ export const POLYGON_CHAIN_ID = 137;
12
+ // --- Contracts (Polygon 137) ---
13
+ // Exchange contracts are per-order-version; production CLOB reports version 2
14
+ // (GET /version) as of 2026-07. The SDK routes orders to the right exchange by
15
+ // itself — these copies exist for the APPROVALS batch and redeem calldata.
16
+ export const CTF_EXCHANGE_V2 = "0xE111180000d2663C0091e4f400237545B87B996B";
17
+ export const NEG_RISK_CTF_EXCHANGE_V2 = "0xe2222d279d744050d28e00520010520000310F59";
18
+ export const NEG_RISK_ADAPTER = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296";
19
+ export const CONDITIONAL_TOKENS = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
20
+ // pUSD — Polymarket's 1:1 collateral wrapper (labelled CollateralToken proxy).
21
+ export const PUSD_COLLATERAL = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
22
+ export const COLLATERAL_ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee";
23
+ export const DEPOSIT_WALLET_FACTORY = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07";
24
+ /**
25
+ * Cross-check our address copies against the SDK's canonical config. Called
26
+ * once from the client factory; throwing here is deliberate — a silent
27
+ * mismatch would mean approvals/redeem target different contracts than the
28
+ * orders the SDK signs.
29
+ */
30
+ export function assertContractConfig() {
31
+ const cfg = getContractConfig(POLYGON_CHAIN_ID);
32
+ const checks = [
33
+ ["exchangeV2", cfg.exchangeV2, CTF_EXCHANGE_V2],
34
+ ["negRiskExchangeV2", cfg.negRiskExchangeV2, NEG_RISK_CTF_EXCHANGE_V2],
35
+ ["negRiskAdapter", cfg.negRiskAdapter, NEG_RISK_ADAPTER],
36
+ ["collateral", cfg.collateral, PUSD_COLLATERAL],
37
+ ["conditionalTokens", cfg.conditionalTokens, CONDITIONAL_TOKENS],
38
+ ];
39
+ for (const [name, sdkAddr, ours] of checks) {
40
+ if (sdkAddr.toLowerCase() !== ours.toLowerCase()) {
41
+ throw new Error(`Polymarket contract mismatch for '${name}': SDK says ${sdkAddr}, ` +
42
+ `blockrun-mcp has ${ours}. Update src/utils/polymarket/constants.ts ` +
43
+ `after verifying https://docs.polymarket.com/resources/contracts.`);
44
+ }
45
+ }
46
+ }
47
+ // --- Hosts (env-overridable so Phase 2 can point them at the BlockRun gateway) ---
48
+ // CLOB order placement is geoblocked by IP (US/UK/EU and many regions). We
49
+ // DEFAULT to BlockRun's hosted Tokyo egress so trading works out of the box with
50
+ // zero config — it only forwards to Polymarket's CLOB (it can't see or move
51
+ // funds; every order is still signed locally by the user's key). Override with
52
+ // POLYMARKET_CLOB_HOST to hit Polymarket directly (from a permitted region) or to
53
+ // run your own egress. Direct Polymarket host: https://clob.polymarket.com
54
+ export const CLOB_HOST = process.env.POLYMARKET_CLOB_HOST || "https://pm-egress-vbsbhh7lea-an.a.run.app/clob";
55
+ export const RELAYER_URL = process.env.POLYMARKET_RELAYER_URL || "https://relayer-v2.polymarket.com";
56
+ export const DATA_API_HOST = process.env.POLYMARKET_DATA_API_HOST || "https://data-api.polymarket.com";
57
+ export const BRIDGE_API_HOST = process.env.POLYMARKET_BRIDGE_HOST || "https://bridge.polymarket.com";
58
+ // Default withdrawal destination: native USDC on Base (chainId 8453) — the same
59
+ // token/chain the BlockRun agent wallet already uses for x402 payments, so
60
+ // winnings cash out to the very wallet that pays for AI. (Same address as
61
+ // USDC_ADDRESS in ../constants.ts.)
62
+ export const BASE_CHAIN_ID = 8453;
63
+ export const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
64
+ // Overridable so a demo routing orders through a Tokyo relay can report the
65
+ // SAME egress's region (a permitted ✅) instead of the local IP's status.
66
+ export const GEOBLOCK_URL = process.env.POLYMARKET_GEOBLOCK_URL || "https://polymarket.com/api/geoblock";
67
+ export const BRIDGE_UI_URL = "https://polymarket.com"; // deposits happen via the Polymarket bridge UI/API
68
+ // Public Polygon RPCs with fallback, mirroring BASE_RPC_URLS in ../constants.ts.
69
+ // Used only for read-only approval/balance checks (viem public client).
70
+ // 1rpc first — polygon-rpc.com was observed lagging several blocks behind, which
71
+ // made freshly-confirmed deploys/approvals read as still-pending.
72
+ export const POLYGON_RPC_URLS = [
73
+ "https://1rpc.io/matic",
74
+ "https://polygon.llamarpc.com",
75
+ "https://polygon-rpc.com",
76
+ ];
77
+ // --- Safety knobs ---
78
+ /**
79
+ * Parse a money-cap env var with FAIL-CLOSED semantics for safety controls:
80
+ * - unset/blank → `unsetDefault` (the intended default when the knob is absent)
81
+ * - a valid non-negative number → that number (0 is honored, e.g. "freeze")
82
+ * - garbage (typo like "$100", negative) → 0 and a stderr warning, so a
83
+ * misconfigured cap blocks trading rather than silently reverting to a
84
+ * permissive default.
85
+ */
86
+ function parseCapEnv(name, raw, unsetDefault) {
87
+ if (raw === undefined || raw.trim() === "")
88
+ return unsetDefault;
89
+ const n = Number(raw);
90
+ if (Number.isFinite(n) && n >= 0)
91
+ return n;
92
+ console.error(`[blockrun_polymarket] ${name}="${raw}" is not a valid number — treating it as 0 ` +
93
+ `(orders blocked) so a misconfigured safety cap fails closed. Set a positive dollar amount.`);
94
+ return 0;
95
+ }
96
+ /** Hard per-order notional cap in pUSD dollars (default $25; 0/invalid blocks). */
97
+ export function getMaxBetUsd() {
98
+ return parseCapEnv("POLYMARKET_MAX_BET_USD", process.env.POLYMARKET_MAX_BET_USD, 25);
99
+ }
100
+ /** Optional cumulative per-process cap; null = uncapped (unset); 0 = freeze. */
101
+ export function getMaxSessionUsd() {
102
+ return parseCapEnv("POLYMARKET_MAX_SESSION_USD", process.env.POLYMARKET_MAX_SESSION_USD, null);
103
+ }
104
+ /**
105
+ * Bounded pUSD approvals in dollars; null = unlimited (maxUint256). The CTF
106
+ * ERC-1155 approval is inherently all-or-nothing either way. Only a valid
107
+ * positive value bounds; 0/garbage → unlimited (approvals are not a per-order
108
+ * spend gate, so failing them "closed" would just block setup).
109
+ */
110
+ export function getBoundedApprovalsUsd() {
111
+ const raw = process.env.POLYMARKET_BOUNDED_APPROVALS;
112
+ if (raw === undefined || raw.trim() === "")
113
+ return null;
114
+ const n = Number(raw);
115
+ return Number.isFinite(n) && n > 0 ? n : null;
116
+ }
117
+ /**
118
+ * Signature type override: 3 (POLY_1271 deposit wallet, default) or 0 (plain
119
+ * EOA "demo insurance" mode — EOA holds pUSD itself, pays its own POL gas).
120
+ */
121
+ export function getSigType() {
122
+ return process.env.POLYMARKET_SIG_TYPE === "0" ? 0 : 3;
123
+ }
124
+ /**
125
+ * Optional builder attribution code (bytes32 or plain string per Polymarket
126
+ * builder settings). Absent → orders carry no builder fee attribution.
127
+ */
128
+ export function getBuilderCode() {
129
+ const v = process.env.BLOCKRUN_BUILDER_CODE?.trim();
130
+ return v ? v : undefined;
131
+ }
132
+ /** Egress proxy for CLOB order traffic (see README: geoblock). */
133
+ export function getClobProxy() {
134
+ const v = process.env.POLYMARKET_CLOB_PROXY?.trim();
135
+ return v ? v : undefined;
136
+ }
137
+ export function getRelayerCreds() {
138
+ const key = process.env.POLYMARKET_RELAYER_API_KEY?.trim();
139
+ const keyAddress = process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS?.trim();
140
+ if (key && keyAddress)
141
+ return { key, keyAddress };
142
+ return null;
143
+ }
144
+ // ERC-20/1155 minimal ABIs for approval + balance reads and approval calldata.
145
+ export const ERC20_ABI = [
146
+ {
147
+ name: "allowance", type: "function", stateMutability: "view",
148
+ inputs: [{ name: "owner", type: "address" }, { name: "spender", type: "address" }],
149
+ outputs: [{ name: "", type: "uint256" }],
150
+ },
151
+ {
152
+ name: "approve", type: "function", stateMutability: "nonpayable",
153
+ inputs: [{ name: "spender", type: "address" }, { name: "amount", type: "uint256" }],
154
+ outputs: [{ name: "", type: "bool" }],
155
+ },
156
+ {
157
+ name: "transfer", type: "function", stateMutability: "nonpayable",
158
+ inputs: [{ name: "to", type: "address" }, { name: "amount", type: "uint256" }],
159
+ outputs: [{ name: "", type: "bool" }],
160
+ },
161
+ {
162
+ name: "balanceOf", type: "function", stateMutability: "view",
163
+ inputs: [{ name: "account", type: "address" }],
164
+ outputs: [{ name: "", type: "uint256" }],
165
+ },
166
+ ];
167
+ export const ERC1155_ABI = [
168
+ {
169
+ name: "isApprovedForAll", type: "function", stateMutability: "view",
170
+ inputs: [{ name: "account", type: "address" }, { name: "operator", type: "address" }],
171
+ outputs: [{ name: "", type: "bool" }],
172
+ },
173
+ {
174
+ name: "balanceOf", type: "function", stateMutability: "view",
175
+ inputs: [{ name: "account", type: "address" }, { name: "id", type: "uint256" }],
176
+ outputs: [{ name: "", type: "uint256" }],
177
+ },
178
+ {
179
+ name: "setApprovalForAll", type: "function", stateMutability: "nonpayable",
180
+ inputs: [{ name: "operator", type: "address" }, { name: "approved", type: "bool" }],
181
+ outputs: [],
182
+ },
183
+ {
184
+ name: "redeemPositions", type: "function", stateMutability: "nonpayable",
185
+ inputs: [
186
+ { name: "collateralToken", type: "address" },
187
+ { name: "parentCollectionId", type: "bytes32" },
188
+ { name: "conditionId", type: "bytes32" },
189
+ { name: "indexSets", type: "uint256[]" },
190
+ ],
191
+ outputs: [],
192
+ },
193
+ ];
194
+ // NegRisk adapter redeem takes explicit YES/NO amounts instead of index sets.
195
+ export const NEG_RISK_ADAPTER_ABI = [
196
+ {
197
+ name: "redeemPositions", type: "function", stateMutability: "nonpayable",
198
+ inputs: [
199
+ { name: "conditionId", type: "bytes32" },
200
+ { name: "amounts", type: "uint256[]" },
201
+ ],
202
+ outputs: [],
203
+ },
204
+ ];
205
+ export const PUSD_DECIMALS = 6;
@@ -0,0 +1,33 @@
1
+ export interface L2Creds {
2
+ key: string;
3
+ secret: string;
4
+ passphrase: string;
5
+ derivedAt: string;
6
+ }
7
+ export interface BuilderCreds {
8
+ key: string;
9
+ secret: string;
10
+ passphrase: string;
11
+ createdAt: string;
12
+ }
13
+ export interface PolymarketState {
14
+ depositWallet?: string;
15
+ signer?: string;
16
+ deployed?: boolean;
17
+ approvalsDone?: boolean;
18
+ }
19
+ export declare function loadL2Creds(address: string, sigType: number): L2Creds | null;
20
+ export declare function saveL2Creds(address: string, sigType: number, creds: Omit<L2Creds, "derivedAt">): void;
21
+ /** Drop cached creds (called on CLOB 401 / the issue-#65 error fingerprint). */
22
+ export declare function invalidateL2Creds(address: string, sigType: number): void;
23
+ export declare function loadBuilderCreds(owner: string): BuilderCreds | null;
24
+ export declare function saveBuilderCreds(owner: string, creds: Omit<BuilderCreds, "createdAt">): void;
25
+ export declare function loadState(): PolymarketState;
26
+ /**
27
+ * The persisted deposit wallet, but ONLY if it belongs to `signer`. After a
28
+ * BlockRun key rotation (~/.blockrun/.session regenerated) the stored wallet is
29
+ * a CREATE2 vault the new key cannot control, so returning it would point
30
+ * trading/funding at unrecoverable funds. Returns undefined on signer mismatch.
31
+ */
32
+ export declare function loadDepositWalletForSigner(signer: string): string | undefined;
33
+ export declare function saveState(patch: Partial<PolymarketState>): PolymarketState;
@@ -0,0 +1,96 @@
1
+ // src/utils/polymarket/creds.ts
2
+ //
3
+ // On-disk state for the Polymarket tool, kept alongside the wallet session in
4
+ // ~/.blockrun/ with 0600 modes (same discipline as setChain() in ../wallet.ts):
5
+ //
6
+ // .polymarket-creds — CLOB L2 API credentials keyed by `${address}:${sigType}`.
7
+ // The key encodes the identity the creds are bound to
8
+ // (deposit wallet for sig type 3, EOA for type 0), so a
9
+ // sig-type switch never reuses mismatched creds — exactly
10
+ // the mismatch behind clob-client-v2 issue #65.
11
+ // .polymarket.json — tool state (deposit wallet address, deploy/approval
12
+ // progress) so setup is idempotent across restarts.
13
+ //
14
+ // L2 `secret`/`passphrase` are betting-account credentials, not BlockRun keys.
15
+ // They are only ever read back into the ClobClient (client.ts) — no code path
16
+ // prints them: setup/positions/orders report field presence or key prefixes,
17
+ // never the values, and the credential-derivation error path (l1-auth-1271.ts)
18
+ // reports only which fields a response contained, never the body.
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import os from "node:os";
22
+ const BLOCKRUN_DIR = path.join(os.homedir(), ".blockrun");
23
+ const CREDS_FILE = path.join(BLOCKRUN_DIR, ".polymarket-creds");
24
+ const BUILDER_CREDS_FILE = path.join(BLOCKRUN_DIR, ".polymarket-builder-creds");
25
+ const STATE_FILE = path.join(BLOCKRUN_DIR, ".polymarket.json");
26
+ function readJsonFile(file) {
27
+ try {
28
+ if (!fs.existsSync(file))
29
+ return null;
30
+ const raw = fs.readFileSync(file, "utf-8").trim();
31
+ return raw ? JSON.parse(raw) : null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ function writeJsonFile(file, value) {
38
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
39
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), { mode: 0o600 });
40
+ }
41
+ function credsKey(address, sigType) {
42
+ return `${address.toLowerCase()}:${sigType}`;
43
+ }
44
+ export function loadL2Creds(address, sigType) {
45
+ const all = readJsonFile(CREDS_FILE);
46
+ const entry = all?.[credsKey(address, sigType)];
47
+ if (!entry?.key || !entry?.secret || !entry?.passphrase)
48
+ return null;
49
+ return entry;
50
+ }
51
+ export function saveL2Creds(address, sigType, creds) {
52
+ const all = readJsonFile(CREDS_FILE) ?? {};
53
+ all[credsKey(address, sigType)] = { ...creds, derivedAt: new Date().toISOString() };
54
+ writeJsonFile(CREDS_FILE, all);
55
+ }
56
+ /** Drop cached creds (called on CLOB 401 / the issue-#65 error fingerprint). */
57
+ export function invalidateL2Creds(address, sigType) {
58
+ const all = readJsonFile(CREDS_FILE);
59
+ if (!all)
60
+ return;
61
+ delete all[credsKey(address, sigType)];
62
+ writeJsonFile(CREDS_FILE, all);
63
+ }
64
+ export function loadBuilderCreds(owner) {
65
+ const all = readJsonFile(BUILDER_CREDS_FILE);
66
+ const entry = all?.[owner.toLowerCase()];
67
+ if (!entry?.key || !entry?.secret || !entry?.passphrase)
68
+ return null;
69
+ return entry;
70
+ }
71
+ export function saveBuilderCreds(owner, creds) {
72
+ const all = readJsonFile(BUILDER_CREDS_FILE) ?? {};
73
+ all[owner.toLowerCase()] = { ...creds, createdAt: new Date().toISOString() };
74
+ writeJsonFile(BUILDER_CREDS_FILE, all);
75
+ }
76
+ export function loadState() {
77
+ return readJsonFile(STATE_FILE) ?? {};
78
+ }
79
+ /**
80
+ * The persisted deposit wallet, but ONLY if it belongs to `signer`. After a
81
+ * BlockRun key rotation (~/.blockrun/.session regenerated) the stored wallet is
82
+ * a CREATE2 vault the new key cannot control, so returning it would point
83
+ * trading/funding at unrecoverable funds. Returns undefined on signer mismatch.
84
+ */
85
+ export function loadDepositWalletForSigner(signer) {
86
+ const state = loadState();
87
+ if (state.depositWallet && state.signer && state.signer.toLowerCase() === signer.toLowerCase()) {
88
+ return state.depositWallet;
89
+ }
90
+ return undefined;
91
+ }
92
+ export function saveState(patch) {
93
+ const next = { ...loadState(), ...patch };
94
+ writeJsonFile(STATE_FILE, next);
95
+ return next;
96
+ }
@@ -0,0 +1,5 @@
1
+ import type { ToolResult } from "./orders.js";
2
+ export declare function fundVault(input: {
3
+ amount_usd?: number;
4
+ confirm?: boolean;
5
+ }): Promise<ToolResult>;
@@ -0,0 +1,141 @@
1
+ // src/utils/polymarket/fund.ts
2
+ //
3
+ // action:"fund" — top up the Polymarket deposit wallet from the agent's OWN Base
4
+ // USDC, gaslessly, in one call. NON-CUSTODIAL: the agent signs an EIP-3009
5
+ // authorization transferring USDC (Base) DIRECTLY to the Polymarket bridge
6
+ // address for its vault; BlockRun's /v1/polymarket/fund endpoint hands it to the
7
+ // CDP facilitator (which broadcasts + pays gas) and charges a $0.01 fee. The
8
+ // principal never touches a BlockRun wallet — it goes agent → bridge → vault
9
+ // (wrapped to pUSD). The agent needs ZERO Base ETH for gas.
10
+ import axios from "axios";
11
+ import { BlockrunClient, createPaymentPayload } from "@blockrun/llm";
12
+ import { getOrCreateWalletKey, getChainBalance } from "./wallet-key.js";
13
+ import { getPolymarketAccount } from "./client.js";
14
+ import { BASE_CHAIN_ID, BRIDGE_API_HOST, getSigType } from "./constants.js";
15
+ import { getFundsAddress } from "./positions.js";
16
+ import { getPublicClient } from "./setup.js";
17
+ const FUND_FEE_USD = 0.01;
18
+ const USDC_DECIMALS = 6;
19
+ // The Polymarket bridge does NOT process Base-USDC deposits below this — a
20
+ // smaller amount lands at the bridge address but is never wrapped/delivered to
21
+ // the vault (verified live: a $0.10 deposit confirmed on Base but never reached
22
+ // the vault). Override with POLYMARKET_FUND_MIN_USD if the bridge minimum moves.
23
+ const FUND_MIN_USD = Number(process.env.POLYMARKET_FUND_MIN_USD || "2");
24
+ /** Bridge deposit address for a Polymarket vault (delivers pUSD to the vault). */
25
+ async function bridgeAddressFor(vault) {
26
+ const res = await axios.post(`${BRIDGE_API_HOST}/deposit`, { address: vault }, { headers: { "content-type": "application/json" }, timeout: 20_000 });
27
+ const evm = res.data?.address?.evm;
28
+ if (!evm)
29
+ throw new Error(`Bridge did not return a deposit address (got: ${JSON.stringify(res.data)}).`);
30
+ return evm;
31
+ }
32
+ export async function fundVault(input) {
33
+ if (input.amount_usd === undefined || input.amount_usd <= 0) {
34
+ return { text: `Pass amount_usd — the USDC amount to move from your Base wallet into your Polymarket vault (e.g. amount_usd:5).`, isError: true };
35
+ }
36
+ if (input.amount_usd < FUND_MIN_USD) {
37
+ return {
38
+ text: `Minimum funding is $${FUND_MIN_USD} — the Polymarket bridge does not process smaller Base-USDC deposits ` +
39
+ `(a smaller amount would confirm on Base but never wrap to pUSD in your vault). Use amount_usd ≥ ${FUND_MIN_USD}.`,
40
+ isError: true,
41
+ };
42
+ }
43
+ const amountUsd = input.amount_usd;
44
+ let vault;
45
+ try {
46
+ vault = getFundsAddress();
47
+ }
48
+ catch (err) {
49
+ return { text: err instanceof Error ? err.message : String(err), isError: true };
50
+ }
51
+ const agent = getPolymarketAccount().address;
52
+ try {
53
+ // The deposit wallet must be DEPLOYED before funding: the bridge delivers
54
+ // pUSD to the vault contract, and it can't credit a vault that doesn't
55
+ // exist on-chain yet (verified live — funding an undeployed vault let the
56
+ // bridge sweep the USDC but never deliver pUSD). Correct order is
57
+ // setup(deploy) → fund. EOA mode (the funds ARE the EOA) is exempt.
58
+ if (getSigType() === 3) {
59
+ const code = await getPublicClient().getCode({ address: vault }).catch(() => undefined);
60
+ if (!code || code === "0x") {
61
+ return {
62
+ text: `Your deposit wallet ${vault} is not deployed yet — deploy it FIRST with ` +
63
+ `action:"setup" confirm:true (needs relayer creds), then fund. Funding an undeployed ` +
64
+ `vault strands your USDC at the bridge (it can't deliver pUSD to a vault that doesn't exist).`,
65
+ isError: true,
66
+ };
67
+ }
68
+ }
69
+ const baseBalance = (await getChainBalance("base", agent)) ?? 0;
70
+ const needed = amountUsd + FUND_FEE_USD;
71
+ if (baseBalance < needed) {
72
+ return {
73
+ text: `Your Base wallet ${agent} holds $${baseBalance.toFixed(2)} USDC — need $${needed.toFixed(2)} ` +
74
+ `($${amountUsd.toFixed(2)} deposit + $${FUND_FEE_USD} fee). Top up your Base USDC first.`,
75
+ isError: true,
76
+ };
77
+ }
78
+ const bridge = await bridgeAddressFor(vault);
79
+ if (input.confirm !== true) {
80
+ return {
81
+ text: [
82
+ `DRY RUN — nothing moved.`,
83
+ `Fund your Polymarket vault with $${amountUsd.toFixed(2)} USDC (gasless):`,
84
+ ` from Base wallet: ${agent}`,
85
+ ` → bridge: ${bridge}`,
86
+ ` → wraps to pUSD in your vault: ${vault}`,
87
+ ` fee: $${FUND_FEE_USD} (BlockRun pays the Base gas; you need no ETH)`,
88
+ ``,
89
+ `Re-call with confirm:true to sign and submit.`,
90
+ ].join("\n"),
91
+ structured: { dryRun: true, amountUsd, agent, bridge, vault, feeUsd: FUND_FEE_USD },
92
+ };
93
+ }
94
+ // Sign the EIP-3009 deposit authorization: Base USDC → bridge address.
95
+ const privateKey = getOrCreateWalletKey();
96
+ const amountMicro = String(Math.floor(amountUsd * 10 ** USDC_DECIMALS));
97
+ const depositAuthorization = await createPaymentPayload(privateKey, agent, bridge, amountMicro, `eip155:${BASE_CHAIN_ID}`);
98
+ // Call the gateway fund endpoint — it charges $0.01 via x402 automatically
99
+ // and relays the deposit authorization to the CDP facilitator (pays gas).
100
+ const client = new BlockrunClient({ privateKey });
101
+ const result = (await client.post("/v1/polymarket/fund", {
102
+ depositWallet: vault,
103
+ recipient: bridge,
104
+ amountMicro,
105
+ depositAuthorization,
106
+ }));
107
+ if (!result?.success) {
108
+ return { text: `Funding failed: ${result?.error ?? JSON.stringify(result)}`, isError: true };
109
+ }
110
+ // success:true = the deposit was SUBMITTED to the bridge + fee charged on
111
+ // Base. It does NOT mean the vault is funded: the Polymarket bridge credits
112
+ // pUSD on Polygon asynchronously (usually minutes, occasionally 30+),
113
+ // off-chain and un-pollable here — don't claim "Funded" (issue #226).
114
+ return {
115
+ text: [
116
+ `✅ Deposit of $${amountUsd.toFixed(2)} USDC submitted to the Polymarket bridge (gasless).`,
117
+ ` from Base wallet: ${agent}`,
118
+ ...(result.deposit?.txHash ? [` deposit tx: https://basescan.org/tx/${result.deposit.txHash}`] : []),
119
+ ` ⏳ pUSD credit to your vault ${vault} is PENDING — the bridge settles on Polygon`,
120
+ ` asynchronously (usually minutes, occasionally 30+). Re-run action:"setup"`,
121
+ ` and watch for the pUSD balance; it is not instant.`,
122
+ ` Fee charged: $${FUND_FEE_USD}.`,
123
+ ].join("\n"),
124
+ structured: {
125
+ success: true,
126
+ funded: false,
127
+ creditPending: true,
128
+ amountUsd,
129
+ agent,
130
+ bridge,
131
+ vault,
132
+ deposit: result.deposit,
133
+ fee: result.fee,
134
+ },
135
+ };
136
+ }
137
+ catch (err) {
138
+ const msg = err instanceof Error ? err.message : String(err);
139
+ return { text: `Funding error: ${msg}`, isError: true };
140
+ }
141
+ }
@@ -0,0 +1,29 @@
1
+ import { type Hex } from "viem";
2
+ import type { PrivateKeyAccount } from "viem/accounts";
3
+ export interface DerivedCreds {
4
+ key: string;
5
+ secret: string;
6
+ passphrase: string;
7
+ }
8
+ interface L1Headers extends Record<string, string> {
9
+ POLY_ADDRESS: string;
10
+ POLY_SIGNATURE: string;
11
+ POLY_TIMESTAMP: string;
12
+ POLY_NONCE: string;
13
+ }
14
+ /**
15
+ * Build 7739-wrapped L1 headers binding the attestation to `depositWallet`,
16
+ * signed by the local EOA account. Exported for the golden-vector unit test.
17
+ */
18
+ export declare function buildWrapped1271Headers(account: PrivateKeyAccount, depositWallet: Hex, timestampSec?: number): Promise<L1Headers>;
19
+ /**
20
+ * Create-or-derive CLOB L2 API creds. sigType 3 binds them to the deposit
21
+ * wallet via the wrapped headers; sigType 0 binds them to the EOA. Mirrors the
22
+ * SDK's createOrDeriveApiKey flow (POST /auth/api-key, falling back to
23
+ * GET /auth/derive-api-key when the key already exists).
24
+ */
25
+ export declare function deriveApiCreds(account: PrivateKeyAccount, opts: {
26
+ sigType: 0 | 3;
27
+ depositWallet?: Hex;
28
+ }): Promise<DerivedCreds>;
29
+ export {};