@blockrun/franklin 3.27.2 → 3.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Coinbase Onramp link client.
3
+ *
4
+ * Exchanges the user's Base wallet address for a one-time Coinbase Onramp
5
+ * URL via the BlockRun gateway. The gateway holds the CDP API key, signs the
6
+ * JWT, and mints a single-use `sessionToken` (Coinbase requires Secure Init
7
+ * since 2025-07-31 — plain appId URLs are deprecated). The returned URL is
8
+ * one-time and expires in ~5 minutes, so it must be minted at click time and
9
+ * never cached.
10
+ *
11
+ * Base / USDC only. Mirrors the gateway-call pattern in src/phone/client.ts
12
+ * and reuses the shared x402 POST helper.
13
+ */
14
+ export interface OnrampLinkResult {
15
+ /** One-time https://pay.coinbase.com/... URL prefilled for this wallet. */
16
+ url: string;
17
+ }
18
+ /**
19
+ * Mint a one-time Coinbase Onramp link that funds `address` (Base USDC).
20
+ * Throws if the gateway is unreachable, not configured, or returns no URL.
21
+ */
22
+ export declare function getOnrampUrl(address: string): Promise<OnrampLinkResult>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Coinbase Onramp link client.
3
+ *
4
+ * Exchanges the user's Base wallet address for a one-time Coinbase Onramp
5
+ * URL via the BlockRun gateway. The gateway holds the CDP API key, signs the
6
+ * JWT, and mints a single-use `sessionToken` (Coinbase requires Secure Init
7
+ * since 2025-07-31 — plain appId URLs are deprecated). The returned URL is
8
+ * one-time and expires in ~5 minutes, so it must be minted at click time and
9
+ * never cached.
10
+ *
11
+ * Base / USDC only. Mirrors the gateway-call pattern in src/phone/client.ts
12
+ * and reuses the shared x402 POST helper.
13
+ */
14
+ import { API_URLS } from '../config.js';
15
+ import { postWithPayment } from '../payments/post-with-payment.js';
16
+ /**
17
+ * Mint a one-time Coinbase Onramp link that funds `address` (Base USDC).
18
+ * Throws if the gateway is unreachable, not configured, or returns no URL.
19
+ */
20
+ export async function getOnrampUrl(address) {
21
+ const endpoint = `${API_URLS.base}/v1/onramp/token`;
22
+ const result = await postWithPayment(endpoint, { address, network: 'base', asset: 'USDC' }, 'Mint a Coinbase Onramp session link to fund this wallet');
23
+ if (!result.ok) {
24
+ const msg = typeof result.body.error === 'string'
25
+ ? result.body.error
26
+ : `gateway ${result.status}`;
27
+ throw new Error(msg);
28
+ }
29
+ const url = String(result.body.url ?? '');
30
+ if (!url.startsWith('https://pay.coinbase.com/')) {
31
+ throw new Error('gateway returned no onramp url');
32
+ }
33
+ return { url };
34
+ }
@@ -409,6 +409,15 @@ a:hover { text-decoration:underline; }
409
409
  .btn-warn:hover { background:oklch(0.78 0.14 85 / 30%); }
410
410
  .btn-danger { background:oklch(0.65 0.20 25 / 18%); color:var(--danger); border-color:oklch(0.65 0.20 25 / 35%); }
411
411
  .btn-danger:hover { background:oklch(0.65 0.20 25 / 30%); }
412
+ .btn-onramp {
413
+ display:block; width:100%; text-align:center;
414
+ font-size:14px; font-weight:700; letter-spacing:0.01em;
415
+ padding:13px 18px; border-radius:10px;
416
+ background:oklch(0.55 0.19 256); color:#fff; border:1px solid oklch(0.55 0.19 256);
417
+ box-shadow:0 1px 0 oklch(0 0 0 / 12%);
418
+ }
419
+ .btn-onramp:hover { background:oklch(0.50 0.19 256); border-color:oklch(0.50 0.19 256); }
420
+ .btn-onramp:disabled { opacity:0.55; cursor:default; }
412
421
 
