@blockrun/franklin 3.12.2 → 3.12.3

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.
@@ -232,6 +232,53 @@ A bare \`402\` on a POST means the endpoint is healthy and the payment flow is w
232
232
 
233
233
  **Verifying gateway health**: GET \`/v1/health/overview\` (free) is the right probe. Listing endpoints? Fetch \`/openapi.json\` and read the \`paths\` object — that is the source of truth, not your training memory.`;
234
234
  }
235
+ function getTradingPlaybookSection() {
236
+ return `# Trading playbook (built-in tools)
237
+
238
+ Franklin has built-in tools for live Solana DEX swaps (\`JupiterSwap\`, \`JupiterQuote\`) and DeFi-data lookups (\`DeFiLlamaProtocols\`, \`DeFiLlamaProtocol\`, \`DeFiLlamaChains\`, \`DeFiLlamaYields\`, \`DeFiLlamaPrice\`). When the user asks for live trades or DeFi data, route through these tools — NOT WebSearch, NOT Bash + curl, NOT WebFetch (those won't sign x402 payments and will hit 402 walls).
239
+
240
+ ## Before any live swap
241
+
242
+ 1. **Quote first if the user hasn't already seen the numbers.** Run \`JupiterQuote\` to surface input amount, output amount, rate, price impact, and route. Users make informed decisions when they see numbers, not vibes.
243
+ 2. **Reject \`priceImpactPct\` > 5 %** unless the user has explicitly asked to proceed despite impact. Memecoins on illiquid days routinely have 10–30 % impact — that is a money-losing trade. Tell them, ask them, then maybe proceed.
244
+ 3. **Large-swap warning above ~\$20 USD equivalent.** Estimate via stablecoin reference if available (USDC, USDT inputs are 1:1). If you can't reliably estimate, say so in the AskUser prompt: "I cannot easily price-check this output token in USD before the swap; please confirm only if you know what you are buying."
245
+
246
+ ## During a swap
247
+
248
+ - **Default \`auto_approve: false\`.** Only set true if the user has just authorized this specific call ("yes, swap 0.01 SOL for USDC"). NEVER set auto-approve session-wide. NEVER set it to "just do all three swaps I asked about" — each swap gets its own AskUser confirmation.
249
+ - **Be transparent about the 20 bps BlockRun referral fee.** It is shown by \`JupiterQuote\` automatically; if the user asks why, explain: it's BlockRun's integrator cut via Jupiter's official Referral Program — same mechanism Phantom and other Solana wallets use. The user is paying for the convenience layer.
250
+ - **Surface the Solscan link prominently after execution.** Trust is built on receipts. "Done" without a signature link is a red flag for the user.
251
+
252
+ ## Failure handling
253
+
254
+ - \`No Solana wallet found\` → run \`franklin setup solana\`. The harness usually auto-creates on first run; this error means the file is corrupt or unreadable.
255
+ - \`/execute\` returns \`InsufficientFundsForRent\` / \`insufficient lamports\` / \`TokenAccountNotFound\` → user's Solana wallet is empty for the input mint. Show them the wallet pubkey (it was in the AskUser prompt) and tell them to send the input token to that address.
256
+ - \`/order\` returns no transaction or 30 %+ price impact → no liquidity for the pair. Suggest a smaller amount or a different output token.
257
+ - Live-swap session cap reached → user has done many live swaps in this session. Hard-stop is intentional; suggest \`/retry\` or set \`FRANKLIN_LIVE_SWAP_CAP\` to raise.
258
+
259
+ ## Never
260
+
261
+ - Chain multiple live swaps without showing the running USD spent so far this turn.
262
+ - Tell the user "I executed your trade" without the Solscan link or signature.
263
+ - Compute USD value or P&L by guessing prices. Use \`TradingMarket\`, \`DeFiLlamaPrice\`, or \`JupiterQuote\` (with stablecoin reference) for ground truth.
264
+ - Mix paper and live state in your reply. Paper trading lives in \`TradingPortfolio\` (\`~/.blockrun/portfolio.json\`); live swaps are recorded in \`~/.blockrun/trades.jsonl\` with \`kind: 'live'\`. Be explicit about which one you're acting in.
265
+
266
+ ## DeFi data (DeFiLlama tools)
267
+
268
+ - Match the tool to the question.
269
+ - "What's pumping on Solana?" → \`DeFiLlamaProtocols(chain='Solana', top_n=10)\`
270
+ - "Top yield for USDC" → \`DeFiLlamaYields(symbol='USDC', stablecoin_only=true)\`
271
+ - "Aave's TVL" → \`DeFiLlamaProtocol(slug='aave-v3')\`
272
+ - "BTC price" → \`DeFiLlamaPrice(coins=['coingecko:bitcoin'])\` or \`TradingMarket\`
273
+ - **Filter aggressively.** Default \`top_n=10\` unless the user asked for more. Raw DefiLlama payloads are 5–10 MB and will blow your context window.
274
+ - **Never call the same DeFiLlama endpoint twice in one turn.** Each call is paid. If you find yourself doing it, your plan is wrong.
275
+
276
+ ## Paper vs. live
277
+
278
+ - Paper trading (TradingPortfolio etc.) is for plan-grade simulation: positions, risk caps, P&L tracking, no on-chain. Use it when the user wants to "test" or "simulate" a strategy.
279
+ - Live trading is JupiterSwap. It costs real USDC, signs an on-chain tx, and shows up on Solscan. NEVER conflate — if the user says "swap" they usually mean live; if they say "simulate" or "paper" they mean paper.
280
+ `;
281
+ }
235
282
  function getToolPatternsSection() {
236
283
  return `# Tool Selection Patterns
237
284
  - **Finding files**: Glob first (by name/pattern), then Grep (by content), then Read (specific file). Don't start with Read unless you know the exact path.
@@ -300,6 +347,7 @@ export function assembleInstructions(workingDir, model) {
300
347
  getMissingAccessSection(),
301
348
  getWalletKnowledgeSection(),
302
349
  getBlockRunApiSection(),
350
+ getTradingPlaybookSection(),
303
351
  getToolPatternsSection(),
304
352
  getTokenEfficiencySection(),
305
353
  getVerificationSection(),
@@ -27,6 +27,47 @@ const BLOCKRUN_REFERRAL_FEE_BPS = 20; // 0.2% — Jupiter docs default; well bel
27
27
  const ULTRA_BASE = 'https://lite-api.jup.ag/ultra/v1';
28
28
  const ORDER_TIMEOUT_MS = 15_000;
29
29
  const EXECUTE_TIMEOUT_MS = 30_000;
30
+ // ─── Session safety: cumulative live-swap counter ─────────────────────────
31
+ // We removed the per-turn $-cap in v3.11.0 because it kept firing on legit
32
+ // LLM workloads — but a live on-chain swap is irreversible, so a cap here is
33
+ // different in kind. Default 10 swaps per Franklin process; user can override
34
+ // via FRANKLIN_LIVE_SWAP_CAP env (set to 0 to disable). Resets on restart.
35
+ const DEFAULT_LIVE_SWAP_CAP = 10;
36
+ const liveSwapCap = (() => {
37
+ const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
38
+ if (!raw)
39
+ return DEFAULT_LIVE_SWAP_CAP;
40
+ const n = Number(raw);
41
+ if (!Number.isFinite(n))
42
+ return DEFAULT_LIVE_SWAP_CAP;
43
+ if (n <= 0)
44
+ return Infinity;
45
+ return Math.floor(n);
46
+ })();
47
+ let liveSwapCount = 0;
48
+ // ─── Large-swap warning threshold ────────────────────────────────────────
49
+ // USD value above which we surface a "Large swap" line in the AskUser
50
+ // confirm — only computable when input is a known stablecoin. Override via
51
+ // FRANKLIN_LIVE_SWAP_WARN_USD env (default $20).
52
+ const DEFAULT_LARGE_SWAP_USD = 20;
53
+ const largeSwapThresholdUsd = (() => {
54
+ const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
55
+ if (!raw)
56
+ return DEFAULT_LARGE_SWAP_USD;
57
+ const n = Number(raw);
58
+ if (!Number.isFinite(n) || n < 0)
59
+ return DEFAULT_LARGE_SWAP_USD;
60
+ return n;
61
+ })();
62
+ const STABLECOIN_MINTS = new Set([
63
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
64
+ 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
65
+ ]);
66
+ function estimateUsdValue(inputMint, humanAmount) {
67
+ if (STABLECOIN_MINTS.has(inputMint))
68
+ return humanAmount;
69
+ return null; // unknown — caller will surface a "couldn't price" warning instead
70
+ }
30
71
  // ─── Symbol → mint shortcuts ──────────────────────────────────────────────
31
72
  // Agents prefer "USDC" / "SOL" over 44-char base58 mint addresses. Anything
32
73
  // not in this map is passed through verbatim — power users can drop in any
@@ -180,22 +221,37 @@ async function executeJupiterQuote(input) {
180
221
  }
181
222
  }
182
223
  async function executeJupiterSwap(input, ctx) {
224
+ // Session-cap pre-check (cheapest, fail fast).
225
+ if (liveSwapCount >= liveSwapCap) {
226
+ return {
227
+ output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). ` +
228
+ `Stopping to protect your wallet — this is a deliberate guardrail, not an error in your prompt.\n\n` +
229
+ `To raise: \`FRANKLIN_LIVE_SWAP_CAP=20 franklin\` (or 0 to disable).\n` +
230
+ `To continue with a fresh count: restart Franklin (\`exit\` then re-launch).`,
231
+ isError: true,
232
+ };
233
+ }
183
234
  const inputMint = resolveMint(input.input_mint);
