@blockrun/franklin 3.27.3 → 3.28.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.
@@ -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,39 @@
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, loadChain } 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
+ // postWithPayment signs with the active chain's wallet; on Solana that
22
+ // would crash confusingly against this Base-only endpoint. Fail clearly.
23
+ if (loadChain() !== 'base') {
24
+ throw new Error('Onramp is Base-only — switch to Base to buy USDC with a card.');
25
+ }
26
+ const endpoint = `${API_URLS.base}/v1/onramp/token`;
27
+ const result = await postWithPayment(endpoint, { address, network: 'base', asset: 'USDC' }, 'Mint a Coinbase Onramp session link to fund this wallet');
28
+ if (!result.ok) {
29
+ const msg = typeof result.body.error === 'string'
30
+ ? result.body.error
31
+ : `gateway ${result.status}`;
32
+ throw new Error(msg);
33
+ }
34
+ const url = String(result.body.url ?? '');
35
+ if (!url.startsWith('https://pay.coinbase.com/')) {
36
+ throw new Error('gateway returned no onramp url');
37
+ }
38
+ return { url };
39
+ }
@@ -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,43 @@ 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
+ // The mint round-trip can outlive the browser's transient user-activation
1250
+ // window, so popup blockers may eat this open. The token stays valid for
1251
+ // ~5 min — on block, hand the user a real link (a fresh gesture).
1252
+ const win = window.open(data.url, '_blank', 'noopener');
1253
+ if (win) {
1254
+ status.textContent = '';
1255
+ } else {
1256
+ status.textContent = 'Popup blocked — ';
1257
+ const a = document.createElement('a');
1258
+ a.href = data.url;
1259
+ a.target = '_blank';
1260
+ a.rel = 'noopener';
1261
+ a.textContent = 'click here to open Coinbase';
1262
+ status.appendChild(a);
1263
+ }
1264
+ // Funding an empty wallet creates it server-side on first mint — re-render
1265
+ // so the address/QR/balance reflect the wallet Coinbase is about to fund.
1266
+ loadWallet().catch(() => {});
1267
+ } catch (err) {
1268
+ status.textContent = err && err.message ? err.message : 'Failed to open Coinbase';
1269
+ } finally {
1270
+ btn.disabled = false;
1271
+ }
1272
+ });
1273
+
1216
1274
  // Reveal private key
1217
1275
  document.getElementById('wallet-reveal-btn').addEventListener('click', async () => {
1218
1276
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.27.3",
3
+ "version": "3.28.1",
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": {