@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,26 @@
1
+ import type { Hex } from "viem";
2
+ import type { ToolResult } from "./orders.js";
3
+ /** The wallet that actually holds funds/positions for the active sig mode. */
4
+ export declare function getFundsAddress(): Hex;
5
+ export interface DataApiPosition {
6
+ asset?: string;
7
+ conditionId?: string;
8
+ title?: string;
9
+ outcome?: string;
10
+ outcomeIndex?: number;
11
+ size?: number;
12
+ avgPrice?: number;
13
+ curPrice?: number;
14
+ currentValue?: number;
15
+ cashPnl?: number;
16
+ percentPnl?: number;
17
+ redeemable?: boolean;
18
+ negativeRisk?: boolean;
19
+ }
20
+ /**
21
+ * Fetch positions with offset pagination so wallets with >100 holdings aren't
22
+ * silently truncated (a redeemable winner sorted past the first page would
23
+ * otherwise be invisible). Bounded at POSITIONS_MAX pages of safety.
24
+ */
25
+ export declare function fetchPositions(user: string): Promise<DataApiPosition[]>;
26
+ export declare function listPositions(): Promise<ToolResult>;
@@ -0,0 +1,88 @@
1
+ // src/utils/polymarket/positions.ts
2
+ //
3
+ // Positions via Polymarket's free, unauthenticated Data-API — deliberately NOT
4
+ // the paid Predexon route in blockrun_markets (don't pay for what's free). If
5
+ // the Data-API is down, the error text points at the paid fallback.
6
+ import axios from "axios";
7
+ import { getPolymarketAccount } from "./client.js";
8
+ import { DATA_API_HOST, getSigType } from "./constants.js";
9
+ import { loadDepositWalletForSigner } from "./creds.js";
10
+ /** The wallet that actually holds funds/positions for the active sig mode. */
11
+ export function getFundsAddress() {
12
+ const account = getPolymarketAccount();
13
+ if (getSigType() === 3) {
14
+ const depositWallet = loadDepositWalletForSigner(account.address);
15
+ if (!depositWallet) {
16
+ throw new Error(`No deposit wallet configured for this signer yet — run blockrun_polymarket action:"setup" first.`);
17
+ }
18
+ return depositWallet;
19
+ }
20
+ return account.address;
21
+ }
22
+ const POSITIONS_PAGE = 100;
23
+ const POSITIONS_MAX = 500;
24
+ /**
25
+ * Fetch positions with offset pagination so wallets with >100 holdings aren't
26
+ * silently truncated (a redeemable winner sorted past the first page would
27
+ * otherwise be invisible). Bounded at POSITIONS_MAX pages of safety.
28
+ */
29
+ export async function fetchPositions(user) {
30
+ const all = [];
31
+ for (let offset = 0; offset < POSITIONS_MAX; offset += POSITIONS_PAGE) {
32
+ const res = await axios.get(`${DATA_API_HOST}/positions`, {
33
+ params: { user, limit: POSITIONS_PAGE, offset },
34
+ timeout: 15_000,
35
+ });
36
+ const page = Array.isArray(res.data) ? res.data : [];
37
+ all.push(...page);
38
+ if (page.length < POSITIONS_PAGE)
39
+ break;
40
+ }
41
+ return all;
42
+ }
43
+ export async function listPositions() {
44
+ let user;
45
+ try {
46
+ user = getFundsAddress();
47
+ }
48
+ catch (err) {
49
+ return { text: err instanceof Error ? err.message : String(err), isError: true };
50
+ }
51
+ try {
52
+ const positions = await fetchPositions(user);
53
+ if (!positions.length) {
54
+ return {
55
+ text: `No positions for ${user}.`,
56
+ structured: { user, positions: [] },
57
+ };
58
+ }
59
+ const fmtUsd = (n) => (typeof n === "number" ? `$${n.toFixed(2)}` : "n/a");
60
+ const lines = positions.map((p) => {
61
+ const pnl = typeof p.cashPnl === "number"
62
+ ? ` · PnL ${p.cashPnl >= 0 ? "+" : ""}${fmtUsd(p.cashPnl)}${typeof p.percentPnl === "number" ? ` (${p.percentPnl.toFixed(1)}%)` : ""}`
63
+ : "";
64
+ const redeem = p.redeemable ? ` · 🏆 REDEEMABLE (action:"redeem" condition_id:"${p.conditionId}")` : "";
65
+ return ` ${p.title ?? p.conditionId ?? "?"} — ${p.outcome ?? "?"}: ` +
66
+ `${p.size?.toFixed(2) ?? "?"} shares @ ${p.avgPrice?.toFixed(3) ?? "?"} → ` +
67
+ `${p.curPrice?.toFixed(3) ?? "?"} (${fmtUsd(p.currentValue)})${pnl}${redeem}`;
68
+ });
69
+ const totalValue = positions.reduce((s, p) => s + (p.currentValue ?? 0), 0);
70
+ const redeemableCount = positions.filter((p) => p.redeemable).length;
71
+ return {
72
+ text: [
73
+ `Positions for ${user} (${positions.length}, total value ~$${totalValue.toFixed(2)}):`,
74
+ ...lines,
75
+ ...(redeemableCount ? [``, `${redeemableCount} position(s) are redeemable — claim with action:"redeem".`] : []),
76
+ ].join("\n"),
77
+ structured: { user, positions, totalValue },
78
+ };
79
+ }
80
+ catch (err) {
81
+ const msg = err instanceof Error ? err.message : String(err);
82
+ return {
83
+ text: `Could not fetch positions from Polymarket's Data-API (${msg}). ` +
84
+ `Fallback: blockrun_markets path:"polymarket/positions" params:{user:"${user}"} ($0.001).`,
85
+ isError: true,
86
+ };
87
+ }
88
+ }
@@ -0,0 +1,5 @@
1
+ import type { ToolResult } from "./orders.js";
2
+ export declare function redeemPosition(input: {
3
+ condition_id?: string;
4
+ confirm?: boolean;
5
+ }): Promise<ToolResult>;
@@ -0,0 +1,121 @@
1
+ // src/utils/polymarket/redeem.ts
2
+ //
3
+ // Claim winnings for a resolved market. Burns the ERC-1155 outcome tokens and
4
+ // credits collateral back to the funds wallet:
5
+ // - POLY_1271: a gasless relayer WALLET batch executed BY the deposit wallet
6
+ // (redeemPositions credits msg.sender, i.e. the deposit wallet).
7
+ // - EOA mode: a direct transaction from the EOA (needs POL gas).
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.
19
+ import { createWalletClient, encodeFunctionData, http } from "viem";
20
+ import { polygon } from "viem/chains";
21
+ 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";
23
+ import { mapClobError } from "./orders.js";
24
+ import { getFundsAddress } from "./positions.js";
25
+ import { sendWalletBatch } from "./relayer.js";
26
+ import { getPublicClient, getPusdBalance } from "./setup.js";
27
+ export async function redeemPosition(input) {
28
+ if (!input.condition_id) {
29
+ return { text: `Pass condition_id:"0x…" (see action:"positions" for redeemable markets).`, isError: true };
30
+ }
31
+ const conditionId = input.condition_id;
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
+ try {
40
+ // Market metadata (question, outcome tokens, negRisk) via the CLOB.
41
+ const clob = await getClobClient();
42
+ const market = (await clob.getMarket(conditionId));
43
+ const tokens = (market?.tokens ?? []).filter((t) => t.token_id);
44
+ if (!tokens.length)
45
+ return { text: `No tokens found for condition ${conditionId}.`, isError: true };
46
+ // Exact on-chain balances per outcome token — the redeem amounts.
47
+ const pc = getPublicClient();
48
+ const balances = [];
49
+ for (const t of tokens) {
50
+ balances.push(await pc.readContract({
51
+ address: CONDITIONAL_TOKENS,
52
+ abi: ERC1155_ABI,
53
+ functionName: "balanceOf",
54
+ args: [owner, BigInt(t.token_id)],
55
+ }));
56
+ }
57
+ if (balances.every((b) => b === 0n)) {
58
+ return { text: `Nothing to redeem: ${owner} holds no outcome tokens for "${market?.question ?? conditionId}".`, isError: true };
59
+ }
60
+ const negRisk = Boolean(market?.neg_risk);
61
+ const held = tokens
62
+ .map((t, i) => ({ outcome: t.outcome, winner: t.winner, shares: Number(balances[i]) / 10 ** PUSD_DECIMALS }))
63
+ .filter((h) => h.shares > 0);
64
+ const heldText = held
65
+ .map((h) => ` ${h.shares.toFixed(2)} × "${h.outcome}"${h.winner ? " (winner → pays $1/share)" : ""}`)
66
+ .join("\n");
67
+ if (input.confirm !== true) {
68
+ return {
69
+ text: [
70
+ `DRY RUN — nothing redeemed.`,
71
+ `Market: ${market?.question ?? conditionId}${market?.closed === false ? " ⚠️ (not closed yet — redeem will revert until resolution)" : ""}`,
72
+ `Holdings:`,
73
+ heldText,
74
+ ``,
75
+ `Re-call with confirm:true to redeem the FULL balance (Polymarket redeems`,
76
+ `everything for the condition; partial redemption is not supported).`,
77
+ ].join("\n"),
78
+ structured: { dryRun: true, conditionId, negRisk, holdings: held },
79
+ };
80
+ }
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);
93
+ let txHash;
94
+ if (getSigType() === 3) {
95
+ const res = await sendWalletBatch([{ target, value: "0", data }], owner, "Redeem");
96
+ txHash = res.transactionHash;
97
+ }
98
+ else {
99
+ const account = getPolymarketAccount();
100
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
101
+ txHash = await wallet.sendTransaction({ to: target, data, chain: polygon, account });
102
+ await pc.waitForTransactionReceipt({ hash: txHash });
103
+ }
104
+ const balanceAfter = await getPusdBalance(owner).catch(() => null);
105
+ return {
106
+ text: [
107
+ `✅ Redeemed "${market?.question ?? conditionId}".`,
108
+ heldText,
109
+ ...(txHash ? [` tx: https://polygonscan.com/tx/${txHash}`] : []),
110
+ ...(balanceAfter !== null ? [` Funds wallet pUSD balance: $${balanceAfter.toFixed(2)}`] : []),
111
+ ].join("\n"),
112
+ structured: { conditionId, negRisk, transactionHash: txHash, pusdBalance: balanceAfter },
113
+ };
114
+ }
115
+ catch (err) {
116
+ 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 };
120
+ }
121
+ }
@@ -0,0 +1,37 @@
1
+ import { RelayClient, type DepositWalletCall } from "@polymarket/builder-relayer-client";
2
+ import { type Hex } from "viem";
3
+ export type { DepositWalletCall };
4
+ export declare function relayerCredsMissing(): boolean;
5
+ export declare function relayerCredsMissingMessage(): string;
6
+ /**
7
+ * RelayClient bound to the REAL account address (the deposit-wallet owner), with
8
+ * builder-HMAC auth from bootstrapped Builder API creds. Async because the first
9
+ * call may create the builder key. The relayer is not geoblocked → direct.
10
+ */
11
+ export declare function getRelayClient(): Promise<RelayClient>;
12
+ /** CREATE2-derived deposit wallet address for the local key (pre-deploy safe). */
13
+ 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
+ export declare function isDepositWalletDeployed(address: string): Promise<boolean>;
22
+ /**
23
+ * Deploy the deposit wallet (idempotence guarded by the caller via
24
+ * isDepositWalletDeployed). Waits for on-chain confirmation; throws with the
25
+ * relayer transaction id on failure/timeout so the user can re-run setup.
26
+ */
27
+ export declare function deployDepositWallet(): Promise<{
28
+ transactionHash?: string;
29
+ }>;
30
+ /**
31
+ * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
32
+ * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
33
+ * submits; we wait for confirmation.
34
+ */
35
+ export declare function sendWalletBatch(calls: DepositWalletCall[], depositWallet: string, description: string): Promise<{
36
+ transactionHash?: string;
37
+ }>;
@@ -0,0 +1,140 @@
1
+ // src/utils/polymarket/relayer.ts
2
+ //
3
+ // Thin wrapper over @polymarket/builder-relayer-client for the deposit-wallet
4
+ // lifecycle: derive (CREATE2, pre-deploy), deploy (WALLET-CREATE), and signed
5
+ // WALLET batches (approvals, redeem). Everything here is GASLESS — the relayer
6
+ // sponsors gas. It is a courier, not a custodian: it only ever receives
7
+ // EIP-712 payloads signed by the local key, which it can neither alter (the
8
+ // signature covers every byte) nor replay (nonce + deadline).
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.
13
+ import { RelayClient } from "@polymarket/builder-relayer-client";
14
+ import { BuilderConfig } from "@polymarket/builder-signing-sdk";
15
+ import { ClobClient } from "@polymarket/clob-client-v2";
16
+ import { createWalletClient, http } from "viem";
17
+ import { polygon } from "viem/chains";
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";
21
+ import { deriveApiCreds } from "./l1-auth-1271.js";
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
+ /**
33
+ * Programmatically obtain Builder API credentials (key/secret/passphrase) for
34
+ * the local wallet — created via the CLOB createBuilderApiKey() (L2-authed),
35
+ * cached on disk (the secret is only returned once). This replaces the manual
36
+ * "get a relayer API key from polymarket.com" step: the relayer authenticates
37
+ * via the builder-HMAC path, and because the builder == the deposit-wallet
38
+ * owner (this wallet), the relayer's from==owner check is satisfied.
39
+ */
40
+ async function getOrCreateBuilderCreds() {
41
+ const account = getPolymarketAccount();
42
+ const cached = loadBuilderCreds(account.address);
43
+ if (cached)
44
+ return { key: cached.key, secret: cached.secret, passphrase: cached.passphrase };
45
+ // Plain EOA CLOB L2 creds (sig type 0) — needed to authenticate the builder-key
46
+ // creation. Cached like any L2 creds.
47
+ let l2 = loadL2Creds(account.address, 0);
48
+ if (!l2) {
49
+ const derived = await deriveApiCreds(account, { sigType: 0 });
50
+ saveL2Creds(account.address, 0, derived);
51
+ l2 = loadL2Creds(account.address, 0);
52
+ if (!l2)
53
+ throw new Error("failed to derive CLOB credentials for builder-key creation");
54
+ }
55
+ const wc = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC_URLS[0]) });
56
+ const clob = new ClobClient({
57
+ host: CLOB_HOST,
58
+ chain: POLYGON_CHAIN_ID,
59
+ signer: wc,
60
+ creds: { key: l2.key, secret: l2.secret, passphrase: l2.passphrase },
61
+ throwOnError: true,
62
+ });
63
+ const builder = (await clob.createBuilderApiKey());
64
+ if (!builder?.key || !builder?.secret || !builder?.passphrase) {
65
+ throw new Error(`createBuilderApiKey did not return complete credentials (${JSON.stringify(Object.keys(builder ?? {}))})`);
66
+ }
67
+ saveBuilderCreds(account.address, builder);
68
+ return builder;
69
+ }
70
+ /**
71
+ * RelayClient bound to the REAL account address (the deposit-wallet owner), with
72
+ * builder-HMAC auth from bootstrapped Builder API creds. Async because the first
73
+ * call may create the builder key. The relayer is not geoblocked → direct.
74
+ */
75
+ export async function getRelayClient() {
76
+ if (_relayClient)
77
+ return _relayClient;
78
+ const walletClient = createWalletClient({
79
+ account: getPolymarketAccount(),
80
+ chain: polygon,
81
+ transport: http(POLYGON_RPC_URLS[0]),
82
+ });
83
+ const builderCreds = await getOrCreateBuilderCreds();
84
+ const builderConfig = new BuilderConfig({ localBuilderCreds: builderCreds });
85
+ _relayClient = new RelayClient(RELAYER_URL, POLYGON_CHAIN_ID, walletClient, builderConfig);
86
+ return _relayClient;
87
+ }
88
+ /** CREATE2-derived deposit wallet address for the local key (pre-deploy safe). */
89
+ export async function deriveDepositWallet() {
90
+ const addr = await (await getRelayClient()).deriveDepositWalletAddress();
91
+ return addr;
92
+ }
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
+ export async function isDepositWalletDeployed(address) {
110
+ return (await getRelayClient()).getDeployed(address, "WALLET");
111
+ }
112
+ /**
113
+ * Deploy the deposit wallet (idempotence guarded by the caller via
114
+ * isDepositWalletDeployed). Waits for on-chain confirmation; throws with the
115
+ * relayer transaction id on failure/timeout so the user can re-run setup.
116
+ */
117
+ export async function deployDepositWallet() {
118
+ const response = await (await getRelayClient()).deployDepositWallet();
119
+ const confirmed = await response.wait();
120
+ if (!confirmed) {
121
+ throw new Error(`Deposit wallet deployment did not confirm (relayer tx ${response.transactionID}). ` +
122
+ `It may still be pending — re-run action:"setup" in a minute.`);
123
+ }
124
+ return { transactionHash: confirmed.transactionHash };
125
+ }
126
+ /**
127
+ * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
128
+ * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
129
+ * submits; we wait for confirmation.
130
+ */
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);
134
+ const confirmed = await response.wait();
135
+ 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.`);
138
+ }
139
+ return { transactionHash: confirmed.transactionHash };
140
+ }
@@ -0,0 +1,9 @@
1
+ import { type Hex, type PublicClient } from "viem";
2
+ export declare function getPublicClient(): PublicClient;
3
+ export declare function getPusdBalance(owner: Hex): Promise<number>;
4
+ export declare function runSetup(opts: {
5
+ confirm: boolean;
6
+ }): Promise<{
7
+ text: string;
8
+ structured: Record<string, unknown>;
9
+ }>;