@blockrun/franklin 3.29.16 → 3.30.1
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.
- package/dist/tools/index.js +3 -1
- package/dist/tools/polymarket/client.d.ts +61 -0
- package/dist/tools/polymarket/client.js +236 -0
- package/dist/tools/polymarket/constants.d.ts +192 -0
- package/dist/tools/polymarket/constants.js +205 -0
- package/dist/tools/polymarket/creds.d.ts +33 -0
- package/dist/tools/polymarket/creds.js +96 -0
- package/dist/tools/polymarket/fund.d.ts +5 -0
- package/dist/tools/polymarket/fund.js +141 -0
- package/dist/tools/polymarket/l1-auth-1271.d.ts +29 -0
- package/dist/tools/polymarket/l1-auth-1271.js +198 -0
- package/dist/tools/polymarket/orders.d.ts +44 -0
- package/dist/tools/polymarket/orders.js +455 -0
- package/dist/tools/polymarket/positions.d.ts +26 -0
- package/dist/tools/polymarket/positions.js +88 -0
- package/dist/tools/polymarket/redeem.d.ts +5 -0
- package/dist/tools/polymarket/redeem.js +121 -0
- package/dist/tools/polymarket/relayer.d.ts +37 -0
- package/dist/tools/polymarket/relayer.js +140 -0
- package/dist/tools/polymarket/setup.d.ts +9 -0
- package/dist/tools/polymarket/setup.js +385 -0
- package/dist/tools/polymarket/wallet-key.d.ts +14 -0
- package/dist/tools/polymarket/wallet-key.js +69 -0
- package/dist/tools/polymarket/withdraw.d.ts +8 -0
- package/dist/tools/polymarket/withdraw.js +108 -0
- package/dist/tools/polymarket-bet.d.ts +4 -0
- package/dist/tools/polymarket-bet.js +164 -0
- package/dist/tools/tool-categories.js +4 -0
- package/package.json +7 -2
- package/dist/agent/media-router.d.ts +0 -98
- package/dist/agent/media-router.js +0 -328
|
@@ -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
|
+
}>;
|