184
235
  const outputMint = resolveMint(input.output_mint);
185
236
  const inDec = decimalsFor(inputMint);
186
237
  const amountAtomic = toAtomicUnits(input.amount, inDec);
187
- // Load wallet first fail fast if Solana isn't set up.
238
+ // Load wallet — `getOrCreateSolanaWallet` auto-creates on first run, so this
239
+ // path firing means the file is corrupt or the .blockrun dir is unreadable.
188
240
  let keypair;
189
241
  try {
190
242
  keypair = await loadSolanaKeypair();
191
243
  }
192
244
  catch (err) {
245
+ const msg = err instanceof Error ? err.message : String(err);
193
246
  return {
194
- output: `No Solana wallet found. Run \`franklin setup solana\` to generate one, or check ~/.blockrun/solana-wallet.json.\n` +
195
- `(${err instanceof Error ? err.message : 'unknown error'})`,
247
+ output: `Couldn't load your Solana wallet. ` +
248
+ `Run \`franklin setup solana\` to (re)generate one. ` +
249
+ `If that's already worked before, check ~/.blockrun/solana-wallet.json is readable.\n\n` +
250
+ `Underlying error: ${msg}`,
196
251
  isError: true,
197
252
  };
198
253
  }
254
+ const walletAddress = keypair.publicKey.toBase58();
199
255
  // Step 1 — fetch order with our referral identity attached.
