@blockrun/franklin 3.37.0 → 3.38.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.
@@ -52,10 +52,10 @@ export interface GeoblockStatus {
52
52
  * routes through POLYMARKET_CLOB_HOST, i.e. the exact egress real orders use.
53
53
  *
54
54
  * We deliberately do NOT trust polymarket.com/api/geoblock's boolean: it
55
- * reflects FRONTEND blocking (it returns blocked=true for Japan even though the
56
- * Japanese API accepts orders — verified: POST /order from a Tokyo egress
57
- * returns 401, not 403). The /api/geoblock call is kept only for country/ip
58
- * context. Cached 10 min; fail-open (unknown) on network error so a hiccup never
59
- * blocks a call that might succeed.
55
+ * reflects FRONTEND blocking, which can diverge from what the order API accepts
56
+ * (e.g. Japan returns blocked=true on the frontend while its API still accepts
57
+ * orders — POST /order there returns 401, not 403). The /api/geoblock call is
58
+ * kept only for country/ip context. Cached 10 min; fail-open (unknown) on
59
+ * network error so a hiccup never blocks a call that might succeed.
60
60
  */
61
61
  export declare function checkGeoblock(): Promise<GeoblockStatus>;
@@ -22,7 +22,7 @@ import { privateKeyToAccount } from "viem/accounts";
22
22
  import { polygon } from "viem/chains";
23
23
  import { ClobClient, SignatureTypeV2 } from "@polymarket/clob-client-v2";
24
24
  import { getOrCreateWalletKey } from "./wallet-key.js";
25
- import { assertContractConfig, CLOB_HOST, GEOBLOCK_URL, getBuilderCode, getClobProxy, getSigType, POLYGON_CHAIN_ID, POLYGON_RPC_URLS, } from "./constants.js";
25
+ import { assertContractConfig, CLOB_HOST, GEOBLOCK_URL, getBuilderCode, getClobProxy, getSigType, POLYGON_CHAIN_ID, POLYGON_WRITE_RPC_URL, } from "./constants.js";
26
26
  import { loadDepositWalletForSigner, loadL2Creds, saveL2Creds } from "./creds.js";
27
27
  import { deriveApiCreds } from "./l1-auth-1271.js";
28
28
  let _account = null;
@@ -37,7 +37,7 @@ let _bridgeApplied = false;
37
37
  // that silently strips POLY_ADDRESS et al. and every authed call fails with
38
38
  // "missing address header" / "Invalid L1 Request headers". Fix: also send each
39
39
  // as a hyphenated copy (POLY_ADDRESS → poly-address) which survives proxies; the
40
- // relay maps them back to underscores (see deploy/tokyo-egress/Caddyfile).
40
+ // relay maps them back to underscores (see deploy/finland-egress/Caddyfile).
41
41
  // Sending both is harmless direct — Polymarket reads the underscore header and
42
42
  // ignores the extra hyphenated one.
43
43
  const UNDERSCORE_AUTH_HEADERS = [
@@ -131,7 +131,7 @@ function buildWalletClient(reportAddress) {
131
131
  return createWalletClient({
132
132
  account,
133
133
  chain: polygon,
134
- transport: http(POLYGON_RPC_URLS[0]),
134
+ transport: http(POLYGON_WRITE_RPC_URL),
135
135
  });
136
136
  }
137
137
  /**
@@ -146,7 +146,8 @@ export async function getClobClient() {
146
146
  const depositWallet = loadDepositWalletForSigner(account.address);
147
147
  if (sigType === 3 && !depositWallet) {
148
148
  throw new Error(`No Polymarket deposit wallet configured for this signer yet. Run blockrun_polymarket ` +
149
- `action:"setup" first (or set POLYMARKET_SIG_TYPE=0 for plain EOA mode).`);
149
+ `action:"setup" first. (POLYMARKET_SIG_TYPE=0 plain EOA mode exists as a diagnostic ` +
150
+ `fallback; the CLOB may reject plain-EOA makers.)`);
150
151
  }
151
152
  // L2 API credentials are ALWAYS bound to the owner EOA (POLY_ADDRESS = EOA),
152
153
  // even in POLY_1271 mode. This mirrors the reference Rust client (rs-clob-
@@ -156,7 +157,10 @@ export async function getClobClient() {
156
157
  // bind creds to the deposit wallet via an ERC-7739-wrapped L1 ClobAuth is what
157
158
  // the CLOB rejects with "Invalid L1 Request headers" — issue #65 misdiagnosed
158
159
  // the fix as wrapping L1 auth; the real path keeps L1 auth as the EOA.
159
- const cacheKey = `${sigType}:${account.address.toLowerCase()}`;
160
+ // The deposit wallet is part of the key: funderAddress is baked into the
161
+ // cached client, so a wallet change within the process lifetime (re-setup,
162
+ // state file rewritten) must not keep building orders against the old funder.
163
+ const cacheKey = `${sigType}:${account.address.toLowerCase()}:${(depositWallet ?? "").toLowerCase()}`;
160
164
  if (_clobClient && _clobClientKey === cacheKey)
161
165
  return _clobClient;
162
166
  let creds = loadL2Creds(account.address, 0);
@@ -196,11 +200,11 @@ let _geoCache = null;
196
200
  * routes through POLYMARKET_CLOB_HOST, i.e. the exact egress real orders use.
197
201
  *
198
202
  * We deliberately do NOT trust polymarket.com/api/geoblock's boolean: it
199
- * reflects FRONTEND blocking (it returns blocked=true for Japan even though the
200
- * Japanese API accepts orders — verified: POST /order from a Tokyo egress
201
- * returns 401, not 403). The /api/geoblock call is kept only for country/ip
202
- * context. Cached 10 min; fail-open (unknown) on network error so a hiccup never
203
- * blocks a call that might succeed.
203
+ * reflects FRONTEND blocking, which can diverge from what the order API accepts
204
+ * (e.g. Japan returns blocked=true on the frontend while its API still accepts
205
+ * orders — POST /order there returns 401, not 403). The /api/geoblock call is
206
+ * kept only for country/ip context. Cached 10 min; fail-open (unknown) on
207
+ * network error so a hiccup never blocks a call that might succeed.
204
208
  */
205
209
  export async function checkGeoblock() {
206
210
  applyClobProxyOnce();
@@ -209,7 +213,18 @@ export async function checkGeoblock() {
209
213
  let orderPlacement = "unknown";
210
214
  try {
211
215
  const res = await axios.post(`${CLOB_HOST}/order`, {}, { timeout: 6_000, validateStatus: () => true });
212
- orderPlacement = res.status === 403 ? "blocked" : "permitted";
216
+ // Treating "anything that is not 403" as permitted meant a 502/404/429 from
217
+ // a misconfigured POLYMARKET_CLOB_HOST rendered as "✅ Region: order
218
+ // placement permitted" + "🎯 Ready to trade", cached for 10 minutes — so the
219
+ // user funded the wallet and only discovered the truth on the first buy.
220
+ // An empty body reaching a WORKING CLOB is rejected as a bad request, so
221
+ // those codes are the positive signal; everything else is genuinely unknown.
222
+ if (res.status === 403)
223
+ orderPlacement = "blocked";
224
+ else if (res.status === 400 || res.status === 401 || res.status === 422)
225
+ orderPlacement = "permitted";
226
+ else
227
+ orderPlacement = "unknown";
213
228
  }
214
229
  catch { /* network error → unknown */ }
215
230
  // Country/ip context — route it through the SAME egress as orders so the
@@ -4,7 +4,10 @@ export declare const NEG_RISK_CTF_EXCHANGE_V2 = "0xe2222d279d744050d28e005200105
4
4
  export declare const NEG_RISK_ADAPTER = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296";
5
5
  export declare const CONDITIONAL_TOKENS = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
6
6
  export declare const PUSD_COLLATERAL = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
7
+ export declare const CTF_COLLATERAL_ADAPTER = "0xAdA100Db00Ca00073811820692005400218FcE1f";
8
+ export declare const NEG_RISK_CTF_COLLATERAL_ADAPTER = "0xadA2005600Dec949baf300f4C6120000bDB6eAab";
7
9
  export declare const COLLATERAL_ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee";
10
+ export declare const USDCE_COLLATERAL = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
8
11
  export declare const DEPOSIT_WALLET_FACTORY = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07";
9
12
  /**
10
13
  * Cross-check our address copies against the SDK's canonical config. Called
@@ -21,7 +24,28 @@ export declare const BASE_CHAIN_ID = 8453;
21
24
  export declare const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
22
25
  export declare const GEOBLOCK_URL: string;
23
26
  export declare const BRIDGE_UI_URL = "https://polymarket.com";
24
- export declare const POLYGON_RPC_URLS: string[];
27
+ export declare const POLYGON_READ_RPC_URLS: string[];
28
+ /**
29
+ * WRITES. Separate on purpose.
30
+ *
31
+ * There used to be one list, and entry 0 doubled as the sole un-fallbacked
32
+ * transport for every SIGNING wallet client (withdraw, redeem, relayer, setup).
33
+ * So reordering what looked like a read-only fallback list silently changed
34
+ * which endpoint broadcasts every money transaction — a write-path change
35
+ * disguised as a comment tweak, and one nobody would review as such.
36
+ * (Splitting these was @KillerQueen-Z's idea in #66; the default below is not.)
37
+ *
38
+ * publicnode, not 1rpc: 1rpc answers once and then returns
39
+ * -32001 "usage limit" (measured 2026-07-21), which is the last thing you want
40
+ * broadcasting a withdrawal. Override per-deployment with POLYMARKET_WRITE_RPC_URL.
41
+ *
42
+ * Deliberately a single endpoint rather than a fallback list: viem's fallback()
43
+ * would re-send a signed transaction to the next provider on a timeout, and a
44
+ * transaction that was actually mined by the first provider must not be
45
+ * broadcast again. Failing loudly on one endpoint is correct here; silently
46
+ * retrying a money movement is not.
47
+ */
48
+ export declare const POLYGON_WRITE_RPC_URL: string;
25
49
  /** Hard per-order notional cap in pUSD dollars (default $25; 0/invalid blocks). */
26
50
  export declare function getMaxBetUsd(): number;
27
51
  /** Optional cumulative per-process cap; null = uncapped (unset); 0 = freeze. */
@@ -45,18 +69,6 @@ export declare function getSigType(): 0 | 3;
45
69
  export declare function getBuilderCode(): string | undefined;
46
70
  /** Egress proxy for CLOB order traffic (see README: geoblock). */
47
71
  export declare function getClobProxy(): string | undefined;
48
- /**
49
- * Relayer API credentials — required for the deposit-wallet path (Phase 1:
50
- * user-provided from polymarket.com → Settings → API Keys; Phase 2 moves these
51
- * behind the BlockRun gateway). The relayer only ever receives pre-signed
52
- * payloads; these creds authenticate use of its gas-sponsoring service and
53
- * grant no control over funds.
54
- */
55
- export interface RelayerCreds {
56
- key: string;
57
- keyAddress: string;
58
- }
59
- export declare function getRelayerCreds(): RelayerCreds | null;
60
72
  export declare const ERC20_ABI: readonly [{
61
73
  readonly name: "allowance";
62
74
  readonly type: "function";
@@ -176,17 +188,4 @@ export declare const ERC1155_ABI: readonly [{
176
188
  }];
177
189
  readonly outputs: readonly [];
178
190
  }];
179
- export declare const NEG_RISK_ADAPTER_ABI: readonly [{
180
- readonly name: "redeemPositions";
181
- readonly type: "function";
182
- readonly stateMutability: "nonpayable";
183
- readonly inputs: readonly [{
184
- readonly name: "conditionId";
185
- readonly type: "bytes32";
186
- }, {
187
- readonly name: "amounts";
188
- readonly type: "uint256[]";
189
- }];
190
- readonly outputs: readonly [];
191
- }];
192
191
  export declare const PUSD_DECIMALS = 6;
@@ -19,7 +19,25 @@ export const NEG_RISK_ADAPTER = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296";
19
19
  export const CONDITIONAL_TOKENS = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
20
20
  // pUSD — Polymarket's 1:1 collateral wrapper (labelled CollateralToken proxy).
21
21
  export const PUSD_COLLATERAL = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
22
+ // pUSD collateral adapters — the ONLY correct redeem targets in the pUSD era.
23
+ // CTF positions (the CLOB token_ids) are still keyed to USDC.e (standard) or
24
+ // the legacy NegRiskAdapter's wrapped collateral (neg-risk); calling the CTF /
25
+ // legacy adapter with pUSD burns a positionId nobody holds, which SUCCEEDS
26
+ // redeeming 0 (CTF redeemPositions never reverts on zero balance). These
27
+ // adapters pull the caller's outcome tokens (need a one-time CTF operator
28
+ // approval), redeem through the right underlying path, wrap the USDC.e payout
29
+ // into pUSD, and return it to the caller. Verified on-chain 2026-07-13:
30
+ // Sourcify exact_match; COLLATERAL_TOKEN/CONDITIONAL_TOKENS/USDCE (and
31
+ // NEG_RISK_ADAPTER/WRAPPED_COLLATERAL) all point at the addresses above.
32
+ export const CTF_COLLATERAL_ADAPTER = "0xAdA100Db00Ca00073811820692005400218FcE1f";
33
+ export const NEG_RISK_CTF_COLLATERAL_ADAPTER = "0xadA2005600Dec949baf300f4C6120000bDB6eAab";
22
34
  export const COLLATERAL_ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee";
35
+ // USDC.e — the legacy collateral CTF position ids are keyed to. Withdrawals
36
+ // sweep any residue of it (historic direct-CTF redemptions paid out USDC.e)
37
+ // through the onramp's wrap(asset, to, amount) — signature verified against the
38
+ // Sourcify exact-match source of COLLATERAL_ONRAMP, 2026-07-21 — since the
39
+ // bridge only accepts pUSD.
40
+ export const USDCE_COLLATERAL = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
23
41
  export const DEPOSIT_WALLET_FACTORY = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07";
24
42
  /**
25
43
  * Cross-check our address copies against the SDK's canonical config. Called
@@ -46,12 +64,15 @@ export function assertContractConfig() {
46
64
  }
47
65
  // --- Hosts (env-overridable so Phase 2 can point them at the BlockRun gateway) ---
48
66
  // CLOB order placement is geoblocked by IP (US/UK/EU and many regions). We
49
- // DEFAULT to BlockRun's hosted Tokyo egress so trading works out of the box with
50
- // zero config — it only forwards to Polymarket's CLOB (it can't see or move
51
- // funds; every order is still signed locally by the user's key). Override with
52
- // POLYMARKET_CLOB_HOST to hit Polymarket directly (from a permitted region) or to
53
- // run your own egress. Direct Polymarket host: https://clob.polymarket.com
54
- export const CLOB_HOST = process.env.POLYMARKET_CLOB_HOST || "https://pm-egress-vbsbhh7lea-an.a.run.app/clob";
67
+ // DEFAULT to BlockRun's hosted Finland egress (europe-north1) so trading works
68
+ // out of the box with zero config — Finland is FULLY unrestricted under
69
+ // Polymarket's geographic policy (frontend + API), a more durable choice than
70
+ // Japan (close-only on the frontend). The relay only forwards to Polymarket's
71
+ // CLOB (it can't see or move funds; every order is still signed locally by the
72
+ // user's key). Override with POLYMARKET_CLOB_HOST to hit Polymarket directly
73
+ // (from a permitted region) or run your own egress (see deploy/finland-egress).
74
+ // Direct Polymarket host: https://clob.polymarket.com
75
+ export const CLOB_HOST = process.env.POLYMARKET_CLOB_HOST || "https://pm-egress-1092497648280.europe-north1.run.app/clob";
55
76
  export const RELAYER_URL = process.env.POLYMARKET_RELAYER_URL || "https://relayer-v2.polymarket.com";
56
77
  export const DATA_API_HOST = process.env.POLYMARKET_DATA_API_HOST || "https://data-api.polymarket.com";
57
78
  export const BRIDGE_API_HOST = process.env.POLYMARKET_BRIDGE_HOST || "https://bridge.polymarket.com";
@@ -61,19 +82,50 @@ export const BRIDGE_API_HOST = process.env.POLYMARKET_BRIDGE_HOST || "https://br
61
82
  // USDC_ADDRESS in ../constants.ts.)
62
83
  export const BASE_CHAIN_ID = 8453;
63
84
  export const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
64
- // Overridable so a demo routing orders through a Tokyo relay can report the
85
+ // Overridable so a demo routing orders through the egress relay can report the
65
86
  // SAME egress's region (a permitted ✅) instead of the local IP's status.
66
87
  export const GEOBLOCK_URL = process.env.POLYMARKET_GEOBLOCK_URL || "https://polymarket.com/api/geoblock";
67
88
  export const BRIDGE_UI_URL = "https://polymarket.com"; // deposits happen via the Polymarket bridge UI/API
68
89
  // Public Polygon RPCs with fallback, mirroring BASE_RPC_URLS in ../constants.ts.
69
- // Used only for read-only approval/balance checks (viem public client).
70
- // 1rpc first — polygon-rpc.com was observed lagging several blocks behind, which
71
- // made freshly-confirmed deploys/approvals read as still-pending.
72
- export const POLYGON_RPC_URLS = [
90
+ // Probed 2026-07-21 with a real eth_call (not just eth_blockNumber):
91
+ // polygon-bor-rpc.publicnode.com 200 OK
92
+ // polygon.drpc.org 200 OK
93
+ // 1rpc.io/matic 200 OK once, then -32001 "usage limit" — rate-limited
94
+ // polygon.llamarpc.com DNS/fetch failure
95
+ // polygon-rpc.com 401 "tenant disabled"
96
+ // rpc.ankr.com/polygon -32000 "Unauthorized: you must authenticate"
97
+ // Two of the three entries here were dead, so fallback() depth was effectively 1
98
+ // while ~9 reads x 4 retries piled onto a single rate-limited endpoint. Dead
99
+ // entries are not free: each costs retryCount x timeout before the chain moves on.
100
+ //
101
+ // READS ONLY. Used by the viem public client, which fans out across all of them
102
+ // via fallback().
103
+ export const POLYGON_READ_RPC_URLS = [
104
+ "https://polygon-bor-rpc.publicnode.com",
105
+ "https://polygon.drpc.org",
73
106
  "https://1rpc.io/matic",
74
- "https://polygon.llamarpc.com",
75
- "https://polygon-rpc.com",
76
107
  ];
108
+ /**
109
+ * WRITES. Separate on purpose.
110
+ *
111
+ * There used to be one list, and entry 0 doubled as the sole un-fallbacked
112
+ * transport for every SIGNING wallet client (withdraw, redeem, relayer, setup).
113
+ * So reordering what looked like a read-only fallback list silently changed
114
+ * which endpoint broadcasts every money transaction — a write-path change
115
+ * disguised as a comment tweak, and one nobody would review as such.
116
+ * (Splitting these was @KillerQueen-Z's idea in #66; the default below is not.)
117
+ *
118
+ * publicnode, not 1rpc: 1rpc answers once and then returns
119
+ * -32001 "usage limit" (measured 2026-07-21), which is the last thing you want
120
+ * broadcasting a withdrawal. Override per-deployment with POLYMARKET_WRITE_RPC_URL.
121
+ *
122
+ * Deliberately a single endpoint rather than a fallback list: viem's fallback()
123
+ * would re-send a signed transaction to the next provider on a timeout, and a
124
+ * transaction that was actually mined by the first provider must not be
125
+ * broadcast again. Failing loudly on one endpoint is correct here; silently
126
+ * retrying a money movement is not.
127
+ */
128
+ export const POLYGON_WRITE_RPC_URL = process.env.POLYMARKET_WRITE_RPC_URL || "https://polygon-bor-rpc.publicnode.com";
77
129
  // --- Safety knobs ---
78
130
  /**
79
131
  * Parse a money-cap env var with FAIL-CLOSED semantics for safety controls:
@@ -134,13 +186,6 @@ export function getClobProxy() {
134
186
  const v = process.env.POLYMARKET_CLOB_PROXY?.trim();
135
187
  return v ? v : undefined;
136
188
  }
137
- export function getRelayerCreds() {
138
- const key = process.env.POLYMARKET_RELAYER_API_KEY?.trim();
139
- const keyAddress = process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS?.trim();
140
- if (key && keyAddress)
141
- return { key, keyAddress };
142
- return null;
143
- }
144
189
  // ERC-20/1155 minimal ABIs for approval + balance reads and approval calldata.
145
190
  export const ERC20_ABI = [
146
191
  {
@@ -191,15 +236,4 @@ export const ERC1155_ABI = [
191
236
  outputs: [],
192
237
  },
193
238
  ];
194
- // NegRisk adapter redeem takes explicit YES/NO amounts instead of index sets.
195
- export const NEG_RISK_ADAPTER_ABI = [
196
- {
197
- name: "redeemPositions", type: "function", stateMutability: "nonpayable",
198
- inputs: [
199
- { name: "conditionId", type: "bytes32" },
200
- { name: "amounts", type: "uint256[]" },
201
- ],
202
- outputs: [],
203
- },
204
- ];
205
239
  export const PUSD_DECIMALS = 6;
@@ -15,6 +15,16 @@ export interface PolymarketState {
15
15
  signer?: string;
16
16
  deployed?: boolean;
17
17
  approvalsDone?: boolean;
18
+ /**
19
+ * A withdrawal batch whose relayer confirmation timed out. Its EIP-712
20
+ * signature stays executable until `deadline` (unix seconds), so a fresh
21
+ * withdrawal signed before then can DOUBLE-SEND — withdraw refuses to sign
22
+ * while this is set and unresolved. Cleared on confirm/failure.
23
+ */
24
+ pendingWithdraw?: {
25
+ transactionID: string;
26
+ deadline: number;
27
+ };
18
28
  }
19
29
  export declare function loadL2Creds(address: string, sigType: number): L2Creds | null;
20
30
  export declare function saveL2Creds(address: string, sigType: number, creds: Omit<L2Creds, "derivedAt">): void;
@@ -36,7 +36,13 @@ function readJsonFile(file) {
36
36
  }
37
37
  function writeJsonFile(file, value) {
38
38
  fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
39
- fs.writeFileSync(file, JSON.stringify(value, null, 2), { mode: 0o600 });
39
+ // tmp + rename: a crash mid-write must never leave a half-written creds or
40
+ // state file — reads swallow parse errors to null, so corruption would
41
+ // silently drop credentials (and the deposit-wallet mapping) instead of
42
+ // failing loudly. rename(2) on the same filesystem is atomic.
43
+ const tmp = `${file}.${process.pid}.tmp`;
44
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 });
45
+ fs.renameSync(tmp, file);
40
46
  }
41
47
  function credsKey(address, sigType) {
42
48
  return `${address.toLowerCase()}:${sigType}`;
@@ -60,13 +60,25 @@ export async function fundVault(input) {
60
60
  if (!code || code === "0x") {
61
61
  return {
62
62
  text: `Your deposit wallet ${vault} is not deployed yet — deploy it FIRST with ` +
63
- `action:"setup" confirm:true (needs relayer creds), then fund. Funding an undeployed ` +
64
- `vault strands your USDC at the bridge (it can't deliver pUSD to a vault that doesn't exist).`,
63
+ `action:"setup" confirm:true (gasless, credentials bootstrapped automatically), then fund. ` +
64
+ `Funding an undeployed vault strands your USDC at the bridge (it can't deliver pUSD to a vault that doesn't exist).`,
65
65
  isError: true,
66
66
  };
67
67
  }
68
68
  }
69
- const baseBalance = (await getChainBalance("base", agent)) ?? 0;
69
+ // getChainBalance returns null specifically to distinguish "could not read"
70
+ // from "holds nothing". Coercing that to 0 printed "holds $0.00 USDC — top up
71
+ // first" as a statement of fact to a user holding $200, on nothing more than
72
+ // an RPC blip, and sent them off to fund a wallet that was already funded.
73
+ const baseBalanceRaw = await getChainBalance("base", agent);
74
+ if (baseBalanceRaw === null) {
75
+ return {
76
+ text: `Could not read the USDC balance of your Base wallet ${agent} (RPC unavailable). ` +
77
+ `Not funding blind — re-run in a moment. Your funds are untouched.`,
78
+ isError: true,
79
+ };
80
+ }
81
+ const baseBalance = baseBalanceRaw;
70
82
  const needed = amountUsd + FUND_FEE_USD;
71
83
  if (baseBalance < needed) {
72
84
  return {
@@ -54,7 +54,13 @@ function commitBet() {
54
54
  export function roundToTick(price, tickSize, side = "buy") {
55
55
  const tick = parseFloat(tickSize);
56
56
  const decimals = Math.max(0, (tickSize.split(".")[1] ?? "").length);
57
- const steps = side === "buy" ? Math.floor(price / tick) : Math.ceil(price / tick);
57
+ // The epsilon absorbs float-division noise on prices ALREADY on the grid:
58
+ // 0.58/0.001 is 579.9999…, which floor alone turns into 0.579 (a buy signed
59
+ // one tick below the stated limit), and 0.42/0.01 is 42.000…01, which ceil
60
+ // alone turns into 0.43 (a sell one tick above). 1e-9 is far below half a
61
+ // tick for every real tick size, so genuine off-grid prices still round in
62
+ // the conservative direction (issue #72 finding 7).
63
+ const steps = side === "buy" ? Math.floor(price / tick + 1e-9) : Math.ceil(price / tick - 1e-9);
58
64
  return Number((steps * tick).toFixed(decimals));
59
65
  }
60
66
  async function resolveToken(clob, input) {
@@ -139,19 +145,20 @@ export async function mapClobError(err) {
139
145
  const where = geo.country ? ` (egress country: ${geo.country})` : "";
140
146
  return `Order rejected with 403 — Polymarket geoblocks order placement from this egress${where} ` +
141
147
  `(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}`;
148
+ `Fix: point POLYMARKET_CLOB_HOST + POLYMARKET_RELAYER_URL at a permitted-region relay ` +
149
+ `(deploy/finland-egress) or restore the default. A proxy alone (POLYMARKET_CLOB_PROXY / HTTPS_PROXY) ` +
150
+ `does not change the Polymarket-facing egress. Raw: ${message}`;
144
151
  }
145
152
  if (m.includes("maker address not allowed") || m.includes("deposit wallet flow")) {
146
153
  return `Polymarket rejected this maker address — CLOB V2 requires the deposit-wallet flow to place ` +
147
154
  `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}`;
155
+ `POLYMARKET_SIG_TYPE (=3) and run action:"setup" to create your deposit wallet ` +
156
+ `(credentials are bootstrapped automatically — no API keys needed). Raw: ${message}`;
150
157
  }
151
158
  if (isCredsMismatchError(e)) {
152
159
  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).`;
160
+ `if this persists, run action:"setup", or as a last resort set POLYMARKET_SIG_TYPE=0 for plain ` +
161
+ `EOA mode (see clob-client-v2 issue #65; note the CLOB may reject plain-EOA makers).`;
155
162
  }
156
163
  if (m.includes("not enough balance") || m.includes("insufficient") || m.includes("allowance")) {
157
164
  return `Not enough balance/allowance (${message}). The funds wallet needs pUSD and exchange approvals — ` +
@@ -81,7 +81,7 @@ export async function listPositions() {
81
81
  const msg = err instanceof Error ? err.message : String(err);
82
82
  return {
83
83
  text: `Could not fetch positions from Polymarket's Data-API (${msg}). ` +
84
- `Fallback: blockrun_markets path:"polymarket/positions" params:{user:"${user}"} ($0.001).`,
84
+ `Fallback: blockrun_markets path:"polymarket/positions" params:{user:"${user}"} ($0.0075).`,
85
85
  isError: true,
86
86
  };
87
87
  }
@@ -1,4 +1,30 @@
1
+ import { type Hex } from "viem";
1
2
  import type { ToolResult } from "./orders.js";
3
+ /**
4
+ * Redeem call for the pUSD collateral adapter (standard or neg-risk). Exported
5
+ * for unit tests — the target/calldata pair is the money-critical part of this
6
+ * file. The CTF-mirror arguments besides conditionId are ignored by the
7
+ * adapter; we pass the canonical values anyway so the calldata reads sanely on
8
+ * a block explorer.
9
+ */
10
+ export declare function buildRedeemCall(negRisk: boolean, conditionId: Hex): {
11
+ target: Hex;
12
+ data: Hex;
13
+ };
14
+ /**
15
+ * Did the redeem actually consume something we held?
16
+ *
17
+ * A transaction hash is not proof: redeeming through the wrong collateral path
18
+ * burns a positionId nobody holds, which SUCCEEDS on-chain having done nothing
19
+ * (CTF redeemPositions never reverts on a zero balance). Only a DECREASE in a
20
+ * balance that was non-zero before proves the position was consumed.
21
+ *
22
+ * Conservative on length mismatch: a missing `after` entry reads as unchanged,
23
+ * i.e. "not redeemed", so a truncated read can never fake success.
24
+ *
25
+ * Pure and exported for tests. Design from @KillerQueen-Z's #66.
26
+ */
27
+ export declare function didRedeemAnyHeldPosition(before: readonly bigint[], after: readonly bigint[]): boolean;
2
28
  export declare function redeemPosition(input: {
3
29
  condition_id?: string;
4
30
  confirm?: boolean;