413
422
  .nav-badge {
414
423
  margin-left:auto; font-size:10px; font-weight:700; letter-spacing:0.3px;
@@ -642,6 +651,11 @@ a:hover { text-decoration:underline; }
642
651
  <div class="wallet-balance-big" id="wallet-balance-big">—</div>
643
652
  <div class="wallet-qr" id="wallet-qr"></div>
644
653
  <p class="wallet-hint" id="wallet-qr-hint">Scan to send USDC to this wallet.</p>
654
+ <div class="wallet-actions" id="wallet-onramp-actions" style="margin-top:16px;flex-direction:column;align-items:stretch;gap:6px">
655
+ <button class="btn btn-onramp" id="wallet-onramp-btn">&#128179;&nbsp; Buy USDC with card</button>
656
+ <span class="wallet-import-status" id="wallet-onramp-status"></span>
657
+ </div>
658
+ <p class="wallet-hint" id="wallet-onramp-hint">Powered by Coinbase Onramp &middot; Base only &middot; 60+ fiat currencies</p>
645
659
  </div>
646
660
 
647
661
  <div class="card">
@@ -1135,6 +1149,13 @@ async function loadWallet() {
1135
1149
  solanaBtn.classList.toggle('active', w.chain === 'solana');
1136
1150
  }
1137
1151
 
1152
+ // Coinbase Onramp is Base-only — hide the buy button + hint on Solana.
1153
+ const onrampActions = document.getElementById('wallet-onramp-actions');
1154
+ const onrampHint = document.getElementById('wallet-onramp-hint');
1155
+ const onBase = w.chain === 'base';
1156
+ if (onrampActions) onrampActions.style.display = onBase ? '' : 'none';
1157
+ if (onrampHint) onrampHint.style.display = onBase ? '' : 'none';
1158
+
1138
1159
  // QR via server — never leak address to third parties.
1139
1160
  // Encode chain + USDC token in the QR payload so wallet apps land
1140
1161
  // directly on the right network/token instead of a bare address:
@@ -1213,6 +1234,27 @@ document.getElementById('wallet-copy-btn').addEventListener('click', async () =>
1213
1234
  } catch { /* clipboard may be blocked — user can select manually */ }
1214
1235
  });
1215
1236
 
1237
+ // Buy USDC with card — mint a one-time Coinbase Onramp link and open it.
1238
+ // The session token is single-use and expires in ~5 min, so we mint it at
1239
+ // click time and never cache it.
1240
+ document.getElementById('wallet-onramp-btn').addEventListener('click', async () => {
1241
+ const btn = document.getElementById('wallet-onramp-btn');
1242
+ const status = document.getElementById('wallet-onramp-status');
1243
+ btn.disabled = true;
1244
+ status.textContent = 'Opening Coinbase…';
1245
+ try {
1246
+ const r = await fetch('/api/wallet/onramp', { method: 'POST' });
1247
+ const data = await r.json().catch(() => ({}));
1248
+ if (!r.ok || !data.url) throw new Error(data.error || r.statusText || 'failed');
1249
+ window.open(data.url, '_blank', 'noopener');
1250
+ status.textContent = '';
1251
+ } catch (err) {
1252
+ status.textContent = err && err.message ? err.message : 'Failed to open Coinbase';
1253
+ } finally {
1254
+ btn.disabled = false;
1255
+ }
1256
+ });
1257
+
1216
1258
  // Reveal private key
1217
1259
  document.getElementById('wallet-reveal-btn').addEventListener('click', async () => {
1218
1260
  if (!confirm('Show the private key on screen?\\n\\nAnyone who sees or records the key can drain this wallet. Make sure nobody is looking over your shoulder or recording your screen.')) return;
@@ -290,6 +290,34 @@ export function createPanelServer(port) {
290
290
  }
291
291
  return;
292
292
  }
293
+ // ─── Wallet onramp (loopback only) ──────────────────────────────────
294
+ // Mints a one-time Coinbase Onramp link to fund the wallet with a card.
295
+ // Spends nothing locally, but it talks to the gateway with this wallet's
296
+ // identity and opens a payment flow, so it gets the same loopback +
297
+ // same-origin posture as the wallet-mutating routes. Base only — the
298
+ // gateway mints a session token scoped to the Base address.
299
+ if (p === '/api/wallet/onramp' && req.method === 'POST') {
300
+ if (!isLocalPanelRequest(req)) {
301
+ json(res, { error: 'forbidden' }, 403);
302
+ return;
303
+ }
304
+ try {
305
+ const chain = loadChain();
306
+ if (chain !== 'base') {
307
+ json(res, { error: 'Onramp currently supports Base only — switch to Base to buy USDC with a card.' }, 400);
308
+ return;
309
+ }
310
+ const { setupAgentWallet } = await import('@blockrun/llm');
311
+ const address = setupAgentWallet({ silent: true }).getWalletAddress();
312
+ const { getOnrampUrl } = await import('../onramp/client.js');
313
+ const { url } = await getOnrampUrl(address);
314
+ json(res, { url });
315
+ }
316
+ catch (err) {
317
+ json(res, { error: err.message }, 500);
318
+ }
319
+ return;
320
+ }
293
321
  // ─── Wallet secret (loopback only) ──────────────────────────────────
294
322
  // Returns the private key so the user can back it up / move it.
295
323
  // Hardened: loopback-only (belt-and-suspenders on the 127.0.0.1 bind),
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Shared x402 POST helper.
3
+ *
4
+ * Posts JSON to a BlockRun gateway endpoint and transparently completes the
5
+ * x402 payment handshake: the first POST may return 402 with payment
6
+ * requirements, we sign with the local wallet (Base or Solana, per active
7
+ * chain) and retry once with the signature header.
8
+ *
9
+ * Extracted from src/phone/client.ts so phone, onramp, and any future
10
+ * gateway clients share one implementation instead of copy-pasting the
11
+ * 402 dance. Endpoints that are free simply return 200 on the first POST,
12
+ * in which case no signing happens.
13
+ */
14
+ export interface PostResult {
15
+ ok: boolean;
16
+ status: number;
17
+ body: Record<string, unknown>;
18
+ raw: string;
19
+ }
20
+ /**
21
+ * POST JSON to a gateway endpoint, completing the x402 handshake if the
22
+ * endpoint demands payment. `resourceDescription` is surfaced to the user
23
+ * in the wallet signature for free-text context.
24
+ */
25
+ export declare function postWithPayment(endpoint: string, body: Record<string, unknown>, resourceDescription: string, timeoutMs?: number): Promise<PostResult>;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Shared x402 POST helper.
3
+ *
4
+ * Posts JSON to a BlockRun gateway endpoint and transparently completes the
5
+ * x402 payment handshake: the first POST may return 402 with payment
6
+ * requirements, we sign with the local wallet (Base or Solana, per active
7
+ * chain) and retry once with the signature header.
8
+ *
9
+ * Extracted from src/phone/client.ts so phone, onramp, and any future
10
+ * gateway clients share one implementation instead of copy-pasting the
11
+ * 402 dance. Endpoints that are free simply return 200 on the first POST,
12
+ * in which case no signing happens.
13
+ */
14
+ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
15
+ import { loadChain, USER_AGENT } from '../config.js';
16
+ async function extractPaymentReq(response) {
17
+ let header = response.headers.get('payment-required');
18
+ if (!header) {
19
+ try {
20
+ const body = (await response.clone().json());
21
+ if (body.x402 || body.accepts)
22
+ header = btoa(JSON.stringify(body));
23
+ }
24
+ catch { /* not JSON, no header */ }
25
+ }
26
+ return header;
27
+ }
28
+ async function signPayment(response, chain, endpoint, resourceDescription) {
29
+ const paymentHeader = await extractPaymentReq(response);
30
+ if (!paymentHeader)
31
+ return null;
32
+ if (chain === 'solana') {
33
+ const wallet = await getOrCreateSolanaWallet();
34
+ const paymentRequired = parsePaymentRequired(paymentHeader);
35
+ const details = extractPaymentDetails(paymentRequired, SOLANA_NETWORK);
36
+ const secretBytes = await solanaKeyToBytes(wallet.privateKey);
37
+ const feePayer = details.extra?.feePayer || details.recipient;
38
+ const payload = await createSolanaPaymentPayload(secretBytes, wallet.address, details.recipient, details.amount, feePayer, {
39
+ resourceUrl: details.resource?.url || endpoint,
40
+ resourceDescription: details.resource?.description || resourceDescription,
41
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
42
+ extra: details.extra,
43
+ });
44
+ return { 'PAYMENT-SIGNATURE': payload };
45
+ }
46
+ else {
47
+ const wallet = getOrCreateWallet();
48
+ const paymentRequired = parsePaymentRequired(paymentHeader);
49
+ const details = extractPaymentDetails(paymentRequired);
50
+ const payload = await createPaymentPayload(wallet.privateKey, wallet.address, details.recipient, details.amount, details.network || 'eip155:8453', {
51
+ resourceUrl: details.resource?.url || endpoint,
52
+ resourceDescription: details.resource?.description || resourceDescription,
53
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
54
+ extra: details.extra,
55
+ });
56
+ return { 'PAYMENT-SIGNATURE': payload };
57
+ }
58
+ }
59
+ /**
60
+ * POST JSON to a gateway endpoint, completing the x402 handshake if the
61
+ * endpoint demands payment. `resourceDescription` is surfaced to the user
62
+ * in the wallet signature for free-text context.
63
+ */
64
+ export async function postWithPayment(endpoint, body, resourceDescription, timeoutMs = 30_000) {
65
+ const chain = loadChain();
66
+ const headers = {
67
+ 'Content-Type': 'application/json',
68
+ 'User-Agent': USER_AGENT,
69
+ };
70
+ const ctrl = new AbortController();
71
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
72
+ try {
73
+ const payload = JSON.stringify(body);
74
+ let response = await fetch(endpoint, {
75
+ method: 'POST',
76
+ signal: ctrl.signal,
77
+ headers,
78
+ body: payload,
79
+ });
80
+ if (response.status === 402) {
81
+ const paymentHeaders = await signPayment(response, chain, endpoint, resourceDescription);
82
+ if (!paymentHeaders) {
83
+ return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '' };
84
+ }
85
+ response = await fetch(endpoint, {
86
+ method: 'POST',
87
+ signal: ctrl.signal,
88
+ headers: { ...headers, ...paymentHeaders },
89
+ body: payload,
90
+ });
91
+ }
92
+ const raw = await response.text().catch(() => '');
93
+ let parsed = {};
94
+ try {
95
+ parsed = raw ? JSON.parse(raw) : {};
96
+ }
97
+ catch { /* leave as {} */ }
98
+ return { ok: response.ok, status: response.status, body: parsed, raw };
99
+ }
100
+ finally {
101
+ clearTimeout(timer);
102
+ }
103
+ }
@@ -12,95 +12,12 @@
12
12
  * - phone cache refresh (background)
