@blockrun/franklin 3.12.3 → 3.13.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.
@@ -213,6 +213,12 @@ You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun
213
213
  - Use the **\`JupiterQuote\` and \`JupiterSwap\` built-in tools** — they call Jupiter's Ultra API directly from this process. The user is the first-party caller of Jupiter; we are not a gateway proxy here. A 20 bps platform fee is collected on-chain as part of the swap (Jupiter Referral Program — official integrator mechanism, not a hidden cost).
214
214
  - Do NOT try to call \`/v1/jupiter/...\` on the BlockRun gateway — there is no such endpoint (Jupiter ToU forbids the gateway-proxy model).
215
215
 
216
+ **Base DEX swap (0x V2 Permit2)**
217
+ - Use the **\`Base0xQuote\` and \`Base0xSwap\` built-in tools** for swaps on Base (chain id 8453). Mirrors Jupiter's local-call posture: 0x's API is hit directly, the user signs the Permit2 EIP-712 with their Base keypair, the tx settles on Base RPC. 0x's official affiliate program embeds 20 bps in the sell-token automatically (BlockRun affiliate, on-chain).
218
+ - Symbol shortcuts pre-mapped: ETH (native), WETH, USDC, USDT, CBBTC, CBETH, AERO, DAI. Raw \`0x...\` addresses pass through.
219
+ - **Each Franklin user supplies their OWN \`ZERO_EX_API_KEY\`** (free, no credit card, 10 req/s — sign up at https://dashboard.0x.org). The affiliate cut routes to BlockRun via the swap query params regardless of whose API key is making the call. If the swap tool errors with the env-var message, repeat the URL to the user — do not try to set the env yourself or invent a key.
220
+ - For native ETH → token: no Permit2 approval needed (native value path). For ERC-20 → token: first-time-per-token Permit2 approval auto-runs before the swap (one-time gas cost; future swaps of the same sell-token reuse it).
221
+
216
222
  **Sandbox (POST, x402-paid)**
217
223
  - \`/v1/modal/{...path}\` — Modal GPU sandbox passthrough (create/exec/etc.).
218
224
  - \`/v1/pm/{...path}\` — prediction-market data passthrough.
@@ -9,6 +9,10 @@ export interface AppConfig {
9
9
  'auto-compact'?: string;
10
10
  'session-save'?: string;
11
11
  'debug'?: string;
12
+ /** 0x V2 Swap API key for Base swaps. Free at https://dashboard.0x.org. Each user supplies their own; the on-chain affiliate fee routes to BlockRun regardless. */
13
+ 'zerox-api-key'?: string;
14
+ /** Optional Base RPC URL override (Alchemy, QuickNode public, etc.). Defaults to https://mainnet.base.org. */
15
+ 'base-rpc-url'?: string;
12
16
  }
13
17
  export declare function loadConfig(): AppConfig;
14
18
  export declare function configCommand(action: string, keyOrUndefined?: string, value?: string): void;
@@ -15,6 +15,8 @@ const VALID_KEYS = [
15
15
  'auto-compact',
16
16
  'session-save',
17
17
  'debug',
18
+ 'zerox-api-key',
19
+ 'base-rpc-url',
18
20
  ];
19
21
  export function loadConfig() {
20
22
  try {
@@ -26,6 +26,7 @@ import { moaCapability } from './moa.js';
26
26
  import { webhookPostCapability } from './webhook.js';
27
27
  import { walletCapability } from './wallet.js';
28
28
  import { jupiterQuoteCapability, jupiterSwapCapability } from './jupiter.js';
29
+ import { base0xQuoteCapability, base0xSwapCapability } from './zerox-base.js';
29
30
  import { defiLlamaProtocolsCapability, defiLlamaProtocolCapability, defiLlamaChainsCapability, defiLlamaYieldsCapability, defiLlamaPriceCapability, } from './defillama.js';
30
31
  import { createTradingCapabilities } from './trading-execute.js';
31
32
  import { Portfolio } from '../trading/portfolio.js';
@@ -148,6 +149,8 @@ export const allCapabilities = [
148
149
  walletCapability,
149
150
  jupiterQuoteCapability,
150
151
  jupiterSwapCapability,
152
+ base0xQuoteCapability,
153
+ base0xSwapCapability,
151
154
  defiLlamaProtocolsCapability,
152
155
  defiLlamaProtocolCapability,
153
156
  defiLlamaChainsCapability,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 0x Swap API V2 (Permit2) — Franklin built-in tools for Base trading.
3
+ *
4
+ * Same posture as the JupiterSwap tools, different chain + aggregator:
5
+ * - Calls 0x's API directly from this Franklin process (the user is the
6
+ * first-party caller; we are not a gateway proxy → no ToS violation).
7
+ * - Embeds BlockRun's affiliate identity in every quote (`swapFeeRecipient`
8
+ * + `swapFeeBps` + `swapFeeToken`). Fee flows on-chain to BlockRun at
9
+ * swap settlement — 0x's officially-supported integrator monetization.
10
+ * - User signs locally with their existing Base/EVM keypair (via @blockrun/
11
+ * llm's `getOrCreateWallet`); we never custody.
12
+ *
13
+ * Two tools exposed:
14
+ * - Base0xQuote — indicative price, free, no signing
15
+ * - Base0xSwap — full quote → sign Permit2 → submit raw tx → BaseScan link
16
+ *
17
+ * Reference (official 0x example):
18
+ * https://github.com/0xProject/0x-examples/tree/main/swap-v2-permit2-headless-example
19
+ *
20
+ * Required env:
21
+ * ZERO_EX_API_KEY — get one free at https://dashboard.0x.org
22
+ * BASE_RPC_URL — optional override; defaults to public Base RPC
23
+ */
24
+ import type { CapabilityHandler } from '../agent/types.js';
25
+ export declare const base0xQuoteCapability: CapabilityHandler;
26
+ export declare const base0xSwapCapability: CapabilityHandler;
@@ -0,0 +1,481 @@
1
+ /**
2
+ * 0x Swap API V2 (Permit2) — Franklin built-in tools for Base trading.
3
+ *
4
+ * Same posture as the JupiterSwap tools, different chain + aggregator:
5
+ * - Calls 0x's API directly from this Franklin process (the user is the
6
+ * first-party caller; we are not a gateway proxy → no ToS violation).
7
+ * - Embeds BlockRun's affiliate identity in every quote (`swapFeeRecipient`
8
+ * + `swapFeeBps` + `swapFeeToken`). Fee flows on-chain to BlockRun at
9
+ * swap settlement — 0x's officially-supported integrator monetization.
10
+ * - User signs locally with their existing Base/EVM keypair (via @blockrun/
11
+ * llm's `getOrCreateWallet`); we never custody.
12
+ *
13
+ * Two tools exposed:
14
+ * - Base0xQuote — indicative price, free, no signing
15
+ * - Base0xSwap — full quote → sign Permit2 → submit raw tx → BaseScan link
16
+ *
17
+ * Reference (official 0x example):
18
+ * https://github.com/0xProject/0x-examples/tree/main/swap-v2-permit2-headless-example
19
+ *
20
+ * Required env:
21
+ * ZERO_EX_API_KEY — get one free at https://dashboard.0x.org
22
+ * BASE_RPC_URL — optional override; defaults to public Base RPC
23
+ */
24
+ import { createWalletClient, http, publicActions, concat, numberToHex, size, parseUnits, formatUnits, maxUint256, erc20Abi, getContract, } from 'viem';
25
+ import { privateKeyToAccount } from 'viem/accounts';
26
+ import { base } from 'viem/chains';
27
+ import { getOrCreateWallet } from '@blockrun/llm';
28
+ import { loadConfig } from '../commands/config.js';
29
+ // ─── BlockRun affiliate identity on Base ─────────────────────────────────
30
+ // Reuses the existing BlockRun ops wallet that already receives x402
31
+ // settlements on Base. Every swap routed through these tools deposits 20
32
+ // bps of the sell-token amount into this address at settlement.
33
+ const BLOCKRUN_BASE_AFFILIATE = '0xe9030014F5DAe217d0A152f02A043567b16c1aBf';
34
+ const BLOCKRUN_AFFILIATE_FEE_BPS = 20; // 0.2% — matches Jupiter Ultra path.
35
+ // ─── 0x API endpoints ─────────────────────────────────────────────────────
36
+ const ZEROX_BASE = 'https://api.0x.org/swap/permit2';
37
+ const ZEROX_VERSION = 'v2';
38
+ const ZEROX_TIMEOUT_MS = 20_000;
39
+ // ─── Default Base RPC ────────────────────────────────────────────────────
40
+ // Public Base mainnet endpoint. Override via BASE_RPC_URL env or
41
+ // `franklin config set base-rpc-url <url>` (Alchemy, QuickNode public, etc.).
42
+ // The user-facing call is the swap submission; quote fetches are off-chain.
43
+ const DEFAULT_BASE_RPC = 'https://mainnet.base.org';
44
+ function resolveBaseRpcUrl() {
45
+ return (process.env.BASE_RPC_URL ||
46
+ loadConfig()['base-rpc-url'] ||
47
+ DEFAULT_BASE_RPC);
48
+ }
49
+ function resolveZeroxApiKey() {
50
+ return process.env.ZERO_EX_API_KEY || loadConfig()['zerox-api-key'];
51
+ }
52
+ // ─── Session safety: cumulative live-swap counter ─────────────────────────
53
+ const DEFAULT_LIVE_SWAP_CAP = 10;
54
+ const liveSwapCap = (() => {
55
+ const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
56
+ if (!raw)
57
+ return DEFAULT_LIVE_SWAP_CAP;
58
+ const n = Number(raw);
59
+ if (!Number.isFinite(n))
60
+ return DEFAULT_LIVE_SWAP_CAP;
61
+ if (n <= 0)
62
+ return Infinity;
63
+ return Math.floor(n);
64
+ })();
65
+ let liveSwapCount = 0;
66
+ const DEFAULT_LARGE_SWAP_USD = 20;
67
+ const largeSwapThresholdUsd = (() => {
68
+ const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
69
+ if (!raw)
70
+ return DEFAULT_LARGE_SWAP_USD;
71
+ const n = Number(raw);
72
+ if (!Number.isFinite(n) || n < 0)
73
+ return DEFAULT_LARGE_SWAP_USD;
74
+ return n;
75
+ })();
76
+ // ─── Base token map ──────────────────────────────────────────────────────
77
+ // EVM addresses are case-sensitive in some libraries — store as checksum.
78
+ const NATIVE_ETH = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
79
+ const SYMBOL_TO_ADDRESS = {
80
+ ETH: NATIVE_ETH,
81
+ WETH: '0x4200000000000000000000000000000000000006',
82
+ USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
83
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
84
+ CBBTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',
85
+ CBETH: '0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22',
86
+ AERO: '0x940181a94A35A4569E4529A3CDfB74e38FD98631',
87
+ DAI: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb',
88
+ };
89
+ const TOKEN_DECIMALS = {
90
+ [NATIVE_ETH.toLowerCase()]: 18,
91
+ '0x4200000000000000000000000000000000000006': 18, // WETH
92
+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': 6, // USDC
93
+ '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2': 6, // USDT
94
+ '0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf': 8, // CBBTC
95
+ '0x2ae3f1ec7f1f5012cfeab0185bfc7aa3cf0dec22': 18, // CBETH
96
+ '0x940181a94a35a4569e4529a3cdfb74e38fd98631': 18, // AERO
97
+ '0x50c5725949a6f0c72e6c4a641f24049a917db0cb': 18, // DAI
98
+ };
99
+ const STABLECOIN_ADDRESSES = new Set([
100
+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // USDC
101
+ '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT
102
+ '0x50c5725949a6f0c72e6c4a641f24049a917db0cb', // DAI
103
+ ]);
104
+ function resolveTokenAddress(input) {
105
+ const upper = input.trim().toUpperCase();
106
+ if (SYMBOL_TO_ADDRESS[upper])
107
+ return SYMBOL_TO_ADDRESS[upper];
108
+ return input.trim();
109
+ }
110
+ function decimalsFor(address) {
111
+ const lower = address.toLowerCase();
112
+ return TOKEN_DECIMALS[lower] ?? 18;
113
+ }
114
+ function symbolFor(address) {
115
+ const lower = address.toLowerCase();
116
+ for (const [sym, addr] of Object.entries(SYMBOL_TO_ADDRESS)) {
117
+ if (addr.toLowerCase() === lower)
118
+ return sym;
119
+ }
120
+ return `${address.slice(0, 6)}…${address.slice(-4)}`;
121
+ }
122
+ function isStablecoin(address) {
123
+ return STABLECOIN_ADDRESSES.has(address.toLowerCase());
124
+ }
125
+ function estimateUsdValue(sellTokenAddr, humanAmount) {
126
+ if (isStablecoin(sellTokenAddr))
127
+ return humanAmount;
128
+ return null; // unknown — caller surfaces a "couldn't price" notice
129
+ }
130
+ function isNativeEth(addr) {
131
+ return addr.toLowerCase() === NATIVE_ETH.toLowerCase();
132
+ }
133
+ // ─── Wallet + client setup ───────────────────────────────────────────────
134
+ async function loadEvmWallet() {
135
+ const raw = await getOrCreateWallet();
136
+ // @blockrun/llm returns { privateKey: '0x...', address: '0x...' } — use it
137
+ // verbatim for viem.
138
+ const account = privateKeyToAccount(raw.privateKey);
139
+ return { account, address: raw.address };
140
+ }
141
+ function makeClient(account) {
142
+ return createWalletClient({
143
+ account,
144
+ chain: base,
145
+ transport: http(resolveBaseRpcUrl()),
146
+ }).extend(publicActions);
147
+ }
148
+ function zeroxHeaders() {
149
+ const apiKey = resolveZeroxApiKey();
150
+ if (!apiKey) {
151
+ throw new Error("Base swaps need a 0x API key. Each Franklin user sets their own (free, no credit card, 10 req/s): " +
152
+ "1) Sign up at https://dashboard.0x.org · " +
153
+ "2) Copy the API key from the Demo App or your own app · " +
154
+ "3a) Persist it: `franklin setup zerox` (interactive) or `franklin config set zerox-api-key zx_...`, OR " +
155
+ "3b) Per-session: `ZERO_EX_API_KEY=zx_... franklin`. " +
156
+ "BlockRun does NOT need a 0x account — the affiliate fee routes to BlockRun's wallet regardless of whose key is making the call.");
157
+ }
158
+ return {
159
+ 'Content-Type': 'application/json',
160
+ '0x-api-key': apiKey,
161
+ '0x-version': ZEROX_VERSION,
162
+ };
163
+ }
164
+ // ─── 0x API calls ────────────────────────────────────────────────────────
165
+ async function zeroxFetch(path, params) {
166
+ const url = `${ZEROX_BASE}/${path}?${params.toString()}`;
167
+ const controller = new AbortController();
168
+ const timer = setTimeout(() => controller.abort(), ZEROX_TIMEOUT_MS);
169
+ try {
170
+ const res = await fetch(url, { headers: zeroxHeaders(), signal: controller.signal });
171
+ if (!res.ok) {
172
+ const text = await res.text();
173
+ throw new Error(`0x ${path} returned ${res.status}: ${text.slice(0, 300)}`);
174
+ }
175
+ return (await res.json());
176
+ }
177
+ finally {
178
+ clearTimeout(timer);
179
+ }
180
+ }
181
+ function buildSwapParams(args) {
182
+ const p = new URLSearchParams({
183
+ chainId: String(base.id),
184
+ sellToken: args.sellTokenAddr,
185
+ buyToken: args.buyTokenAddr,
186
+ sellAmount: args.sellAmountAtomic,
187
+ taker: args.taker,
188
+ });
189
+ if (args.feeRecipient && args.feeBps && args.feeBps > 0 && args.feeToken) {
190
+ p.set('swapFeeRecipient', args.feeRecipient);
191
+ p.set('swapFeeBps', String(args.feeBps));
192
+ p.set('swapFeeToken', args.feeToken);
193
+ }
194
+ return p;
195
+ }
196
+ // ─── Formatting ──────────────────────────────────────────────────────────
197
+ function formatQuoteText(q) {
198
+ const sellDec = decimalsFor(q.sellToken);
199
+ const buyDec = decimalsFor(q.buyToken);
200
+ const sellHuman = Number(formatUnits(BigInt(q.sellAmount), sellDec));
201
+ const buyHuman = Number(formatUnits(BigInt(q.buyAmount), buyDec));
202
+ const sellSym = symbolFor(q.sellToken);
203
+ const buySym = symbolFor(q.buyToken);
204
+ const rate = sellHuman > 0 ? buyHuman / sellHuman : 0;
205
+ const route = q.route?.fills?.map((f) => f.source).filter(Boolean).slice(0, 4).join(' → ') ||
206
+ '0x V2 router';
207
+ const minOut = q.minBuyAmount
208
+ ? Number(formatUnits(BigInt(q.minBuyAmount), buyDec))
209
+ : null;
210
+ const lines = [
211
+ `${sellHuman.toFixed(Math.min(8, sellDec))} ${sellSym} → ${buyHuman.toFixed(Math.min(8, buyDec))} ${buySym}`,
212
+ `Rate: 1 ${sellSym} ≈ ${rate.toPrecision(6)} ${buySym}`,
213
+ ];
214
+ if (minOut != null) {
215
+ lines.push(`Min received: ${minOut.toFixed(Math.min(8, buyDec))} ${buySym}`);
216
+ }
217
+ lines.push(`Route: ${route}`);
218
+ lines.push(`Affiliate fee: ${BLOCKRUN_AFFILIATE_FEE_BPS} bps (BlockRun affiliate, taken in ${sellSym})`);
219
+ return lines.join('\n');
220
+ }
221
+ // ─── Quote (read-only) ───────────────────────────────────────────────────
222
+ async function executeBase0xQuote(input) {
223
+ let walletAddress;
224
+ try {
225
+ const wallet = await loadEvmWallet();
226
+ walletAddress = wallet.address;
227
+ }
228
+ catch (err) {
229
+ return {
230
+ output: `Couldn't load Base wallet: ${err instanceof Error ? err.message : String(err)}`,
231
+ isError: true,
232
+ };
233
+ }
234
+ const sellTokenAddr = resolveTokenAddress(input.sell_token);
235
+ const buyTokenAddr = resolveTokenAddress(input.buy_token);
236
+ const sellDec = decimalsFor(sellTokenAddr);
237
+ const sellAmount = parseUnits(input.sell_amount.toString(), sellDec).toString();
238
+ const params = buildSwapParams({
239
+ sellTokenAddr,
240
+ buyTokenAddr,
241
+ sellAmountAtomic: sellAmount,
242
+ taker: walletAddress,
243
+ feeRecipient: BLOCKRUN_BASE_AFFILIATE,
244
+ feeBps: BLOCKRUN_AFFILIATE_FEE_BPS,
245
+ // Take the fee in the sell token so it's deterministic and doesn't
246
+ // depend on the output token having an existing recipient ATA / balance.
247
+ feeToken: sellTokenAddr,
248
+ });
249
+ try {
250
+ const price = await zeroxFetch('price', params);
251
+ if (!price.liquidityAvailable && price.liquidityAvailable !== undefined) {
252
+ return {
253
+ output: `0x reports no liquidity for ${symbolFor(sellTokenAddr)} → ${symbolFor(buyTokenAddr)} on Base.`,
254
+ isError: true,
255
+ };
256
+ }
257
+ return { output: formatQuoteText(price) };
258
+ }
259
+ catch (err) {
260
+ return { output: `0x /price failed: ${err instanceof Error ? err.message : String(err)}`, isError: true };
261
+ }
262
+ }
263
+ // ─── Swap (full execute) ─────────────────────────────────────────────────
264
+ async function executeBase0xSwap(input, ctx) {
265
+ if (liveSwapCount >= liveSwapCap) {
266
+ return {
267
+ output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
268
+ `Override with FRANKLIN_LIVE_SWAP_CAP=20 (or 0 to disable), or restart Franklin to reset.`,
269
+ isError: true,
270
+ };
271
+ }
272
+ let wallet;
273
+ try {
274
+ wallet = await loadEvmWallet();
275
+ }
276
+ catch (err) {
277
+ return {
278
+ output: `Couldn't load Base wallet. Run \`franklin setup\` to (re)generate a Base wallet, ` +
279
+ `or check ~/.blockrun/.session.\n\nUnderlying error: ${err instanceof Error ? err.message : String(err)}`,
280
+ isError: true,
281
+ };
282
+ }
283
+ const client = makeClient(wallet.account);
284
+ const sellTokenAddr = resolveTokenAddress(input.sell_token);
285
+ const buyTokenAddr = resolveTokenAddress(input.buy_token);
286
+ const sellDec = decimalsFor(sellTokenAddr);
287
+ const sellAmount = parseUnits(input.sell_amount.toString(), sellDec).toString();
288
+ const params = buildSwapParams({
289
+ sellTokenAddr,
290
+ buyTokenAddr,
291
+ sellAmountAtomic: sellAmount,
292
+ taker: wallet.address,
293
+ feeRecipient: BLOCKRUN_BASE_AFFILIATE,
294
+ feeBps: BLOCKRUN_AFFILIATE_FEE_BPS,
295
+ feeToken: sellTokenAddr,
296
+ });
297
+ // Step 1 — fetch the firm quote (returns tx + permit2.eip712 to sign).
298
+ let quote;
299
+ try {
300
+ quote = await zeroxFetch('quote', params);
301
+ }
302
+ catch (err) {
303
+ return {
304
+ output: `0x /quote failed: ${err instanceof Error ? err.message : String(err)}`,
305
+ isError: true,
306
+ };
307
+ }
308
+ if (!quote.transaction) {
309
+ return {
310
+ output: `0x returned no transaction — likely no liquidity for this pair.`,
311
+ isError: true,
312
+ };
313
+ }
314
+ // Step 2 — confirm with user (unless explicit auto_approve override).
315
+ if (!input.auto_approve && ctx.onAskUser) {
316
+ const quoteText = formatQuoteText(quote);
317
+ const usdEst = estimateUsdValue(sellTokenAddr, input.sell_amount);
318
+ const sections = ['Execute this 0x swap on Base?', '', quoteText];
319
+ if (usdEst != null && usdEst >= largeSwapThresholdUsd) {
320
+ sections.push('', `⚠ Large swap warning — input is ~$${usdEst.toFixed(2)} (above $${largeSwapThresholdUsd} threshold).`);
321
+ }
322
+ else if (usdEst == null) {
323
+ sections.push('', `Note: input is not a stablecoin, so I cannot price-check this in USD before signing. Verify the output amount matches your intent.`);
324
+ }
325
+ sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
326
+ const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
327
+ if (answer.toLowerCase() !== 'confirm') {
328
+ return { output: 'Swap cancelled by user.' };
329
+ }
330
+ }
331
+ // Step 3 — for ERC-20 sell tokens, ensure Permit2 has an allowance.
332
+ // Native ETH skips this entirely.
333
+ if (!isNativeEth(sellTokenAddr)) {
334
+ const allowanceIssue = quote.issues?.allowance ?? null;
335
+ if (allowanceIssue) {
336
+ try {
337
+ const erc20 = getContract({ address: sellTokenAddr, abi: erc20Abi, client });
338
+ const { request } = await erc20.simulate.approve([allowanceIssue.spender, maxUint256]);
339
+ const approveHash = await erc20.write.approve(request.args);
340
+ await client.waitForTransactionReceipt({ hash: approveHash });
341
+ }
342
+ catch (err) {
343
+ return {
344
+ output: `Permit2 approval failed for ${symbolFor(sellTokenAddr)}: ${err instanceof Error ? err.message : String(err)}\n` +
345
+ `This is a one-time setup step per token; retry the swap and it should succeed.`,
346
+ isError: true,
347
+ };
348
+ }
349
+ }
350
+ // Step 4 — sign the Permit2 EIP-712 typed-data and append signature to
351
+ // transaction.data per the canonical 0x recipe.
352
+ if (!quote.permit2?.eip712) {
353
+ return {
354
+ output: '0x quote did not include permit2.eip712 — non-Permit2 path required, not yet supported.',
355
+ isError: true,
356
+ };
357
+ }
358
+ let signature;
359
+ try {
360
+ signature = await client.signTypedData(quote.permit2.eip712);
361
+ }
362
+ catch (err) {
363
+ return {
364
+ output: `Permit2 signing failed: ${err instanceof Error ? err.message : String(err)}`,
365
+ isError: true,
366
+ };
367
+ }
368
+ const sigLengthHex = numberToHex(size(signature), { signed: false, size: 32 });
369
+ quote.transaction.data = concat([quote.transaction.data, sigLengthHex, signature]);
370
+ }
371
+ // Step 5 — submit. Native ETH path uses sendTransaction (with value);
372
+ // ERC-20 path uses signTransaction + sendRawTransaction (matches the
373
+ // official 0x example to avoid double-signing pitfalls).
374
+ let txHash;
375
+ try {
376
+ if (isNativeEth(sellTokenAddr)) {
377
+ txHash = await client.sendTransaction({
378
+ account: wallet.account,
379
+ chain: base,
380
+ to: quote.transaction.to,
381
+ data: quote.transaction.data,
382
+ value: BigInt(quote.transaction.value),
383
+ gas: quote.transaction.gas ? BigInt(quote.transaction.gas) : undefined,
384
+ gasPrice: quote.transaction.gasPrice ? BigInt(quote.transaction.gasPrice) : undefined,
385
+ });
386
+ }
387
+ else {
388
+ const nonce = await client.getTransactionCount({ address: wallet.address });
389
+ const signedTx = await client.signTransaction({
390
+ account: wallet.account,
391
+ chain: base,
392
+ to: quote.transaction.to,
393
+ data: quote.transaction.data,
394
+ gas: quote.transaction.gas ? BigInt(quote.transaction.gas) : undefined,
395
+ gasPrice: quote.transaction.gasPrice ? BigInt(quote.transaction.gasPrice) : undefined,
396
+ nonce,
397
+ });
398
+ txHash = await client.sendRawTransaction({ serializedTransaction: signedTx });
399
+ }
400
+ }
401
+ catch (err) {
402
+ const msg = err instanceof Error ? err.message : String(err);
403
+ const lower = msg.toLowerCase();
404
+ if (lower.includes('insufficient') ||
405
+ lower.includes('exceeds balance') ||
406
+ lower.includes('not enough')) {
407
+ return {
408
+ output: `Swap failed: insufficient balance. Your Base wallet (${wallet.address}) does not hold enough ${symbolFor(sellTokenAddr)}.\n\n` +
409
+ `Send ${symbolFor(sellTokenAddr)} to that address (or fund it via Coinbase / a bridge), then retry.\n\n` +
410
+ `Underlying error: ${msg}`,
411
+ isError: true,
412
+ };
413
+ }
414
+ return {
415
+ output: `Submit failed: ${msg}`,
416
+ isError: true,
417
+ };
418
+ }
419
+ liveSwapCount += 1;
420
+ const explorer = `https://basescan.org/tx/${txHash}`;
421
+ return {
422
+ output: [
423
+ '✓ Swap executed on Base.',
424
+ formatQuoteText(quote),
425
+ `Tx hash: ${txHash}`,
426
+ explorer,
427
+ `(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
428
+ ].join('\n'),
429
+ };
430
+ }
431
+ // ─── Capability handlers ─────────────────────────────────────────────────
432
+ const COMMON_INPUT_PROPERTIES = {
433
+ sell_token: {
434
+ type: 'string',
435
+ description: "Sell-token address (Base EVM 0x... 42 chars), OR a symbol shortcut: ETH, WETH, USDC, USDT, CBBTC, CBETH, AERO, DAI.",
436
+ },
437
+ buy_token: {
438
+ type: 'string',
439
+ description: 'Buy-token address or symbol shortcut (same list as sell_token).',
440
+ },
441
+ sell_amount: {
442
+ type: 'number',
443
+ description: 'Amount of sell_token to swap, in human units (e.g. 0.01 ETH, 1.5 USDC). Decimals are looked up automatically for known tokens; defaults to 18 for unknown ERC-20s.',
444
+ },
445
+ };
446
+ export const base0xQuoteCapability = {
447
+ spec: {
448
+ name: 'Base0xQuote',
449
+ description: "Read-only price quote for a Base DEX swap via 0x V2. Returns sell/buy amounts, rate, minimum-received, route, and the BlockRun affiliate fee that would apply. Free — no on-chain transaction. Use before Base0xSwap to inspect the trade.",
450
+ input_schema: {
451
+ type: 'object',
452
+ required: ['sell_token', 'buy_token', 'sell_amount'],
453
+ properties: COMMON_INPUT_PROPERTIES,
454
+ },
455
+ },
456
+ execute: async (input) => {
457
+ return executeBase0xQuote(input);
458
+ },
459
+ concurrent: true,
460
+ };
461
+ export const base0xSwapCapability = {
462
+ spec: {
463
+ name: 'Base0xSwap',
464
+ description: "Execute a Base DEX swap via 0x V2 (Permit2). Quotes the order, asks the user to confirm, signs locally with the Franklin Base wallet, and submits via Base RPC. A 20 bps affiliate fee in the sell-token is collected on-chain by 0x as part of the swap (BlockRun affiliate program — official 0x integrator mechanism). Returns the BaseScan transaction link. Requires ZERO_EX_API_KEY env var (free at dashboard.0x.org).",
465
+ input_schema: {
466
+ type: 'object',
467
+ required: ['sell_token', 'buy_token', 'sell_amount'],
468
+ properties: {
469
+ ...COMMON_INPUT_PROPERTIES,
470
+ auto_approve: {
471
+ type: 'boolean',
472
+ description: 'If true, skip the AskUser confirm. Default false — agent should leave this false unless the user explicitly authorized this specific call.',
473
+ },
474
+ },
475
+ },
476
+ },
477
+ execute: async (input, ctx) => {
478
+ return executeBase0xSwap(input, ctx);
479
+ },
480
+ concurrent: false,
481
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 0x Gasless API V2 — Franklin built-in tool for Base swaps WITHOUT user gas.
3
+ *
4
+ * UX win over Base0xSwap (Permit2): the user signs only EIP-712 typed-data
5
+ * (no on-chain approval, no on-chain swap submission). 0x's relayer
6
+ * broadcasts the trade and pays gas; the user pays nothing in ETH and only
7
+ * needs to hold the input token (USDC, DAI, or other Permit-supporting
8
+ * ERC-20).
9
+ *
10
+ * For tokens that don't support Permit (USDT etc.) we error out and tell
11
+ * the user to either use Base0xSwap (which can do a one-time approve+swap
12
+ * with ETH gas) or swap from a Permit-supporting token instead.
13
+ *
14
+ * Routes through BlockRun gateway (/v1/zerox/gasless/{price,quote,submit,status})
15
+ * — server holds the 0x API key, no user setup needed. On-chain affiliate
16
+ * (20 bps) is force-set at quote time on the gateway side.
17
+ *
18
+ * Reference: https://github.com/0xProject/0x-examples/tree/main/gasless-v2-headless-example
19
+ */
20
+ import type { CapabilityHandler } from '../agent/types.js';
21
+ export declare const base0xGaslessSwapCapability: CapabilityHandler;
@@ -0,0 +1,460 @@
1
+ /**
2
+ * 0x Gasless API V2 — Franklin built-in tool for Base swaps WITHOUT user gas.
3
+ *
4
+ * UX win over Base0xSwap (Permit2): the user signs only EIP-712 typed-data
5
+ * (no on-chain approval, no on-chain swap submission). 0x's relayer
6
+ * broadcasts the trade and pays gas; the user pays nothing in ETH and only
7
+ * needs to hold the input token (USDC, DAI, or other Permit-supporting
8
+ * ERC-20).
9
+ *
10
+ * For tokens that don't support Permit (USDT etc.) we error out and tell
11
+ * the user to either use Base0xSwap (which can do a one-time approve+swap
12
+ * with ETH gas) or swap from a Permit-supporting token instead.
13
+ *
14
+ * Routes through BlockRun gateway (/v1/zerox/gasless/{price,quote,submit,status})
15
+ * — server holds the 0x API key, no user setup needed. On-chain affiliate
16
+ * (20 bps) is force-set at quote time on the gateway side.
17
+ *
18
+ * Reference: https://github.com/0xProject/0x-examples/tree/main/gasless-v2-headless-example
19
+ */
20
+ import { parseUnits, formatUnits, } from 'viem';
21
+ import { privateKeyToAccount } from 'viem/accounts';
22
+ import { base } from 'viem/chains';
23
+ import { createWalletClient, http, publicActions } from 'viem';
24
+ import { getOrCreateWallet } from '@blockrun/llm';
25
+ import { loadConfig } from '../commands/config.js';
26
+ import { loadChain, API_URLS, VERSION } from '../config.js';
27
+ // ─── Constants ────────────────────────────────────────────────────────────
28
+ const ZEROX_GATEWAY_PATH = '/v1/zerox/gasless';
29
+ const QUOTE_TIMEOUT_MS = 30_000;
30
+ const SUBMIT_TIMEOUT_MS = 30_000;
31
+ const STATUS_TIMEOUT_MS = 10_000;
32
+ const MAX_STATUS_POLL_MS = 60_000; // hard ceiling on confirmation wait
33
+ const STATUS_POLL_INTERVAL_MS = 3_000;
34
+ // 0x SignatureType.EIP712 = 2 (per @0x/utils/signature.ts)
35
+ const SIGNATURE_TYPE_EIP712 = 2;
36
+ // Session safety guards — same pattern as zerox-base.ts
37
+ const DEFAULT_LIVE_SWAP_CAP = 10;
38
+ const liveSwapCap = (() => {
39
+ const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
40
+ if (!raw)
41
+ return DEFAULT_LIVE_SWAP_CAP;
42
+ const n = Number(raw);
43
+ if (!Number.isFinite(n))
44
+ return DEFAULT_LIVE_SWAP_CAP;
45
+ if (n <= 0)
46
+ return Infinity;
47
+ return Math.floor(n);
48
+ })();
49
+ let liveSwapCount = 0;
50
+ const DEFAULT_LARGE_SWAP_USD = 20;
51
+ const largeSwapThresholdUsd = (() => {
52
+ const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
53
+ if (!raw)
54
+ return DEFAULT_LARGE_SWAP_USD;
55
+ const n = Number(raw);
56
+ if (!Number.isFinite(n) || n < 0)
57
+ return DEFAULT_LARGE_SWAP_USD;
58
+ return n;
59
+ })();
60
+ // ─── Base token map (mirror zerox-base.ts) ────────────────────────────────
61
+ const SYMBOL_TO_ADDRESS = {
62
+ WETH: '0x4200000000000000000000000000000000000006',
63
+ USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
64
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
65
+ CBBTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',
66
+ CBETH: '0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22',
67
+ AERO: '0x940181a94A35A4569E4529A3CDfB74e38FD98631',
68
+ DAI: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb',
69
+ };
70
+ const TOKEN_DECIMALS = {
71
+ '0x4200000000000000000000000000000000000006': 18,
72
+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': 6,
73
+ '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2': 6,
74
+ '0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf': 8,
75
+ '0x2ae3f1ec7f1f5012cfeab0185bfc7aa3cf0dec22': 18,
76
+ '0x940181a94a35a4569e4529a3cdfb74e38fd98631': 18,
77
+ '0x50c5725949a6f0c72e6c4a641f24049a917db0cb': 18,
78
+ };
79
+ const STABLECOIN_ADDRESSES = new Set([
80
+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
81
+ '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2',
82
+ '0x50c5725949a6f0c72e6c4a641f24049a917db0cb',
83
+ ]);
84
+ function resolveTokenAddress(input) {
85
+ const upper = input.trim().toUpperCase();
86
+ if (SYMBOL_TO_ADDRESS[upper])
87
+ return SYMBOL_TO_ADDRESS[upper];
88
+ return input.trim();
89
+ }
90
+ function decimalsFor(address) {
91
+ return TOKEN_DECIMALS[address.toLowerCase()] ?? 18;
92
+ }
93
+ function symbolFor(address) {
94
+ const lower = address.toLowerCase();
95
+ for (const [sym, addr] of Object.entries(SYMBOL_TO_ADDRESS)) {
96
+ if (addr.toLowerCase() === lower)
97
+ return sym;
98
+ }
99
+ return `${address.slice(0, 6)}…${address.slice(-4)}`;
100
+ }
101
+ function isStablecoin(address) {
102
+ return STABLECOIN_ADDRESSES.has(address.toLowerCase());
103
+ }
104
+ function estimateUsdValue(addr, humanAmount) {
105
+ if (isStablecoin(addr))
106
+ return humanAmount;
107
+ return null;
108
+ }
109
+ // ─── Signature helpers ────────────────────────────────────────────────────
110
+ // Split a 65-byte 0x-prefixed signature into the {r, s, v, signatureType}
111
+ // shape that 0x's /gasless/submit expects.
112
+ function splitEip712Signature(sig) {
113
+ if (!sig.startsWith('0x'))
114
+ throw new Error('signature must be 0x-prefixed');
115
+ const noPrefix = sig.slice(2);
116
+ if (noPrefix.length !== 130) {
117
+ throw new Error(`expected 65-byte signature, got ${noPrefix.length / 2} bytes`);
118
+ }
119
+ return {
120
+ r: `0x${noPrefix.slice(0, 64)}`,
121
+ s: `0x${noPrefix.slice(64, 128)}`,
122
+ v: parseInt(noPrefix.slice(128, 130), 16),
123
+ signatureType: SIGNATURE_TYPE_EIP712,
124
+ };
125
+ }
126
+ // ─── Wallet + RPC ─────────────────────────────────────────────────────────
127
+ const DEFAULT_BASE_RPC = 'https://mainnet.base.org';
128
+ function resolveBaseRpcUrl() {
129
+ return (process.env.BASE_RPC_URL ||
130
+ loadConfig()['base-rpc-url'] ||
131
+ DEFAULT_BASE_RPC);
132
+ }
133
+ async function loadEvmWallet() {
134
+ const raw = await getOrCreateWallet();
135
+ const account = privateKeyToAccount(raw.privateKey);
136
+ return { account, address: raw.address };
137
+ }
138
+ function makeClient(account) {
139
+ return createWalletClient({
140
+ account,
141
+ chain: base,
142
+ transport: http(resolveBaseRpcUrl()),
143
+ }).extend(publicActions);
144
+ }
145
+ async function gatewayGet(pathSuffix, query, timeoutMs, ctx) {
146
+ const apiUrl = API_URLS[loadChain()];
147
+ const url = `${apiUrl}${ZEROX_GATEWAY_PATH}/${pathSuffix}?${query.toString()}`;
148
+ const controller = new AbortController();
149
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
150
+ const onAbort = () => controller.abort();
151
+ ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
152
+ try {
153
+ const res = await fetch(url, {
154
+ method: 'GET',
155
+ headers: { Accept: 'application/json', 'User-Agent': `franklin/${VERSION}` },
156
+ signal: controller.signal,
157
+ });
158
+ if (!res.ok) {
159
+ const text = await res.text().catch(() => '');
160
+ throw new Error(`gateway ${pathSuffix} returned ${res.status}: ${text.slice(0, 300)}`);
161
+ }
162
+ return (await res.json());
163
+ }
164
+ finally {
165
+ clearTimeout(timer);
166
+ ctx.abortSignal.removeEventListener('abort', onAbort);
167
+ }
168
+ }
169
+ async function gatewayPost(pathSuffix, body, timeoutMs, ctx) {
170
+ const apiUrl = API_URLS[loadChain()];
171
+ const url = `${apiUrl}${ZEROX_GATEWAY_PATH}/${pathSuffix}`;
172
+ const controller = new AbortController();
173
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
174
+ const onAbort = () => controller.abort();
175
+ ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
176
+ try {
177
+ const res = await fetch(url, {
178
+ method: 'POST',
179
+ headers: {
180
+ Accept: 'application/json',
181
+ 'Content-Type': 'application/json',
182
+ 'User-Agent': `franklin/${VERSION}`,
183
+ },
184
+ body: JSON.stringify(body),
185
+ signal: controller.signal,
186
+ });
187
+ if (!res.ok) {
188
+ const text = await res.text().catch(() => '');
189
+ throw new Error(`gateway ${pathSuffix} returned ${res.status}: ${text.slice(0, 300)}`);
190
+ }
191
+ return (await res.json());
192
+ }
193
+ finally {
194
+ clearTimeout(timer);
195
+ ctx.abortSignal.removeEventListener('abort', onAbort);
196
+ }
197
+ }
198
+ // ─── Formatting ──────────────────────────────────────────────────────────
199
+ function formatGaslessQuoteText(q) {
200
+ const sellDec = decimalsFor(q.sellToken);
201
+ const buyDec = decimalsFor(q.buyToken);
202
+ const sellHuman = Number(formatUnits(BigInt(q.sellAmount), sellDec));
203
+ const buyHuman = Number(formatUnits(BigInt(q.buyAmount), buyDec));
204
+ const sellSym = symbolFor(q.sellToken);
205
+ const buySym = symbolFor(q.buyToken);
206
+ const rate = sellHuman > 0 ? buyHuman / sellHuman : 0;
207
+ const route = q.route?.fills?.map((f) => f.source).filter(Boolean).slice(0, 4).join(' → ') ||
208
+ '0x V2 router';
209
+ const minOut = q.minBuyAmount
210
+ ? Number(formatUnits(BigInt(q.minBuyAmount), buyDec))
211
+ : null;
212
+ const lines = [
213
+ `${sellHuman.toFixed(Math.min(8, sellDec))} ${sellSym} → ${buyHuman.toFixed(Math.min(8, buyDec))} ${buySym}`,
214
+ `Rate: 1 ${sellSym} ≈ ${rate.toPrecision(6)} ${buySym}`,
215
+ ];
216
+ if (minOut != null) {
217
+ lines.push(`Min received: ${minOut.toFixed(Math.min(8, buyDec))} ${buySym}`);
218
+ }
219
+ lines.push(`Route: ${route}`);
220
+ lines.push(`Gas: paid by 0x relayer (you pay nothing in ETH)`);
221
+ lines.push(`Affiliate fee: 20 bps in ${sellSym} (BlockRun affiliate)`);
222
+ return lines.join('\n');
223
+ }
224
+ // ─── Status polling ──────────────────────────────────────────────────────
225
+ async function pollUntilDone(tradeHash, ctx) {
226
+ const deadline = Date.now() + MAX_STATUS_POLL_MS;
227
+ let last = { status: 'pending' };
228
+ while (Date.now() < deadline) {
229
+ if (ctx.abortSignal.aborted) {
230
+ throw new Error('aborted while polling status');
231
+ }
232
+ const params = new URLSearchParams({ chainId: String(base.id) });
233
+ try {
234
+ last = await gatewayGet(`status/${tradeHash}`, params, STATUS_TIMEOUT_MS, ctx);
235
+ }
236
+ catch (err) {
237
+ // Surface a transient failure but keep polling — relayer might be backlogged.
238
+ console.error(`[franklin] gasless status poll error: ${err.message}`);
239
+ }
240
+ if (last.status === 'confirmed' ||
241
+ last.status === 'succeeded' ||
242
+ last.status === 'failed') {
243
+ return last;
244
+ }
245
+ await new Promise((resolve) => setTimeout(resolve, STATUS_POLL_INTERVAL_MS));
246
+ }
247
+ return last;
248
+ }
249
+ async function executeBase0xGaslessSwap(input, ctx) {
250
+ if (liveSwapCount >= liveSwapCap) {
251
+ return {
252
+ output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
253
+ `Override with FRANKLIN_LIVE_SWAP_CAP=20 (or 0 to disable), or restart Franklin to reset.`,
254
+ isError: true,
255
+ };
256
+ }
257
+ let wallet;
258
+ try {
259
+ wallet = await loadEvmWallet();
260
+ }
261
+ catch (err) {
262
+ return {
263
+ output: `Couldn't load Base wallet: ${err instanceof Error ? err.message : String(err)}`,
264
+ isError: true,
265
+ };
266
+ }
267
+ const sellTokenAddr = resolveTokenAddress(input.sell_token);
268
+ const buyTokenAddr = resolveTokenAddress(input.buy_token);
269
+ const sellDec = decimalsFor(sellTokenAddr);
270
+ const sellAmount = parseUnits(input.sell_amount.toString(), sellDec).toString();
271
+ // Step 1 — fetch the gasless firm quote.
272
+ const quoteParams = new URLSearchParams({
273
+ chainId: String(base.id),
274
+ sellToken: sellTokenAddr,
275
+ buyToken: buyTokenAddr,
276
+ sellAmount,
277
+ taker: wallet.address,
278
+ });
279
+ let quote;
280
+ try {
281
+ quote = await gatewayGet('quote', quoteParams, QUOTE_TIMEOUT_MS, ctx);
282
+ }
283
+ catch (err) {
284
+ return {
285
+ output: `Gasless /quote failed: ${err instanceof Error ? err.message : String(err)}`,
286
+ isError: true,
287
+ };
288
+ }
289
+ if (!quote.trade?.eip712) {
290
+ return {
291
+ output: `0x didn't return a tradable gasless quote — likely the pair has insufficient liquidity for gasless. ` +
292
+ `Try Base0xSwap (Permit2) instead, or a different output token.`,
293
+ isError: true,
294
+ };
295
+ }
296
+ // Determine if approval is needed and whether gasless approval is available.
297
+ const approvalRequired = quote.issues?.allowance != null;
298
+ const gaslessApprovalAvailable = quote.approval != null;
299
+ if (approvalRequired && !gaslessApprovalAvailable) {
300
+ return {
301
+ output: `${symbolFor(sellTokenAddr)} doesn't support gasless approval (Permit) on Base — first-time use needs a one-time on-chain approve, which requires ETH.\n\n` +
302
+ `Two ways forward:\n` +
303
+ `1. Use Base0xSwap instead — it can do approve+swap with ETH gas.\n` +
304
+ `2. Swap from a Permit-supporting token (USDC, DAI) to ${symbolFor(buyTokenAddr)} instead.`,
305
+ isError: true,
306
+ };
307
+ }
308
+ // Step 2 — confirm with user.
309
+ if (!input.auto_approve && ctx.onAskUser) {
310
+ const quoteText = formatGaslessQuoteText(quote);
311
+ const usdEst = estimateUsdValue(sellTokenAddr, input.sell_amount);
312
+ const sections = [
313
+ 'Execute this gasless 0x swap on Base (no ETH needed)?',
314
+ '',
315
+ quoteText,
316
+ ];
317
+ if (usdEst != null && usdEst >= largeSwapThresholdUsd) {
318
+ sections.push('', `⚠ Large swap warning — input is ~$${usdEst.toFixed(2)} (above $${largeSwapThresholdUsd} threshold).`);
319
+ }
320
+ else if (usdEst == null) {
321
+ sections.push('', `Note: input is not a stablecoin, so I cannot price-check this in USD before signing. Verify the output amount matches your intent.`);
322
+ }
323
+ sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
324
+ const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
325
+ if (answer.toLowerCase() !== 'confirm') {
326
+ return { output: 'Swap cancelled by user.' };
327
+ }
328
+ }
329
+ const client = makeClient(wallet.account);
330
+ // Step 3 — sign trade typed-data.
331
+ let tradeSigHex;
332
+ try {
333
+ tradeSigHex = (await client.signTypedData({
334
+ account: wallet.account,
335
+ types: quote.trade.eip712.types,
336
+ domain: quote.trade.eip712.domain,
337
+ message: quote.trade.eip712.message,
338
+ primaryType: quote.trade.eip712.primaryType,
339
+ }));
340
+ }
341
+ catch (err) {
342
+ return {
343
+ output: `Trade signature failed: ${err instanceof Error ? err.message : String(err)}`,
344
+ isError: true,
345
+ };
346
+ }
347
+ const tradeSplitSig = splitEip712Signature(tradeSigHex);
348
+ const tradeSubmitObject = {
349
+ type: quote.trade.type,
350
+ eip712: quote.trade.eip712,
351
+ signature: tradeSplitSig,
352
+ };
353
+ // Step 4 — sign approval typed-data if required and available.
354
+ let approvalSubmitObject;
355
+ if (approvalRequired && gaslessApprovalAvailable && quote.approval) {
356
+ try {
357
+ const approvalSigHex = (await client.signTypedData({
358
+ account: wallet.account,
359
+ types: quote.approval.eip712.types,
360
+ domain: quote.approval.eip712.domain,
361
+ message: quote.approval.eip712.message,
362
+ primaryType: quote.approval.eip712.primaryType,
363
+ }));
364
+ const approvalSplitSig = splitEip712Signature(approvalSigHex);
365
+ approvalSubmitObject = {
366
+ type: quote.approval.type,
367
+ eip712: quote.approval.eip712,
368
+ signature: approvalSplitSig,
369
+ };
370
+ }
371
+ catch (err) {
372
+ return {
373
+ output: `Approval signature failed: ${err instanceof Error ? err.message : String(err)}`,
374
+ isError: true,
375
+ };
376
+ }
377
+ }
378
+ // Step 5 — submit to 0x relayer via gateway.
379
+ const submitBody = {
380
+ trade: tradeSubmitObject,
381
+ chainId: base.id,
382
+ };
383
+ if (approvalSubmitObject)
384
+ submitBody.approval = approvalSubmitObject;
385
+ let submitRes;
386
+ try {
387
+ submitRes = await gatewayPost('submit', submitBody, SUBMIT_TIMEOUT_MS, ctx);
388
+ }
389
+ catch (err) {
390
+ return {
391
+ output: `Gasless /submit failed: ${err instanceof Error ? err.message : String(err)}`,
392
+ isError: true,
393
+ };
394
+ }
395
+ if (!submitRes.tradeHash) {
396
+ return {
397
+ output: `0x relayer didn't return a tradeHash — submission may have been rejected.`,
398
+ isError: true,
399
+ };
400
+ }
401
+ // Step 6 — poll status until confirmed / failed / timeout.
402
+ const final = await pollUntilDone(submitRes.tradeHash, ctx);
403
+ liveSwapCount += 1;
404
+ const onChainHash = final.transactions?.[0]?.hash;
405
+ const explorer = onChainHash ? `https://basescan.org/tx/${onChainHash}` : null;
406
+ const statusLine = final.status === 'confirmed' || final.status === 'succeeded'
407
+ ? '✓ Swap confirmed.'
408
+ : final.status === 'failed'
409
+ ? `✗ Swap failed: ${final.reason ?? 'unknown reason'}`
410
+ : `⏳ Still pending after ${MAX_STATUS_POLL_MS / 1000}s — relayer is backlogged. Check status later via /v1/zerox/gasless/status/${submitRes.tradeHash}.`;
411
+ const lines = [
412
+ statusLine,
413
+ formatGaslessQuoteText(quote),
414
+ `Trade hash: ${submitRes.tradeHash}`,
415
+ ];
416
+ if (onChainHash)
417
+ lines.push(`On-chain tx: ${onChainHash}`);
418
+ if (explorer)
419
+ lines.push(explorer);
420
+ lines.push(`(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`);
421
+ return {
422
+ output: lines.join('\n'),
423
+ isError: final.status === 'failed',
424
+ };
425
+ }
426
+ // ─── Capability handler ──────────────────────────────────────────────────
427
+ export const base0xGaslessSwapCapability = {
428
+ spec: {
429
+ name: 'Base0xGaslessSwap',
430
+ description: "Execute a Base DEX swap via 0x Gasless V2. The user signs only EIP-712 typed-data (offline, no on-chain action) — 0x's relayer broadcasts the trade and pays gas. **The user does NOT need any ETH for gas.** Only input token (USDC, DAI, etc. — Permit-supporting ERC-20) is required. Returns the BaseScan link once the relayer confirms. " +
431
+ "Routes through BlockRun gateway /v1/zerox/gasless/* — no 0x signup needed. Affiliate 20 bps in sell-token to BlockRun treasury (server-side enforced). " +
432
+ "Use this instead of Base0xSwap when the user has 0 ETH but holds USDC/DAI. For tokens that don't support Permit (USDT etc.), the tool errors with a clear instruction to use Base0xSwap instead.",
433
+ input_schema: {
434
+ type: 'object',
435
+ required: ['sell_token', 'buy_token', 'sell_amount'],
436
+ properties: {
437
+ sell_token: {
438
+ type: 'string',
439
+ description: 'Sell-token address or symbol. ONLY Permit-supporting tokens work for fully-gasless flow on Base: USDC, DAI. ETH is native — use Base0xSwap for ETH input. USDT does NOT support Permit on Base.',
440
+ },
441
+ buy_token: {
442
+ type: 'string',
443
+ description: 'Buy-token address or symbol (any token).',
444
+ },
445
+ sell_amount: {
446
+ type: 'number',
447
+ description: 'Amount of sell_token in human units (e.g. 0.1 USDC).',
448
+ },
449
+ auto_approve: {
450
+ type: 'boolean',
451
+ description: 'If true, skip the AskUser confirm. Default false. Only use when the user just authorized this specific call.',
452
+ },
453
+ },
454
+ },
455
+ },
456
+ execute: async (input, ctx) => {
457
+ return executeBase0xGaslessSwap(input, ctx);
458
+ },
459
+ concurrent: false,
460
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.12.3",
3
+ "version": "3.13.1",
4
4
  "description": "Franklin — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {