@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,455 @@
|
|
|
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 { AssetType, 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
|
+
/**
|
|
116
|
+
* True when a CLOB submit failed because the EXCHANGE thinks the funds wallet
|
|
117
|
+
* lacks balance/allowance. On-chain the deposit wallet may be fully funded and
|
|
118
|
+
* approved (setup verifies both) yet the CLOB's SERVER-SIDE balance cache lags —
|
|
119
|
+
* refreshing that cache (updateBalanceAllowance) and retrying clears it. Matched
|
|
120
|
+
* in the human message OR the response data body. Deliberately narrow: only
|
|
121
|
+
* these phrases, so a genuine unrelated error is never silently retried.
|
|
122
|
+
*/
|
|
123
|
+
function isBalanceAllowanceError(err) {
|
|
124
|
+
const e = err;
|
|
125
|
+
const msg = (e?.message ?? "").toLowerCase();
|
|
126
|
+
const dataText = typeof e?.data === "string" ? e.data.toLowerCase()
|
|
127
|
+
: e?.data ? JSON.stringify(e.data).toLowerCase() : "";
|
|
128
|
+
const text = `${msg} ${dataText}`;
|
|
129
|
+
return text.includes("not enough balance") || text.includes("insufficient") || text.includes("allowance");
|
|
130
|
+
}
|
|
131
|
+
/** Map CLOB errors to actionable guidance. Exported for unit tests. */
|
|
132
|
+
export async function mapClobError(err) {
|
|
133
|
+
const e = err;
|
|
134
|
+
const dataText = e?.data ? ` — ${typeof e.data === "string" ? e.data : JSON.stringify(e.data)}` : "";
|
|
135
|
+
const message = `${e?.message ?? String(err)}${dataText}`;
|
|
136
|
+
const m = message.toLowerCase();
|
|
137
|
+
if (e?.status === 403 || (/(^|[^0-9.])403($|[^0-9.])/).test(m)) {
|
|
138
|
+
const geo = await checkGeoblock();
|
|
139
|
+
const where = geo.country ? ` (egress country: ${geo.country})` : "";
|
|
140
|
+
return `Order rejected with 403 — Polymarket geoblocks order placement from this egress${where} ` +
|
|
141
|
+
`(US/UK/EU and many regions are restricted; automated trading is allowed from unrestricted egress). ` +
|
|
142
|
+
`Fix: set POLYMARKET_CLOB_PROXY / HTTPS_PROXY, or point POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL ` +
|
|
143
|
+
`at a Tokyo relay (deploy/tokyo-egress). Raw: ${message}`;
|
|
144
|
+
}
|
|
145
|
+
if (m.includes("maker address not allowed") || m.includes("deposit wallet flow")) {
|
|
146
|
+
return `Polymarket rejected this maker address — CLOB V2 requires the deposit-wallet flow to place ` +
|
|
147
|
+
`orders (a plain EOA maker is not accepted). Use the default deposit-wallet mode: unset ` +
|
|
148
|
+
`POLYMARKET_SIG_TYPE (=3) and set relayer creds (POLYMARKET_RELAYER_API_KEY/_SECRET/_PASSPHRASE) so ` +
|
|
149
|
+
`action:"setup" can create your deposit wallet. Raw: ${message}`;
|
|
150
|
+
}
|
|
151
|
+
if (isCredsMismatchError(e)) {
|
|
152
|
+
return `CLOB rejected the API credentials (${message}). Credentials were re-derived automatically; ` +
|
|
153
|
+
`if this persists, run action:"setup", or set POLYMARKET_SIG_TYPE=0 to fall back to plain EOA mode ` +
|
|
154
|
+
`(see clob-client-v2 issue #65).`;
|
|
155
|
+
}
|
|
156
|
+
if (m.includes("not enough balance") || m.includes("insufficient") || m.includes("allowance")) {
|
|
157
|
+
return `Not enough balance/allowance (${message}). The funds wallet needs pUSD and exchange approvals — ` +
|
|
158
|
+
`run action:"setup" (it also refreshes the CLOB's balance cache if you just funded).`;
|
|
159
|
+
}
|
|
160
|
+
if (m.includes("invalid price") || m.includes("tick")) {
|
|
161
|
+
return `Price rejected (${message}). Prices are probabilities on the market's tick grid — ` +
|
|
162
|
+
`this tool rounds automatically, so if you see this the market's tick size may have changed; retry.`;
|
|
163
|
+
}
|
|
164
|
+
if (m.includes("closed") || m.includes("resolved") || m.includes("not accepting")) {
|
|
165
|
+
return `Market is not accepting orders (${message}). If it resolved in your favor, use action:"positions" ` +
|
|
166
|
+
`then action:"redeem".`;
|
|
167
|
+
}
|
|
168
|
+
if (m.includes("fok") || m.includes("killed") || m.includes("not filled")) {
|
|
169
|
+
return `Fill-or-kill order could not fill completely (${message}). Try order_type:"FAK" (fills what it can) ` +
|
|
170
|
+
`or a limit order at the shown book price.`;
|
|
171
|
+
}
|
|
172
|
+
return `Polymarket CLOB error: ${message}`;
|
|
173
|
+
}
|
|
174
|
+
function bindAddressForCreds() {
|
|
175
|
+
// CLOB API creds are ALWAYS bound to the owner EOA (sigType 0), even in
|
|
176
|
+
// POLY_1271 mode — see the note in client.ts getClobClient. The on-401 retry
|
|
177
|
+
// must invalidate that same key, not the deposit wallet's.
|
|
178
|
+
return { address: getPolymarketAccount().address, sigType: 0 };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Run a CLOB call; on a creds-mismatch/401 (stale or EOA-bound creds — the
|
|
182
|
+
* issue-#65 signature), invalidate the cached creds, rebuild the client (which
|
|
183
|
+
* re-derives with the 7739-wrapped headers) and retry exactly once.
|
|
184
|
+
*/
|
|
185
|
+
async function withCredsRetry(fn) {
|
|
186
|
+
const clob = await getClobClient();
|
|
187
|
+
try {
|
|
188
|
+
return await fn(clob);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
if (!isCredsMismatchError(err))
|
|
192
|
+
throw err;
|
|
193
|
+
const { address, sigType } = bindAddressForCreds();
|
|
194
|
+
if (address)
|
|
195
|
+
invalidateL2Creds(address, sigType);
|
|
196
|
+
resetClobClient();
|
|
197
|
+
const fresh = await getClobClient();
|
|
198
|
+
return fn(fresh);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
export async function executeTrade(input) {
|
|
202
|
+
const side = input.action === "buy" ? Side.BUY : Side.SELL;
|
|
203
|
+
const isLimit = input.price !== undefined;
|
|
204
|
+
// Cross-field validation (zod schema is per-field; rules live here).
|
|
205
|
+
if (isLimit && input.size === undefined) {
|
|
206
|
+
return { text: `Limit orders need both price and size (shares).`, isError: true };
|
|
207
|
+
}
|
|
208
|
+
if (!isLimit && input.action === "buy" && input.amount_usd === undefined) {
|
|
209
|
+
return { text: `Market buys need amount_usd (pUSD dollars to spend). For a limit order pass price + size.`, isError: true };
|
|
210
|
+
}
|
|
211
|
+
if (!isLimit && input.action === "sell" && input.size === undefined) {
|
|
212
|
+
return { text: `Market sells need size (shares to sell).`, isError: true };
|
|
213
|
+
}
|
|
214
|
+
if (input.order_type === "GTD" && input.expires_at === undefined) {
|
|
215
|
+
return { text: `GTD orders need expires_at (unix seconds, at least ~3 minutes in the future).`, isError: true };
|
|
216
|
+
}
|
|
217
|
+
if (isLimit && (input.order_type === "FOK" || input.order_type === "FAK")) {
|
|
218
|
+
return { text: `FOK/FAK are market-order types — omit price for a market order, or use GTC/GTD for limits.`, isError: true };
|
|
219
|
+
}
|
|
220
|
+
if (!isLimit && (input.order_type === "GTC" || input.order_type === "GTD")) {
|
|
221
|
+
return { text: `GTC/GTD need a limit price. Pass price + size, or use FOK/FAK for market orders.`, isError: true };
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
return await withCredsRetry(async (clob) => {
|
|
225
|
+
const token = await resolveToken(clob, input);
|
|
226
|
+
if (token.closed || token.acceptingOrders === false) {
|
|
227
|
+
return {
|
|
228
|
+
text: `Market "${token.question ?? token.conditionId}" is not accepting orders (closed/resolved). ` +
|
|
229
|
+
`Use action:"positions" and action:"redeem" if you hold a winning position.`,
|
|
230
|
+
isError: true,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const book = await clob.getOrderBook(token.tokenId);
|
|
234
|
+
const tickSize = book.tick_size;
|
|
235
|
+
const negRisk = Boolean(book.neg_risk);
|
|
236
|
+
const minSize = parseFloat(book.min_order_size || "0");
|
|
237
|
+
const quote = bestQuote(book, input.action);
|
|
238
|
+
// Normalize the order economics for validation + preview. Round
|
|
239
|
+
// conservatively by side so the signed price never beats the user's limit.
|
|
240
|
+
const price = input.price !== undefined ? roundToTick(input.price, tickSize, input.action) : undefined;
|
|
241
|
+
const tick = parseFloat(tickSize);
|
|
242
|
+
if (price !== undefined && (price < tick || price > 1 - tick)) {
|
|
243
|
+
return {
|
|
244
|
+
text: `Price ${input.price} rounds to ${price}, outside this market's valid range ` +
|
|
245
|
+
`(${tick} – ${1 - tick}, tick ${tickSize}). A buy below one tick cannot cross any valid ask.`,
|
|
246
|
+
isError: true,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
const size = input.size;
|
|
250
|
+
// A market SELL's notional depends on the live best bid; if the book has
|
|
251
|
+
// no parseable bid we cannot bound the spend, so REJECT rather than let a
|
|
252
|
+
// $0 notional silently bypass the caps (the SDK would still fill it).
|
|
253
|
+
if (!isLimit && input.action === "sell" && !quote) {
|
|
254
|
+
return {
|
|
255
|
+
text: `Cannot price a market sell right now — the order book has no bid to estimate against. ` +
|
|
256
|
+
`Retry shortly, or place a limit sell with an explicit price.`,
|
|
257
|
+
isError: true,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const notional = isLimit
|
|
261
|
+
? price * size
|
|
262
|
+
: input.action === "buy"
|
|
263
|
+
? input.amount_usd
|
|
264
|
+
: size * quote;
|
|
265
|
+
if (isLimit && minSize > 0 && size < minSize) {
|
|
266
|
+
return { text: `Size ${size} is below this market's minimum order size of ${minSize} shares.`, isError: true };
|
|
267
|
+
}
|
|
268
|
+
const maxBet = getMaxBetUsd();
|
|
269
|
+
if (notional > maxBet) {
|
|
270
|
+
return {
|
|
271
|
+
text: `Order notional ~$${notional.toFixed(2)} exceeds the per-order cap of $${maxBet} ` +
|
|
272
|
+
`(POLYMARKET_MAX_BET_USD). Reduce the order or raise the cap explicitly.`,
|
|
273
|
+
isError: true,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// Reserve against the session cap ATOMICALLY, before the awaited submit,
|
|
277
|
+
// so two concurrent orders can't both pass the check against a stale total
|
|
278
|
+
// and jointly overshoot. Rolled back below if the order fails to place.
|
|
279
|
+
const sessionCap = getMaxSessionUsd();
|
|
280
|
+
if (sessionCap !== null && ledger.totalUsd + notional > sessionCap) {
|
|
281
|
+
return {
|
|
282
|
+
text: `Session betting total would reach $${(ledger.totalUsd + notional).toFixed(2)}, over the ` +
|
|
283
|
+
`POLYMARKET_MAX_SESSION_USD cap of $${sessionCap} (spent so far: $${ledger.totalUsd.toFixed(2)}).`,
|
|
284
|
+
isError: true,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const orderKind = isLimit ? (input.order_type ?? "GTC") : (input.order_type ?? "FOK");
|
|
288
|
+
const summary = [
|
|
289
|
+
`${input.action.toUpperCase()} ${token.outcome ? `"${token.outcome}"` : `token ${token.tokenId.slice(0, 12)}…`}` +
|
|
290
|
+
(token.question ? ` — ${token.question}` : ""),
|
|
291
|
+
isLimit
|
|
292
|
+
? ` Limit ${orderKind}: ${size} shares @ ${price} (notional $${notional.toFixed(2)})`
|
|
293
|
+
: input.action === "buy"
|
|
294
|
+
? ` Market ${orderKind}: spend $${input.amount_usd.toFixed(2)}${quote ? ` (best ask ${quote})` : ""}`
|
|
295
|
+
: ` Market ${orderKind}: sell ${size} shares${quote ? ` (best bid ${quote}, est. $${notional.toFixed(2)})` : ""}`,
|
|
296
|
+
` Tick ${tickSize} · negRisk ${negRisk} · min size ${minSize || "n/a"} · fees are taker-only`,
|
|
297
|
+
].join("\n");
|
|
298
|
+
// Dry-run: no confirm → preview only, nothing is signed.
|
|
299
|
+
if (input.confirm !== true) {
|
|
300
|
+
return {
|
|
301
|
+
text: `DRY RUN — no order placed.\n${summary}\n\nRe-call with confirm:true to sign and submit.`,
|
|
302
|
+
structured: {
|
|
303
|
+
dryRun: true,
|
|
304
|
+
action: input.action,
|
|
305
|
+
tokenId: token.tokenId,
|
|
306
|
+
price,
|
|
307
|
+
size,
|
|
308
|
+
amountUsd: input.amount_usd,
|
|
309
|
+
orderType: orderKind,
|
|
310
|
+
notionalUsd: notional,
|
|
311
|
+
tickSize,
|
|
312
|
+
negRisk,
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
const options = { tickSize: tickSize, negRisk };
|
|
317
|
+
// The signed submit, factored out so it can be retried after a CLOB
|
|
318
|
+
// balance-cache refresh (below) without rebuilding/re-signing anything else.
|
|
319
|
+
const submitOrder = () => isLimit
|
|
320
|
+
? clob.createAndPostOrder({
|
|
321
|
+
tokenID: token.tokenId,
|
|
322
|
+
price: price,
|
|
323
|
+
size: size,
|
|
324
|
+
side,
|
|
325
|
+
...(orderKind === "GTD" && input.expires_at ? { expiration: input.expires_at } : {}),
|
|
326
|
+
}, options, orderKind === "GTD" ? OrderType.GTD : OrderType.GTC, input.post_only ?? false)
|
|
327
|
+
: clob.createAndPostMarketOrder({
|
|
328
|
+
tokenID: token.tokenId,
|
|
329
|
+
amount: input.action === "buy" ? input.amount_usd : size,
|
|
330
|
+
side,
|
|
331
|
+
orderType: orderKind === "FAK" ? OrderType.FAK : OrderType.FOK,
|
|
332
|
+
}, options, orderKind === "FAK" ? OrderType.FAK : OrderType.FOK);
|
|
333
|
+
// Reserve now (before the await) so a concurrent order sees this spend;
|
|
334
|
+
// roll back if the submit throws so a failed order doesn't consume budget.
|
|
335
|
+
reserveBet(notional, input.agent_id);
|
|
336
|
+
let response;
|
|
337
|
+
try {
|
|
338
|
+
try {
|
|
339
|
+
response = await submitOrder();
|
|
340
|
+
}
|
|
341
|
+
catch (submitErr) {
|
|
342
|
+
// Funded + approved on-chain, but the CLOB's server-side balance cache
|
|
343
|
+
// can lag reality — setup's warm-up refresh is best-effort and freshly
|
|
344
|
+
// bridged pUSD takes a moment to register — so the exchange rejects a
|
|
345
|
+
// fully-funded wallet with "not enough balance/allowance". Refresh the
|
|
346
|
+
// cache for the traded asset and retry the submit ONCE before giving up
|
|
347
|
+
// (COLLATERAL for buys, the specific outcome token for sells).
|
|
348
|
+
if (!isBalanceAllowanceError(submitErr))
|
|
349
|
+
throw submitErr;
|
|
350
|
+
await clob.updateBalanceAllowance(input.action === "buy"
|
|
351
|
+
? { asset_type: AssetType.COLLATERAL }
|
|
352
|
+
: { asset_type: AssetType.CONDITIONAL, token_id: token.tokenId });
|
|
353
|
+
response = await submitOrder();
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
catch (submitErr) {
|
|
357
|
+
releaseBet(notional, input.agent_id);
|
|
358
|
+
throw submitErr;
|
|
359
|
+
}
|
|
360
|
+
const r = response;
|
|
361
|
+
// The order is placed unless the CLOB explicitly says success:false (or
|
|
362
|
+
// returns an error with no orderID). A non-empty errorMsg WITH success and
|
|
363
|
+
// an orderID is informational — e.g. status "delayed", "order match delayed
|
|
364
|
+
// due to market conditions" — the order IS live, so don't roll it back or a
|
|
365
|
+
// retrying agent double-submits.
|
|
366
|
+
const placed = r?.success !== false && (r?.orderID || r?.status === "matched");
|
|
367
|
+
if (!placed) {
|
|
368
|
+
releaseBet(notional, input.agent_id);
|
|
369
|
+
throw new Error(r?.errorMsg || "order rejected");
|
|
370
|
+
}
|
|
371
|
+
commitBet();
|
|
372
|
+
const filled = r?.status === "matched" || (r?.transactionsHashes?.length ?? 0) > 0;
|
|
373
|
+
return {
|
|
374
|
+
text: [
|
|
375
|
+
`✅ Order submitted.\n${summary}`,
|
|
376
|
+
` orderID: ${r?.orderID ?? "n/a"}`,
|
|
377
|
+
` status: ${r?.status ?? "submitted"}${filled ? "" : " (resting in the book until filled or cancelled)"}`,
|
|
378
|
+
...(r?.errorMsg ? [` note: ${r.errorMsg}`] : []),
|
|
379
|
+
...(r?.transactionsHashes?.length ? [` tx: ${r.transactionsHashes.join(", ")}`] : []),
|
|
380
|
+
` Session bets so far: $${ledger.totalUsd.toFixed(2)} across ${ledger.count} order(s).`,
|
|
381
|
+
].join("\n"),
|
|
382
|
+
structured: {
|
|
383
|
+
orderID: r?.orderID,
|
|
384
|
+
status: r?.status,
|
|
385
|
+
success: true,
|
|
386
|
+
transactionsHashes: r?.transactionsHashes,
|
|
387
|
+
tradeIDs: r?.tradeIDs,
|
|
388
|
+
takingAmount: r?.takingAmount,
|
|
389
|
+
makingAmount: r?.makingAmount,
|
|
390
|
+
notionalUsd: notional,
|
|
391
|
+
session: getSessionLedger(),
|
|
392
|
+
},
|
|
393
|
+
};
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
catch (err) {
|
|
397
|
+
return { text: await mapClobError(err), isError: true };
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// --- Open orders / cancel ---
|
|
401
|
+
export async function listOpenOrders(input) {
|
|
402
|
+
try {
|
|
403
|
+
return await withCredsRetry(async (clob) => {
|
|
404
|
+
const orders = await clob.getOpenOrders(input.condition_id ? { market: input.condition_id } : undefined);
|
|
405
|
+
if (!orders?.length) {
|
|
406
|
+
return { text: `No open orders.`, structured: { orders: [] } };
|
|
407
|
+
}
|
|
408
|
+
const lines = orders.map((o) => ` ${o.side} ${o.original_size} @ ${o.price} (${o.outcome ?? o.asset_id?.slice(0, 10)}) — ` +
|
|
409
|
+
`filled ${o.size_matched ?? "0"} · ${o.order_type} · id ${o.id}`);
|
|
410
|
+
return {
|
|
411
|
+
text: `Open orders (${orders.length}):\n${lines.join("\n")}\n\nCancel with action:"cancel" order_id:"…" (or all:true).`,
|
|
412
|
+
structured: { orders },
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
catch (err) {
|
|
417
|
+
return { text: await mapClobError(err), isError: true };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
export async function cancelOrdersAction(input) {
|
|
421
|
+
if (!input.order_id && input.all !== true) {
|
|
422
|
+
return { text: `Pass order_id:"…" or all:true.`, isError: true };
|
|
423
|
+
}
|
|
424
|
+
try {
|
|
425
|
+
return await withCredsRetry(async (clob) => {
|
|
426
|
+
const result = (input.all === true
|
|
427
|
+
? await clob.cancelAll()
|
|
428
|
+
: await clob.cancelOrder({ orderID: input.order_id }));
|
|
429
|
+
// The CLOB reports per-order outcomes: {canceled:[...], not_canceled:{id:reason}}.
|
|
430
|
+
// Don't claim success blindly — an order mid-settlement stays live and the
|
|
431
|
+
// agent must know it still has exposure.
|
|
432
|
+
const canceled = result?.canceled ?? [];
|
|
433
|
+
const notCanceled = result?.not_canceled ?? {};
|
|
434
|
+
const failedIds = Object.keys(notCanceled);
|
|
435
|
+
if (failedIds.length) {
|
|
436
|
+
const detail = failedIds.map((id) => `${id}: ${notCanceled[id]}`).join("; ");
|
|
437
|
+
return {
|
|
438
|
+
text: `⚠️ Cancelled ${canceled.length} order(s); ${failedIds.length} could NOT be cancelled ` +
|
|
439
|
+
`(still live — you retain exposure): ${detail}`,
|
|
440
|
+
structured: { canceled, notCanceled },
|
|
441
|
+
isError: true,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
return {
|
|
445
|
+
text: input.all === true
|
|
446
|
+
? `✅ Cancelled all open orders${canceled.length ? ` (${canceled.length})` : ""}.`
|
|
447
|
+
: `✅ Cancelled order ${input.order_id}.`,
|
|
448
|
+
structured: { result },
|
|
449
|
+
};
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
catch (err) {
|
|
453
|
+
return { text: await mapClobError(err), isError: true };
|
|
454
|
+
}
|
|
455
|
+
}
|
|
@@ -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
|
+
}
|