13
13
  * - future Phone/Call tools surfaced to the agent
14
14
  */
15
- import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
16
- import { loadChain, API_URLS, USER_AGENT } from '../config.js';
15
+ import { API_URLS, loadChain } from '../config.js';
16
+ import { postWithPayment } from '../payments/post-with-payment.js';
17
17
  import { writeCache } from './cache.js';
18
18
  function phoneEndpoint(chain, path) {
19
19
  return `${API_URLS[chain]}/v1/phone/${path}`;
20
20
  }
21
- async function extractPaymentReq(response) {
22
- let header = response.headers.get('payment-required');
23
- if (!header) {
24
- try {
25
- const body = (await response.clone().json());
26
- if (body.x402 || body.accepts)
27
- header = btoa(JSON.stringify(body));
28
- }
29
- catch { /* not JSON, no header */ }
30
- }
31
- return header;
32
- }
33
- async function signPayment(response, chain, endpoint, resourceDescription) {
34
- const paymentHeader = await extractPaymentReq(response);
35
- if (!paymentHeader)
36
- return null;
37
- if (chain === 'solana') {
38
- const wallet = await getOrCreateSolanaWallet();
39
- const paymentRequired = parsePaymentRequired(paymentHeader);
40
- const details = extractPaymentDetails(paymentRequired, SOLANA_NETWORK);
41
- const secretBytes = await solanaKeyToBytes(wallet.privateKey);
42
- const feePayer = details.extra?.feePayer || details.recipient;
43
- const payload = await createSolanaPaymentPayload(secretBytes, wallet.address, details.recipient, details.amount, feePayer, {
44
- resourceUrl: details.resource?.url || endpoint,
45
- resourceDescription: details.resource?.description || resourceDescription,
46
- maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
47
- extra: details.extra,
48
- });
49
- return { 'PAYMENT-SIGNATURE': payload };
50
- }
51
- else {
52
- const wallet = getOrCreateWallet();
53
- const paymentRequired = parsePaymentRequired(paymentHeader);
54
- const details = extractPaymentDetails(paymentRequired);
55
- const payload = await createPaymentPayload(wallet.privateKey, wallet.address, details.recipient, details.amount, details.network || 'eip155:8453', {
56
- resourceUrl: details.resource?.url || endpoint,
57
- resourceDescription: details.resource?.description || resourceDescription,
58
- maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
59
- extra: details.extra,
60
- });
61
- return { 'PAYMENT-SIGNATURE': payload };
62
- }
63
- }
64
- async function postWithPayment(endpoint, body, resourceDescription, timeoutMs = 30_000) {
65
- const chain = loadChain();
66
- const headers = {
67
- 'Content-Type': 'application/json',
68
- 'User-Agent': USER_AGENT,
69
- };
70
- const ctrl = new AbortController();
71
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
72
- try {
73
- const payload = JSON.stringify(body);
74
- let response = await fetch(endpoint, {
75
- method: 'POST',
76
- signal: ctrl.signal,
77
- headers,
78
- body: payload,
79
- });
80
- if (response.status === 402) {
81
- const paymentHeaders = await signPayment(response, chain, endpoint, resourceDescription);
82
- if (!paymentHeaders) {
83
- return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '' };
84
- }
85
- response = await fetch(endpoint, {
86
- method: 'POST',
87
- signal: ctrl.signal,
88
- headers: { ...headers, ...paymentHeaders },
89
- body: payload,
90
- });
91
- }
92
- const raw = await response.text().catch(() => '');
93
- let parsed = {};
94
- try {
95
- parsed = raw ? JSON.parse(raw) : {};
96
- }
97
- catch { /* leave as {} */ }
98
- return { ok: response.ok, status: response.status, body: parsed, raw };
99
- }
100
- finally {
101
- clearTimeout(timer);
102
- }
103
- }
104
21
  /**
105
22
  * Fetch the wallet's owned numbers from BlockRun. Refreshes the local
106
23
  * cache on success so the terminal status bar picks up the same data.
@@ -30,6 +30,7 @@ import { jupiterQuoteCapability, jupiterSwapCapability } from './jupiter.js';
30
30
  import { base0xQuoteCapability, base0xSwapCapability } from './zerox-base.js';
31
31
  import { base0xGaslessSwapCapability } from './zerox-gasless.js';
32
32
  import { defiLlamaProtocolsCapability, defiLlamaProtocolCapability, defiLlamaChainsCapability, defiLlamaYieldsCapability, defiLlamaPriceCapability, } from './defillama.js';
33
+ import { multiChainRpcCapability } from './rpc.js';
33
34
  import { predictionMarketCapability } from './prediction.js';
34
35
  import { modalCapabilities } from './modal.js';
35
36
  import { blockrunCapability } from './blockrun.js';
@@ -167,6 +168,7 @@ export const allCapabilities = [
167
168
  defiLlamaChainsCapability,
168
169
  defiLlamaYieldsCapability,
169
170
  defiLlamaPriceCapability,
171
+ multiChainRpcCapability, // read-only JSON-RPC across 40+ chains ($0.002/call)
170
172
  predictionMarketCapability, // Polymarket / Kalshi / matching / smart money via Predexon
171
173
  blockrunCapability, // Generic x402-paid gateway primitive — future partners + long-tail Surf paths
172
174
  ...surfCapabilities, // SurfMarket / SurfChain / SurfSocial — endpoint-enum function tools (no path guessing, auto x402)
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Multi-chain RPC — read-only JSON-RPC across 40+ chains via the BlockRun
3
+ * `/v1/rpc/{network}` endpoint (Tatum gateway). x402-paid against the user's
4
+ * USDC wallet, flat $0.002 per call.
5
+ *
6
+ * For a trading agent this covers the on-chain reads the dedicated tools don't:
7
+ * native + ERC-20 balances on any chain, contract reads (eth_call), gas price,
8
+ * nonce, block height, and "did my tx land?" receipt checks — without needing
9
+ * a per-chain RPC key.
10
+ *
11
+ * READ-ONLY by design (per product decision): state-changing / signing methods
12
+ * are rejected. Sending transactions goes through the wallet / Jupiter / 0x
13
+ * tools, which handle signing + confirmation. This tool never signs a chain tx
14
+ * (the only signature it produces is the x402 micropayment for the API call).
15
+ *
16
+ * Direct gateway fetch (same pattern as the DefiLlama / Surf tools) — does not
17
+ * depend on the SDK's RpcClient, so it works on the pinned @blockrun/llm 2.x.
18
+ */
19
+ import type { CapabilityHandler } from '../agent/types.js';
20
+ declare const KNOWN_NETWORKS: string[];
21
+ export declare const multiChainRpcCapability: CapabilityHandler;
22
+ export { KNOWN_NETWORKS };
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Multi-chain RPC — read-only JSON-RPC across 40+ chains via the BlockRun
3
+ * `/v1/rpc/{network}` endpoint (Tatum gateway). x402-paid against the user's
4
+ * USDC wallet, flat $0.002 per call.
5
+ *
6
+ * For a trading agent this covers the on-chain reads the dedicated tools don't:
7
+ * native + ERC-20 balances on any chain, contract reads (eth_call), gas price,
8
+ * nonce, block height, and "did my tx land?" receipt checks — without needing
9
+ * a per-chain RPC key.
10
+ *
11
+ * READ-ONLY by design (per product decision): state-changing / signing methods
12
+ * are rejected. Sending transactions goes through the wallet / Jupiter / 0x
13
+ * tools, which handle signing + confirmation. This tool never signs a chain tx
14
+ * (the only signature it produces is the x402 micropayment for the API call).
15
+ *
16
+ * Direct gateway fetch (same pattern as the DefiLlama / Surf tools) — does not
17
+ * depend on the SDK's RpcClient, so it works on the pinned @blockrun/llm 2.x.
18
+ */
19
+ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
20
+ import { loadChain, API_URLS, VERSION } from '../config.js';
21
+ import { logger } from '../logger.js';
22
+ const TIMEOUT_MS = 30_000;
23
+ // Curated chains the gateway exposes (for the agent + validation). Unknown but
24
+ // well-formed slugs still pass through — the gateway resolves them — so this is
25
+ // guidance, not a hard allowlist. Mirrors backend src/lib/tatum.ts.
26
+ const KNOWN_NETWORKS = [
27
+ 'ethereum', 'base', 'arbitrum', 'optimism', 'polygon', 'bsc', 'avalanche',
28
+ 'fantom', 'cronos', 'celo', 'gnosis', 'zksync', 'berachain', 'unichain',
29
+ 'monad', 'sonic', 'xdc', 'abstract', 'hyperevm', 'plume', 'ronin', 'rootstock',
30
+ 'solana', 'bitcoin', 'litecoin', 'dogecoin', 'bitcoin-cash', 'near', 'sui',
31
+ 'ripple', 'polkadot', 'zcash',
32
+ ];
33
+ // State-changing / signing methods — rejected (read-only tool). Matched
34
+ // case-insensitively against the method name.
35
+ const WRITE_METHODS = new Set([
36
+ // EVM
37
+ 'eth_sendrawtransaction', 'eth_sendtransaction', 'eth_sign',
38
+ 'eth_signtransaction', 'eth_signtypeddata', 'eth_signtypeddata_v3',
39
+ 'eth_signtypeddata_v4', 'personal_sign', 'personal_sendtransaction',
40
+ 'personal_unlockaccount', 'personal_importrawkey',
41
+ // Solana
42
+ 'sendtransaction', 'requestairdrop',
43
+ // Bitcoin-family
44
+ 'sendrawtransaction',
45
+ ].map((m) => m.toLowerCase()));
46
+ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
47
+ const chain = loadChain();
48
+ const apiUrl = API_URLS[chain];
49
+ const endpoint = `${apiUrl}/v1/rpc/${network}`;
50
+ const bodyStr = JSON.stringify(jsonRpcBody);
51
+ const headers = {
52
+ 'Content-Type': 'application/json',
53
+ Accept: 'application/json',
54
+ 'User-Agent': `franklin/${VERSION}`,
55
+ };
56
+ const controller = new AbortController();
57
+ const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
58
+ const onAbort = () => controller.abort();
59
+ ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
60
+ try {
61
+ let response = await fetch(endpoint, {
62
+ method: 'POST',
63
+ signal: controller.signal,
64
+ headers,
65
+ body: bodyStr,
66
+ });
67
+ if (response.status === 402) {
68
+ const paymentHeaders = await signPayment(response, chain, endpoint);
69
+ if (!paymentHeaders) {
70
+ throw new Error('Payment signing failed — check wallet balance');
71
+ }
72
+ response = await fetch(endpoint, {
73
+ method: 'POST',
74
+ signal: controller.signal,
75
+ headers: { ...headers, ...paymentHeaders },
76
+ body: bodyStr,
77
+ });
78
+ }
79
+ if (!response.ok) {
80
+ const errText = await response.text().catch(() => '');
81
+ throw new Error(`RPC ${network} failed (${response.status}): ${errText.slice(0, 200)}`);
82
+ }
83
+ return {
84
+ body: await response.json(),
85
+ network: response.headers.get('x-network') || network,
86
+ cacheHit: (response.headers.get('x-cache') || '').toUpperCase() === 'HIT',
87
+ txHash: response.headers.get('x-payment-receipt'),
88
+ };
89
+ }
90
+ finally {
91
+ clearTimeout(timeout);
92
+ ctx.abortSignal.removeEventListener('abort', onAbort);
93
+ }
94
+ }
95
+ async function signPayment(response, chain, endpoint) {
96
+ try {
97
+ const paymentHeader = await extractPaymentReq(response);
98
+ if (!paymentHeader)
99
+ return null;
100
+ if (chain === 'solana') {
101
+ const wallet = await getOrCreateSolanaWallet();
102
+ const paymentRequired = parsePaymentRequired(paymentHeader);
103
+ const details = extractPaymentDetails(paymentRequired, SOLANA_NETWORK);
104
+ const secretBytes = await solanaKeyToBytes(wallet.privateKey);
105
+ const feePayer = details.extra?.feePayer || details.recipient;
106
+ const payload = await createSolanaPaymentPayload(secretBytes, wallet.address, details.recipient, details.amount, feePayer, {
107
+ resourceUrl: details.resource?.url || endpoint,
108
+ resourceDescription: details.resource?.description || 'Franklin multi-chain RPC',
109
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
110
+ extra: details.extra,
111
+ });
112
+ return { 'PAYMENT-SIGNATURE': payload };
113
+ }
114
+ const wallet = await getOrCreateWallet();
115
+ const paymentRequired = parsePaymentRequired(paymentHeader);
116
+ const details = extractPaymentDetails(paymentRequired);
117
+ const payload = await createPaymentPayload(wallet.privateKey, wallet.address, details.recipient, details.amount, details.network || 'eip155:8453', {
118
+ resourceUrl: details.resource?.url || endpoint,
119
+ resourceDescription: details.resource?.description || 'Franklin multi-chain RPC',
120
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
121
+ extra: details.extra,
122
+ });
123
+ return { 'PAYMENT-SIGNATURE': payload };
124
+ }
125
+ catch (err) {
126
+ logger.warn(`[franklin] RPC payment error: ${err.message}`);
127
+ return null;
128
+ }
129
+ }
130
+ async function extractPaymentReq(response) {
131
+ let header = response.headers.get('payment-required');
132
+ if (!header) {
133
+ try {
134
+ const body = (await response.json());
135
+ if (body.x402 || body.accepts)
136
+ header = btoa(JSON.stringify(body));
137
+ }
138
+ catch {
139
+ /* ignore */
140
+ }
141
+ }
142
+ return header;
143
+ }
144
+ export const multiChainRpcCapability = {
145
+ spec: {
146
+ name: 'MultiChainRPC',
147
+ description: 'Read-only JSON-RPC against 40+ chains through the BlockRun gateway (one endpoint, no per-chain key). ' +
148
+ '$0.002 per call (USDC). Use for on-chain reads the other tools do not cover: native/token balances on any ' +
149
+ 'chain, contract reads (eth_call), gas price, nonce, block height, and tx receipt checks ("did my swap land?"). ' +
150
+ 'EVM chains speak eth_* (eth_blockNumber, eth_getBalance, eth_call, eth_gasPrice, eth_getTransactionReceipt, ...); ' +
151
+ 'Solana speaks getSlot/getBalance/getAccountInfo/getTransaction; Bitcoin-family speaks getblockcount etc. ' +
152
+ 'Networks: ethereum, base, arbitrum, optimism, polygon, bsc, avalanche, solana, bitcoin, sui, ripple, and 30+ more ' +
153
+ '(common aliases like eth/arb/op/matic/sol/btc also work). ' +
154
+ 'READ-ONLY: signing / send-transaction methods are rejected — use the wallet, Jupiter, or 0x tools to move funds.',
155
+ input_schema: {
156
+ type: 'object',
157
+ properties: {
158
+ network: {
159
+ type: 'string',
160
+ description: 'Chain name or alias, e.g. "ethereum", "base", "solana", "arbitrum", "bitcoin".',
161
+ },
162
+ method: {
163
+ type: 'string',
164
+ description: 'JSON-RPC method, e.g. "eth_getBalance", "eth_call", "eth_blockNumber", "getSlot".',
165
+ },
166
+ params: {
167
+ type: 'array',
168
+ description: 'Method params array (optional). E.g. ["0xADDR","latest"] for eth_getBalance.',
169
+ items: {},
170
+ },
171
+ },
172
+ required: ['network', 'method'],
173
+ },
174
+ },
175
+ execute: async (input, ctx) => {
176
+ const params = input;
177
+ const network = (params.network ?? '').trim().toLowerCase();
178
+ const method = (params.method ?? '').trim();
179
+ if (!network)
180
+ return { output: 'Error: network is required', isError: true };
181
+ if (!method)
182
+ return { output: 'Error: method is required', isError: true };
183
+ if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(network)) {
184
+ return { output: `Error: malformed network "${params.network}"`, isError: true };
185
+ }
186
+ if (WRITE_METHODS.has(method.toLowerCase())) {
187
+ return {
188
+ output: `Error: "${method}" is a state-changing method and is blocked — MultiChainRPC is read-only. ` +
189
+ `To send funds or sign transactions, use the wallet / JupiterSwap / Base0x* tools.`,
190
+ isError: true,
191
+ };
192
+ }
193
+ const rpcParams = Array.isArray(params.params) ? params.params : [];
194
+ const jsonRpcBody = { jsonrpc: '2.0', id: 1, method, params: rpcParams };
195
+ try {
196
+ const res = await postRpcWithPayment(network, jsonRpcBody, ctx);
197
+ const envelope = res.body;
198
+ if (envelope && envelope.error) {
199
+ return {
200
+ output: `JSON-RPC error from ${res.network} ${method}: ` +
201
+ `${envelope.error.message ?? 'unknown'} (code ${envelope.error.code ?? 'n/a'})`,
202
+ isError: true,
203
+ };
204
+ }
205
+ const result = envelope?.result;
206
+ const pretty = typeof result === 'string'
207
+ ? result
208
+ : JSON.stringify(result, null, 2);
209
+ // Guard context size — chain reads (getLogs, large account data) can be big.
210
+ const trimmed = pretty.length > 6000 ? `${pretty.slice(0, 6000)}\n…(truncated)` : pretty;
211
+ const meta = res.cacheHit ? ' · cached' : '';
212
+ return { output: `## ${res.network} · ${method}${meta}\n\n${trimmed}` };
213
+ }
214
+ catch (err) {
215
+ return { output: `Error: ${err.message}`, isError: true };
216
+ }
217
+ },
218
+ concurrent: true,
219
+ };
220
+ export { KNOWN_NETWORKS };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.27.2",
3
+ "version": "3.28.0",
4
4
  "description": "Franklin Agent — 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": {