@blockrun/franklin 3.49.5 → 3.49.7

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.
Files changed (39) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/approvals.d.ts +1 -1
  3. package/dist/agent/commands.js +2 -0
  4. package/dist/agent/context.js +15 -2
  5. package/dist/agent/payment-hold.d.ts +116 -0
  6. package/dist/agent/payment-hold.js +821 -0
  7. package/dist/agent/streaming-executor.js +10 -3
  8. package/dist/agent/tool-guard.d.ts +25 -1
  9. package/dist/agent/tool-guard.js +305 -1
  10. package/dist/agent/types.d.ts +7 -0
  11. package/dist/audit/approvals.d.ts +2 -2
  12. package/dist/audit/approvals.js +1 -1
  13. package/dist/hooks/runner.js +8 -2
  14. package/dist/mcp/client.js +4 -1
  15. package/dist/mcp/codegraph.js +2 -0
  16. package/dist/memory/store.js +2 -0
  17. package/dist/tasks/runner.js +2 -1
  18. package/dist/tasks/spawn.js +2 -1
  19. package/dist/tools/bash.js +11 -10
  20. package/dist/tools/grep.js +3 -0
  21. package/dist/tools/jupiter.d.ts +1 -0
  22. package/dist/tools/jupiter.js +1 -1
  23. package/dist/tools/polymarket/creds.d.ts +8 -2
  24. package/dist/tools/polymarket/creds.js +1 -0
  25. package/dist/tools/polymarket/orders.d.ts +7 -0
  26. package/dist/tools/polymarket/orders.js +36 -0
  27. package/dist/tools/polymarket/relayer.js +38 -4
  28. package/dist/tools/polymarket/withdraw.js +122 -10
  29. package/dist/tools/polymarket-bet.js +6 -6
  30. package/dist/tools/subprocess-env.d.ts +2 -0
  31. package/dist/tools/subprocess-env.js +15 -0
  32. package/dist/tools/trade-plan.js +6 -3
  33. package/dist/tools/zerox-base.d.ts +2 -0
  34. package/dist/tools/zerox-base.js +1 -1
  35. package/dist/tools/zerox-gasless.d.ts +2 -0
  36. package/dist/tools/zerox-gasless.js +1 -1
  37. package/dist/trading/trade-plan.d.ts +9 -1
  38. package/dist/trading/trade-plan.js +153 -36
  39. package/package.json +2 -2
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { BLOCKRUN_DIR } from '../config.js';
8
8
  import { WALLET_KEY_PATHS, hostCredentialDirPaths, isHostCredentialPath, isWalletKeyPath, secretPathRefusal, } from './sensitive-paths.js';
9
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
9
10
  const MAX_GREP_OUTPUT_CHARS = 16_000; // ~4,000 tokens — prevents huge grep results
10
11
  let _hasRipgrep = null;
