@blockrun/franklin 3.30.0 → 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.
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// - per-order notional capped by POLYMARKET_MAX_BET_USD (default $25).
|
|
9
9
|
// - optional POLYMARKET_MAX_SESSION_USD cumulative cap, tracked in-memory
|
|
10
10
|
// with per-agent attribution (agent_id).
|
|
11
|
-
import { OrderType, Side } from "@polymarket/clob-client-v2";
|
|
11
|
+
import { AssetType, OrderType, Side } from "@polymarket/clob-client-v2";
|
|
12
12
|
import { checkGeoblock, getClobClient, getPolymarketAccount, resetClobClient } from "./client.js";
|
|
13
13
|
import { getMaxBetUsd, getMaxSessionUsd } from "./constants.js";
|
|
14
14
|
import { invalidateL2Creds } from "./creds.js";
|
|
@@ -112,6 +112,22 @@ function isCredsMismatchError(err) {
|
|
|
112
112
|
return true;
|
|
113
113
|
return msg.includes("unauthorized") || msg.includes("api key not found") || msg.includes("invalid api key");
|
|
114
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
|
+
}
|
|
115
131
|
/** Map CLOB errors to actionable guidance. Exported for unit tests. */
|
|
116
132
|
export async function mapClobError(err) {
|
|
117
133
|
const e = err;
|
|
@@ -298,25 +314,44 @@ export async function executeTrade(input) {
|
|
|
298
314
|
};
|
|
299
315
|
}
|
|
300
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);
|
|
301
333
|
// Reserve now (before the await) so a concurrent order sees this spend;
|
|
302
334
|
// roll back if the submit throws so a failed order doesn't consume budget.
|
|
303
335
|
reserveBet(notional, input.agent_id);
|
|
304
336
|
let response;
|
|
305
337
|
try {
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
+
}
|
|
320
355
|
}
|
|
321
356
|
catch (submitErr) {
|
|
322
357
|
releaseBet(notional, input.agent_id);
|
|
@@ -58,15 +58,26 @@ function pusdApprovalTarget() {
|
|
|
58
58
|
return bounded === null ? maxUint256 : parseUnits(String(bounded), PUSD_DECIMALS);
|
|
59
59
|
}
|
|
60
60
|
/**
|
|
61
|
-
* The approval set Polymarket V2 trading needs from the funds-holding wallet
|
|
62
|
-
*
|
|
63
|
-
*
|
|
61
|
+
* The approval set Polymarket V2 trading needs from the funds-holding wallet,
|
|
62
|
+
* mirroring Polymarket's own canonical approveTokensForTrading.ts (proxy/safe
|
|
63
|
+
* wallet): pUSD spend for ALL FOUR collateral spenders — both exchanges, the
|
|
64
|
+
* Conditional Tokens contract (direct split/merge), AND the NegRisk Adapter
|
|
65
|
+
* (negRisk order settlement / convert / redeem pulls collateral through it) —
|
|
66
|
+
* plus the CTF operator for both exchanges and the adapter.
|
|
67
|
+
*
|
|
68
|
+
* The NegRisk Adapter pUSD approval is REQUIRED to trade neg-risk markets (e.g.
|
|
69
|
+
* multi-outcome "winner" markets): without it the CLOB accepts the order but
|
|
70
|
+
* settlement through the adapter reverts. It was previously missing while the
|
|
71
|
+
* adapter's CTF (ERC1155) operator approval was granted — an asymmetry that let
|
|
72
|
+
* setup report "ready" yet neg-risk buys fail.
|
|
64
73
|
*/
|
|
65
74
|
async function readApprovals(owner) {
|
|
66
75
|
const pc = getPublicClient();
|
|
67
76
|
const erc20Spenders = [
|
|
68
77
|
["pUSD → CTF Exchange V2", CTF_EXCHANGE_V2],
|
|
69
78
|
["pUSD → NegRisk Exchange V2", NEG_RISK_CTF_EXCHANGE_V2],
|
|
79
|
+
["pUSD → NegRisk Adapter", NEG_RISK_ADAPTER],
|
|
80
|
+
["pUSD → Conditional Tokens", CONDITIONAL_TOKENS],
|
|
70
81
|
];
|
|
71
82
|
const erc1155Operators = [
|
|
72
83
|
["CTF → CTF Exchange V2", CTF_EXCHANGE_V2],
|
|
@@ -208,10 +219,21 @@ async function runSetupDepositWallet(opts) {
|
|
|
208
219
|
// which is guaranteed above). Non-fatal: report instead of failing setup.
|
|
209
220
|
let credsReady = false;
|
|
210
221
|
let credsNote = "";
|
|
222
|
+
let balanceCacheWarned = "";
|
|
211
223
|
try {
|
|
212
224
|
const clob = await getClobClient();
|
|
213
225
|
credsReady = true;
|
|
214
|
-
|
|
226
|
+
// Warm the CLOB's server-side balance cache so the first buy sees the funds.
|
|
227
|
+
// Best-effort — but do NOT swallow silently: if it fails, setup used to still
|
|
228
|
+
// print "ready" while the exchange thought the wallet was empty, so the first
|
|
229
|
+
// buy failed with "not enough balance". Surface it instead; the buy path also
|
|
230
|
+
// refreshes on demand now (see orders.ts), so this is a note, not a blocker.
|
|
231
|
+
try {
|
|
232
|
+
await clob.updateBalanceAllowance({ asset_type: AssetType.COLLATERAL });
|
|
233
|
+
}
|
|
234
|
+
catch (refreshErr) {
|
|
235
|
+
balanceCacheWarned = refreshErr instanceof Error ? refreshErr.message.split("\n")[0] : String(refreshErr);
|
|
236
|
+
}
|
|
215
237
|
}
|
|
216
238
|
catch (err) {
|
|
217
239
|
credsNote = ` (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
|
|
@@ -245,6 +267,9 @@ async function runSetupDepositWallet(opts) {
|
|
|
245
267
|
]
|
|
246
268
|
: []),
|
|
247
269
|
`${credsReady ? "✅" : "❌"} CLOB API credentials${credsNote}`,
|
|
270
|
+
...(balanceCacheWarned
|
|
271
|
+
? [` ⚠️ Balance cache not pre-warmed (${balanceCacheWarned}) — your first buy refreshes it automatically.`]
|
|
272
|
+
: []),
|
|
248
273
|
geo,
|
|
249
274
|
``,
|
|
250
275
|
ready ? `🎯 Ready to trade. Discover markets with blockrun_markets, then action:"buy".` : `Re-run action:"setup" after completing the ❌ items.`,
|
package/package.json
CHANGED