200
256
  let order;
201
257
  try {
@@ -203,7 +259,7 @@ async function executeJupiterSwap(input, ctx) {
203
259
  inputMint,
204
260
  outputMint,
205
261
  amount: amountAtomic,
206
- taker: keypair.publicKey.toBase58(),
262
+ taker: walletAddress,
207
263
  });
208
264
  }
209
265
  catch (err) {
@@ -221,8 +277,16 @@ async function executeJupiterSwap(input, ctx) {
221
277
  // Step 2 — confirm with user (unless explicit auto_approve override).
222
278
  if (!input.auto_approve && ctx.onAskUser) {
223
279
  const quoteText = formatQuote(order);
224
- const question = `Execute this Jupiter swap?\n\n${quoteText}\n\nWallet: ${keypair.publicKey.toBase58()}`;
225
- const answer = await ctx.onAskUser(question, ['Confirm', 'Cancel']);
280
+ const usdEst = estimateUsdValue(inputMint, input.amount);
281
+ const sections = ['Execute this Jupiter swap?', '', quoteText];
282
+ if (usdEst != null && usdEst >= largeSwapThresholdUsd) {
283
+ sections.push('', `⚠ Large swap warning — input is ~$${usdEst.toFixed(2)} (above $${largeSwapThresholdUsd} threshold). Confirm only if this matches your intent.`);
284
+ }
285
+ else if (usdEst == null) {
286
+ 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.`);
287
+ }
288
+ sections.push('', `Wallet: ${walletAddress}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
289
+ const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
226
290
  if (answer.toLowerCase() !== 'confirm') {
227
291
  return { output: 'Swap cancelled by user.' };
228
292
  }
@@ -248,6 +312,19 @@ async function executeJupiterSwap(input, ctx) {
248
312
  requestId: order.requestId,
249
313
  });
250
314
  if (exec.status !== 'Success') {
315
+ const errStr = (exec.error ?? '').toLowerCase();
316
+ const looksInsufficient = errStr.includes('insufficient') ||
317
+ errStr.includes('lamports') ||
318
+ errStr.includes('tokenaccountnotfound') ||
319
+ errStr.includes('not enough');
320
+ if (looksInsufficient) {
321
+ return {
322
+ output: `Swap failed: insufficient balance. Your Solana wallet (${walletAddress}) does not hold enough of the input token.\n\n` +
323
+ `Send ${symbolFor(inputMint)} to that address (or fund it via the Franklin UI), then retry.\n\n` +
324
+ `Underlying error: ${exec.error ?? exec.code ?? 'unknown'}`,
325
+ isError: true,
326
+ };
327
+ }
251
328
  return {
252
329
  output: `Jupiter Ultra /execute reported ${exec.status}` +
253
330
  (exec.error ? `: ${exec.error}` : '') +
@@ -255,6 +332,7 @@ async function executeJupiterSwap(input, ctx) {
255
332
  isError: true,
256
333
  };
257
334
  }
335
+ liveSwapCount += 1;
258
336
  const sig = exec.signature ?? '<unknown>';
259
337
  const explorer = `https://solscan.io/tx/${sig}`;
260
338
  return {
@@ -263,6 +341,7 @@ async function executeJupiterSwap(input, ctx) {
263
341
  formatQuote(order),
264
342
  `Signature: ${sig}`,
265
343
  explorer,
344
+ `(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
266
345
  ].join('\n'),
267
346
  };
268
347
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.12.2",
3
+ "version": "3.12.3",
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": {