11
12
  function hasRipgrep() {
@@ -123,6 +124,7 @@ function runRipgrep(opts, searchPath, mode, limit, cwd) {
123
124
  args.push(searchPath);
124
125
  try {
125
126
  const result = execFileSync('rg', args, {
127
+ env: sanitizeSubprocessEnv(),
126
128
  encoding: 'utf-8',
127
129
  maxBuffer: 2 * 1024 * 1024,
128
130
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -193,6 +195,7 @@ function runNativeGrep(opts, searchPath, mode, limit, cwd) {
193
195
  args.push('-e', opts.pattern, searchPath);
194
196
  try {
195
197
  const result = execFileSync('grep', args, {
198
+ env: sanitizeSubprocessEnv(),
196
199
  encoding: 'utf-8',
197
200
  maxBuffer: 2 * 1024 * 1024,
198
201
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -16,6 +16,7 @@
16
16
  * https://github.com/Jupiter-DevRel/typescript-examples/tree/main/ultra/order-execute-with-referral-accounts
17
17
  */
18
18
  import type { CapabilityHandler } from '../agent/types.js';
19
+ export declare function resolveMint(input: string): string;
19
20
  export declare function toAtomicUnits(amount: number, decimals: number): string;
20
21
  export declare const jupiterQuoteCapability: CapabilityHandler;
21
22
  export declare const jupiterSwapCapability: CapabilityHandler;
@@ -68,7 +68,7 @@ const TOKEN_DECIMALS = {
68
68
  // WIF — 6
69
69
  EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm: 6,
70
70
  };
71
- function resolveMint(input) {
71
+ export function resolveMint(input) {
72
72
  const upper = input.trim().toUpperCase();
73
73
  if (SYMBOL_TO_MINT[upper])
74
74
  return SYMBOL_TO_MINT[upper];
@@ -22,8 +22,14 @@ export interface PolymarketState {
22
22
  * while this is set and unresolved. Cleared on confirm/failure.
23
23
  */
24
24
  pendingWithdraw?: {
25
- transactionID: string;
26
- deadline: number;
25
+ transactionID?: string;
26
+ deadline?: number;
27
+ payloadHash?: string;
28
+ txHash?: string;
29
+ nonce?: string | number;
30
+ from?: string;
31
+ /** EOA path: the signed bytes, so a retry re-broadcasts them instead of signing anew. */
32
+ serializedTransaction?: string;
27
33
  };
28
34
  }
29
35
  export declare function loadL2Creds(address: string, sigType: number): L2Creds | null;
@@ -96,6 +96,7 @@ export function loadDepositWalletForSigner(signer) {
96
96
  return undefined;
97
97
  }
98
98
  export function saveState(patch) {
99
+ // franklin-local: TODO: serialize read/modify/write across processes with a lock.
99
100
  const next = { ...loadState(), ...patch };
100
101
  writeJsonFile(STATE_FILE, next);
101
102
  return next;
@@ -33,6 +33,13 @@ export interface ToolResult {
33
33
  text: string;
34
34
  structured?: Record<string, unknown>;
35
35
  isError?: boolean;
36
+ /**
37
+ * franklin-local: true only when this call provably never handed an order or
38
+ * transaction to the venue (validation, preview, or a definite rejection).
39
+ * Callers holding a spend reservation may release it ONLY on this signal;
40
+ * any other error may have been accepted upstream.
41
+ */
42
+ notSubmitted?: boolean;
36
43
  }
37
44
  export declare function executeTrade(input: TradeInput): Promise<ToolResult>;
38
45
  export declare function listOpenOrders(input: {
@@ -205,7 +205,24 @@ async function withCredsRetry(fn) {
205
205
  return fn(fresh);
206
206
  }
207
207
  }
208
+ /**
209
+ * franklin-local: a submit error is a definite rejection only when the CLOB
210
+ * answered with a 4xx. A missing status (no response: timeout, reset) or a 5xx
211
+ * means the order may have been accepted and its acknowledgement lost.
212
+ */
213
+ function isDefiniteSubmitRejection(err) {
214
+ const status = err?.status;
215
+ return typeof status === "number" && status >= 400 && status < 500 && status !== 408;
216
+ }
208
217
  export async function executeTrade(input) {
218
+ // franklin-local: report whether the order could have reached the CLOB.
219
+ const progress = { submitStarted: false, rejected: false };
220
+ const result = await executeTradeUnchecked(input, progress);
221
+ if (result.isError && (!progress.submitStarted || progress.rejected))
222
+ return { ...result, notSubmitted: true };
223
+ return result;
224
+ }
225
+ async function executeTradeUnchecked(input, progress) {
209
226
  const side = input.action === "buy" ? Side.BUY : Side.SELL;
210
227
  const isLimit = input.price !== undefined;
211
228
  // Cross-field validation (zod schema is per-field; rules live here).
@@ -340,6 +357,10 @@ export async function executeTrade(input) {
340
357
  // Reserve now (before the await) so a concurrent order sees this spend;
341
358
  // roll back if the submit throws so a failed order doesn't consume budget.
342
359
  reserveBet(notional, input.agent_id);
360
+ // withCredsRetry may re-run this body after a definite 401; each attempt
361
+ // starts unrejected so a later ambiguous failure is never mislabelled.
362
+ progress.submitStarted = true;
363
+ progress.rejected = false;
343
364
  let response;
344
365
  try {
345
366
  try {
@@ -361,7 +382,21 @@ export async function executeTrade(input) {
361
382
  }
362
383
  }
363
384
  catch (submitErr) {
385
+ // franklin-local: only a definite rejection frees the reservation. A
386
+ // lost acknowledgement may still be a live order; releasing here let
387
+ // the retry place a second one under a cap that no longer counted it.
388
+ if (!isDefiniteSubmitRejection(submitErr)) {
389
+ commitBet();
390
+ const raw = submitErr instanceof Error ? submitErr.message : String(submitErr);
391
+ return {
392
+ text: `Order outcome UNKNOWN — the submit failed without a definite rejection (${raw}), so the CLOB ` +
393
+ `may have accepted it. Do NOT place it again. Check action:"orders" and action:"positions" first; ` +
394
+ `the session cap still counts this order.\n${summary}`,
395
+ isError: true,
396
+ };
397
+ }
364
398
  releaseBet(notional, input.agent_id);
399
+ progress.rejected = true;
365
400
  throw submitErr;
366
401
  }
367
402
  const r = response;
@@ -373,6 +408,7 @@ export async function executeTrade(input) {
373
408
  const placed = r?.success !== false && (r?.orderID || r?.status === "matched");
374
409
  if (!placed) {
375
410
  releaseBet(notional, input.agent_id);
411
+ progress.rejected = true;
376
412
  throw new Error(r?.errorMsg || "order rejected");
377
413
  }
378
414
  commitBet();
@@ -19,6 +19,13 @@ import { getPolymarketAccount } from "./client.js";
19
19
  import { CLOB_HOST, POLYGON_CHAIN_ID, POLYGON_WRITE_RPC_URL, RELAYER_URL } from "./constants.js";
20
20
  import { loadBuilderCreds, loadL2Creds, saveBuilderCreds, saveL2Creds, saveState } from "./creds.js";
21
21
  import { deriveApiCreds } from "./l1-auth-1271.js";
22
+ // franklin-local: use the SDK builder to persist the signed batch before submission.
23
+ import { AxiosHeaders } from "axios";
24
+ import { keccak256, toHex } from "viem";
25
+ import { buildDepositWalletBatchRequest } from "@polymarket/builder-relayer-client/dist/builder/deposit-wallet.js";
26
+ import { isDepositWalletContractConfigValid } from "@polymarket/builder-relayer-client/dist/config/index.js";
27
+ import { ClientRelayerTransactionResponse } from "@polymarket/builder-relayer-client/dist/response/index.js";
28
+ import { SUBMIT_TRANSACTION } from "@polymarket/builder-relayer-client/dist/endpoints.js";
22
29
  let _relayClient = null;
23
30
  /**
24
31
  * Programmatically obtain Builder API credentials (key/secret/passphrase) for
@@ -112,6 +119,32 @@ export async function getRelayerTransactionState(transactionID) {
112
119
  return undefined;
113
120
  }
114
121
  }
122
+ // franklin-local: signing/auth failures leave no marker; once send starts, a lost
123
+ // response must retain the guard because the relayer may already have the batch.
124
+ async function submitTrackedWithdraw(client, calls, depositWallet, deadline) {
125
+ if (!client.signer)
126
+ throw new Error("Relayer signer unavailable");
127
+ const config = client.contractConfig.DepositWalletContracts;
128
+ if (!isDepositWalletContractConfigValid(config))
129
+ throw new Error("Deposit wallet config unavailable");
130
+ const from = await client.signer.getAddress();
131
+ const { nonce } = await client.getNonce(from, "WALLET");
132
+ const request = await buildDepositWalletBatchRequest(client.signer, {
133
+ from, chainId: client.chainId, walletAddress: depositWallet, nonce, deadline: String(deadline), calls,
134
+ }, config);
135
+ const body = JSON.stringify(request);
136
+ // Mirrors the SDK's private sendAuthedRequest: builder headers only when the
137
+ // builder config is valid, otherwise an unauthenticated submit.
138
+ const headers = client.builderConfig?.isValid()
139
+ ? await client.builderConfig.generateBuilderHeaders("POST", SUBMIT_TRANSACTION, body)
140
+ : undefined;
141
+ const pending = { deadline, from, nonce, payloadHash: keccak256(toHex(body)) };
142
+ const options = { headers: new AxiosHeaders(headers ? { ...headers } : {}), data: body };
143
+ saveState({ pendingWithdraw: pending });
144
+ const { data } = await client.httpClient.send(`${client.relayerUrl}${SUBMIT_TRANSACTION}`, "POST", options);
145
+ saveState({ pendingWithdraw: { ...pending, transactionID: data.transactionID } });
146
+ return new ClientRelayerTransactionResponse(data.transactionID, data.state, data.transactionHash, client);
147
+ }
115
148
  /**
116
149
  * Execute a signed WALLET batch from the deposit wallet (approvals, redeem…).
117
150
  * The SDK fetches the nonce, EIP-712-signs the Batch with the local key, and
@@ -131,10 +164,11 @@ export async function getRelayerTransactionState(transactionID) {
131
164
  */
132
165
  export async function sendWalletBatch(calls, depositWallet, description, opts) {
133
166
  const deadlineSec = Math.floor(Date.now() / 1000) + BATCH_DEADLINE_SECS;
134
- const response = await (await getRelayClient()).executeDepositWalletBatch(calls, depositWallet, String(deadlineSec));
135
- if (opts?.trackPendingWithdraw) {
136
- saveState({ pendingWithdraw: { transactionID: response.transactionID, deadline: deadlineSec } });
137
- }
167
+ // franklin-local: only withdrawals need the pre-submission persistence boundary.
168
+ const client = await getRelayClient();
169
+ const response = opts?.trackPendingWithdraw
170
+ ? await submitTrackedWithdraw(client, calls, depositWallet, deadlineSec)
171
+ : await client.executeDepositWalletBatch(calls, depositWallet, String(deadlineSec));
138
172
  const confirmed = await response.wait();
139
173
  if (!confirmed) {
140
174
  const state = await getRelayerTransactionState(response.transactionID);
@@ -29,6 +29,8 @@ import { getFundsAddress } from "./positions.js";
29
29
  import { loadState, saveState } from "./creds.js";
30
30
  import { getRelayerTransactionState, sendWalletBatch } from "./relayer.js";
31
31
  import { getPublicClient } from "./setup.js";
32
+ // franklin-local: identify an EOA transfer before handing it to the RPC.
33
+ import { keccak256 } from "viem";
32
34
  async function rawTokenBalance(token, owner) {
33
35
  return getPublicClient().readContract({
34
36
  address: token,
@@ -101,17 +103,67 @@ async function readPusdUntil(owner, minimum) {
101
103
  }
102
104
  return observed;
103
105
  }
106
+ // franklin-local: RPC rejections that prove a node refused (and so never
107
+ // relayed) a raw transaction. "already known" is deliberately absent: it means
108
+ // the node HAS the transaction. So is "nonce too low": nonce movement is not
109
+ // evidence about which transaction used the nonce.
110
+ const DEFINITE_REJECTION_RE = /insufficient funds|intrinsic gas too low|max fee per gas less than block base fee|transaction underpriced|invalid sender/i;
111
+ function isDefiniteBroadcastRejection(err) {
112
+ for (let e = err, depth = 0; e && depth < 5; e = e.cause, depth++) {
113
+ const msg = e instanceof Error ? `${e.message} ${e.details ?? ""}` : String(e);
114
+ if (DEFINITE_REJECTION_RE.test(msg))
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+ /** True unless the RPC positively reports the hash as unknown. Read errors count as known (fail closed). */
120
+ async function transactionKnown(hash) {
121
+ try {
122
+ await getPublicClient().getTransaction({ hash });
123
+ return true;
124
+ }
125
+ catch (err) {
126
+ return !(err instanceof Error && err.name === "TransactionNotFoundError");
127
+ }
128
+ }
129
+ /**
130
+ * franklin-local: the EOA withdrawal's on-chain outcome, or null while unknown.
131
+ * Only a receipt resolves it. An advanced account nonce plus an RPC that does
132
+ * not know our hash proves nothing — the RPC may lag, or our transaction may
133
+ * be the one that used the nonce — so it is never read as "dropped". While
134
+ * unknown, the same signed bytes are re-broadcast (same nonce, so at most one
135
+ * transfer can ever execute) — never a fresh signature.
136
+ */
137
+ async function eoaPendingStatus(pending) {
138
+ const receipt = await getPublicClient().getTransactionReceipt({ hash: pending.txHash }).catch(() => null);
139
+ if (receipt)
140
+ return receipt.status === "success" ? "success" : "reverted";
141
+ if (pending.serializedTransaction) {
142
+ const account = getPolymarketAccount();
143
+ const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
144
+ await wallet.sendRawTransaction({ serializedTransaction: pending.serializedTransaction }).catch(() => undefined);
145
+ }
146
+ return null;
147
+ }
104
148
  const WITHDRAW_GUIDANCE = 'check the pUSD balance with action:"setup" and the bridge status endpoint before ANY retry — ' +
105
149
  "a resubmitted withdrawal signs a SECOND transfer and can double-send";
106
150
  export async function withdrawFunds(input) {
107
151
  let owner;
152
+ let recipient;
108
153
  try {
154
+ // franklin-local: this is the agent's x402 signer, not the deposit wallet.
155
+ recipient = getPolymarketAccount().address;
156
+ if (input.to_address !== undefined && (typeof input.to_address !== "string" || input.to_address.toLowerCase() !== recipient.toLowerCase())) {
157
+ return {
158
+ text: "Withdraw to your agent wallet first; moving funds to an external address is not something the agent does on its own.",
159
+ isError: true,
160
+ };
161
+ }
109
162
  owner = getFundsAddress();
110
163
  }
111
164
  catch (err) {
112
165
  return { text: err instanceof Error ? err.message : String(err), isError: true };
113
166
  }
114
- const recipient = input.to_address || getPolymarketAccount().address;
115
167
  try {
116
168
  // Refuse to sign while an earlier withdrawal batch may still land: its
117
169
  // signature stays executable until its deadline, and a second signed
@@ -120,15 +172,39 @@ export async function withdrawFunds(input) {
120
172
  const pending = loadState().pendingWithdraw;
121
173
  if (pending && input.confirm === true) {
122
174
  const graceSec = 60; // relayer can mine right at the deadline; don't race it
123
- if (Math.floor(Date.now() / 1000) < pending.deadline + graceSec) {
124
- const state = await getRelayerTransactionState(pending.transactionID);
125
- if (state === "STATE_MINED" || state === "STATE_CONFIRMED" || state === "STATE_FAILED" || state === "STATE_INVALID") {
126
- saveState({ pendingWithdraw: undefined });
175
+ // franklin-local: resolving an earlier withdrawal ENDS this call. The
176
+ // retry that finds the first transfer settled is the same call that
177
+ // would otherwise sign a second one on top of it — the double-send this
178
+ // guard exists to stop. The outcome is reported; another withdrawal
179
+ // needs a fresh, deliberate call.
180
+ let resolution = null;
181
+ if (pending.txHash) {
182
+ // franklin-local: EOA transfers have no deadline; only a receipt proves resolution.
183
+ const status = await eoaPendingStatus(pending);
184
+ if (status === null) {
185
+ return {
186
+ text: `A previous withdrawal (${pending.txHash}) has no receipt and may still land — it was re-broadcast ` +
187
+ `as the same signed transaction. Do not retry; check the balance again in a few minutes.`,
188
+ isError: true,
189
+ };
190
+ }
191
+ resolution = status === "success"
192
+ ? `The previous withdrawal SETTLED on-chain (tx ${pending.txHash}).`
193
+ : `The previous withdrawal REVERTED on-chain (tx ${pending.txHash}); no pUSD moved.`;
194
+ // franklin-local: an unacknowledged batch cannot be queried, but can still execute.
195
+ }
196
+ else if (pending.deadline === undefined || Math.floor(Date.now() / 1000) < pending.deadline + graceSec) {
197
+ const state = pending.transactionID ? await getRelayerTransactionState(pending.transactionID) : undefined;
198
+ if (state === "STATE_MINED" || state === "STATE_CONFIRMED") {
199
+ resolution = `The previous withdrawal SETTLED (relayer tx ${pending.transactionID}, ${state}).`;
200
+ }
201
+ else if (state === "STATE_FAILED" || state === "STATE_INVALID") {
202
+ resolution = `The previous withdrawal FAILED (relayer tx ${pending.transactionID}, ${state}); no pUSD moved.`;
127
203
  }
128
204
  else {
129
- const waitSecs = pending.deadline + graceSec - Math.floor(Date.now() / 1000);
205
+ const waitSecs = pending.deadline === undefined ? "unknown" : pending.deadline + graceSec - Math.floor(Date.now() / 1000);
130
206
  return {
131
- text: `A previous withdrawal (relayer tx ${pending.transactionID}, state: ${state ?? "unreachable"}) ` +
207
+ text: `A previous withdrawal (relayer tx ${pending.transactionID ?? "unacknowledged"}, state: ${state ?? "unreachable"}) ` +
132
208
  `may still execute — its signed transfer stays valid for up to ~${waitSecs}s more. Signing another ` +
133
209
  `one now could double-send. Re-run after that window, when the balance reads will show what happened.`,
134
210
  isError: true,
@@ -136,8 +212,18 @@ export async function withdrawFunds(input) {
136
212
  }
137
213
  }
138
214
  else {
139
- saveState({ pendingWithdraw: undefined }); // deadline long past — expired, safe
215
+ // Deadline long past: the batch can no longer execute, but it may
216
+ // already have, so this is not proof that nothing moved.
217
+ resolution = `The previous withdrawal's signature expired (relayer tx ${pending.transactionID ?? "unacknowledged"}). ` +
218
+ `It may or may not have executed before its deadline.`;
140
219
  }
220
+ saveState({ pendingWithdraw: undefined });
221
+ return {
222
+ text: `${resolution} Nothing new was signed. Check the balances (action:"setup") and the bridge status ` +
223
+ `before deciding whether ANOTHER withdrawal is wanted; only then call withdraw again.`,
224
+ isError: true,
225
+ structured: { previousWithdrawal: resolution },
226
+ };
141
227
  }
142
228
  // Withdrawable = pUSD + legacy USDC.e (wrapped on demand below).
143
229
  const [pusdRaw, usdceRaw] = await Promise.all([
@@ -227,14 +313,40 @@ export async function withdrawFunds(input) {
227
313
  else {
228
314
  const account = getPolymarketAccount();
229
315
  const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
230
- txHash = await wallet.sendTransaction({ to: PUSD_COLLATERAL, data, chain: polygon, account });
316
+ // franklin-local: hash the locally signed bytes and persist before any broadcast.
317
+ // franklin-local: the nonce comes from the WRITE endpoint
318
+ // (prepareTransactionRequest asks the wallet's own transport), not the
319
+ // fallback public readers, which are separate providers with their own
320
+ // pending pools. A load-balanced write URL can still answer from a
321
+ // different backend than the broadcast; safety does not rest on this —
322
+ // the bytes are persisted first and a retry re-sends only those.
323
+ const request = await wallet.prepareTransactionRequest({ to: PUSD_COLLATERAL, data, chain: polygon, account });
324
+ const nonce = request.nonce;
325
+ const serializedTransaction = await wallet.signTransaction(request);
326
+ txHash = keccak256(serializedTransaction);
327
+ saveState({ pendingWithdraw: { txHash, nonce, from: account.address, serializedTransaction } });
328
+ try {
329
+ await wallet.sendRawTransaction({ serializedTransaction });
330
+ }
331
+ catch (err) {
332
+ // franklin-local: a node that rejected these bytes outright never
333
+ // relayed them, so only that case may release the guard. Anything
334
+ // ambiguous (timeout, 5xx) keeps it until a receipt says otherwise.
335
+ if (isDefiniteBroadcastRejection(err) && !(await transactionKnown(txHash))) {
336
+ saveState({ pendingWithdraw: undefined });
337
+ }
338
+ throw err;
339
+ }
231
340
  // viem does NOT throw on a reverted tx — it resolves with status:"reverted".
232
341
  // Discarding the receipt meant a REVERTED pUSD transfer still printed
233
342
  // "✅ Withdrawal submitted … the bridge delivers USDC to Base" with a link
234
343
  // to the failed tx and no isError, so the user waited for money that was
235
344
  // never sent and blamed the bridge. redeem.ts and setup.ts both assert
236
345
  // status; this path was the one that did not.
237
- assertTransactionSucceeded(await getPublicClient().waitForTransactionReceipt({ hash: txHash }), "pUSD transfer", txHash);
346
+ // franklin-local: either receipt status resolves the guard; timeouts retain it.
347
+ const receipt = await getPublicClient().waitForTransactionReceipt({ hash: txHash });
348
+ saveState({ pendingWithdraw: undefined });
349
+ assertTransactionSucceeded(receipt, "pUSD transfer", txHash);
238
350
  }
239
351
  return {
240
352
  text: [
@@ -62,7 +62,7 @@ async function execute(raw, ctx) {
62
62
  await ensurePolymarketWallet();
63
63
  }
64
64
  catch (err) {
65
- return { output: `Wallet unavailable: ${err instanceof Error ? err.message : String(err)}`, isError: true };
65
+ return { output: `Wallet unavailable: ${err instanceof Error ? err.message : String(err)}`, isError: true, notSubmitted: true };
66
66
  }
67
67
  const wantsConfirm = input.confirm === true;
68
68
  const autoApprove = input.auto_approve === true || process.env.FRANKLIN_POLYMARKET_AUTO_APPROVE === '1';
@@ -77,11 +77,11 @@ async function execute(raw, ctx) {
77
77
  if (preview.isError) {
78
78
  // The dry-run itself failed (bad params, insufficient balance, not set
79
79
  // up) — surface that instead of prompting to sign a doomed action.
80
- return { output: preview.text, isError: true, fullOutput: preview.text };
80
+ return { output: preview.text, isError: true, fullOutput: preview.text, notSubmitted: true };
81
81
  }
82
82
  }
83
83
  catch (err) {
84
- return { output: `Preview failed: ${err instanceof Error ? err.message : String(err)}`, isError: true };
84
+ return { output: `Preview failed: ${err instanceof Error ? err.message : String(err)}`, isError: true, notSubmitted: true };
85
85
  }
86
86
  const answer = await ctx.onAskUser([
87
87
  previewText,
@@ -89,7 +89,7 @@ async function execute(raw, ctx) {
89
89
  '⚠ REAL MONEY — confirming signs and submits this on-chain (Polygon). Proceed?',
90
90
  ].join('\n'), ['Confirm', 'Cancel']);
91
91
  if (answer.toLowerCase() !== 'confirm') {
92
- return { output: 'Polymarket action cancelled by user.' };
92
+ return { output: 'Polymarket action cancelled by user.', notSubmitted: true };
93
93
  }
94
94
  }
95
95
  // Execute for real (or return the dry-run when confirm was never requested).
@@ -113,7 +113,7 @@ async function execute(raw, ctx) {
113
113
  }
114
114
  }
115
115
  if (result.isError) {
116
- return { output: result.text, isError: true, fullOutput: result.text };
116
+ return { output: result.text, isError: true, fullOutput: result.text, ...(result.notSubmitted ? { notSubmitted: true } : {}) };
117
117
  }
118
118
  return { output: result.text, fullOutput: result.text };
119
119
  }
@@ -149,7 +149,7 @@ export const polymarketBetCapability = {
149
149
  post_only: { type: 'boolean', description: 'Maker-only limit order (rejected if it would cross the book).' },
150
150
  order_id: { type: 'string', description: 'Order ID to cancel.' },
151
151
  all: { type: 'boolean', description: 'cancel: cancel ALL open orders.' },
152
- to_address: { type: 'string', description: 'withdraw: destination address on Base (default: your agent wallet).' },
152
+ to_address: { type: 'string', description: 'withdraw: your agent wallet on Base only (default). Other recipients are refused; withdraw to your agent wallet first.' },
153
153
  confirm: { type: 'boolean', description: 'Must be true to place orders / sign approvals / redeem. Omit for a dry-run preview.' },
154
154
  auto_approve: { type: 'boolean', description: 'Skip the interactive user confirmation prompt (headless use). Caps still apply.' },
155
155
  agent_id: { type: 'string', description: 'Tag for the session betting ledger (bets do NOT draw from the x402 API budget).' },
@@ -0,0 +1,2 @@
1
+ export declare const SENSITIVE_ENV_NAMES: readonly ['BLOCKRUN_API_KEY', 'BLOCKRUN_WALLET_KEY', 'BASE_CHAIN_WALLET_KEY', 'SOLANA_WALLET_KEY'];
2
+ export declare function sanitizeSubprocessEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -0,0 +1,15 @@
1
+ // SDK credential env names must not reach model-driven commands or their output.
2
+ export const SENSITIVE_ENV_NAMES = [
3
+ 'BLOCKRUN_API_KEY',
4
+ 'BLOCKRUN_WALLET_KEY',
5
+ 'BASE_CHAIN_WALLET_KEY',
6
+ 'SOLANA_WALLET_KEY',
7
+ ];
8
+ export function sanitizeSubprocessEnv(env = process.env) {
9
+ const sanitized = { ...env };
10
+ for (const name of SENSITIVE_ENV_NAMES)
11
+ delete sanitized[name];
12
+ // The same OS user can still read key files under ~/.blockrun. This closes
13
+ // the environment path, not file access; in-process gateway calls keep theirs.
14
+ return sanitized;
15
+ }
@@ -33,7 +33,7 @@ export function createTradePlanCapability() {
33
33
  properties: {
34
34
  venue: { type: 'string', enum: ['jupiter', 'zerox', 'polymarket'] },
35
35
  action: { type: 'string', enum: ['buy', 'sell', 'swap', 'bet'] },
36
- asset: { type: 'string', description: 'Symbol, mint/token address, or market outcome.' },
36
+ asset: { type: 'string', description: 'Exactly what the execution call will name: the token symbol/mint/address being bought (or sold, for sells); for polymarket, the token_id, or the condition_id with direction set to the outcome. Matched against that field only.' },
37
37
  direction: { type: 'string', enum: ['long', 'short', 'yes', 'no'] },
38
38
  amountUsd: { type: 'number', description: 'USD to commit to this trade.' },
39
39
  maxSlippageBps: { type: 'number' },
@@ -117,8 +117,11 @@ export function createTradePlanCapability() {
117
117
  decideTradePlan(plan, 'approved', decision.message === 'auto' ? 'flag' : 'user');
118
118
  return {
119
119
  output: `Trade plan ${plan.id} APPROVED — $${plan.totalSpendUsd.toFixed(2)} authorized until ` +
120
- `${new Date(plan.expiresAt).toLocaleTimeString()}. Execute ONLY the planned trades; each ` +
121
- 'execution draws down the budget. Per-swap confirmation is skipped — the plan approval was the confirmation.',
120
+ `${new Date(plan.expiresAt).toLocaleTimeString()}. Approval executes NOTHING: no trade has been ` +
121
+ 'placed and no money has moved yet. Execute ONLY the planned trades, each with its own tool call; each ' +
122
+ 'execution draws down the budget, and only a successful execution result means money moved. Never ' +
123
+ 'report or record a trade or payment as done on the strength of this approval. Per-swap confirmation ' +
124
+ 'is skipped because this approval already covers it.',
122
125
  };
123
126
  }
124
127
  if (choice === 'request changes') {
@@ -21,6 +21,8 @@
21
21
  * ZERO_EX_API_KEY — get one free at https://dashboard.0x.org
22
22
  * BASE_RPC_URL — optional override; defaults to public Base RPC
23
23
  */
24
+ import { type Address } from 'viem';
24
25
  import type { CapabilityHandler } from '../agent/types.js';
26
+ export declare function resolveTokenAddress(input: string): Address;
25
27
  export declare const base0xQuoteCapability: CapabilityHandler;
26
28
  export declare const base0xSwapCapability: CapabilityHandler;
@@ -83,7 +83,7 @@ const STABLECOIN_ADDRESSES = new Set([
83
83
  '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT
84
84
  '0x50c5725949a6f0c72e6c4a641f24049a917db0cb', // DAI
85
85
  ]);
86
- function resolveTokenAddress(input) {
86
+ export function resolveTokenAddress(input) {
87
87
  const upper = input.trim().toUpperCase();
88
88
  if (SYMBOL_TO_ADDRESS[upper])
89
89
  return SYMBOL_TO_ADDRESS[upper];
@@ -17,5 +17,7 @@
17
17
  *
18
18
  * Reference: https://github.com/0xProject/0x-examples/tree/main/gasless-v2-headless-example
19
19
  */
20
+ import { type Address } from 'viem';
20
21
  import type { CapabilityHandler } from '../agent/types.js';
22
+ export declare function resolveTokenAddress(input: string): Address;
21
23
  export declare const base0xGaslessSwapCapability: CapabilityHandler;
@@ -63,7 +63,7 @@ const STABLECOIN_ADDRESSES = new Set([
63
63
  '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2',
64
64
  '0x50c5725949a6f0c72e6c4a641f24049a917db0cb',
65
65
  ]);
66
- function resolveTokenAddress(input) {
66
+ export function resolveTokenAddress(input) {
67
67
  const upper = input.trim().toUpperCase();
68
68
  if (SYMBOL_TO_ADDRESS[upper])
69
69
  return SYMBOL_TO_ADDRESS[upper];
@@ -39,6 +39,7 @@ export interface TradePlan {
39
39
  decidedBy?: string;
40
40
  changeRequest?: string;
41
41
  consumedUsd: number;
42
+ consumedLineUsd?: number[];
42
43
  }
43
44
  export declare const TRADE_PLAN_TTL_MS: number;
44
45
  export declare function tradePlansDir(): string;
@@ -61,6 +62,11 @@ export declare function formatTradePlanText(plan: TradePlan, walletBalanceUsd?:
61
62
  export declare function setTradePlanSessionId(id: string): void;
62
63
  /** The session's live (approved, unexpired, unconsumed) plan, if any. */
63
64
  export declare function activeTradePlan(sessionId?: string): TradePlan | null;
65
+ /**
66
+ * Release a reservation for a call that was denied before it executed.
67
+ * Safe to call for any invocation id; a no-op when nothing was reserved.
68
+ */
69
+ export declare function releaseTradeReservation(invocationId: string): void;
64
70
  /**
65
71
  * Trade-plan gate — called from SessionToolGuard.beforeExecute for every
66
72
  * invocation. Returns a deny result when a trade-execution call lacks plan
@@ -69,7 +75,9 @@ export declare function activeTradePlan(sessionId?: string): TradePlan | null;
69
75
  */
70
76
  export declare function checkTradePlanGate(invocation: CapabilityInvocation, sessionId?: string): CapabilityResult | null;
71
77
  /**
72
- * Draw down the plan budget after a successful gated execution. Called from
78
+ * Settle the reservation made at the gate. Called from
73
79
  * SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
80
+ * The budget stays spent unless the tool reports `notSubmitted`; an error
81
+ * without that signal may be an accepted order whose response was lost.
74
82
  */
75
83
  export declare function recordTradeExecution(invocation: CapabilityInvocation, result: CapabilityResult, sessionId?: string): void;