Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance Solana payment support with wallet key management and payment handling
qbdz78d77e29670d
diff --git a/packages/vscode-x402/src/extension.js b/packages/vscode-x402/src/extension.jsindex 171fc45bb..2918a72ef 100644--- a/packages/vscode-x402/src/extension.js+++ b/packages/vscode-x402/src/extension.js@@ -7,7 +7,7 @@ import * as vscode from 'vscode';import { BazaarProvider } from './tree.js';import { inspectEndpoint, summarize } from './inspect.js';import { showService } from './panel.js';-import { setKey, clearKey, getAddress } from './wallet.js';+import { setKey, clearKey, getAddress, setSolanaKey, clearSolanaKey, getSolanaAddress } from './wallet.js';import { scaffoldEndpoint } from './scaffold.js';let output;@@ -19,7 +19,7 @@ export function activate(context) {const tree = vscode.window.createTreeView('threewsX402.bazaar', { treeDataProvider: provider });statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);- statusBar.command = 'threewsX402.setWalletKey';+ statusBar.command = 'threewsX402.manageWallet';context.subscriptions.push(output, tree, statusBar);refreshStatusBar(context);@@ -82,23 +82,65 @@ export function activate(context) {reg('threewsX402.clearWalletKey', async () => {await clearKey(context);- vscode.window.showInformationMessage('x402 wallet key cleared.');+ vscode.window.showInformationMessage('x402 EVM wallet key cleared.');refreshStatusBar(context);});+ reg('threewsX402.setSolanaWalletKey', async () => {+ const address = await setSolanaKey(context);+ if (address) {+ vscode.window.showInformationMessage(`x402 Solana wallet set: ${address}`);+ refreshStatusBar(context);+ }+ });++ reg('threewsX402.clearSolanaWalletKey', async () => {+ await clearSolanaKey(context);+ vscode.window.showInformationMessage('x402 Solana wallet key cleared.');+ refreshStatusBar(context);+ });++ reg('threewsX402.manageWallet', async () => {+ const [evm, sol] = await Promise.all([getAddress(context), getSolanaAddress(context)]);+ const pick = await vscode.window.showQuickPick(+ [+ { label: '$(key) Set Solana wallet key', detail: sol ? `Current: ${sol}` : 'Pay USDC or $THREE on Solana', id: 'setSol' },+ { label: '$(key) Set EVM wallet key', detail: evm ? `Current: ${evm}` : 'Pay USDC on Base and other EVM chains', id: 'setEvm' },+ ...(sol ? [{ label: '$(trash) Clear Solana wallet key', id: 'clrSol' }] : []),+ ...(evm ? [{ label: '$(trash) Clear EVM wallet key', id: 'clrEvm' }] : []),+ ],+ { title: 'x402 wallets' },+ );+ if (!pick) return;+ const cmd = {+ setSol: 'threewsX402.setSolanaWalletKey',+ setEvm: 'threewsX402.setWalletKey',+ clrSol: 'threewsX402.clearSolanaWalletKey',+ clrEvm: 'threewsX402.clearWalletKey',+ }[pick.id];+ if (cmd) await vscode.commands.executeCommand(cmd);+ });+reg('threewsX402.scaffoldEndpoint', () => scaffoldEndpoint());provider.refresh();}async function refreshStatusBar(context) {- const address = await getAddress(context);- if (address) {- statusBar.text = `$(key) x402 ${address.slice(0, 6)}…${address.slice(-4)}`;- statusBar.tooltip = `x402 wallet: ${address}\nClick to change`;+ const [evm, sol] = await Promise.all([getAddress(context), getSolanaAddress(context)]);+ const short = (a) => `${a.slice(0, 4)}…${a.slice(-4)}`;+ const parts = [];+ if (sol) parts.push(`◎ ${short(sol)}`);+ if (evm) parts.push(`⟠ ${short(evm)}`);+ if (parts.length) {+ statusBar.text = `$(key) x402 ${parts.join(' ')}`;+ statusBar.tooltip =+ `x402 wallets — click to manage\n` ++ (sol ? `Solana: ${sol}\n` : 'Solana: not set\n') ++ (evm ? `EVM: ${evm}` : 'EVM: not set');} else {statusBar.text = '$(key) x402: no wallet';- statusBar.tooltip = 'No x402 wallet key set — click to set one';+ statusBar.tooltip = 'No x402 wallet key set — click to set a Solana or EVM key';}statusBar.show();}diff --git a/packages/vscode-x402/src/inspect.js b/packages/vscode-x402/src/inspect.jsindex d9a5549aa..9b5ea0fd8 100644--- a/packages/vscode-x402/src/inspect.js+++ b/packages/vscode-x402/src/inspect.js@@ -1,23 +1,68 @@// Inspect any endpoint: do an unpaid request, and if it answers 402, decode the-// payment challenge into a readable summary using the same parser the payer-// uses. Reachable as a standalone command (paste a URL) or from a bazaar item.+// payment challenge into a readable summary. Selection is dual-rail: the+// extension can satisfy USDC EIP-3009 on EVM (Base + other chains) OR the+// `exact` scheme in USDC/$THREE on Solana. Reachable as a standalone command+// (paste a URL) or from a bazaar item.-import {- parseChallenge,- selectRequirement,- amountToUsd,-} from '../../x402-fetch/src/parse-challenge.js';+import { parseChallenge, amountToUsd, isEip3009Accept } from '../../x402-fetch/src/parse-challenge.js';+import { isSolanaExactAccept, isThreeAccept, isUsdcAccept, tokenLabel } from './solana.js';++const NETWORK_BASE = 'eip155:8453';++/** Which rail settles this accept, or null if this extension can't pay it. */+export function railOf(a) {+ if (isSolanaExactAccept(a)) return 'solana';+ if (isEip3009Accept(a)) return 'evm';+ return null;+}++// Auth-hint placeholders (amount "0" / extra.authRequired) are never payable.+function isNonZero(a) {+ if (!a || typeof a !== 'object') return false;+ if (a.extra?.authRequired != null) return false;+ return String(a.amount ?? a.maxAmountRequired ?? '') !== '0';+}/**- * @returns {Promise<{ status:number, paid:boolean, accepts:any[], chosen:any|null, resource:any, raw:any }>}+ * Select the payment requirement to settle across both rails.+ * @param {any[]} accepts+ * @param {{ preferNetwork?: string, preferToken?: 'auto'|'usdc'|'three', wallets?: {evm?:boolean, solana?:boolean} }} [opts]*/-export async function inspectEndpoint(url, { method = 'GET', preferNetwork } = {}) {- const res = await fetch(url, {- method,- headers: { accept: 'application/json' },- // MCP endpoints expect a body; for inspection a HEAD-ish GET is enough to- // trigger the 402 on three.ws + CDP merchants.- });+export function selectRequirement(accepts, { preferNetwork, preferToken, wallets = { evm: true, solana: true } } = {}) {+ const payable = accepts.filter(+ (a) => isNonZero(a) && ((wallets.solana && isSolanaExactAccept(a)) || (wallets.evm && isEip3009Accept(a))),+ );+ if (!payable.length) return null;++ // 1. An explicit CAIP-2 network preference wins (covers eip155:* and solana:*).+ if (preferNetwork) {+ const m = payable.find((a) => a.network === preferNetwork);+ if (m) return m;+ }+ // 2. Explicit token preference.+ if (preferToken === 'three') {+ const m = payable.find(isThreeAccept);+ if (m) return m;+ }+ if (preferToken === 'usdc') {+ const m = payable.find((a) => isUsdcAccept(a));+ if (m) return m;+ }+ // 3. Auto: prefer Solana USDC, then any Solana accept (incl. $THREE),+ // then Base USDC, then anything payable.+ return (+ payable.find((a) => isSolanaExactAccept(a) && isUsdcAccept(a)) ||+ payable.find((a) => isSolanaExactAccept(a)) ||+ payable.find((a) => a.network === NETWORK_BASE) ||+ payable[0]+ );+}++/**+ * @returns {Promise<{ status:number, paid:boolean, accepts:any[], chosen:any|null, rail:string|null, resource:any, raw:any }>}+ */+export async function inspectEndpoint(url, { method = 'GET', preferNetwork, preferToken, wallets } = {}) {+ const res = await fetch(url, { method, headers: { accept: 'application/json' } });if (res.status !== 402) {return {@@ -25,6 +70,7 @@ export async function inspectEndpoint(url, { method = 'GET', preferNetwork } = {paid: res.status >= 200 && res.status < 300,accepts: [],chosen: null,+ rail: null,resource: null,raw: null,};@@ -32,12 +78,13 @@ export async function inspectEndpoint(url, { method = 'GET', preferNetwork } = {const parsed = await parseChallenge(res);const accepts = parsed?.accepts || [];- const chosen = selectRequirement(accepts, { preferNetwork });+ const chosen = selectRequirement(accepts, { preferNetwork, preferToken, wallets });return {status: 402,paid: false,accepts,chosen,+ rail: chosen ? railOf(chosen) : null,resource: parsed?.resource || null,raw: parsed?.raw || null,};@@ -56,19 +103,17 @@ export function summarize(result) {const lines = ['Status: 402 Payment Required', ''];result.accepts.forEach((a, i) => {const usd = amountToUsd(a);+ const rail = railOf(a);+ const railTag = rail ? ` [${rail}]` : '';const mark = a === result.chosen ? ' ← payable by this wallet' : '';- lines.push(- `#${i + 1} ${a.network || '?'} · ${a.scheme || 'exact'} · $${usd.toFixed(6)} ${shortAsset(a.asset)}${mark}`,- );+ lines.push(`#${i + 1} ${a.network || '?'} · ${a.scheme || 'exact'} · $${usd.toFixed(6)} ${tokenLabel(a)}${railTag}${mark}`);if (a.payTo) lines.push(` payTo: ${a.payTo}`);});if (!result.chosen) {- lines.push('', '⚠ No requirement this wallet can satisfy (needs an EVM EIP-3009 USDC accept).');+ lines.push(+ '',+ '⚠ No requirement this wallet can satisfy. This extension pays USDC EIP-3009 on EVM (Base + other chains) or the exact scheme in USDC/$THREE on Solana — set the matching wallet key.',+ );}return lines;}--function shortAsset(asset) {- if (!asset) return '';- return asset.length > 12 ? `${asset.slice(0, 6)}…${asset.slice(-4)}` : asset;-}diff --git a/packages/vscode-x402/src/pay.js b/packages/vscode-x402/src/pay.jsindex 269b26b63..69e98bc73 100644--- a/packages/vscode-x402/src/pay.js+++ b/packages/vscode-x402/src/pay.js@@ -1,19 +1,23 @@-// Pay-per-call flow. Pre-checks the 402 to show the exact USD amount, asks for-// confirmation (honouring the spend cap), then performs the real paid request-// with @three-ws/x402-fetch and surfaces the settlement receipt.+// Pay-per-call flow. Pre-checks the 402 to show the exact USD amount and token,+// asks for confirmation (honouring the spend cap), then performs the real paid+// request on the correct rail and surfaces the settlement receipt:+// • EVM accept → @three-ws/x402-fetch (USDC EIP-3009 on Base + other chains)+// • Solana accept → @x402/svm exact scheme (USDC or $THREE on Solana)import * as vscode from 'vscode';import { withX402, privateKeyToWallet } from '../../x402-fetch/src/index.js';import { amountToUsd } from '../../x402-fetch/src/parse-challenge.js';-import { getKey, setKey } from './wallet.js';-import { inspectEndpoint } from './inspect.js';+import { getKey, setKey, getSolanaKey, setSolanaKey } from './wallet.js';+import { inspectEndpoint, railOf } from './inspect.js';+import { buildSolanaPayingFetch, solanaAddressFromSecret, tokenLabel, isThreeAccept, isUsdcAccept } from './solana.js';function config() {const c = vscode.workspace.getConfiguration('threewsX402');return {maxPaymentUsd: c.get('maxPaymentUsd', 0.1),confirmEachPayment: c.get('confirmEachPayment', true),- network: c.get('network', 'eip155:8453'),+ network: c.get('network', ''), // '' = auto+ preferToken: c.get('preferToken', 'auto'),};}@@ -27,27 +31,38 @@ function decodeReceipt(res) {}}+function networkLabel(accept, rail) {+ if (rail === 'solana') return 'Solana';+ if (accept?.network === 'eip155:8453') return 'Base';+ return accept?.network || 'EVM';+}+/*** @param {{ url:string, method?:string, body?:string, serviceName?:string }} req- * @returns {Promise<{ ok:boolean, status:number, amountUsd:number|null, address:string, receipt:any, bodyText:string }|null>}+ * @returns {Promise<{ ok:boolean, status:number, amountUsd:number|null, address:string, token:string, network:string, receipt:any, bodyText:string }|null>}*/export async function payAndCall(context, req) {const cfg = config();- let pk = await getKey(context);- if (!pk) {+ let evmKey = await getKey(context);+ let solKey = await getSolanaKey(context);+ if (!evmKey && !solKey) {const choice = await vscode.window.showWarningMessage(- 'No wallet key set. Set one to pay for x402 endpoints?',- 'Set Wallet Key',+ 'No wallet key set. Set one to pay for x402 endpoints.',+ 'Set Solana key',+ 'Set EVM key','Cancel',);- if (choice !== 'Set Wallet Key') return null;- await setKey(context);- pk = await getKey(context);- if (!pk) return null;+ if (choice === 'Set Solana key') {+ await setSolanaKey(context);+ solKey = await getSolanaKey(context);+ } else if (choice === 'Set EVM key') {+ await setKey(context);+ evmKey = await getKey(context);+ } else return null;+ if (!evmKey && !solKey) return null;}- const { address } = privateKeyToWallet(pk);const method = (req.method || 'GET').toUpperCase();const init = { method, headers: { accept: 'application/json' } };if (req.body != null && method !== 'GET' && method !== 'HEAD') {@@ -55,55 +70,114 @@ export async function payAndCall(context, req) {init.body = req.body;}- // Pre-check the challenge so the confirmation shows a real amount.- const probe = await inspectEndpoint(req.url, { method, preferNetwork: cfg.network });+ // Pre-check the challenge, restricted to the rails we actually hold a key for.+ const probe = await inspectEndpoint(req.url, {+ method,+ preferNetwork: cfg.network || undefined,+ preferToken: cfg.preferToken,+ wallets: { evm: !!evmKey, solana: !!solKey },+ });+if (probe.status !== 402) {// Free or non-paid endpoint — just run it, no signing.const res = await fetch(req.url, init);- return finalize(res, { amountUsd: 0, address });+ return finalize(res, { amountUsd: 0, address: '', token: '', network: '' });}+if (!probe.chosen) {+ // Payable in principle by a rail whose key we don't have? Offer to set it.+ const inPrinciple = await inspectEndpoint(req.url, {+ method,+ preferNetwork: cfg.network || undefined,+ preferToken: cfg.preferToken,+ wallets: { evm: true, solana: true },+ });+ if (inPrinciple.chosen) {+ const needRail = railOf(inPrinciple.chosen);+ const label = needRail === 'solana' ? 'Solana' : 'EVM';+ const set = await vscode.window.showWarningMessage(+ `This endpoint is payable on ${needRail === 'solana' ? 'Solana' : 'an EVM network'}, but no ${label} wallet key is set.`,+ `Set ${label} key`,+ 'Cancel',+ );+ if (set === `Set ${label} key`) {+ if (needRail === 'solana') await setSolanaKey(context);+ else await setKey(context);+ return payAndCall(context, req); // retry now that a key exists+ }+ return null;+ }throw new Error(- 'This endpoint requires payment but offers no requirement this wallet can satisfy (needs USDC EIP-3009 on an EVM network).',+ 'This endpoint requires payment but offers no requirement this extension can satisfy (needs USDC EIP-3009 on an EVM network, or the exact scheme in USDC/$THREE on Solana).',);}- const amountUsd = amountToUsd(probe.chosen);+ const chosen = probe.chosen;+ const rail = probe.rail;+ const amountUsd = amountToUsd(chosen);+ const token = tokenLabel(chosen);+ const netLabel = networkLabel(chosen, rail);++ // Derive the paying address for the confirmation prompt.+ let address = '';+ if (rail === 'evm') {+ address = privateKeyToWallet(evmKey).address;+ } else if (rail === 'solana') {+ try {+ address = await solanaAddressFromSecret(solKey);+ } catch {+ /* shown without address if derivation fails */+ }+ }+if (amountUsd > cfg.maxPaymentUsd) {const raise = await vscode.window.showWarningMessage(- `This call costs $${amountUsd.toFixed(4)}, above your cap of $${cfg.maxPaymentUsd.toFixed(4)}.`,+ `This call costs $${amountUsd.toFixed(4)} (${token} on ${netLabel}), above your cap of $${cfg.maxPaymentUsd.toFixed(4)}.`,'Raise cap & pay','Cancel',);if (raise !== 'Raise cap & pay') return null;} else if (cfg.confirmEachPayment) {+ const from = address ? ` from ${short(address)}` : '';const go = await vscode.window.showInformationMessage(- `Pay $${amountUsd.toFixed(6)} from ${short(address)} to call ${req.serviceName || req.url}?`,+ `Pay $${amountUsd.toFixed(6)} in ${token} on ${netLabel}${from} to call ${req.serviceName || req.url}?`,{ modal: true },'Pay & call',);if (go !== 'Pay & call') return null;}- const paidFetch = withX402(pk, {- maxPaymentUsd: Math.max(cfg.maxPaymentUsd, amountUsd),- network: cfg.network,- });+ let paidFetch;+ if (rail === 'solana') {+ // Pin the paid token to the one we quoted so the receipt matches the prompt.+ const payToken =+ cfg.preferToken !== 'auto' ? cfg.preferToken : isThreeAccept(chosen) ? 'three' : isUsdcAccept(chosen) ? 'usdc' : 'auto';+ const built = await buildSolanaPayingFetch(solKey, { preferToken: payToken });+ paidFetch = built.payingFetch;+ address = built.address;+ } else {+ paidFetch = withX402(evmKey, {+ maxPaymentUsd: Math.max(cfg.maxPaymentUsd, amountUsd),+ network: chosen.network,+ });+ }const res = await vscode.window.withProgress(- { location: vscode.ProgressLocation.Notification, title: `Paying $${amountUsd.toFixed(6)} & calling…` },+ { location: vscode.ProgressLocation.Notification, title: `Paying $${amountUsd.toFixed(6)} in ${token} & calling…` },() => paidFetch(req.url, init),);- return finalize(res, { amountUsd, address });+ return finalize(res, { amountUsd, address, token, network: netLabel });}-async function finalize(res, { amountUsd, address }) {+async function finalize(res, { amountUsd, address, token, network }) {const bodyText = await res.text();return {ok: res.ok,status: res.status,amountUsd,address,+ token,+ network,receipt: decodeReceipt(res),bodyText,};diff --git a/packages/vscode-x402/src/solana.js b/packages/vscode-x402/src/solana.jsnew file mode 100644index 000000000..cdbd7241e--- /dev/null+++ b/packages/vscode-x402/src/solana.js@@ -0,0 +1,132 @@+// Solana x402 payer for the extension.+//+// Ports the real `@x402/svm` `exact`-scheme buyer used by @three-ws/x402-mcp so+// the extension can pay Solana services in USDC OR $THREE from a local keypair.+// Nothing is mocked: the 402 dance, the SPL transfer, and the settlement are all+// handled by the real `@x402/*` libraries. $THREE is the three.ws platform token+// on Solana, so paying it is just selecting that advertised `accept`.++import bs58 from 'bs58';++// Solana mainnet-beta CAIP-2 network id.+export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';++// $THREE — the three.ws platform token (Solana SPL).+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Canonical USDC mints we recognise (Solana + Base, lowercased for EVM).+const USDC_MINTS = new Set([+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // Solana+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // Base+]);++export function isSolanaNetwork(net) {+ return typeof net === 'string' && net.startsWith('solana:');+}++/** A Solana `exact`-scheme accept this signer can settle. */+export function isSolanaExactAccept(a) {+ return !!a && isSolanaNetwork(a.network) && (!a.scheme || a.scheme === 'exact');+}++/** True when an `accepts[]` entry settles in $THREE (by token name or mint). */+export function isThreeAccept(a) {+ const name = String(a?.extra?.name || '').trim().toUpperCase();+ return name === 'THREE' || String(a?.asset || '') === THREE_MINT;+}++/** True when an `accepts[]` entry settles in USDC (by token name or mint). */+export function isUsdcAccept(a) {+ const name = String(a?.extra?.name || '').trim().toUpperCase().replace('USD COIN', 'USDC');+ return name === 'USDC' || USDC_MINTS.has(String(a?.asset || '').toLowerCase());+}++/** Human token label for a requirement ($THREE / USDC / declared name). */+export function tokenLabel(a) {+ if (isThreeAccept(a)) return '$THREE';+ if (isUsdcAccept(a)) return 'USDC';+ const n = String(a?.extra?.name || '').trim();+ return n || 'token';+}++/** Narrow accepts to a preferred token; fail-open so a payment still settles. */+function filterAcceptsByToken(accepts, token) {+ if (!Array.isArray(accepts) || !token || token === 'auto') return Array.isArray(accepts) ? accepts : [];+ const want = String(token).toLowerCase();+ const matches = accepts.filter((a) => (want === 'three' ? isThreeAccept(a) : want === 'usdc' ? isUsdcAccept(a) : true));+ return matches.length ? matches : accepts;+}++// A fetch that rewrites a 402 challenge's `accepts` down to the preferred token+// BEFORE the payment layer reads it, so the exact scheme signs that asset.+function makeTokenFilteringFetch(token) {+ return async (input, init) => {+ const res = await globalThis.fetch(input, init);+ if (res.status !== 402) return res;+ let body;+ try {+ body = await res.clone().json();+ } catch {+ return res;+ }+ if (!body || !Array.isArray(body.accepts)) return res;+ const filtered = filterAcceptsByToken(body.accepts, token);+ if (filtered === body.accepts || filtered.length === body.accepts.length) return res;+ body.accepts = filtered;+ const headers = new Headers(res.headers);+ headers.delete('content-length');+ return new Response(JSON.stringify(body), { status: 402, statusText: res.statusText, headers });+ };+}++/** base58 string OR JSON byte array → raw secret-key bytes. Throws on bad input. */+export function solanaSecretBytes(secret) {+ const s = String(secret || '').trim();+ if (!s) throw new Error('No Solana signer configured.');+ if (s.startsWith('[')) {+ let arr;+ try {+ arr = JSON.parse(s);+ } catch {+ throw new Error('Solana key looks like a JSON array but failed to parse.');+ }+ return Uint8Array.from(arr);+ }+ try {+ return bs58.decode(s);+ } catch {+ throw new Error('Solana key must be a base58 string or a JSON byte array.');+ }+}++/** Validate a Solana secret and return its base58 address (throws if invalid). */+export async function solanaAddressFromSecret(secret) {+ const { createKeyPairSignerFromBytes } = await import('@solana/kit');+ const signer = await createKeyPairSignerFromBytes(solanaSecretBytes(secret));+ return String(signer.address);+}++/**+ * Build a payment-aware fetch bound to a Solana keypair, settling the `exact`+ * SVM scheme. `preferToken` ('usdc' | 'three' | 'auto') narrows which advertised+ * accept is paid before the payment layer selects one.+ *+ * @param {string} secret base58 secret key or JSON byte array+ * @param {{ preferToken?: 'usdc'|'three'|'auto' }} [opts]+ * @returns {Promise<{ payingFetch: typeof fetch, address: string }>}+ */+export async function buildSolanaPayingFetch(secret, opts = {}) {+ const [{ x402Client }, { ExactSvmScheme }, { wrapFetchWithPayment }, { createKeyPairSignerFromBytes }] =+ await Promise.all([+ import('@x402/core/client'),+ import('@x402/svm/exact/client'),+ import('@x402/fetch'),+ import('@solana/kit'),+ ]);+ const signer = await createKeyPairSignerFromBytes(solanaSecretBytes(secret));+ const client = new x402Client();+ client.register('solana:*', new ExactSvmScheme(signer));+ const base = opts.preferToken && opts.preferToken !== 'auto' ? makeTokenFilteringFetch(opts.preferToken) : globalThis.fetch;+ const payingFetch = wrapFetchWithPayment(base, client);+ return { payingFetch, address: String(signer.address) };+}diff --git a/packages/vscode-x402/src/wallet.js b/packages/vscode-x402/src/wallet.jsindex 04c081269..37b73cdcc 100644--- a/packages/vscode-x402/src/wallet.js+++ b/packages/vscode-x402/src/wallet.js@@ -1,12 +1,20 @@-// Wallet key handling. The EVM private key lives ONLY in VS Code SecretStorage-// (OS keychain) — never in settings.json, never on disk in plaintext. From the-// key we derive the public address with the bundled, zero-dep signer so we can-// show the user which account they're paying from.+// Wallet key handling. Private keys live ONLY in VS Code SecretStorage (the OS+// keychain), never in settings.json, never on disk in plaintext. The extension+// holds two independent, optional keys so it can pay on both rails:+// • an EVM key → USDC EIP-3009 on Base and other EVM chains+// • a Solana key → USDC or $THREE (SPL, `exact` scheme) on Solana+// From each key we derive the public address so we can show which account pays.import * as vscode from 'vscode';import { privateKeyToWallet } from '../../x402-fetch/src/index.js';+import { solanaAddressFromSecret } from './solana.js';-const SECRET_KEY = 'threewsX402.walletPrivateKey';+const SECRET_EVM = 'threewsX402.walletPrivateKey';+const SECRET_SOL = 'threewsX402.solanaSecretKey';++// ---------------------------------------------------------------------------+// EVM+// ---------------------------------------------------------------------------function normalizePk(raw) {const pk = raw.trim();@@ -19,36 +27,30 @@ function normalizePk(raw) {/** Prompt for and store an EVM private key. Returns the derived address. */export async function setKey(context) {const raw = await vscode.window.showInputBox({- title: 'x402 — Set Wallet Key',+ title: 'x402: Set EVM Wallet Key',prompt: 'EVM private key (0x + 64 hex). Stored in the OS keychain, never in settings or files.',password: true,ignoreFocusOut: true,validateInput(value) {if (!value) return 'Required';- return /^0x[0-9a-fA-F]{64}$/.test(value.trim())- ? null- : 'Must be 0x followed by 64 hex characters';+ return /^0x[0-9a-fA-F]{64}$/.test(value.trim()) ? null : 'Must be 0x followed by 64 hex characters';},});if (!raw) return null;const pk = normalizePk(raw);- // Validate it derives a real address before persisting.- const { address } = privateKeyToWallet(pk);- await context.secrets.store(SECRET_KEY, pk);+ const { address } = privateKeyToWallet(pk); // validate it derives before persisting+ await context.secrets.store(SECRET_EVM, pk);return address;}-/** Remove the stored key. */export async function clearKey(context) {- await context.secrets.delete(SECRET_KEY);+ await context.secrets.delete(SECRET_EVM);}-/** The stored private key, or null. */export async function getKey(context) {- return (await context.secrets.get(SECRET_KEY)) || null;+ return (await context.secrets.get(SECRET_EVM)) || null;}-/** Derived address for the stored key, or null if none set. */export async function getAddress(context) {const pk = await getKey(context);if (!pk) return null;@@ -58,3 +60,49 @@ export async function getAddress(context) {return null;}}++// ---------------------------------------------------------------------------+// Solana+// ---------------------------------------------------------------------------++/** Prompt for and store a Solana secret key. Returns the derived address. */+export async function setSolanaKey(context) {+ const raw = await vscode.window.showInputBox({+ title: 'x402: Set Solana Wallet Key',+ prompt: 'Solana secret key (base58, or a JSON byte array). Stored in the OS keychain, never in settings or files.',+ password: true,+ ignoreFocusOut: true,+ validateInput(value) {+ return value && value.trim() ? null : 'Required';+ },+ });+ if (!raw) return null;+ const secret = raw.trim();+ let address;+ try {+ address = await solanaAddressFromSecret(secret); // validate before persisting+ } catch (e) {+ vscode.window.showErrorMessage(`Invalid Solana key: ${e?.message || e}`);+ return null;+ }+ await context.secrets.store(SECRET_SOL, secret);+ return address;+}++export async function clearSolanaKey(context) {+ await context.secrets.delete(SECRET_SOL);+}++export async function getSolanaKey(context) {+ return (await context.secrets.get(SECRET_SOL)) || null;+}++export async function getSolanaAddress(context) {+ const secret = await getSolanaKey(context);+ if (!secret) return null;+ try {+ return await solanaAddressFromSecret(secret);+ } catch {+ return null;+ }+}