@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.
- 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 +420 -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 +360 -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,198 @@
|
|
|
1
|
+
// src/utils/polymarket/l1-auth-1271.ts
|
|
2
|
+
//
|
|
3
|
+
// Workaround for https://github.com/Polymarket/clob-client-v2/issues/65
|
|
4
|
+
// (open as of v1.0.8, 2026-07): the SDK's createApiKey()/createL1Headers()
|
|
5
|
+
// signs the L1 ClobAuth attestation as a PLAIN EOA signature bound to the EOA
|
|
6
|
+
// address, while POLY_1271 orders set order.signer = deposit wallet — so the
|
|
7
|
+
// CLOB rejects every order with 400 "the order signer address has to be the
|
|
8
|
+
// address of the API KEY". The SDK's ORDER signing does wrap correctly
|
|
9
|
+
// (ExchangeOrderBuilderV2.buildOrderSignature); only L1 auth lacks the wrap.
|
|
10
|
+
//
|
|
11
|
+
// This module applies the SAME ERC-7739 TypedDataSign envelope the SDK uses
|
|
12
|
+
// for orders to the L1 ClobAuth message, with POLY_ADDRESS = the deposit
|
|
13
|
+
// wallet, so the derived API creds are bound to the deposit wallet:
|
|
14
|
+
//
|
|
15
|
+
// contentsHash = hashStruct(ClobAuth message) (app = ClobAuthDomain v1)
|
|
16
|
+
// innerSig = eth_signTypedData(TypedDataSign{contents, DepositWallet domain})
|
|
17
|
+
// envelope = innerSig ‖ appDomainSeparator ‖ contentsHash
|
|
18
|
+
// ‖ typeString(ClobAuth) ‖ uint16(len(typeString))
|
|
19
|
+
//
|
|
20
|
+
// Re-check issue #65 when bumping @polymarket/clob-client-v2 — if fixed
|
|
21
|
+
// upstream, delete this module and use client.createOrDeriveApiKey().
|
|
22
|
+
import axios from "axios";
|
|
23
|
+
import { encodeAbiParameters, hashDomain, keccak256, toHex, zeroHash, } from "viem";
|
|
24
|
+
import { CLOB_HOST, POLYGON_CHAIN_ID } from "./constants.js";
|
|
25
|
+
// Must match the SDK byte-for-byte (dist/signing/{constants,eip712}.js).
|
|
26
|
+
const MSG_TO_SIGN = "This message attests that I control the given wallet";
|
|
27
|
+
const CLOB_AUTH_DOMAIN = {
|
|
28
|
+
name: "ClobAuthDomain",
|
|
29
|
+
version: "1",
|
|
30
|
+
chainId: POLYGON_CHAIN_ID,
|
|
31
|
+
};
|
|
32
|
+
const CLOB_AUTH_FIELDS = [
|
|
33
|
+
{ name: "address", type: "address" },
|
|
34
|
+
{ name: "timestamp", type: "string" },
|
|
35
|
+
{ name: "nonce", type: "uint256" },
|
|
36
|
+
{ name: "message", type: "string" },
|
|
37
|
+
];
|
|
38
|
+
const CLOB_AUTH_TYPE_STRING = "ClobAuth(address address,string timestamp,uint256 nonce,string message)";
|
|
39
|
+
const CLOB_AUTH_TYPE_HASH = keccak256(toHex(CLOB_AUTH_TYPE_STRING));
|
|
40
|
+
// TypedDataSign layout mirrors TYPED_DATA_SIGN_STRUCT in the SDK's
|
|
41
|
+
// exchangeOrderBuilderV2, with `contents` retyped to ClobAuth. The embedded
|
|
42
|
+
// domain fields describe the DEPOSIT WALLET (the ERC-1271 validator), which is
|
|
43
|
+
// what binds the signature to that one wallet and prevents cross-wallet replay.
|
|
44
|
+
const TYPED_DATA_SIGN_FIELDS = [
|
|
45
|
+
{ name: "contents", type: "ClobAuth" },
|
|
46
|
+
{ name: "name", type: "string" },
|
|
47
|
+
{ name: "version", type: "string" },
|
|
48
|
+
{ name: "chainId", type: "uint256" },
|
|
49
|
+
{ name: "verifyingContract", type: "address" },
|
|
50
|
+
{ name: "salt", type: "bytes32" },
|
|
51
|
+
];
|
|
52
|
+
/** hashStruct(ClobAuth) — string fields keccak-hashed per EIP-712. */
|
|
53
|
+
function clobAuthContentsHash(address, timestamp, nonce) {
|
|
54
|
+
return keccak256(encodeAbiParameters([
|
|
55
|
+
{ type: "bytes32" },
|
|
56
|
+
{ type: "address" },
|
|
57
|
+
{ type: "bytes32" },
|
|
58
|
+
{ type: "uint256" },
|
|
59
|
+
{ type: "bytes32" },
|
|
60
|
+
], [
|
|
61
|
+
CLOB_AUTH_TYPE_HASH,
|
|
62
|
+
address,
|
|
63
|
+
keccak256(toHex(timestamp)),
|
|
64
|
+
nonce,
|
|
65
|
+
keccak256(toHex(MSG_TO_SIGN)),
|
|
66
|
+
]));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Build 7739-wrapped L1 headers binding the attestation to `depositWallet`,
|
|
70
|
+
* signed by the local EOA account. Exported for the golden-vector unit test.
|
|
71
|
+
*/
|
|
72
|
+
export async function buildWrapped1271Headers(account, depositWallet, timestampSec) {
|
|
73
|
+
const ts = String(timestampSec ?? Math.floor(Date.now() / 1000));
|
|
74
|
+
const nonce = 0n;
|
|
75
|
+
const innerSig = await account.signTypedData({
|
|
76
|
+
domain: CLOB_AUTH_DOMAIN,
|
|
77
|
+
types: {
|
|
78
|
+
TypedDataSign: [...TYPED_DATA_SIGN_FIELDS],
|
|
79
|
+
ClobAuth: [...CLOB_AUTH_FIELDS],
|
|
80
|
+
},
|
|
81
|
+
primaryType: "TypedDataSign",
|
|
82
|
+
message: {
|
|
83
|
+
contents: {
|
|
84
|
+
address: depositWallet,
|
|
85
|
+
timestamp: ts,
|
|
86
|
+
nonce,
|
|
87
|
+
message: MSG_TO_SIGN,
|
|
88
|
+
},
|
|
89
|
+
name: "DepositWallet",
|
|
90
|
+
version: "1",
|
|
91
|
+
chainId: BigInt(POLYGON_CHAIN_ID),
|
|
92
|
+
verifyingContract: depositWallet,
|
|
93
|
+
salt: zeroHash,
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
const appDomainSep = hashDomain({
|
|
97
|
+
domain: { ...CLOB_AUTH_DOMAIN, chainId: BigInt(POLYGON_CHAIN_ID) },
|
|
98
|
+
types: {
|
|
99
|
+
EIP712Domain: [
|
|
100
|
+
{ name: "name", type: "string" },
|
|
101
|
+
{ name: "version", type: "string" },
|
|
102
|
+
{ name: "chainId", type: "uint256" },
|
|
103
|
+
],
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
const contentsHash = clobAuthContentsHash(depositWallet, ts, nonce);
|
|
107
|
+
const typeHex = toHex(CLOB_AUTH_TYPE_STRING).slice(2);
|
|
108
|
+
const lenHex = (typeHex.length / 2).toString(16).padStart(4, "0");
|
|
109
|
+
const envelope = `0x${innerSig.slice(2)}${appDomainSep.slice(2)}${contentsHash.slice(2)}${typeHex}${lenHex}`;
|
|
110
|
+
return {
|
|
111
|
+
POLY_ADDRESS: depositWallet,
|
|
112
|
+
POLY_SIGNATURE: envelope,
|
|
113
|
+
POLY_TIMESTAMP: ts,
|
|
114
|
+
POLY_NONCE: "0",
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** Plain (unwrapped) L1 headers for EOA mode — matches the SDK's own path. */
|
|
118
|
+
async function buildPlainL1Headers(account) {
|
|
119
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
120
|
+
const signature = await account.signTypedData({
|
|
121
|
+
domain: CLOB_AUTH_DOMAIN,
|
|
122
|
+
types: { ClobAuth: [...CLOB_AUTH_FIELDS] },
|
|
123
|
+
primaryType: "ClobAuth",
|
|
124
|
+
message: {
|
|
125
|
+
address: account.address,
|
|
126
|
+
timestamp: ts,
|
|
127
|
+
nonce: 0n,
|
|
128
|
+
message: MSG_TO_SIGN,
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
POLY_ADDRESS: account.address,
|
|
133
|
+
POLY_SIGNATURE: signature,
|
|
134
|
+
POLY_TIMESTAMP: ts,
|
|
135
|
+
POLY_NONCE: "0",
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Create-or-derive CLOB L2 API creds. sigType 3 binds them to the deposit
|
|
140
|
+
* wallet via the wrapped headers; sigType 0 binds them to the EOA. Mirrors the
|
|
141
|
+
* SDK's createOrDeriveApiKey flow (POST /auth/api-key, falling back to
|
|
142
|
+
* GET /auth/derive-api-key when the key already exists).
|
|
143
|
+
*/
|
|
144
|
+
export async function deriveApiCreds(account, opts) {
|
|
145
|
+
const headers = opts.sigType === 3
|
|
146
|
+
? await buildWrapped1271Headers(account, requireDepositWallet(opts.depositWallet))
|
|
147
|
+
: await buildPlainL1Headers(account);
|
|
148
|
+
// POST creates a key; if one already exists it 4xxs and we fall back to
|
|
149
|
+
// deriving. Keep the POST failure reason (redacted) so that when the derive
|
|
150
|
+
// ALSO fails — the common cause is the server rejecting the wrapped 1271
|
|
151
|
+
// signature (e.g. deposit wallet not yet deployed) — we can surface it
|
|
152
|
+
// instead of a misleading "not registered" message.
|
|
153
|
+
let createError;
|
|
154
|
+
const create = await axios
|
|
155
|
+
.post(`${CLOB_HOST}/auth/api-key`, undefined, { headers, timeout: 15_000 })
|
|
156
|
+
.then((r) => r.data)
|
|
157
|
+
.catch((e) => {
|
|
158
|
+
createError = summarizeAxiosError(e);
|
|
159
|
+
return null;
|
|
160
|
+
});
|
|
161
|
+
if (create?.apiKey && create.secret && create.passphrase) {
|
|
162
|
+
return { key: create.apiKey, secret: create.secret, passphrase: create.passphrase };
|
|
163
|
+
}
|
|
164
|
+
const derive = await axios
|
|
165
|
+
.get(`${CLOB_HOST}/auth/derive-api-key`, { headers, timeout: 15_000 })
|
|
166
|
+
.catch((e) => {
|
|
167
|
+
throw new Error(`CLOB credential derivation failed: ${summarizeAxiosError(e)}` +
|
|
168
|
+
(createError ? ` (create attempt: ${createError})` : "") +
|
|
169
|
+
`. If the deposit wallet is not yet deployed, run action:"setup" first.`);
|
|
170
|
+
});
|
|
171
|
+
const d = derive.data;
|
|
172
|
+
if (!d?.apiKey || !d.secret || !d.passphrase) {
|
|
173
|
+
// Never echo the raw body — a partial response could contain a live secret.
|
|
174
|
+
// Report only which fields were present.
|
|
175
|
+
const present = d && typeof d === "object" ? Object.keys(d).join(", ") || "none" : typeof d;
|
|
176
|
+
throw new Error(`CLOB did not return complete API credentials (fields present: ${present}). ` +
|
|
177
|
+
`If this persists, the account may not be registered — run action:"setup".`);
|
|
178
|
+
}
|
|
179
|
+
return { key: d.apiKey, secret: d.secret, passphrase: d.passphrase };
|
|
180
|
+
}
|
|
181
|
+
/** Status + short error text from an axios failure, WITHOUT echoing any body
|
|
182
|
+
* (which for these auth endpoints can carry credential material). */
|
|
183
|
+
function summarizeAxiosError(e) {
|
|
184
|
+
const ax = e;
|
|
185
|
+
if (ax?.response?.status) {
|
|
186
|
+
const body = ax.response.data;
|
|
187
|
+
const reason = body && typeof body === "object"
|
|
188
|
+
? (body.error ?? body.message ?? "")
|
|
189
|
+
: typeof body === "string" ? body : "";
|
|
190
|
+
return `HTTP ${ax.response.status}${reason ? ` (${String(reason).slice(0, 120)})` : ""}`;
|
|
191
|
+
}
|
|
192
|
+
return ax?.message ? ax.message.slice(0, 120) : "network error";
|
|
193
|
+
}
|
|
194
|
+
function requireDepositWallet(addr) {
|
|
195
|
+
if (!addr)
|
|
196
|
+
throw new Error("deposit wallet address required for POLY_1271 credential derivation");
|
|
197
|
+
return addr;
|
|
198
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export declare function getSessionLedger(): {
|
|
2
|
+
totalUsd: number;
|
|
3
|
+
count: number;
|
|
4
|
+
perAgent: Record<string, number>;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Round a probability price onto the market's tick grid, CONSERVATIVELY by side:
|
|
8
|
+
* a BUY rounds DOWN and a SELL rounds UP, so the signed order is never priced
|
|
9
|
+
* worse than the user's stated limit. (Plain Math.round could round a buy at
|
|
10
|
+
* 0.556 up to 0.56 — signing above the limit; near the grid floor a buy at
|
|
11
|
+
* 0.0051 would round up to a full tick, doubling notional.) A sub-tick buy
|
|
12
|
+
* floors to 0, which the caller's range check then rejects with a clear error
|
|
13
|
+
* rather than silently lifting it to the first tick.
|
|
14
|
+
*/
|
|
15
|
+
export declare function roundToTick(price: number, tickSize: string, side?: "buy" | "sell"): number;
|
|
16
|
+
/** Map CLOB errors to actionable guidance. Exported for unit tests. */
|
|
17
|
+
export declare function mapClobError(err: unknown): Promise<string>;
|
|
18
|
+
export interface TradeInput {
|
|
19
|
+
action: "buy" | "sell";
|
|
20
|
+
token_id?: string;
|
|
21
|
+
condition_id?: string;
|
|
22
|
+
outcome?: string;
|
|
23
|
+
price?: number;
|
|
24
|
+
size?: number;
|
|
25
|
+
amount_usd?: number;
|
|
26
|
+
order_type?: "GTC" | "GTD" | "FOK" | "FAK";
|
|
27
|
+
expires_at?: number;
|
|
28
|
+
post_only?: boolean;
|
|
29
|
+
confirm?: boolean;
|
|
30
|
+
agent_id?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface ToolResult {
|
|
33
|
+
text: string;
|
|
34
|
+
structured?: Record<string, unknown>;
|
|
35
|
+
isError?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export declare function executeTrade(input: TradeInput): Promise<ToolResult>;
|
|
38
|
+
export declare function listOpenOrders(input: {
|
|
39
|
+
condition_id?: string;
|
|
40
|
+
}): Promise<ToolResult>;
|
|
41
|
+
export declare function cancelOrdersAction(input: {
|
|
42
|
+
order_id?: string;
|
|
43
|
+
all?: boolean;
|
|
44
|
+
}): Promise<ToolResult>;
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// src/utils/polymarket/orders.ts
|
|
2
|
+
//
|
|
3
|
+
// buy / sell / cancel / open-orders flows. Safety model (deliberately NOT the
|
|
4
|
+
// x402 budget ledger — bets are the user's own pUSD capital on Polygon, a
|
|
5
|
+
// different asset in a different wallet than BlockRun API spend):
|
|
6
|
+
// - confirm:true is HARD-REQUIRED to place an order; without it the call
|
|
7
|
+
// returns a dry-run preview and signs nothing.
|
|
8
|
+
// - per-order notional capped by POLYMARKET_MAX_BET_USD (default $25).
|
|
9
|
+
// - optional POLYMARKET_MAX_SESSION_USD cumulative cap, tracked in-memory
|
|
10
|
+
// with per-agent attribution (agent_id).
|
|
11
|
+
import { OrderType, Side } from "@polymarket/clob-client-v2";
|
|
12
|
+
import { checkGeoblock, getClobClient, getPolymarketAccount, resetClobClient } from "./client.js";
|
|
13
|
+
import { getMaxBetUsd, getMaxSessionUsd } from "./constants.js";
|
|
14
|
+
import { invalidateL2Creds } from "./creds.js";
|
|
15
|
+
// --- Session bet ledger (in-memory; resets with the process) ---
|
|
16
|
+
const ledger = {
|
|
17
|
+
totalUsd: 0,
|
|
18
|
+
count: 0,
|
|
19
|
+
perAgent: new Map(),
|
|
20
|
+
};
|
|
21
|
+
export function getSessionLedger() {
|
|
22
|
+
return {
|
|
23
|
+
totalUsd: ledger.totalUsd,
|
|
24
|
+
count: ledger.count,
|
|
25
|
+
perAgent: Object.fromEntries(ledger.perAgent),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** Reserve spend against the ledger before an awaited submit (no count yet). */
|
|
29
|
+
function reserveBet(usd, agentId) {
|
|
30
|
+
ledger.totalUsd += usd;
|
|
31
|
+
if (agentId)
|
|
32
|
+
ledger.perAgent.set(agentId, (ledger.perAgent.get(agentId) ?? 0) + usd);
|
|
33
|
+
}
|
|
34
|
+
/** Undo a reservation when the order failed to place. */
|
|
35
|
+
function releaseBet(usd, agentId) {
|
|
36
|
+
ledger.totalUsd -= usd;
|
|
37
|
+
if (agentId)
|
|
38
|
+
ledger.perAgent.set(agentId, (ledger.perAgent.get(agentId) ?? 0) - usd);
|
|
39
|
+
}
|
|
40
|
+
/** Confirm a placed order (bump the count; spend was already reserved). */
|
|
41
|
+
function commitBet() {
|
|
42
|
+
ledger.count += 1;
|
|
43
|
+
}
|
|
44
|
+
// --- Helpers ---
|
|
45
|
+
/**
|
|
46
|
+
* Round a probability price onto the market's tick grid, CONSERVATIVELY by side:
|
|
47
|
+
* a BUY rounds DOWN and a SELL rounds UP, so the signed order is never priced
|
|
48
|
+
* worse than the user's stated limit. (Plain Math.round could round a buy at
|
|
49
|
+
* 0.556 up to 0.56 — signing above the limit; near the grid floor a buy at
|
|
50
|
+
* 0.0051 would round up to a full tick, doubling notional.) A sub-tick buy
|
|
51
|
+
* floors to 0, which the caller's range check then rejects with a clear error
|
|
52
|
+
* rather than silently lifting it to the first tick.
|
|
53
|
+
*/
|
|
54
|
+
export function roundToTick(price, tickSize, side = "buy") {
|
|
55
|
+
const tick = parseFloat(tickSize);
|
|
56
|
+
const decimals = Math.max(0, (tickSize.split(".")[1] ?? "").length);
|
|
57
|
+
const steps = side === "buy" ? Math.floor(price / tick) : Math.ceil(price / tick);
|
|
58
|
+
return Number((steps * tick).toFixed(decimals));
|
|
59
|
+
}
|
|
60
|
+
async function resolveToken(clob, input) {
|
|
61
|
+
if (input.token_id)
|
|
62
|
+
return { tokenId: input.token_id };
|
|
63
|
+
if (!input.condition_id) {
|
|
64
|
+
throw new Error(`Provide token_id, or condition_id + outcome (find them via blockrun_markets).`);
|
|
65
|
+
}
|
|
66
|
+
const market = (await clob.getMarket(input.condition_id));
|
|
67
|
+
const tokens = market?.tokens ?? [];
|
|
68
|
+
if (!tokens.length)
|
|
69
|
+
throw new Error(`No tokens found for condition ${input.condition_id}.`);
|
|
70
|
+
const want = input.outcome?.toLowerCase();
|
|
71
|
+
const match = want ? tokens.find((t) => t.outcome?.toLowerCase() === want) : undefined;
|
|
72
|
+
if (!match?.token_id) {
|
|
73
|
+
const available = tokens.map((t) => t.outcome).filter(Boolean).join(", ");
|
|
74
|
+
throw new Error(`Outcome ${input.outcome ? `'${input.outcome}'` : "(none given)"} not found for this market. ` +
|
|
75
|
+
`Available outcomes: ${available}. Pass outcome (e.g. "Yes") with condition_id, or a token_id directly.`);
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
tokenId: match.token_id,
|
|
79
|
+
question: market.question,
|
|
80
|
+
outcome: match.outcome,
|
|
81
|
+
conditionId: market.condition_id ?? input.condition_id,
|
|
82
|
+
closed: market.closed,
|
|
83
|
+
acceptingOrders: market.accepting_orders,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function bestQuote(book, side) {
|
|
87
|
+
// Asks fill buys, bids fill sells. Books are not guaranteed sorted; scan.
|
|
88
|
+
const levels = side === "buy" ? book.asks : book.bids;
|
|
89
|
+
if (!levels?.length)
|
|
90
|
+
return null;
|
|
91
|
+
const prices = levels.map((l) => parseFloat(l.price)).filter((p) => Number.isFinite(p));
|
|
92
|
+
if (!prices.length)
|
|
93
|
+
return null;
|
|
94
|
+
return side === "buy" ? Math.min(...prices) : Math.max(...prices);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* True when an error is a CLOB credential/auth failure worth re-deriving for
|
|
98
|
+
* (the issue-#65 fingerprint, or a genuine auth rejection). Deliberately does
|
|
99
|
+
* NOT scan response DATA for a bare "401": a token/condition id like
|
|
100
|
+
* "0x8a401f…" or a fill line "filled 401 of 500" would false-positive and churn
|
|
101
|
+
* valid creds. Auth signals are matched only in the human message; the HTTP
|
|
102
|
+
* status (when present) is the authoritative 401 signal.
|
|
103
|
+
*/
|
|
104
|
+
function isCredsMismatchError(err) {
|
|
105
|
+
const msg = (err.message ?? "").toLowerCase();
|
|
106
|
+
const dataText = typeof err.data === "string" ? err.data.toLowerCase()
|
|
107
|
+
: err.data ? JSON.stringify(err.data).toLowerCase() : "";
|
|
108
|
+
// The #65 phrase is specific enough to trust anywhere (message or data body).
|
|
109
|
+
if (`${msg} ${dataText}`.includes("order signer address has to be the address of the api key"))
|
|
110
|
+
return true;
|
|
111
|
+
if (err.status === 401)
|
|
112
|
+
return true;
|
|
113
|
+
return msg.includes("unauthorized") || msg.includes("api key not found") || msg.includes("invalid api key");
|
|
114
|
+
}
|
|
115
|
+
/** Map CLOB errors to actionable guidance. Exported for unit tests. */
|
|
116
|
+
export async function mapClobError(err) {
|
|
117
|
+
const e = err;
|
|
118
|
+
const dataText = e?.data ? ` — ${typeof e.data === "string" ? e.data : JSON.stringify(e.data)}` : "";
|
|
119
|
+
const message = `${e?.message ?? String(err)}${dataText}`;
|
|
120
|
+
const m = message.toLowerCase();
|
|
121
|
+
if (e?.status === 403 || (/(^|[^0-9.])403($|[^0-9.])/).test(m)) {
|
|
122
|
+
const geo = await checkGeoblock();
|
|
123
|
+
const where = geo.country ? ` (egress country: ${geo.country})` : "";
|
|
124
|
+
return `Order rejected with 403 — Polymarket geoblocks order placement from this egress${where} ` +
|
|
125
|
+
`(US/UK/EU and many regions are restricted; automated trading is allowed from unrestricted egress). ` +
|
|
126
|
+
`Fix: set POLYMARKET_CLOB_PROXY / HTTPS_PROXY, or point POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL ` +
|
|
127
|
+
`at a Tokyo relay (deploy/tokyo-egress). Raw: ${message}`;
|
|
128
|
+
}
|
|
129
|
+
if (m.includes("maker address not allowed") || m.includes("deposit wallet flow")) {
|
|
130
|
+
return `Polymarket rejected this maker address — CLOB V2 requires the deposit-wallet flow to place ` +
|
|
131
|
+
`orders (a plain EOA maker is not accepted). Use the default deposit-wallet mode: unset ` +
|
|
132
|
+
`POLYMARKET_SIG_TYPE (=3) and set relayer creds (POLYMARKET_RELAYER_API_KEY/_SECRET/_PASSPHRASE) so ` +
|
|
133
|
+
`action:"setup" can create your deposit wallet. Raw: ${message}`;
|
|
134
|
+
}
|
|
135
|
+
if (isCredsMismatchError(e)) {
|
|
136
|
+
return `CLOB rejected the API credentials (${message}). Credentials were re-derived automatically; ` +
|
|
137
|
+
`if this persists, run action:"setup", or set POLYMARKET_SIG_TYPE=0 to fall back to plain EOA mode ` +
|
|
138
|
+
`(see clob-client-v2 issue #65).`;
|
|
139
|
+
}
|
|
140
|
+
if (m.includes("not enough balance") || m.includes("insufficient") || m.includes("allowance")) {
|
|
141
|
+
return `Not enough balance/allowance (${message}). The funds wallet needs pUSD and exchange approvals — ` +
|
|
142
|
+
`run action:"setup" (it also refreshes the CLOB's balance cache if you just funded).`;
|
|
143
|
+
}
|
|
144
|
+
if (m.includes("invalid price") || m.includes("tick")) {
|
|
145
|
+
return `Price rejected (${message}). Prices are probabilities on the market's tick grid — ` +
|
|
146
|
+
`this tool rounds automatically, so if you see this the market's tick size may have changed; retry.`;
|
|
147
|
+
}
|
|
148
|
+
if (m.includes("closed") || m.includes("resolved") || m.includes("not accepting")) {
|
|
149
|
+
return `Market is not accepting orders (${message}). If it resolved in your favor, use action:"positions" ` +
|
|
150
|
+
`then action:"redeem".`;
|
|
151
|
+
}
|
|
152
|
+
if (m.includes("fok") || m.includes("killed") || m.includes("not filled")) {
|
|
153
|
+
return `Fill-or-kill order could not fill completely (${message}). Try order_type:"FAK" (fills what it can) ` +
|
|
154
|
+
`or a limit order at the shown book price.`;
|
|
155
|
+
}
|
|
156
|
+
return `Polymarket CLOB error: ${message}`;
|
|
157
|
+
}
|
|
158
|
+
function bindAddressForCreds() {
|
|
159
|
+
// CLOB API creds are ALWAYS bound to the owner EOA (sigType 0), even in
|
|
160
|
+
// POLY_1271 mode — see the note in client.ts getClobClient. The on-401 retry
|
|
161
|
+
// must invalidate that same key, not the deposit wallet's.
|
|
162
|
+
return { address: getPolymarketAccount().address, sigType: 0 };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Run a CLOB call; on a creds-mismatch/401 (stale or EOA-bound creds — the
|
|
166
|
+
* issue-#65 signature), invalidate the cached creds, rebuild the client (which
|
|
167
|
+
* re-derives with the 7739-wrapped headers) and retry exactly once.
|
|
168
|
+
*/
|
|
169
|
+
async function withCredsRetry(fn) {
|
|
170
|
+
const clob = await getClobClient();
|
|
171
|
+
try {
|
|
172
|
+
return await fn(clob);
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
if (!isCredsMismatchError(err))
|
|
176
|
+
throw err;
|
|
177
|
+
const { address, sigType } = bindAddressForCreds();
|
|
178
|
+
if (address)
|
|
179
|
+
invalidateL2Creds(address, sigType);
|
|
180
|
+
resetClobClient();
|
|
181
|
+
const fresh = await getClobClient();
|
|
182
|
+
return fn(fresh);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export async function executeTrade(input) {
|
|
186
|
+
const side = input.action === "buy" ? Side.BUY : Side.SELL;
|
|
187
|
+
const isLimit = input.price !== undefined;
|
|
188
|
+
// Cross-field validation (zod schema is per-field; rules live here).
|
|
189
|
+
if (isLimit && input.size === undefined) {
|
|
190
|
+
return { text: `Limit orders need both price and size (shares).`, isError: true };
|
|
191
|
+
}
|
|
192
|
+
if (!isLimit && input.action === "buy" && input.amount_usd === undefined) {
|
|
193
|
+
return { text: `Market buys need amount_usd (pUSD dollars to spend). For a limit order pass price + size.`, isError: true };
|
|
194
|
+
}
|
|
195
|
+
if (!isLimit && input.action === "sell" && input.size === undefined) {
|
|
196
|
+
return { text: `Market sells need size (shares to sell).`, isError: true };
|
|
197
|
+
}
|
|
198
|
+
if (input.order_type === "GTD" && input.expires_at === undefined) {
|
|
199
|
+
return { text: `GTD orders need expires_at (unix seconds, at least ~3 minutes in the future).`, isError: true };
|
|
200
|
+
}
|
|
201
|
+
if (isLimit && (input.order_type === "FOK" || input.order_type === "FAK")) {
|
|
202
|
+
return { text: `FOK/FAK are market-order types — omit price for a market order, or use GTC/GTD for limits.`, isError: true };
|
|
203
|
+
}
|
|
204
|
+
if (!isLimit && (input.order_type === "GTC" || input.order_type === "GTD")) {
|
|
205
|
+
return { text: `GTC/GTD need a limit price. Pass price + size, or use FOK/FAK for market orders.`, isError: true };
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
return await withCredsRetry(async (clob) => {
|
|
209
|
+
const token = await resolveToken(clob, input);
|
|
210
|
+
if (token.closed || token.acceptingOrders === false) {
|
|
211
|
+
return {
|
|
212
|
+
text: `Market "${token.question ?? token.conditionId}" is not accepting orders (closed/resolved). ` +
|
|
213
|
+
`Use action:"positions" and action:"redeem" if you hold a winning position.`,
|
|
214
|
+
isError: true,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const book = await clob.getOrderBook(token.tokenId);
|
|
218
|
+
const tickSize = book.tick_size;
|
|
219
|
+
const negRisk = Boolean(book.neg_risk);
|
|
220
|
+
const minSize = parseFloat(book.min_order_size || "0");
|
|
221
|
+
const quote = bestQuote(book, input.action);
|
|
222
|
+
// Normalize the order economics for validation + preview. Round
|
|
223
|
+
// conservatively by side so the signed price never beats the user's limit.
|
|
224
|
+
const price = input.price !== undefined ? roundToTick(input.price, tickSize, input.action) : undefined;
|
|
225
|
+
const tick = parseFloat(tickSize);
|
|
226
|
+
if (price !== undefined && (price < tick || price > 1 - tick)) {
|
|
227
|
+
return {
|
|
228
|
+
text: `Price ${input.price} rounds to ${price}, outside this market's valid range ` +
|
|
229
|
+
`(${tick} – ${1 - tick}, tick ${tickSize}). A buy below one tick cannot cross any valid ask.`,
|
|
230
|
+
isError: true,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const size = input.size;
|
|
234
|
+
// A market SELL's notional depends on the live best bid; if the book has
|
|
235
|
+
// no parseable bid we cannot bound the spend, so REJECT rather than let a
|
|
236
|
+
// $0 notional silently bypass the caps (the SDK would still fill it).
|
|
237
|
+
if (!isLimit && input.action === "sell" && !quote) {
|
|
238
|
+
return {
|
|
239
|
+
text: `Cannot price a market sell right now — the order book has no bid to estimate against. ` +
|
|
240
|
+
`Retry shortly, or place a limit sell with an explicit price.`,
|
|
241
|
+
isError: true,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const notional = isLimit
|
|
245
|
+
? price * size
|
|
246
|
+
: input.action === "buy"
|
|
247
|
+
? input.amount_usd
|
|
248
|
+
: size * quote;
|
|
249
|
+
if (isLimit && minSize > 0 && size < minSize) {
|
|
250
|
+
return { text: `Size ${size} is below this market's minimum order size of ${minSize} shares.`, isError: true };
|
|
251
|
+
}
|
|
252
|
+
const maxBet = getMaxBetUsd();
|
|
253
|
+
if (notional > maxBet) {
|
|
254
|
+
return {
|
|
255
|
+
text: `Order notional ~$${notional.toFixed(2)} exceeds the per-order cap of $${maxBet} ` +
|
|
256
|
+
`(POLYMARKET_MAX_BET_USD). Reduce the order or raise the cap explicitly.`,
|
|
257
|
+
isError: true,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
// Reserve against the session cap ATOMICALLY, before the awaited submit,
|
|
261
|
+
// so two concurrent orders can't both pass the check against a stale total
|
|
262
|
+
// and jointly overshoot. Rolled back below if the order fails to place.
|
|
263
|
+
const sessionCap = getMaxSessionUsd();
|
|
264
|
+
if (sessionCap !== null && ledger.totalUsd + notional > sessionCap) {
|
|
265
|
+
return {
|
|
266
|
+
text: `Session betting total would reach $${(ledger.totalUsd + notional).toFixed(2)}, over the ` +
|
|
267
|
+
`POLYMARKET_MAX_SESSION_USD cap of $${sessionCap} (spent so far: $${ledger.totalUsd.toFixed(2)}).`,
|
|
268
|
+
isError: true,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
const orderKind = isLimit ? (input.order_type ?? "GTC") : (input.order_type ?? "FOK");
|
|
272
|
+
const summary = [
|
|
273
|
+
`${input.action.toUpperCase()} ${token.outcome ? `"${token.outcome}"` : `token ${token.tokenId.slice(0, 12)}…`}` +
|
|
274
|
+
(token.question ? ` — ${token.question}` : ""),
|
|
275
|
+
isLimit
|
|
276
|
+
? ` Limit ${orderKind}: ${size} shares @ ${price} (notional $${notional.toFixed(2)})`
|
|
277
|
+
: input.action === "buy"
|
|
278
|
+
? ` Market ${orderKind}: spend $${input.amount_usd.toFixed(2)}${quote ? ` (best ask ${quote})` : ""}`
|
|
279
|
+
: ` Market ${orderKind}: sell ${size} shares${quote ? ` (best bid ${quote}, est. $${notional.toFixed(2)})` : ""}`,
|
|
280
|
+
` Tick ${tickSize} · negRisk ${negRisk} · min size ${minSize || "n/a"} · fees are taker-only`,
|
|
281
|
+
].join("\n");
|
|
282
|
+
// Dry-run: no confirm → preview only, nothing is signed.
|
|
283
|
+
if (input.confirm !== true) {
|
|
284
|
+
return {
|
|
285
|
+
text: `DRY RUN — no order placed.\n${summary}\n\nRe-call with confirm:true to sign and submit.`,
|
|
286
|
+
structured: {
|
|
287
|
+
dryRun: true,
|
|
288
|
+
action: input.action,
|
|
289
|
+
tokenId: token.tokenId,
|
|
290
|
+
price,
|
|
291
|
+
size,
|
|
292
|
+
amountUsd: input.amount_usd,
|
|
293
|
+
orderType: orderKind,
|
|
294
|
+
notionalUsd: notional,
|
|
295
|
+
tickSize,
|
|
296
|
+
negRisk,
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
const options = { tickSize: tickSize, negRisk };
|
|
301
|
+
// Reserve now (before the await) so a concurrent order sees this spend;
|
|
302
|
+
// roll back if the submit throws so a failed order doesn't consume budget.
|
|
303
|
+
reserveBet(notional, input.agent_id);
|
|
304
|
+
let response;
|
|
305
|
+
try {
|
|
306
|
+
response = isLimit
|
|
307
|
+
? await clob.createAndPostOrder({
|
|
308
|
+
tokenID: token.tokenId,
|
|
309
|
+
price: price,
|
|
310
|
+
size: size,
|
|
311
|
+
side,
|
|
312
|
+
...(orderKind === "GTD" && input.expires_at ? { expiration: input.expires_at } : {}),
|
|
313
|
+
}, options, orderKind === "GTD" ? OrderType.GTD : OrderType.GTC, input.post_only ?? false)
|
|
314
|
+
: await clob.createAndPostMarketOrder({
|
|
315
|
+
tokenID: token.tokenId,
|
|
316
|
+
amount: input.action === "buy" ? input.amount_usd : size,
|
|
317
|
+
side,
|
|
318
|
+
orderType: orderKind === "FAK" ? OrderType.FAK : OrderType.FOK,
|
|
319
|
+
}, options, orderKind === "FAK" ? OrderType.FAK : OrderType.FOK);
|
|
320
|
+
}
|
|
321
|
+
catch (submitErr) {
|
|
322
|
+
releaseBet(notional, input.agent_id);
|
|
323
|
+
throw submitErr;
|
|
324
|
+
}
|
|
325
|
+
const r = response;
|
|
326
|
+
// The order is placed unless the CLOB explicitly says success:false (or
|
|
327
|
+
// returns an error with no orderID). A non-empty errorMsg WITH success and
|
|
328
|
+
// an orderID is informational — e.g. status "delayed", "order match delayed
|
|
329
|
+
// due to market conditions" — the order IS live, so don't roll it back or a
|
|
330
|
+
// retrying agent double-submits.
|
|
331
|
+
const placed = r?.success !== false && (r?.orderID || r?.status === "matched");
|
|
332
|
+
if (!placed) {
|
|
333
|
+
releaseBet(notional, input.agent_id);
|
|
334
|
+
throw new Error(r?.errorMsg || "order rejected");
|
|
335
|
+
}
|
|
336
|
+
commitBet();
|
|
337
|
+
const filled = r?.status === "matched" || (r?.transactionsHashes?.length ?? 0) > 0;
|
|
338
|
+
return {
|
|
339
|
+
text: [
|
|
340
|
+
`✅ Order submitted.\n${summary}`,
|
|
341
|
+
` orderID: ${r?.orderID ?? "n/a"}`,
|
|
342
|
+
` status: ${r?.status ?? "submitted"}${filled ? "" : " (resting in the book until filled or cancelled)"}`,
|
|
343
|
+
...(r?.errorMsg ? [` note: ${r.errorMsg}`] : []),
|
|
344
|
+
...(r?.transactionsHashes?.length ? [` tx: ${r.transactionsHashes.join(", ")}`] : []),
|
|
345
|
+
` Session bets so far: $${ledger.totalUsd.toFixed(2)} across ${ledger.count} order(s).`,
|
|
346
|
+
].join("\n"),
|
|
347
|
+
structured: {
|
|
348
|
+
orderID: r?.orderID,
|
|
349
|
+
status: r?.status,
|
|
350
|
+
success: true,
|
|
351
|
+
transactionsHashes: r?.transactionsHashes,
|
|
352
|
+
tradeIDs: r?.tradeIDs,
|
|
353
|
+
takingAmount: r?.takingAmount,
|
|
354
|
+
makingAmount: r?.makingAmount,
|
|
355
|
+
notionalUsd: notional,
|
|
356
|
+
session: getSessionLedger(),
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
return { text: await mapClobError(err), isError: true };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
// --- Open orders / cancel ---
|
|
366
|
+
export async function listOpenOrders(input) {
|
|
367
|
+
try {
|
|
368
|
+
return await withCredsRetry(async (clob) => {
|
|
369
|
+
const orders = await clob.getOpenOrders(input.condition_id ? { market: input.condition_id } : undefined);
|
|
370
|
+
if (!orders?.length) {
|
|
371
|
+
return { text: `No open orders.`, structured: { orders: [] } };
|
|
372
|
+
}
|
|
373
|
+
const lines = orders.map((o) => ` ${o.side} ${o.original_size} @ ${o.price} (${o.outcome ?? o.asset_id?.slice(0, 10)}) — ` +
|
|
374
|
+
`filled ${o.size_matched ?? "0"} · ${o.order_type} · id ${o.id}`);
|
|
375
|
+
return {
|
|
376
|
+
text: `Open orders (${orders.length}):\n${lines.join("\n")}\n\nCancel with action:"cancel" order_id:"…" (or all:true).`,
|
|
377
|
+
structured: { orders },
|
|
378
|
+
};
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
catch (err) {
|
|
382
|
+
return { text: await mapClobError(err), isError: true };
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
export async function cancelOrdersAction(input) {
|
|
386
|
+
if (!input.order_id && input.all !== true) {
|
|
387
|
+
return { text: `Pass order_id:"…" or all:true.`, isError: true };
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
return await withCredsRetry(async (clob) => {
|
|
391
|
+
const result = (input.all === true
|
|
392
|
+
? await clob.cancelAll()
|
|
393
|
+
: await clob.cancelOrder({ orderID: input.order_id }));
|
|
394
|
+
// The CLOB reports per-order outcomes: {canceled:[...], not_canceled:{id:reason}}.
|
|
395
|
+
// Don't claim success blindly — an order mid-settlement stays live and the
|
|
396
|
+
// agent must know it still has exposure.
|
|
397
|
+
const canceled = result?.canceled ?? [];
|
|
398
|
+
const notCanceled = result?.not_canceled ?? {};
|
|
399
|
+
const failedIds = Object.keys(notCanceled);
|
|
400
|
+
if (failedIds.length) {
|
|
401
|
+
const detail = failedIds.map((id) => `${id}: ${notCanceled[id]}`).join("; ");
|
|
402
|
+
return {
|
|
403
|
+
text: `⚠️ Cancelled ${canceled.length} order(s); ${failedIds.length} could NOT be cancelled ` +
|
|
404
|
+
`(still live — you retain exposure): ${detail}`,
|
|
405
|
+
structured: { canceled, notCanceled },
|
|
406
|
+
isError: true,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
return {
|
|
410
|
+
text: input.all === true
|
|
411
|
+
? `✅ Cancelled all open orders${canceled.length ? ` (${canceled.length})` : ""}.`
|
|
412
|
+
: `✅ Cancelled order ${input.order_id}.`,
|
|
413
|
+
structured: { result },
|
|
414
|
+
};
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
catch (err) {
|
|
418
|
+
return { text: await mapClobError(err), isError: true };
|
|
419
|
+
}
|
|
420
|
+
}
|