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: x402 hardening, x scheduled posts, portfolio snapshots, dashboard polish
nirholas6988634359e3
diff --git a/agent-payments-sdk/src/solana/x402/client.ts b/agent-payments-sdk/src/solana/x402/client.tsindex 1b8c3b955..e3ccde9c7 100644--- a/agent-payments-sdk/src/solana/x402/client.ts+++ b/agent-payments-sdk/src/solana/x402/client.ts@@ -7,7 +7,7 @@** A fetch wrapper that intercepts HTTP 402 responses, builds and signs* a payment transaction matching the server's PaymentRequirements, and- * retries the request with a PAYMENT-SIGNATURE header.+ * retries the request with an X-PAYMENT header.** Supports both "pump-agent" (Pump Agent invoice) and "exact" (SPL* TransferChecked) schemes.@@ -40,7 +40,7 @@ import type {ExactPaymentRequirements,} from "./types";import {- X402_HEADER_PAYMENT_SIGNATURE,+ X402_HEADER_PAYMENT,X402_VERSION,SOLANA_MAINNET,} from "./types";@@ -97,7 +97,7 @@ export function createX402Fetch(if (response.status !== 402) return response;- const paymentRequired = getPaymentRequiredFromResponse(response);+ const paymentRequired = await getPaymentRequiredFromResponse(response);if (!paymentRequired) return response;// Find a compatible requirement@@ -114,18 +114,29 @@ export function createX402Fetch(confirmationTimeoutMs,);- // Build the PaymentPayload+ // Build the PaymentPayload. Top-level scheme/network match the chosen+ // `accepts[]` entry so the server's verify() can route the proof without+ // re-walking `accepted` — this matches the Coinbase v2 wire shape.+ const resourceUrl =+ paymentRequired.resource.url ||+ (typeof input === "string"+ ? input+ : input instanceof URL+ ? input.href+ : input.url);const paymentPayload: PaymentPayload = {x402Version: X402_VERSION,- resource: typeof input === "string" ? input : input instanceof URL ? input.href : input.url,+ scheme: accepted.scheme,+ network: accepted.network,+ resource: resourceUrl,accepted,payload: proof,};- // Retry the original request with PAYMENT-SIGNATURE header+ // Retry the original request with X-PAYMENT headerconst retryInit: RequestInit = { ...init };const headers = new Headers(retryInit.headers);- headers.set(X402_HEADER_PAYMENT_SIGNATURE, encodePaymentPayload(paymentPayload));+ headers.set(X402_HEADER_PAYMENT, encodePaymentPayload(paymentPayload));retryInit.headers = headers;return fetch(input, retryInit);diff --git a/agent-payments-sdk/src/solana/x402/facilitator.ts b/agent-payments-sdk/src/solana/x402/facilitator.tsindex 2e5d1462f..4017a4513 100644--- a/agent-payments-sdk/src/solana/x402/facilitator.ts+++ b/agent-payments-sdk/src/solana/x402/facilitator.ts@@ -36,8 +36,8 @@ import type {} from "./types";import {X402_VERSION,+ X402_HEADER_PAYMENT,X402_HEADER_PAYMENT_REQUIRED,- X402_HEADER_PAYMENT_SIGNATURE,X402_HEADER_PAYMENT_RESPONSE,SOLANA_MAINNET,USDC_MAINNET,@@ -264,8 +264,9 @@ export function buildPumpAgentRequirements(/*** Creates a handler wrapper that implements the x402 Resource Server role.*- * On requests without PAYMENT-SIGNATURE: returns 402 with PAYMENT-REQUIRED.- * On requests with PAYMENT-SIGNATURE: verifies → settles → forwards to handler.+ * On requests without X-PAYMENT: returns 402 with PaymentRequired body+ * (mirrored as the `payment-required` header for Bazaar inspection).+ * On requests with X-PAYMENT: verifies → settles → forwards to handler.** Works with any framework using the standard Request/Response API* (Hono, Next.js App Router, Cloudflare Workers, Bun, Deno, etc.).@@ -300,7 +301,7 @@ export function createResourceServer(request: Request,handler: () => Response | Promise<Response>,): Promise<Response> => {- const paymentHeader = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);+ const paymentHeader = request.headers.get(X402_HEADER_PAYMENT);if (!paymentHeader) {// Build fresh requirements (with new invoice memos)@@ -325,7 +326,7 @@ export function createResourceServer(try {paymentPayload = decodePaymentPayload(paymentHeader);} catch {- return new Response("Invalid PAYMENT-SIGNATURE header", { status: 400 });+ return new Response("Invalid X-PAYMENT header", { status: 400 });}// Find the matching requirement@@ -360,7 +361,7 @@ export function createResourceServer(// Invoke the actual handlerconst finalResponse = await handler();- // Attach PAYMENT-RESPONSE header to the success response+ // Attach X-PAYMENT-RESPONSE header to the success responseconst paymentResponse: PaymentResponse = {success: true,transaction: settleResult.transaction,diff --git a/agent-payments-sdk/src/solana/x402/headers.ts b/agent-payments-sdk/src/solana/x402/headers.tsindex 980376741..fedb76e4a 100644--- a/agent-payments-sdk/src/solana/x402/headers.ts+++ b/agent-payments-sdk/src/solana/x402/headers.ts@@ -3,14 +3,16 @@// All rights reserved./**- * x402 v2 Header encoding / decoding+ * x402 v2 wire encoding / decoding.*- * Standard headers (per coinbase/x402 v2 spec):- * PAYMENT-REQUIRED – server → client (402 response)- * PAYMENT-SIGNATURE – client → server (retry request)- * PAYMENT-RESPONSE – server → client (200 after settlement)+ * Coinbase x402 v2 wire format:+ * - Request: `X-PAYMENT: <base64(JSON PaymentPayload)>`+ * - 402 response: PaymentRequired struct as `application/json` body;+ * mirrored as base64 in the `payment-required` header for+ * header-only inspection (Bazaar crawlers).+ * - Settled reply: `X-PAYMENT-RESPONSE: <base64(JSON PaymentResponse)>`*- * All values are base64-encoded JSON.+ * All header values are base64-encoded JSON.*/import type {@@ -19,8 +21,8 @@ import type {PaymentResponse,} from "./types";import {+ X402_HEADER_PAYMENT,X402_HEADER_PAYMENT_REQUIRED,- X402_HEADER_PAYMENT_SIGNATURE,X402_HEADER_PAYMENT_RESPONSE,} from "./types";@@ -53,32 +55,51 @@ export function decodePaymentResponse(headerValue: string): PaymentResponse {// ─── Request / Response helpers ─────────────────────────────────────────────/**- * Extract PAYMENT-REQUIRED from a 402 Response.- * Returns null if not a 402 or header is missing.+ * Extract PaymentRequired from a 402 Response.+ *+ * v2 servers carry the struct in the JSON body; some also mirror it as a+ * base64 `payment-required` header. Reads body first, falls back to the+ * header for header-only inspection paths. Returns null when not a 402 or+ * neither location is parseable.+ *+ * The response body is consumed when this returns a body-decoded result —+ * callers needing the raw response stream should pass a cloned Response.*/-export function getPaymentRequiredFromResponse(+export async function getPaymentRequiredFromResponse(response: Response,-): PaymentRequired | null {+): Promise<PaymentRequired | null> {if (response.status !== 402) return null;+ const contentType = (response.headers.get("content-type") || "").toLowerCase();+ if (contentType.includes("application/json")) {+ try {+ return (await response.clone().json()) as PaymentRequired;+ } catch {+ // fall through to header+ }+ }const raw = response.headers.get(X402_HEADER_PAYMENT_REQUIRED);if (!raw) return null;- return decodePaymentRequired(raw);+ try {+ return decodePaymentRequired(raw);+ } catch {+ return null;+ }}/**- * Extract PAYMENT-SIGNATURE from a Request.+ * Extract the X-PAYMENT payload from a Request.* Returns null if header is missing.*/export function getPaymentPayloadFromRequest(request: Request,): PaymentPayload | null {- const raw = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);+ const raw = request.headers.get(X402_HEADER_PAYMENT);if (!raw) return null;return decodePaymentPayload(raw);}/**- * Extract PAYMENT-RESPONSE from a Response.+ * Extract X-PAYMENT-RESPONSE from a Response.* Returns null if header is missing.*/export function getPaymentResponseFromResponse(diff --git a/agent-payments-sdk/src/solana/x402/index.ts b/agent-payments-sdk/src/solana/x402/index.tsindex 457ec1e45..bd2be19e8 100644--- a/agent-payments-sdk/src/solana/x402/index.ts+++ b/agent-payments-sdk/src/solana/x402/index.ts@@ -38,8 +38,8 @@ export type {} from "./types";export {X402_VERSION,+ X402_HEADER_PAYMENT,X402_HEADER_PAYMENT_REQUIRED,- X402_HEADER_PAYMENT_SIGNATURE,X402_HEADER_PAYMENT_RESPONSE,SOLANA_MAINNET,SOLANA_DEVNET,diff --git a/agent-payments-sdk/src/solana/x402/types.ts b/agent-payments-sdk/src/solana/x402/types.tsindex 8d622bdab..d9502c1d4 100644--- a/agent-payments-sdk/src/solana/x402/types.ts+++ b/agent-payments-sdk/src/solana/x402/types.ts@@ -16,10 +16,20 @@export const X402_VERSION = 2;-/** Standard x402 header names (v2 spec) */-export const X402_HEADER_PAYMENT_REQUIRED = "PAYMENT-REQUIRED";-export const X402_HEADER_PAYMENT_SIGNATURE = "PAYMENT-SIGNATURE";-export const X402_HEADER_PAYMENT_RESPONSE = "PAYMENT-RESPONSE";+/**+ * Standard x402 header names (Coinbase v2 wire spec).+ *+ * X-PAYMENT – client → server, retry request with payment proof+ * X-PAYMENT-RESPONSE – server → client, settlement receipt on the success reply+ *+ * The 402 response carries the PaymentRequired struct in the response **body**+ * (`application/json`). Some servers also expose it base64-encoded as the+ * `payment-required` response header for header-only inspection by Bazaar+ * crawlers — read the body first, fall back to the header.+ */+export const X402_HEADER_PAYMENT = "X-PAYMENT";+export const X402_HEADER_PAYMENT_RESPONSE = "X-PAYMENT-RESPONSE";+export const X402_HEADER_PAYMENT_REQUIRED = "payment-required";/** CAIP-2 network identifiers for Solana */export const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";@@ -101,13 +111,17 @@ export interface PaymentRequired {accepts: PaymentRequirements[];}-// ─── Payment Payload (client → server proof in PAYMENT-SIGNATURE) ───────────+// ─── Payment Payload (client → server proof in X-PAYMENT header) ───────────export interface PaymentPayload {x402Version: 2;+ /** Payment scheme (matches one of the `accepts[]` entries) */+ scheme: PaymentScheme;+ /** CAIP-2 network identifier (matches the chosen `accepts[]` entry) */+ network: string;/** The resource URL this payment is for */resource?: string;- /** Which accepted scheme/requirements this payment matches */+ /** Which accepted scheme/requirements this payment matches (full entry) */accepted: PaymentRequirements;/** Scheme-specific proof data */payload: Record<string, unknown>;@@ -158,7 +172,7 @@ export interface FacilitatorClient {getSupported(): Promise<SupportedResponse>;}-// ─── Payment Response (server → client via PAYMENT-RESPONSE header) ─────────+// ─── Payment Response (server → client via X-PAYMENT-RESPONSE header) ──────export interface PaymentResponse {success: boolean;diff --git a/agent-payments-sdk/src/x402/evm-facilitator.ts b/agent-payments-sdk/src/x402/evm-facilitator.tsindex ecb245806..ce62b2b72 100644--- a/agent-payments-sdk/src/x402/evm-facilitator.ts+++ b/agent-payments-sdk/src/x402/evm-facilitator.ts@@ -55,7 +55,7 @@ export interface EvmPaymentVerificationResult {export async function verifyEvmPayment(params: VerifyEvmPaymentParams): Promise<EvmPaymentVerificationResult> {- const { proof, expectedMemo, minAmountUsdc, agentMint: _agentMint } = params;+ const { proof, expectedMemo, minAmountUsdc, agentMint } = params;if (proof.scheme !== "pump-agent-evm") {return { valid: false, error: "Unknown payment scheme" };@@ -65,16 +65,39 @@ export async function verifyEvmPayment(return { valid: false, error: "Memo mismatch" };}- // Fetch the deposit record from Pump.fun API using the quoteId / txHash+ // Fetch the deposit record from Pump.fun API using the quoteId / txHash.+ // The deposit response must echo back the Solana agent mint that the quote+ // was created against so we can re-verify the payer didn't reuse a deposit+ // destined for a different agent.let depositId: string;try {const res = await fetch(`${PUMP_CROSSCHAIN_API}/deposit?txHash=${proof.txHash}&chainId=${proof.chainId}`);if (!res.ok) throw new Error(`Deposit lookup failed (${res.status})`);- const data: { depositId: string; amountUsdc: string } = await res.json();+ const data: {+ depositId: string;+ amountUsdc: string;+ agentMint?: string;+ } = await res.json();depositId = data.depositId;+ if (!data.agentMint) {+ return {+ valid: false,+ depositId,+ error:+ "Deposit lookup did not return agentMint — cannot verify the deposit is bound to this agent",+ };+ }+ if (data.agentMint !== agentMint) {+ return {+ valid: false,+ depositId,+ error: `Agent mint mismatch: deposit is for ${data.agentMint}, this endpoint sells ${agentMint}`,+ };+ }+const confirmedAmount = BigInt(data.amountUsdc);if (confirmedAmount < minAmountUsdc) {return {diff --git a/api/_lib/balances.js b/api/_lib/balances.jsnew file mode 100644index 000000000..7859ec33f--- /dev/null+++ b/api/_lib/balances.js@@ -0,0 +1,250 @@+// Live on-chain balance + USD-price helpers, shared by /api/wallet/balances and+// /api/portfolio. Server-side memoizes results per (chain, address) for 60s to+// shield upstream RPCs and CoinGecko from per-page-load fan-out.++const RPC_CACHE_TTL_MS = 60_000;+const _cache = new Map(); // key: `${chain}:${address}` → { at, value }++function cacheGet(key) {+ const hit = _cache.get(key);+ if (!hit) return null;+ if (Date.now() - hit.at > RPC_CACHE_TTL_MS) {+ _cache.delete(key);+ return null;+ }+ return hit.value;+}+function cacheSet(key, value) {+ _cache.set(key, { at: Date.now(), value });+}++async function fetchJson(url, opts = {}) {+ const r = await fetch(url, opts);+ if (!r.ok) {+ const text = await r.text().catch(() => r.status.toString());+ throw Object.assign(new Error(`upstream ${r.status}: ${text}`), { status: 502 });+ }+ return r.json();+}++async function getSolanaBalances(address) {+ const heliusKey = process.env.HELIUS_API_KEY;+ if (!heliusKey) {+ const e = new Error('not_configured: HELIUS_API_KEY');+ e.status = 503;+ e.code = 'not_configured';+ e.missing = 'HELIUS_API_KEY';+ throw e;+ }++ const rpcUrl = `https://mainnet.helius-rpc.com/?api-key=${heliusKey}`;++ const solResp = await fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address] }),+ });+ const lamports = solResp.result?.value ?? 0;+ const solAmount = lamports / 1e9;++ const tokenResp = await fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 2,+ method: 'getTokenAccountsByOwner',+ params: [+ address,+ { programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' },+ { encoding: 'jsonParsed' },+ ],+ }),+ });++ const tokenAccounts = tokenResp.result?.value ?? [];+ const fungible = tokenAccounts+ .map((a) => {+ const info = a.account?.data?.parsed?.info;+ if (!info) return null;+ const { mint, tokenAmount } = info;+ if (!tokenAmount || tokenAmount.uiAmount === 0) return null;+ return { mint, amount: tokenAmount.uiAmount, decimals: tokenAmount.decimals };+ })+ .filter(Boolean)+ .sort((a, b) => b.amount - a.amount)+ .slice(0, 9);++ const mintList = fungible.map((t) => t.mint).join(',');+ let cgTokenPrices = {};+ if (mintList) {+ try {+ cgTokenPrices = await fetchJson(+ `https://api.coingecko.com/api/v3/simple/token_price/solana?contract_addresses=${mintList}&vs_currencies=usd`,+ );+ } catch {+ // best-effort+ }+ }++ let solUsdPrice = 0;+ try {+ const cgSol = await fetchJson(+ 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd',+ );+ solUsdPrice = cgSol?.solana?.usd ?? 0;+ } catch {+ // best-effort+ }++ const tokens = [];+ for (const t of fungible) {+ const price = cgTokenPrices[t.mint.toLowerCase()]?.usd ?? 0;+ let symbol = t.mint.slice(0, 6);+ let logo = null;+ try {+ const das = await fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'meta',+ method: 'getAsset',+ params: { id: t.mint },+ }),+ });+ symbol = das.result?.content?.metadata?.symbol || symbol;+ logo = das.result?.content?.links?.image || null;+ } catch {+ // metadata is best-effort+ }+ tokens.push({ symbol, mint: t.mint, decimals: t.decimals, amount: t.amount, usd: t.amount * price, logo });+ }++ return {+ chain: 'solana',+ address,+ native: { symbol: 'SOL', amount: solAmount, usd: solAmount * solUsdPrice },+ tokens,+ };+}++async function getEvmBalances(address) {+ const alchemyKey = process.env.ALCHEMY_API_KEY;+ if (!alchemyKey) {+ const e = new Error('not_configured: ALCHEMY_API_KEY');+ e.status = 503;+ e.code = 'not_configured';+ e.missing = 'ALCHEMY_API_KEY';+ throw e;+ }++ const rpcUrl = `https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`;++ const ethBalResp = await fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'eth_getBalance',+ params: [address, 'latest'],+ }),+ });+ const ethWei = BigInt(ethBalResp.result ?? '0x0');+ const ethAmount = Number(ethWei) / 1e18;++ const tokenBalResp = await fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 2,+ method: 'alchemy_getTokenBalances',+ params: [address],+ }),+ });++ const rawTokens = (tokenBalResp.result?.tokenBalances ?? [])+ .filter((t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x')+ .slice(0, 9);++ const metadataResults = await Promise.allSettled(+ rawTokens.map((t) =>+ fetchJson(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'meta',+ method: 'alchemy_getTokenMetadata',+ params: [t.contractAddress],+ }),+ }),+ ),+ );++ const contractList = rawTokens.map((t) => t.contractAddress).join(',');+ let cgTokenPrices = {};+ if (contractList) {+ try {+ cgTokenPrices = await fetchJson(+ `https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=${contractList}&vs_currencies=usd`,+ );+ } catch {+ // best-effort+ }+ }++ let ethUsdPrice = 0;+ try {+ const cgEth = await fetchJson(+ 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',+ );+ ethUsdPrice = cgEth?.ethereum?.usd ?? 0;+ } catch {+ // best-effort+ }++ const tokens = rawTokens.map((t, i) => {+ const meta = metadataResults[i].status === 'fulfilled' ? metadataResults[i].value?.result : null;+ const decimals = meta?.decimals ?? 18;+ const rawBal = BigInt(t.tokenBalance || '0x0');+ const amount = Number(rawBal) / Math.pow(10, decimals);+ const price = cgTokenPrices[t.contractAddress.toLowerCase()]?.usd ?? 0;+ return {+ symbol: meta?.symbol || t.contractAddress.slice(0, 8),+ contract: t.contractAddress,+ decimals,+ amount,+ usd: amount * price,+ logo: meta?.logo || null,+ };+ });++ return {+ chain: 'evm',+ address,+ native: { symbol: 'ETH', amount: ethAmount, usd: ethAmount * ethUsdPrice },+ tokens,+ };+}++export async function getBalances({ chain, address }) {+ const key = `${chain}:${address}`;+ const cached = cacheGet(key);+ if (cached) return cached;+ const value = chain === 'solana' ? await getSolanaBalances(address) : await getEvmBalances(address);+ cacheSet(key, value);+ return value;+}++export function invalidateBalances({ chain, address }) {+ _cache.delete(`${chain}:${address}`);+}++export function walletUsdTotal(balances) {+ const nativeUsd = balances?.native?.usd ?? 0;+ const tokensUsd = (balances?.tokens ?? []).reduce((s, t) => s + (t.usd ?? 0), 0);+ return nativeUsd + tokensUsd;+}diff --git a/api/_lib/migrations/2026-05-13-portfolio-snapshots.sql b/api/_lib/migrations/2026-05-13-portfolio-snapshots.sqlnew file mode 100644index 000000000..7d3d67b6d--- /dev/null+++ b/api/_lib/migrations/2026-05-13-portfolio-snapshots.sql@@ -0,0 +1,16 @@+-- Portfolio value snapshots. The dashboard's portfolio page writes one row each+-- time the user hits "Refresh". Chart reads the trailing N days for that user.+--+-- Writes are user-driven (not a cron), so the table grows O(refreshes) — not+-- O(users × time). Index supports the per-user trailing-window read.++create table if not exists portfolio_snapshots (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ captured_at timestamptz not null default now(),+ total_usd numeric(20, 4) not null,+ breakdown jsonb not null default '[]'::jsonb+);++create index if not exists portfolio_snapshots_user_time+ on portfolio_snapshots(user_id, captured_at desc);diff --git a/api/_lib/migrations/2026-05-13-x-scheduled-posts.sql b/api/_lib/migrations/2026-05-13-x-scheduled-posts.sqlnew file mode 100644index 000000000..9550cd189--- /dev/null+++ b/api/_lib/migrations/2026-05-13-x-scheduled-posts.sql@@ -0,0 +1,22 @@+-- Scheduled X posts. Cron runs every minute and publishes due posts that+-- belong to a still-connected social_connection and aren't over quota.++create table if not exists x_scheduled_posts (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id text,+ text text not null,+ scheduled_at timestamptz not null,+ posted_at timestamptz,+ tweet_id text,+ error text,+ attempts int not null default 0,+ created_at timestamptz not null default now()+);++create index if not exists x_scheduled_due_idx+ on x_scheduled_posts(scheduled_at)+ where posted_at is null and error is null;++create index if not exists x_scheduled_user_idx+ on x_scheduled_posts(user_id, scheduled_at desc);diff --git a/api/_lib/x-post.js b/api/_lib/x-post.jsnew file mode 100644index 000000000..1e965f23b--- /dev/null+++ b/api/_lib/x-post.js@@ -0,0 +1,127 @@+// Internal helper: publish a tweet on behalf of a three.ws user whose X+// account is connected. Handles token refresh, quota check, dedup, and logging.+// Used by api/x/post.js (manual) and the scheduled-posts cron job.++import { sql } from './db.js';+import { env } from './env.js';+import { encryptToken, decryptToken } from '../auth/x/[action].js';++export const FREE_MONTHLY_QUOTA = 5;+export const MAX_TWEET_LEN = 280;+export const DEDUP_WINDOW_DAYS = 7;++class XPostError extends Error {+ constructor(code, message, status = 400, extra = {}) {+ super(message);+ this.code = code;+ this.status = status;+ this.extra = extra;+ }+}++async function refreshIfNeeded(conn) {+ const expiresAt = conn.expires_at ? new Date(conn.expires_at).getTime() : 0;+ if (expiresAt - Date.now() > 60_000) return decryptToken(conn.access_token);+ if (!conn.refresh_token) throw new XPostError('reauth_required', 'refresh_token missing — reconnect X account', 401);++ const refreshToken = decryptToken(conn.refresh_token);+ const creds = Buffer.from(`${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`).toString('base64');+ const r = await fetch('https://api.twitter.com/2/oauth2/token', {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded', authorization: `Basic ${creds}` },+ body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: env.X_OAUTH_CLIENT_ID }).toString(),+ });+ if (!r.ok) throw new XPostError('reauth_required', `X token refresh failed: ${await r.text()}`, 401);+ const tok = await r.json();+ const newExpiresAt = new Date(Date.now() + (tok.expires_in ?? 7200) * 1000).toISOString();+ await sql`+ update social_connections+ set access_token = ${encryptToken(tok.access_token)},+ refresh_token = ${tok.refresh_token ? encryptToken(tok.refresh_token) : conn.refresh_token},+ expires_at = ${newExpiresAt},+ updated_at = now()+ where id = ${conn.id}+ `;+ return tok.access_token;+}++export async function publishTweet({ userId, agentId = null, text }) {+ if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {+ throw new XPostError('not_configured', 'X OAuth is not configured', 501);+ }+ const trimmed = String(text || '').trim();+ if (!trimmed) throw new XPostError('validation_error', 'text required', 400);+ if (trimmed.length > MAX_TWEET_LEN) throw new XPostError('validation_error', `text exceeds ${MAX_TWEET_LEN} chars`, 400);++ const rows = await sql`+ select * from social_connections+ where user_id = ${userId} and provider = 'x' and disconnected_at is null+ limit 1+ `;+ const conn = rows[0];+ if (!conn) throw new XPostError('not_connected', 'X account not connected', 400);++ // Reset monthly counter if we crossed the boundary.+ if (new Date(conn.month_resets_at) <= new Date()) {+ await sql`+ update social_connections+ set posts_this_month = 0,+ month_resets_at = date_trunc('month', now()) + interval '1 month'+ where id = ${conn.id}+ `;+ conn.posts_this_month = 0;+ }++ if (conn.posts_this_month >= FREE_MONTHLY_QUOTA) {+ throw new XPostError('quota_exceeded', `free tier limit of ${FREE_MONTHLY_QUOTA} posts/month reached`, 402, {+ posts_used: conn.posts_this_month,+ quota: FREE_MONTHLY_QUOTA,+ month_resets_at: conn.month_resets_at,+ upgrade_url: '/pricing',+ });+ }++ // Dedup — refuse identical text within the window. Prevents X suspension+ // from repetitive content patterns.+ const dup = await sql`+ select 1 from x_posts+ where user_id = ${userId} and text = ${trimmed}+ and created_at > now() - ${`${DEDUP_WINDOW_DAYS} days`}::interval+ limit 1+ `;+ if (dup.length) throw new XPostError('duplicate', `same text posted within the last ${DEDUP_WINDOW_DAYS} days`, 409);++ const accessToken = await refreshIfNeeded(conn);++ const tweetRes = await fetch('https://api.twitter.com/2/tweets', {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${accessToken}` },+ body: JSON.stringify({ text: trimmed }),+ });+ if (!tweetRes.ok) {+ const detail = await tweetRes.text();+ throw new XPostError('tweet_failed', `X API error: ${detail.slice(0, 200)}`, 502);+ }+ const { data } = await tweetRes.json();++ await sql`+ update social_connections+ set posts_this_month = posts_this_month + 1,+ updated_at = now()+ where id = ${conn.id}+ `;+ await sql`+ insert into x_posts (user_id, agent_id, tweet_id, text)+ values (${userId}, ${agentId}, ${data.id}, ${trimmed})+ `;++ return {+ tweet_id: data.id,+ url: `https://x.com/${conn.username}/status/${data.id}`,+ username: conn.username,+ posts_used: conn.posts_this_month + 1,+ quota: FREE_MONTHLY_QUOTA,+ };+}++export { XPostError };diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex 39c3ca36f..53b181b6d 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -206,7 +206,7 @@ export async function probeFacilitators() {try {const probeUrl = `${t.url}/supported`;const headers = { accept: 'application/json' };- if (t.kind === 'cdp') headers.authorization = cdpAuthHeader('GET', probeUrl);+ if (t.token) headers.authorization = `Bearer ${t.token}`;const res = await fetch(probeUrl, {headers,signal: AbortSignal.timeout(10_000),diff --git a/api/_lib/x402.js b/api/_lib/x402.jsindex 6aaf6b934..db2e87dd2 100644--- a/api/_lib/x402.js+++ b/api/_lib/x402.js@@ -1,10 +1,18 @@/**- * x402 — HTTP 402 Payment Required helpers.+ * Pump.fun agent-skill HTTP 402 manifest helpers.*- * Spec: https://x402.org (in flux as of 2026-04). We implement a minimal- * subset that matches the Coinbase x402 client and our internal payment- * pipeline (Pump.fun agent-payments-sdk).+ * NOTE: this module is NOT the Coinbase x402 v2 wire spec — that lives in+ * `api/_lib/x402-spec.js`. This file implements an internal Pump.fun+ * agent-skill payment flow that *also* uses HTTP 402 as the negotiation+ * status, but with its own manifest format (`version: "x402/0.1"`,+ * `kind: "agent-skill"`), retry header (`x-payment-intent`), and+ * server-side payment pipeline (`/api/agents/payments/pay-prep` ++ * `/pay-confirm`). The two flows are deliberately separate.*+ * Used by /api/agents/x402/[action].js (invoke + manifest) for per-skill+ * billing on agent-hosted skills.+ *+* Server-side flow:* 1. Caller hits a paid endpoint.* 2. We look for a payment proof header (x-payment-intent or@@ -140,14 +148,6 @@ export async function consumeIntent(intentId) {`;}-/**- * Emit a structured response that mixes 402 manifests with normal JSON when- * the caller advertises support via `Accept: application/x402+json`.- * Currently a no-op alias for emit402 — kept as a hook for future content- * negotiation.- */-export const emit402Negotiated = emit402;-/*** Helper: respond with the manifest only (no 402), for prefetch/discovery* via `GET /api/agents/:id/x402/:skill/manifest`.diff --git a/api/agents.js b/api/agents.jsindex 5b2e7e5ef..967fc440e 100644--- a/api/agents.js+++ b/api/agents.js@@ -16,6 +16,7 @@ import { sql } from './_lib/db.js';import { cors, json, method, readJson, wrap, error } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-wallet.js';+import { publicUrl } from './_lib/r2.js';import { z } from 'zod';const animationEntrySchema = z.object({@@ -75,11 +76,16 @@ async function handleList(req, res) {if (isMe) return handleGetOrCreateMe(req, res, auth);const text = `- SELECT * FROM agent_identities- WHERE user_id = $1- AND deleted_at IS NULL- ${onchainOnly ? `AND (erc8004_agent_id IS NOT NULL OR meta->>'onchain' IS NOT NULL)` : ''}- ORDER BY created_at ASC+ SELECT i.*,+ a.storage_key AS avatar_storage_key,+ a.thumbnail_key AS avatar_thumbnail_key,+ a.visibility AS avatar_visibility+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.user_id = $1+ AND i.deleted_at IS NULL+ ${onchainOnly ? `AND (i.erc8004_agent_id IS NOT NULL OR i.meta->>'onchain' IS NOT NULL)` : ''}+ ORDER BY i.created_at ASC`;const rows = await sql(text, [auth.userId]);return json(res, 200, { agents: rows.map((row) => decorate(row)) });@@ -90,11 +96,16 @@ async function handleList(req, res) {async function handleGetOrCreateMe(req, res, auth) {try {let [agent] = await sql`- SELECT * FROM agent_identities- WHERE user_id = ${auth.userId}- AND deleted_at IS NULL- ORDER BY created_at ASC- LIMIT 1+ SELECT i.*,+ a.storage_key AS avatar_storage_key,+ a.thumbnail_key AS avatar_thumbnail_key,+ a.visibility AS avatar_visibility+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.user_id = ${auth.userId}+ AND i.deleted_at IS NULL+ ORDER BY i.created_at ASC+ LIMIT 1`;if (!agent) {@@ -117,9 +128,14 @@ async function handleGetOrCreateMe(req, res, auth) {`;// Re-select covers both: we inserted, or a concurrent request beat us.[agent] = await sql`- SELECT * FROM agent_identities- WHERE user_id = ${auth.userId} AND deleted_at IS NULL- ORDER BY created_at ASC LIMIT 1+ SELECT i.*,+ a.storage_key AS avatar_storage_key,+ a.thumbnail_key AS avatar_thumbnail_key,+ a.visibility AS avatar_visibility+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.user_id = ${auth.userId} AND i.deleted_at IS NULL+ ORDER BY i.created_at ASC LIMIT 1`;}@@ -191,9 +207,15 @@ export async function handleGetOne(req, res, id) {if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const [row] = await sql`- SELECT i.*, u.display_name as author_name, u.avatar_url as author_avatar+ SELECT i.*,+ u.display_name as author_name,+ u.avatar_url as author_avatar,+ a.storage_key AS avatar_storage_key,+ a.thumbnail_key AS avatar_thumbnail_key,+ a.visibility AS avatar_visibilityFROM agent_identities i- LEFT JOIN users u ON i.user_id = u.id+ LEFT JOIN users u ON i.user_id = u.id+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULLWHERE i.id = ${id} AND i.deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');@@ -376,11 +398,25 @@ function decorate(row, isOwner = true) {}: null;+ const avatarVisibility = row.avatar_visibility || null;+ const avatarPubliclyReadable =+ avatarVisibility === 'public' || avatarVisibility === 'unlisted';+ const avatarModelUrl =+ row.avatar_storage_key && avatarPubliclyReadable+ ? publicUrl(row.avatar_storage_key)+ : null;+ const avatarThumbnailUrl = row.avatar_thumbnail_key+ ? publicUrl(row.avatar_thumbnail_key)+ : null;+const base = {id: row.id,name: row.name,description: row.description,avatar_id: row.avatar_id,+ avatar_visibility: avatarVisibility,+ avatar_model_url: avatarModelUrl,+ avatar_thumbnail_url: avatarThumbnailUrl,home_url: row.home_url || `/agent/${row.id}`,skills: row.skills || [],skill_prices: row.skill_prices || {},diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].jsindex 227c19360..4926df288 100644--- a/api/agents/x402/[action].js+++ b/api/agents/x402/[action].js@@ -15,6 +15,8 @@ const HANDLERS = { echo: async (args) => ({ ok: true, echoed: args }) };// C1 — x402 bridge: prices come from the canonical agent_skill_prices table// first (the marketplace's source of truth), with the legacy meta.skill_prices// jsonb as a fallback for agents priced before the marketplace migration.+// Returns null when the skill has no canonical price — callers must respond+// with 409 no_payments rather than synthesize a price.async function priceFor(agent, skill) {const [row] = await sql`SELECT amount, currency_mint, chain@@ -28,8 +30,7 @@ async function priceFor(agent, skill) {if (fromMap?.amount && fromMap?.currency) return fromMap;const defaultPrice = agent.meta?.payments?.default_price;if (defaultPrice?.amount && defaultPrice?.currency) return defaultPrice;- const cluster = agent.meta?.payments?.cluster || 'mainnet';- return { amount: '10000', currency: cluster === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' };+ return null;}async function resolveAuth(req) {@@ -68,6 +69,9 @@ async function handleInvoke(req, res) {}const price = await priceFor(agent, body.skill);+ if (!price) {+ return error(res, 409, 'no_payments', `skill "${body.skill}" is not priced on this agent`);+ }const paid = await verifyPaid(req, { agentId: agent.id, skill: body.skill, expectedAmount: price.amount, expectedCurrency: price.currency });if (!paid) return emit402(res, { agent, skill: body.skill, amount: price.amount, currency: price.currency });@@ -131,6 +135,10 @@ async function handleManifest(req, res) {}const price = await priceFor(agent, skill);+ if (!price) {+ // Defensive — the no-payments precheck above should have caught this.+ return error(res, 409, 'no_payments', 'this skill is not priced');+ }return manifestOnly(res, { agent, skill, amount: price.amount, currency: price.currency });}diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 83cd6e199..2aef4ae2c 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -67,6 +67,7 @@ const HANDLERS = {'expire-pending-purchases': handleExpirePendingPurchases,'cleanup-csrf-tokens': handleCleanupCsrfTokens,'process-withdrawals': handleProcessWithdrawals,+ 'run-x-scheduled-posts': handleRunXScheduledPosts,};export default wrap(async (req, res) => {@@ -2552,3 +2553,59 @@ async function handleProcessWithdrawals(req, res) {return json(res, 200, { ok: true, ...report });}++// ═══════════════════════════════════════════════════════════════════════════+// run-x-scheduled-posts+//+// Publishes due rows from x_scheduled_posts. Terminal errors (quota, dedup,+// not connected, reauth) are recorded once; transient errors retry up to 3x.+// ═══════════════════════════════════════════════════════════════════════════++async function handleRunXScheduledPosts(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ const auth = req.headers['authorization'] || '';+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && expected && auth !== expected) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ const { publishTweet, XPostError } = await import('../_lib/x-post.js');++ const due = await sql`+ select id, user_id, agent_id, text, attempts+ from x_scheduled_posts+ where posted_at is null and error is null+ and scheduled_at <= now()+ order by scheduled_at asc+ limit 50+ `;++ const report = { processed: 0, posted: 0, errored: 0 };+ const TERMINAL = new Set(['quota_exceeded', 'duplicate', 'not_connected', 'validation_error', 'reauth_required']);++ for (const row of due) {+ report.processed++;+ try {+ const result = await publishTweet({ userId: row.user_id, agentId: row.agent_id, text: row.text });+ await sql`+ update x_scheduled_posts+ set posted_at = now(), tweet_id = ${result.tweet_id}, attempts = attempts + 1+ where id = ${row.id}+ `;+ report.posted++;+ } catch (err) {+ report.errored++;+ const code = err instanceof XPostError ? err.code : 'internal_error';+ const terminal = TERMINAL.has(code) || row.attempts >= 2;+ await sql`+ update x_scheduled_posts+ set attempts = attempts + 1,+ error = ${terminal ? `${code}: ${err.message}`.slice(0, 500) : null}+ where id = ${row.id}+ `;+ }+ }++ return json(res, 200, report);+}diff --git a/api/wallet/balances.js b/api/wallet/balances.jsindex 4ca694ab4..e27391798 100644--- a/api/wallet/balances.js+++ b/api/wallet/balances.js@@ -4,6 +4,7 @@import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { getBalances } from '../_lib/balances.js';import { z } from 'zod';const bodySchema = z.object({@@ -11,232 +12,6 @@ const bodySchema = z.object({address: z.string().trim().min(1),});-async function fetchJson(url, opts = {}) {- const r = await fetch(url, opts);- if (!r.ok) {- const text = await r.text().catch(() => r.status.toString());- throw Object.assign(new Error(`upstream ${r.status}: ${text}`), { status: 502 });- }- return r.json();-}--async function getSolanaBalances(address) {- const heliusKey = process.env.HELIUS_API_KEY;- if (!heliusKey) {- const e = new Error('not_configured: HELIUS_API_KEY');- e.status = 503;- e.code = 'not_configured';- e.missing = 'HELIUS_API_KEY';- throw e;- }-- const rpcUrl = `https://mainnet.helius-rpc.com/?api-key=${heliusKey}`;-- // Native SOL balance- const solResp = await fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'getBalance',- params: [address],- }),- });- const lamports = solResp.result?.value ?? 0;- const solAmount = lamports / 1e9;-- // Token accounts- const tokenResp = await fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 2,- method: 'getTokenAccountsByOwner',- params: [- address,- { programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' },- { encoding: 'jsonParsed' },- ],- }),- });-- const tokenAccounts = tokenResp.result?.value ?? [];- const fungible = tokenAccounts- .map((a) => {- const info = a.account?.data?.parsed?.info;- if (!info) return null;- const { mint, tokenAmount } = info;- if (!tokenAmount || tokenAmount.uiAmount === 0) return null;- return { mint, amount: tokenAmount.uiAmount, decimals: tokenAmount.decimals };- })- .filter(Boolean)- .sort((a, b) => b.amount - a.amount)- .slice(0, 9); // top 9 + native SOL = 10-- // Price-enrich via CoinGecko — SOL + top tokens by contract address- // CoinGecko uses platform "solana" for SPL tokens- const mintList = fungible.map((t) => t.mint).join(',');- let cgTokenPrices = {};- if (mintList) {- try {- const cgResp = await fetchJson(- `https://api.coingecko.com/api/v3/simple/token_price/solana?contract_addresses=${mintList}&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_last_updated_at=false`,- );- cgTokenPrices = cgResp;- } catch {- // Price enrichment is best-effort- }- }-- let solUsdPrice = 0;- try {- const cgSol = await fetchJson(- 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd',- );- solUsdPrice = cgSol?.solana?.usd ?? 0;- } catch {- // best-effort- }-- // Fetch metadata for fungible tokens via Helius DAS- const tokens = [];- for (const t of fungible) {- const price = cgTokenPrices[t.mint.toLowerCase()]?.usd ?? 0;- let symbol = t.mint.slice(0, 6);- let logo = null;- try {- const das = await fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 'meta',- method: 'getAsset',- params: { id: t.mint },- }),- });- symbol = das.result?.content?.metadata?.symbol || symbol;- logo = das.result?.content?.links?.image || null;- } catch {- // metadata is best-effort- }- tokens.push({ symbol, amount: t.amount, usd: t.amount * price, logo });- }-- return {- chain: 'solana',- address,- native: { symbol: 'SOL', amount: solAmount, usd: solAmount * solUsdPrice },- tokens,- };-}--async function getEvmBalances(address) {- const alchemyKey = process.env.ALCHEMY_API_KEY;- if (!alchemyKey) {- const e = new Error('not_configured: ALCHEMY_API_KEY');- e.status = 503;- e.code = 'not_configured';- e.missing = 'ALCHEMY_API_KEY';- throw e;- }-- const rpcUrl = `https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`;-- // Native ETH balance- const ethBalResp = await fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'eth_getBalance',- params: [address, 'latest'],- }),- });- const ethWei = BigInt(ethBalResp.result ?? '0x0');- const ethAmount = Number(ethWei) / 1e18;-- // Token balances- const tokenBalResp = await fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 2,- method: 'alchemy_getTokenBalances',- params: [address],- }),- });-- const rawTokens = (tokenBalResp.result?.tokenBalances ?? [])- .filter((t) => t.tokenBalance && t.tokenBalance !== '0x0' && t.tokenBalance !== '0x')- .slice(0, 9);-- // Resolve metadata for each token- const metadataResults = await Promise.allSettled(- rawTokens.map((t) =>- fetchJson(rpcUrl, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 'meta',- method: 'alchemy_getTokenMetadata',- params: [t.contractAddress],- }),- }),- ),- );-- // Price-enrich via CoinGecko- const contractList = rawTokens.map((t) => t.contractAddress).join(',');- let cgTokenPrices = {};- if (contractList) {- try {- const cgResp = await fetchJson(- `https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=${contractList}&vs_currencies=usd`,- );- cgTokenPrices = cgResp;- } catch {- // best-effort- }- }-- let ethUsdPrice = 0;- try {- const cgEth = await fetchJson(- 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',- );- ethUsdPrice = cgEth?.ethereum?.usd ?? 0;- } catch {- // best-effort- }-- const tokens = rawTokens.map((t, i) => {- const meta = metadataResults[i].status === 'fulfilled' ? metadataResults[i].value?.result : null;- const decimals = meta?.decimals ?? 18;- const rawBal = BigInt(t.tokenBalance || '0x0');- const amount = Number(rawBal) / Math.pow(10, decimals);- const price = cgTokenPrices[t.contractAddress.toLowerCase()]?.usd ?? 0;- return {- symbol: meta?.symbol || t.contractAddress.slice(0, 8),- amount,- usd: amount * price,- logo: meta?.logo || null,- };- });-- return {- chain: 'evm',- address,- native: { symbol: 'ETH', amount: ethAmount, usd: ethAmount * ethUsdPrice },- tokens,- };-}-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -253,10 +28,7 @@ export default wrap(async (req, res) => {}try {- const result =- body.chain === 'solana'- ? await getSolanaBalances(body.address)- : await getEvmBalances(body.address);+ const result = await getBalances({ chain: body.chain, address: body.address });return json(res, 200, result);} catch (e) {if (e.code === 'not_configured') {@@ -267,6 +39,6 @@ export default wrap(async (req, res) => {if (e.status === 502) {return error(res, 502, 'upstream_error', e.message);}- throw e; // let wrap() handle unexpected errors+ throw e;}});diff --git a/api/x/draft.js b/api/x/draft.jsnew file mode 100644index 000000000..e1a81feff--- /dev/null+++ b/api/x/draft.js@@ -0,0 +1,70 @@+// POST /api/x/draft — generate a tweet draft using Claude based on the agent's+// profile (name + description). Returns a single 280-char proposal that the+// user can edit before posting.++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';+import { env } from '../_lib/env.js';++const MAX_TWEET_LEN = 280;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const body = await readJson(req);+ const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';++ let agentContext = '';+ if (agentId) {+ const rows = await sql`select id, name, description from avatars where id = ${agentId} limit 1`;+ const a = rows[0];+ if (a) agentContext = `Agent name: ${a.name || 'Unnamed'}\nAgent description: ${a.description || '(none)'}`;+ }++ const system = `You write tweets for AI agents on three.ws. Tweets must be:+- Under ${MAX_TWEET_LEN} characters (hard limit).+- In the agent's voice (first person, matching the description).+- No hashtag spam. At most 1 hashtag.+- No leading/trailing quotes. Plain text only.+- Avoid em-dashes.+Output ONLY the tweet text, nothing else.`;++ const userPrompt = [+ agentContext,+ prompt ? `What to post about: ${prompt}` : 'Write something engaging about being an autonomous AI agent.',+ ].filter(Boolean).join('\n\n');++ const upstream = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'anthropic-version': '2023-06-01',+ 'x-api-key': env.ANTHROPIC_API_KEY,+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 200,+ system,+ messages: [{ role: 'user', content: userPrompt }],+ }),+ });++ if (!upstream.ok) {+ const detail = await upstream.text();+ console.error('[x-draft] LLM failed', upstream.status, detail);+ return error(res, 502, 'llm_failed', 'draft generation failed');+ }++ const data = await upstream.json();+ let text = (data.content?.[0]?.text || '').trim();+ if (text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();+ if (text.length > MAX_TWEET_LEN) text = text.slice(0, MAX_TWEET_LEN - 1) + '…';++ return json(res, 200, { text, length: text.length });+});diff --git a/api/x/post.js b/api/x/post.jsindex 1d15e77a3..6a1d1473a 100644--- a/api/x/post.js+++ b/api/x/post.js@@ -1,122 +1,27 @@-// POST /api/x/post — publish a tweet on behalf of the signed-in user's-// connected X account. Free tier: 5 posts per calendar month. When over the-// limit, returns 402 with an upgrade pointer.+// POST /api/x/post — publish a tweet immediately. Body: { text, agent_id? }+// Quota, dedup, and token-refresh logic live in api/_lib/x-post.js.-import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { encryptToken, decryptToken } from '../auth/x/[action].js';--const FREE_MONTHLY_QUOTA = 5;-const MAX_TWEET_LEN = 280;--async function refreshIfNeeded(conn) {- const expiresAt = conn.expires_at ? new Date(conn.expires_at).getTime() : 0;- const stillValid = expiresAt - Date.now() > 60_000;- if (stillValid) return decryptToken(conn.access_token);- if (!conn.refresh_token) throw Object.assign(new Error('refresh_token missing — reconnect X account'), { status: 401, code: 'reauth_required' });-- const refreshToken = decryptToken(conn.refresh_token);- const creds = Buffer.from(`${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`).toString('base64');- const r = await fetch('https://api.twitter.com/2/oauth2/token', {- method: 'POST',- headers: { 'content-type': 'application/x-www-form-urlencoded', authorization: `Basic ${creds}` },- body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: env.X_OAUTH_CLIENT_ID }).toString(),- });- if (!r.ok) throw Object.assign(new Error(`X token refresh failed: ${await r.text()}`), { status: 401, code: 'reauth_required' });- const tok = await r.json();- const newExpiresAt = new Date(Date.now() + (tok.expires_in ?? 7200) * 1000).toISOString();- await sql`- update social_connections- set access_token = ${encryptToken(tok.access_token)},- refresh_token = ${tok.refresh_token ? encryptToken(tok.refresh_token) : conn.refresh_token},- expires_at = ${newExpiresAt},- updated_at = now()- where id = ${conn.id}- `;- return tok.access_token;-}+import { publishTweet, XPostError } from '../_lib/x-post.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {- return error(res, 501, 'not_configured', 'X OAuth is not configured');- }-const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const body = await readJson(req);- const text = typeof body?.text === 'string' ? body.text.trim() : '';+ const text = typeof body?.text === 'string' ? body.text : '';const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;- if (!text) return error(res, 400, 'validation_error', 'text required');- if (text.length > MAX_TWEET_LEN) return error(res, 400, 'validation_error', `text exceeds ${MAX_TWEET_LEN} chars`);-- const rows = await sql`- select * from social_connections- where user_id = ${user.id} and provider = 'x' and disconnected_at is null- limit 1- `;- const conn = rows[0];- if (!conn) return error(res, 400, 'not_connected', 'connect X account first at /api/auth/x/connect');-- // Reset monthly counter if we crossed the boundary.- if (new Date(conn.month_resets_at) <= new Date()) {- await sql`- update social_connections- set posts_this_month = 0,- month_resets_at = date_trunc('month', now()) + interval '1 month'- where id = ${conn.id}- `;- conn.posts_this_month = 0;- }-- if (conn.posts_this_month >= FREE_MONTHLY_QUOTA) {- return error(res, 402, 'quota_exceeded', `free tier limit of ${FREE_MONTHLY_QUOTA} posts/month reached`, {- posts_used: conn.posts_this_month,- quota: FREE_MONTHLY_QUOTA,- month_resets_at: conn.month_resets_at,- upgrade_url: '/pricing',- });- }- let accessToken;try {- accessToken = await refreshIfNeeded(conn);+ const result = await publishTweet({ userId: user.id, agentId, text });+ return json(res, 200, result);} catch (err) {- return error(res, err.status || 500, err.code || 'token_error', err.message);+ if (err instanceof XPostError) return error(res, err.status, err.code, err.message, err.extra);+ console.error('[x-post] unexpected error', err);+ return error(res, 500, 'internal_error', err.message || 'post failed');}-- const tweetRes = await fetch('https://api.twitter.com/2/tweets', {- method: 'POST',- headers: { 'content-type': 'application/json', authorization: `Bearer ${accessToken}` },- body: JSON.stringify({ text }),- });- if (!tweetRes.ok) {- const detail = await tweetRes.text();- console.error('[x-post] tweet failed', tweetRes.status, detail);- return error(res, 502, 'tweet_failed', `X API error: ${detail.slice(0, 200)}`);- }- const { data } = await tweetRes.json();-- await sql`- update social_connections- set posts_this_month = posts_this_month + 1,- updated_at = now()- where id = ${conn.id}- `;- await sql`- insert into x_posts (user_id, agent_id, tweet_id, text)- values (${user.id}, ${agentId}, ${data.id}, ${text})- `;-- return json(res, 200, {- tweet_id: data.id,- url: `https://x.com/${conn.username}/status/${data.id}`,- posts_used: conn.posts_this_month + 1,- quota: FREE_MONTHLY_QUOTA,- });});diff --git a/api/x/schedule.js b/api/x/schedule.jsnew file mode 100644index 000000000..98e3602c8--- /dev/null+++ b/api/x/schedule.js@@ -0,0 +1,67 @@+// GET /api/x/schedule — list pending + recent scheduled posts+// POST /api/x/schedule — schedule a new post { text, scheduled_at, agent_id? }+// DELETE /api/x/schedule?id=<uuid> — cancel a pending scheduled post++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';+import { MAX_TWEET_LEN } from '../_lib/x-post.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') {+ const rows = await sql`+ select id, agent_id, text, scheduled_at, posted_at, tweet_id, error, attempts+ from x_scheduled_posts+ where user_id = ${user.id}+ order by scheduled_at desc+ limit 50+ `;+ return json(res, 200, { posts: rows });+ }++ if (req.method === 'DELETE') {+ const url = new URL(req.url, 'http://x');+ const id = url.searchParams.get('id');+ if (!id) return error(res, 400, 'validation_error', 'id required');+ const result = await sql`+ delete from x_scheduled_posts+ where id = ${id} and user_id = ${user.id} and posted_at is null+ returning id+ `;+ if (!result.length) return error(res, 404, 'not_found', 'no pending post with that id');+ return json(res, 200, { cancelled: id });+ }++ // POST+ const body = await readJson(req);+ const text = typeof body?.text === 'string' ? body.text.trim() : '';+ const scheduledAt = typeof body?.scheduled_at === 'string' ? body.scheduled_at : '';+ const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;+ if (!text) return error(res, 400, 'validation_error', 'text required');+ if (text.length > MAX_TWEET_LEN) return error(res, 400, 'validation_error', `text exceeds ${MAX_TWEET_LEN} chars`);++ const when = new Date(scheduledAt);+ if (!scheduledAt || isNaN(when.getTime())) return error(res, 400, 'validation_error', 'scheduled_at must be a valid ISO timestamp');+ if (when.getTime() < Date.now() - 60_000) return error(res, 400, 'validation_error', 'scheduled_at must be in the future');++ // Require a connected X account before accepting a schedule.+ const conn = await sql`+ select 1 from social_connections+ where user_id = ${user.id} and provider = 'x' and disconnected_at is null+ limit 1+ `;+ if (!conn.length) return error(res, 400, 'not_connected', 'connect X account first');++ const rows = await sql`+ insert into x_scheduled_posts (user_id, agent_id, text, scheduled_at)+ values (${user.id}, ${agentId}, ${text}, ${when.toISOString()})+ returning id, scheduled_at+ `;+ return json(res, 201, { id: rows[0].id, scheduled_at: rows[0].scheduled_at });+});diff --git a/api/x/status.js b/api/x/status.jsnew file mode 100644index 000000000..291c6a051--- /dev/null+++ b/api/x/status.js@@ -0,0 +1,55 @@+// GET /api/x/status — current user's X connection + quota+// DELETE /api/x/status — disconnect X account (soft delete: sets disconnected_at)++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, method, wrap, error, json } from '../_lib/http.js';++const FREE_MONTHLY_QUOTA = 5;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'DELETE'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'DELETE') {+ await sql`+ update social_connections+ set disconnected_at = now(), updated_at = now()+ where user_id = ${user.id} and provider = 'x' and disconnected_at is null+ `;+ return json(res, 200, { disconnected: true });+ }++ const rows = await sql`+ select username, posts_this_month, month_resets_at, connected_at+ from social_connections+ where user_id = ${user.id} and provider = 'x' and disconnected_at is null+ limit 1+ `;+ const conn = rows[0];+ if (!conn) return json(res, 200, { connected: false });++ // Reset counter if month rolled over.+ let postsThisMonth = conn.posts_this_month;+ if (new Date(conn.month_resets_at) <= new Date()) {+ await sql`+ update social_connections+ set posts_this_month = 0,+ month_resets_at = date_trunc('month', now()) + interval '1 month'+ where user_id = ${user.id} and provider = 'x'+ `;+ postsThisMonth = 0;+ }++ return json(res, 200, {+ connected: true,+ username: conn.username,+ posts_used: postsThisMonth,+ quota: FREE_MONTHLY_QUOTA,+ month_resets_at: conn.month_resets_at,+ connected_at: conn.connected_at,+ });+});diff --git a/api/x402-pay.js b/api/x402-pay.jsindex b7200f066..195e58211 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -12,7 +12,7 @@//// Env (required for prod):// X402_AGENT_SOLANA_SECRET_BASE58 base58-encoded 64-byte ed25519 secret-// Local dev fallback (when env unset): reads keypair JSON at+// Local dev fallback (NODE_ENV !== 'production' only): reads keypair JSON at// /home/codespace/.config/x402-test-wallets/solana.json//// Also: GET /api/x402-pay?balance=1 → returns the agent wallet's USDC + SOL@@ -31,20 +31,24 @@ import {import bs58 from 'bs58';import { Redis } from '@upstash/redis';-import { cors, json, readJson, wrap, error } from './_lib/http.js';+import { cors, json, readJson, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import {paymentRequirements,verifyPayment,settlePayment,+ resolveResourceUrl,NETWORK_SOLANA_MAINNET,} from './_lib/x402-spec.js';import { dispatch } from './_mcp/dispatch.js';import { env } from './_lib/env.js';import { sql } from './_lib/db.js';+import { logger } from './_lib/usage.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';+const log = logger('x402-pay');+// ---- Persistent feed of recent paid calls -------------------------------// Backed by Upstash Redis when available; falls back to an in-memory ring// in dev so the feed still works locally.@@ -72,7 +76,9 @@ async function recordFeedEntry(entry) {try {await r.lpush(FEED_KEY, JSON.stringify(entry));await r.ltrim(FEED_KEY, 0, FEED_MAX - 1);- } catch {}+ } catch (err) {+ log.warn('feed_write_failed', { message: err?.message });+ }}memFeed.unshift(entry);if (memFeed.length > FEED_MAX) memFeed.length = FEED_MAX;@@ -86,12 +92,19 @@ async function readFeed(limit = 25) {return rows.map((row) => {if (typeof row === 'string') {- try { return JSON.parse(row); } catch { return null; }+ try {+ return JSON.parse(row);+ } catch (parseErr) {+ log.warn('feed_row_parse_failed', { message: parseErr?.message });+ return null;+ }}return row;}).filter(Boolean);- } catch {}+ } catch (err) {+ log.warn('feed_read_failed', { message: err?.message });+ }}return memFeed.slice(0, limit);}@@ -104,8 +117,11 @@ const CALL_TTL_SECONDS = 60 * 60 * 24 * 30; // 30 daysasync function persistCall(tx, record) {const r = redis();if (r) {- try { await r.set(CALL_KEY(tx), JSON.stringify(record), { ex: CALL_TTL_SECONDS }); }- catch {}+ try {+ await r.set(CALL_KEY(tx), JSON.stringify(record), { ex: CALL_TTL_SECONDS });+ } catch (err) {+ log.warn('call_persist_failed', { tx, message: err?.message });+ }}memCalls.set(tx, record);}@@ -115,9 +131,16 @@ async function readCall(tx) {if (r) {try {const row = await r.get(CALL_KEY(tx));- if (typeof row === 'string') { try { return JSON.parse(row); } catch {} }- else if (row && typeof row === 'object') return row;- } catch {}+ if (typeof row === 'string') {+ try {+ return JSON.parse(row);+ } catch (parseErr) {+ log.warn('call_read_parse_failed', { tx, message: parseErr?.message });+ }+ } else if (row && typeof row === 'object') return row;+ } catch (err) {+ log.warn('call_read_failed', { tx, message: err?.message });+ }}return memCalls.get(tx) || null;}@@ -130,7 +153,9 @@ async function requireAuth(req) {if (session) return { userId: session.id };const bearer = await authenticateBearer(extractBearer(req));if (bearer) return { userId: bearer.userId };- } catch {}+ } catch (err) {+ log.warn('require_auth_failed', { message: err?.message });+ }return null;}@@ -166,7 +191,9 @@ async function getAgentsForUser(userId) {try {const lamports = await conn.getBalance(new PublicKey(address));sol = lamports / 1e9;- } catch {}+ } catch (err) {+ log.warn('agent_sol_balance_failed', { address, message: err?.message });+ }try {const ata = getAssociatedTokenAddressSync(new PublicKey(USDC_MAINNET_MINT),@@ -174,7 +201,14 @@ async function getAgentsForUser(userId) {);const acct = await conn.getTokenAccountBalance(ata);usdc = Number(acct.value.uiAmount || 0);- } catch {}+ } catch (err) {+ // Missing ATA throws TokenAccountNotFoundError — that's an expected+ // state (agent never received USDC), so debug not warn.+ if (!/could not find account|TokenAccountNotFound/i.test(err?.message || '')) {+ log.warn('agent_usdc_balance_failed', { address, message: err?.message });+ }+ usdc = 0;+ }}return {id: row.id,@@ -208,8 +242,8 @@ const ALLOWED_TOOLS = new Set(['search_public_avatars',]);-const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';-const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const SOLANA_RPC = env.SOLANA_RPC_URL;+const USDC_MAINNET_MINT = env.X402_ASSET_MINT_SOLANA;let _agent = null;function loadAgentKeypair() {@@ -219,10 +253,11 @@ function loadAgentKeypair() {let raw;try {raw = bs58.decode(b58);- } catch {- const e = new Error('X402_AGENT_SOLANA_SECRET_BASE58 is not valid base58');+ } catch (decodeErr) {+ const e = new Error(`X402_AGENT_SOLANA_SECRET_BASE58 is not valid base58: ${decodeErr?.message}`);e.status = 503;e.code = 'wallet_misconfigured';+ e.cause = decodeErr;throw e;}if (raw.length !== 64) {@@ -236,17 +271,23 @@ function loadAgentKeypair() {_agent = Keypair.fromSecretKey(raw);return _agent;}- try {- const path = '/home/codespace/.config/x402-test-wallets/solana.json';- const arr = JSON.parse(readFileSync(path, 'utf8'));- _agent = Keypair.fromSecretKey(Uint8Array.from(arr));- return _agent;- } catch {- const e = new Error('agent wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');- e.status = 503;- e.code = 'wallet_unconfigured';- throw e;+ // Local dev only: load the developer's test keypair from a well-known+ // codespace path so `npm run dev` works without setting env vars. Refusing+ // to read it in production prevents accidental key reuse across deploys.+ if (process.env.NODE_ENV !== 'production') {+ try {+ const path = '/home/codespace/.config/x402-test-wallets/solana.json';+ const arr = JSON.parse(readFileSync(path, 'utf8'));+ _agent = Keypair.fromSecretKey(Uint8Array.from(arr));+ return _agent;+ } catch (err) {+ log.warn('dev_keypair_load_failed', { path: '/home/codespace/.config/x402-test-wallets/solana.json', message: err?.message });+ }}+ const e = new Error('agent wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');+ e.status = 503;+ e.code = 'wallet_unconfigured';+ throw e;}function buildJsonRpc(tool, args) {@@ -303,7 +344,9 @@ async function buildSolanaPaymentPayload({ accept, buyer, conn, resourceUrl }) {x402Version: 2,scheme: 'exact',network: accept.network,- resource: { url: resourceUrl, mimeType: 'application/json' },+ // v2 spec: resource is a string URL on the PaymentPayload. The mimeType+ // belongs on the 402-challenge top-level resource object, not on the payload.+ resource: resourceUrl,accepted: accept,payload: { transaction: txBase64 },};@@ -321,7 +364,12 @@ async function getAgentBalance() {);const acct = await conn.getTokenAccountBalance(ata);usdc = Number(acct.value.uiAmount || 0);- } catch {}+ } catch (err) {+ // Missing ATA is the expected case before the demo wallet has ever held USDC.+ if (!/could not find account|TokenAccountNotFound/i.test(err?.message || '')) {+ log.warn('demo_usdc_balance_failed', { address: buyer.publicKey.toBase58(), message: err?.message });+ }+ }return {address: buyer.publicKey.toBase58(),sol: sol / 1e9,@@ -343,7 +391,7 @@ function sseSend(res, event, data) {res.write(`data: ${JSON.stringify(data)}\n\n`);}-async function runFlow({ tool, args, emit, buyer: buyerOverride }) {+async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl }) {const buyer = buyerOverride ?? loadAgentKeypair();const conn = new Connection(SOLANA_RPC, 'confirmed');@@ -355,7 +403,7 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride }) {emit('challenge', { network: accept.network, amount: accept.amount, payTo: accept.payTo });const paymentPayload = await buildSolanaPaymentPayload({- accept, buyer, conn, resourceUrl: 'https://three.ws/api/mcp',+ accept, buyer, conn, resourceUrl,});const tBuilt = Date.now();emit('built', { build_ms: tBuilt - t0, network: accept.network });@@ -405,7 +453,9 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride }) {network: settled.network || accept.network,amount: accept.amount,};- void recordFeedEntry(feedEntry).catch(() => {});+ void recordFeedEntry(feedEntry).catch((err) => {+ log.warn('feed_record_failed', { tx: settled.transaction, message: err?.message });+ });if (settled.transaction) {void persistCall(settled.transaction, {...feedEntry,@@ -415,7 +465,9 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride }) {payTo: accept.payTo,asset: accept.asset,explorer: `https://solscan.io/tx/${settled.transaction}`,- }).catch(() => {});+ }).catch((err) => {+ log.warn('call_persist_failed_outer', { tx: settled.transaction, message: err?.message });+ });}const total_ms = tSettled - t0;@@ -520,12 +572,13 @@ export default wrap(async (req, res) => {const wantsStream =(req.headers.accept || '').includes('text/event-stream') ||input.stream === true;+ const resourceUrl = resolveResourceUrl(req, '/api/mcp');if (wantsStream) {sseInit(res);const emit = (ev, data) => sseSend(res, ev, data);try {- await runFlow({ tool, args, emit, buyer });+ await runFlow({ tool, args, emit, buyer, resourceUrl });} catch (err) {emit('error', {ok: false,@@ -546,7 +599,7 @@ export default wrap(async (req, res) => {else if (ev === 'error') errEnv = data;};try {- await runFlow({ tool, args, emit, buyer });+ await runFlow({ tool, args, emit, buyer, resourceUrl });} catch (err) {errEnv = { ok: false, error: err.message || 'flow_failed', mcpError: err.mcpError || null };}diff --git a/api/x402-pay/og.js b/api/x402-pay/og.jsindex ca9bf3af5..ddf82e183 100644--- a/api/x402-pay/og.js+++ b/api/x402-pay/og.js@@ -6,6 +6,9 @@import sharp from 'sharp';import { Redis } from '@upstash/redis';import { env } from '../_lib/env.js';+import { logger } from '../_lib/usage.js';++const log = logger('x402-og');const FALLBACK_TITLE = 'three.ws · pay-per-call (x402)';const FALLBACK_SUB = 'Live demo — agent pays $0.001 USDC per MCP tool call.';@@ -24,9 +27,16 @@ async function readCall(tx) {if (!r) return null;try {const row = await r.get(`x402:pay:call:${tx}`);- if (typeof row === 'string') { try { return JSON.parse(row); } catch {} }- else if (row && typeof row === 'object') return row;- } catch {}+ if (typeof row === 'string') {+ try {+ return JSON.parse(row);+ } catch (parseErr) {+ log.warn('og_row_parse_failed', { tx, message: parseErr?.message });+ }+ } else if (row && typeof row === 'object') return row;+ } catch (err) {+ log.warn('og_row_read_failed', { tx, message: err?.message });+ }return null;}@@ -60,7 +70,12 @@ function svgFor(record, txParam) {const args = record?.argsSummary || '';const tx = record?.tx || txParam || '';const payer = record?.payer || '';- const amount = ((Number(record?.amount || 1000)) / 1e6).toFixed(6);+ // Persisted records always carry `amount` from accept.amount; if a malformed+ // row sneaks in, render '—' rather than fabricating a $0.001 figure.+ const rawAmount = record?.amount != null ? Number(record.amount) : null;+ const amount = rawAmount != null && Number.isFinite(rawAmount)+ ? (rawAmount / 1e6).toFixed(6)+ : '—';const ago = relativeAgo(record?.ts);return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">@@ -183,7 +198,9 @@ export default async function handler(req, res) {res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');return res.end(png);} catch (err) {- // Graceful fallback to SVG if sharp can't render (some envs).+ // Graceful fallback to SVG if sharp can't render (some envs — e.g.+ // missing libvips). Surface why so we notice if sharp regresses.+ log.warn('og_png_render_failed', { message: err?.message });res.statusCode = 200;res.setHeader('content-type', 'image/svg+xml');res.setHeader('cache-control', 'public, max-age=300');diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex c2895bef9..e40ea73ad 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -914,6 +914,17 @@return;}+ // If the x402 pay-per-call pack is installed, pre-enable its tools on+ // new conversations so the model can immediately call paid MCP tools+ // without the user having to dig through the Tools dropdown first.+ const x402PackMeta = curatedToolPacks.find((p) => p.id === 'x402-pay');+ const x402PackInstalled = x402PackMeta+ ? $toolSchema.find((g) => g.name === x402PackMeta.name)+ : null;+ const defaultTools = x402PackInstalled+ ? x402PackInstalled.schema.map((t) => t.function?.name).filter(Boolean)+ : [];+const convoData = {id: uuidv4(),time: Date.now(),@@ -923,7 +934,7 @@: [models.find((m) => m.id === 'anthropic/claude-3.5-sonnet')],messages: [],versions: {},- tools: [],+ tools: defaultTools,agentId: null,};if ($activeAgent?.preferred_model) {@@ -1451,6 +1462,31 @@window.history.replaceState({}, '', url.toString());}+ // One-time bootstrap of the x402 pay-per-call pack so every chat user+ // can immediately exercise paid MCP tools. Honors removal: once a user+ // uninstalls the pack from Tool Packs, the bootstrap flag prevents us+ // from forcing it back in. Also enables the pack's tools on the active+ // conversation if it's still empty, so the LLM sees them on the first+ // turn without requiring the user to dig through the Tools dropdown.+ try {+ if (!localStorage.getItem('x402PayPackBootstrapped')) {+ const x402Pack = curatedToolPacks.find((p) => p.id === 'x402-pay');+ if (x402Pack && !$toolSchema.some((g) => g.name === x402Pack.name)) {+ $toolSchema = [...$toolSchema, { name: x402Pack.name, schema: x402Pack.schema }];+ }+ if (x402Pack && convo && (convo.messages?.length ?? 0) === 0) {+ const names = x402Pack.schema.map((t) => t.function?.name).filter(Boolean);+ convo.tools = Array.from(new Set([...(convo.tools || []), ...names]));+ saveConversation(convo);+ }+ localStorage.setItem('x402PayPackBootstrapped', '1');+ }+ } catch (err) {+ // Best-effort bootstrap — e.g. Safari private mode blocks+ // localStorage. Don't break the rest of onMount over it.+ console.warn('[x402-pay] bootstrap failed:', err);+ }+initializePWAStyles();// Only probe the local tool server if the user has opted in or clearlydiff --git a/chat/src/PayWalletPicker.svelte b/chat/src/PayWalletPicker.sveltenew file mode 100644index 000000000..5896e19c2--- /dev/null+++ b/chat/src/PayWalletPicker.svelte@@ -0,0 +1,260 @@+<script>+ import { onMount, onDestroy } from 'svelte';+ import { currentUser, payAgentId, payWallet } from './stores.js';++ let open = false;+ let agents = []; // [{ id, name, solana_address, usdc, sol, ... }]+ let agentsLoading = false;+ let agentsError = '';+ let demoWallet = { address: null, usdc: null, sol: null, configured: null };+ let demoLoading = false;+ let demoError = '';+ let popoverEl;+ let buttonEl;++ $: signedIn = !!$currentUser;+ $: agentsWithWallet = agents.filter((a) => !!a.solana_address);+ $: selectedAgent = agentsWithWallet.find((a) => a.id === $payAgentId) || null;++ function fmtUsdc(v) {+ if (v == null || Number.isNaN(Number(v))) return '— USDC';+ return Number(v).toFixed(3) + ' USDC';+ }+ function shortAddr(a) {+ if (!a) return '';+ return a.slice(0, 4) + '…' + a.slice(-4);+ }++ async function loadDemoWallet() {+ demoLoading = true;+ demoError = '';+ try {+ const r = await fetch('/api/x402-pay?balance=1');+ if (!r.ok) throw new Error('HTTP ' + r.status);+ demoWallet = await r.json();+ if (demoWallet?.configured === false && demoWallet.error) {+ demoError = demoWallet.error;+ }+ } catch (err) {+ demoError = err.message || 'failed to load demo wallet';+ } finally {+ demoLoading = false;+ }+ }++ async function loadAgents() {+ if (!signedIn) {+ agents = [];+ return;+ }+ agentsLoading = true;+ agentsError = '';+ try {+ const r = await fetch('/api/x402-pay?agents=1', { credentials: 'include' });+ if (r.status === 401) {+ agents = [];+ agentsError = 'sign in to use your own agent wallets';+ return;+ }+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const j = await r.json();+ agents = j.agents || [];+ // If the persisted agent id no longer maps to a wallet-bearing agent+ // (deleted, wallet removed, signed in as a different user), fall+ // back to the shared demo wallet so paid calls don't 401 silently.+ const stillValid = agents.some((a) => a.id === $payAgentId && a.solana_address);+ if ($payAgentId && !stillValid) {+ $payAgentId = null;+ }+ } catch (err) {+ agentsError = err.message || 'failed to load agents';+ } finally {+ agentsLoading = false;+ }+ }++ function publishWallet() {+ if (selectedAgent) {+ payWallet.set({+ address: selectedAgent.solana_address,+ usdc: selectedAgent.usdc,+ sol: selectedAgent.sol,+ name: selectedAgent.name,+ agentId: selectedAgent.id,+ });+ } else {+ payWallet.set({+ address: demoWallet.address,+ usdc: demoWallet.usdc,+ sol: demoWallet.sol,+ name: 'three.ws demo',+ agentId: null,+ });+ }+ }++ // Re-publish whenever any of the three inputs changes. The bare reference+ // list makes Svelte track them; the guard form `if (x || y || z)` would+ // be always-truthy here because `agents` is always an array and+ // `demoWallet` always an object.+ $: { agents; demoWallet; selectedAgent; publishWallet(); }++ function selectShared() {+ $payAgentId = null;+ open = false;+ // Force refresh so the pill picks up the latest demo wallet balance.+ loadDemoWallet();+ }+ function selectAgent(a) {+ if (!a.solana_address) return; // No wallet — handled via separate flow+ $payAgentId = a.id;+ open = false;+ }++ async function refreshAll() {+ await Promise.all([loadDemoWallet(), loadAgents()]);+ }++ function onSettled() {+ // A paid tool call just settled — refresh balances so the pill ticks down.+ refreshAll();+ }++ function onDocClick(e) {+ if (!open) return;+ if (popoverEl && popoverEl.contains(e.target)) return;+ if (buttonEl && buttonEl.contains(e.target)) return;+ open = false;+ }++ let pollHandle;+ let userUnsub;+ onMount(async () => {+ await refreshAll();+ pollHandle = setInterval(refreshAll, 30_000);+ window.addEventListener('x402-pay-settled', onSettled);+ document.addEventListener('mousedown', onDocClick);+ userUnsub = currentUser.subscribe(() => {+ // Reload agents whenever auth state changes (sign in / sign out).+ loadAgents();+ });+ });++ onDestroy(() => {+ clearInterval(pollHandle);+ window.removeEventListener('x402-pay-settled', onSettled);+ document.removeEventListener('mousedown', onDocClick);+ userUnsub?.();+ });++ $: currentLabel = (() => {+ const w = $payWallet;+ if (w?.address) {+ const usdc = fmtUsdc(w.usdc);+ const who = w.agentId ? w.name : 'demo';+ return `Pay · ${who} · ${usdc}`;+ }+ if (demoLoading || agentsLoading) return 'Pay · loading…';+ if (demoError) return 'Pay · wallet error';+ return 'Pay · not configured';+ })();+ $: dotClass = $payWallet?.address+ ? 'bg-emerald-500'+ : demoError+ ? 'bg-red-500'+ : 'bg-slate-300';+</script>++<div class="relative">+ <button+ bind:this={buttonEl}+ on:click={() => (open = !open)}+ class="flex h-9 items-center gap-2 rounded-full border border-rule bg-white px-3 text-[12px] font-medium text-ink shadow-sm transition-colors hover:bg-paper-deep"+ title="Wallet that pays for x402 paid-tool calls"+ >+ <span class="flex h-2 w-2 rounded-full {dotClass}"></span>+ <span class="font-mono">{currentLabel}</span>+ <span class="text-ink-soft" style="font-size:10px">▾</span>+ </button>++ {#if open}+ <div+ bind:this={popoverEl}+ class="absolute right-0 top-full z-[120] mt-2 w-[300px] rounded-xl border border-rule bg-white p-3 shadow-pop"+ >+ <div class="mb-2 text-[11px] uppercase tracking-wider text-ink-soft">x402 pay-per-call wallet</div>++ <button+ class="flex w-full items-start gap-3 rounded-lg border px-3 py-2 text-left transition-colors {$payAgentId == null+ ? 'border-emerald-500 bg-emerald-50'+ : 'border-rule hover:bg-paper-deep'}"+ on:click={selectShared}+ >+ <div class="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gradient-to-br from-indigo-500 to-cyan-400 text-[10px] font-bold text-white">3</div>+ <div class="min-w-0 flex-1">+ <div class="text-[13px] font-medium text-ink">three.ws demo wallet</div>+ <div class="font-mono text-[11px] text-ink-soft">+ {#if demoLoading}+ loading…+ {:else if demoWallet.address}+ {shortAddr(demoWallet.address)} · {fmtUsdc(demoWallet.usdc)}+ {:else if demoError}+ <span class="text-red-600">{demoError}</span>+ {:else}+ not configured+ {/if}+ </div>+ </div>+ </button>++ <div class="mt-3 mb-1 text-[11px] uppercase tracking-wider text-ink-soft">your agents</div>++ {#if !signedIn}+ <div class="rounded-lg border border-dashed border-rule px-3 py-2 text-[12px] text-ink-soft">+ Sign in to pay from one of your agent's Solana wallets.+ </div>+ {:else if agentsLoading}+ <div class="px-3 py-2 text-[12px] text-ink-soft">loading agents…</div>+ {:else if agentsError}+ <div class="rounded-lg border border-dashed border-rule px-3 py-2 text-[12px] text-ink-soft">{agentsError}</div>+ {:else if agents.length === 0}+ <div class="rounded-lg border border-dashed border-rule px-3 py-2 text-[12px] text-ink-soft">+ No agents yet. <a class="text-indigo-600 underline" href="https://three.ws/create" target="_blank" rel="noopener">Create one →</a>+ </div>+ {:else}+ <div class="flex max-h-[220px] flex-col gap-1 overflow-y-auto pr-1">+ {#each agents as a (a.id)}+ <button+ class="flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors {$payAgentId === a.id+ ? 'border-emerald-500 bg-emerald-50'+ : a.solana_address+ ? 'border-rule hover:bg-paper-deep'+ : 'border-rule opacity-60'}"+ on:click={() => selectAgent(a)}+ disabled={!a.solana_address}+ title={a.solana_address ? `Pay from ${a.name}` : 'This agent has no Solana wallet yet'}+ >+ <div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-gradient-to-br from-violet-500 to-cyan-400 text-[10px] font-bold text-white">+ {a.name?.[0] || '?'}+ </div>+ <div class="min-w-0 flex-1">+ <div class="truncate text-[13px] font-medium text-ink">{a.name}</div>+ <div class="font-mono text-[11px] text-ink-soft">+ {a.solana_address ? `${shortAddr(a.solana_address)} · ${fmtUsdc(a.usdc)}` : 'no wallet'}+ </div>+ </div>+ </button>+ {/each}+ </div>+ <div class="mt-2 text-[11px] text-ink-soft">+ Need a wallet for an agent? <a class="text-indigo-600 underline" href="https://three.ws/pay" target="_blank" rel="noopener">Set one up on /pay</a>.+ </div>+ {/if}++ <div class="mt-3 flex items-center justify-between border-t border-rule pt-2 text-[11px] text-ink-soft">+ <span>$0.001 USDC per call · Solana mainnet</span>+ <a class="text-indigo-600 underline" href="https://three.ws/pay" target="_blank" rel="noopener">/pay demo</a>+ </div>+ </div>+ {/if}+</div>diff --git a/chat/src/stores.js b/chat/src/stores.jsindex 084fb3123..fef7a38b4 100644--- a/chat/src/stores.js+++ b/chat/src/stores.js@@ -110,6 +110,15 @@ export const locale = persisted('locale', 'en');export const currentUser = writable(null);+// Selected agent id whose Solana wallet pays for x402 paid-tool calls.+// Null means "use the shared demo wallet" served by /api/x402-pay.+export const payAgentId = persisted('payAgentId', null);++// Snapshot of {address, usdc, sol} for the currently selected payer (agent+// wallet or shared demo wallet). Refreshed by PayWalletPicker so the topbar+// pill ticks down after each paid tool call.+export const payWallet = writable({ address: null, usdc: null, sol: null, name: null, agentId: null });+export async function loadCurrentUser() {try {const res = await fetch('/api/auth/me', { credentials: 'include' });diff --git a/chat/src/three-ui/TopNav.svelte b/chat/src/three-ui/TopNav.svelteindex d74418aa4..d0b2a9e32 100644--- a/chat/src/three-ui/TopNav.svelte+++ b/chat/src/three-ui/TopNav.svelte@@ -4,6 +4,7 @@import { feMenu, feX } from '../feather.js';import WalletConnect from '../WalletConnect.svelte';import NotificationBell from '../NotificationBell.svelte';+ import PayWalletPicker from '../PayWalletPicker.svelte';let mobileOpen = false;</script>@@ -24,6 +25,7 @@<div class="flex items-center gap-2"><div class="hidden items-center gap-2 md:flex"><NotificationBell />+ <PayWalletPicker /><WalletConnect /></div><button@@ -39,7 +41,8 @@<!-- Mobile sheet -->{#if mobileOpen}<div class="border-t border-rule bg-paper md:hidden">- <div class="flex gap-2 px-6 py-4">+ <div class="flex flex-col gap-3 px-6 py-4">+ <PayWalletPicker /><WalletConnect /></div></div>diff --git a/chat/src/tools.js b/chat/src/tools.jsindex b7537feaf..b131a892b 100644--- a/chat/src/tools.js+++ b/chat/src/tools.js@@ -1,4 +1,183 @@+// Reusable client-side body that POSTs to /api/x402-pay and returns a+// structured envelope the LLM can reason over. Built once and shared by every+// x402-paid tool below so the on-chain payment + MCP dispatch happens for real+// on every call — no mocks, no fallbacks.+//+// Inputs: `tool` (string) → MCP tool name; `args` (object) → MCP arguments.+// Side-effects: dispatches a CustomEvent on window after settlement so the+// PayWalletPicker can refresh its balance pill immediately.+const X402_PAY_BODY = `const agentId = (() => { try { return localStorage.getItem('payAgentId') || null; } catch { return null; } })();+const body = { tool: TOOL_NAME, args: ARGS_BUILDER };+if (agentId) body.agentId = agentId;+const r = await fetch('/api/x402-pay', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify(body),+});+const text = await r.text();+let j = null; try { j = text ? JSON.parse(text) : null; } catch { j = null; }+if (!r.ok) {+ const reason = (j && (j.error || j.mcpError?.message)) || ('HTTP ' + r.status);+ throw new Error('x402 paid call failed: ' + reason);+}+if (!j) throw new Error('x402 paid call returned an empty response');+try { window.dispatchEvent(new CustomEvent('x402-pay-settled', { detail: j })); } catch {}+const amount_usdc = j.payment?.amount != null ? Number(j.payment.amount) / 1e6 : null;+return {+ paid: true,+ network: j.payment?.network || null,+ amount_usdc,+ tx: j.payment?.tx || null,+ explorer: j.payment?.explorer || null,+ payer: j.payment?.payer || null,+ payTo: j.payment?.payTo || null,+ durations_ms: j.durations || null,+ result: j.result ?? null,+};`;++function x402PayBody(toolName, argsBuilder) {+ return X402_PAY_BODY+ .replace('TOOL_NAME', JSON.stringify(toolName))+ .replace('ARGS_BUILDER', argsBuilder);+}+export const curatedToolPacks = [+ {+ id: 'x402-pay',+ name: 'three.ws · Pay-per-call (x402)',+ description:+ 'Call real paid MCP tools on three.ws — every invocation signs an SPL transferChecked, pays $0.001 USDC on Solana mainnet, and settles on-chain. Same flow as /pay, surfaced as native chat tools.',+ schema: [+ {+ clientDefinition: {+ id: 'pack-x402-list-tools-001',+ name: 'x402_list_mcp_tools',+ description: 'List the MCP tools exposed by three.ws via x402, with their per-call USDC prices.',+ arguments: [],+ body: x402PayBody('tools/list', '({})'),+ },+ type: 'function',+ function: {+ name: 'x402_list_mcp_tools',+ description:+ 'List the paid MCP tools exposed by three.ws (via x402). Settles a $0.001 USDC payment on Solana mainnet, then returns the tools/list response. Use first to discover what is available before calling validate/inspect/optimize/search.',+ parameters: { type: 'object', properties: {}, required: [] },+ },+ },+ {+ clientDefinition: {+ id: 'pack-x402-validate-001',+ name: 'x402_validate_glb',+ description: 'Validate a glTF/GLB asset against the glTF spec via three.ws MCP (paid x402 call).',+ arguments: [+ { name: 'url', type: 'string', description: 'Public URL of the .glb or .gltf file to validate.' },+ ],+ body:+ `const url = String(args.url || '').trim();+if (!url) throw new Error('url is required (https URL of a .glb / .gltf)');+` + x402PayBody('validate_model', '({ url })'),+ },+ type: 'function',+ function: {+ name: 'x402_validate_glb',+ description:+ 'Validate a glTF/GLB 3D asset against the glTF spec via the three.ws MCP. Pays $0.001 USDC on Solana mainnet per call and returns the validation report (errors / warnings / infos) plus mesh stats. Use when the user wants to check whether a 3D model is spec-compliant.',+ parameters: {+ type: 'object',+ properties: {+ url: { type: 'string', description: 'Public URL of a .glb or .gltf model.' },+ },+ required: ['url'],+ },+ },+ },+ {+ clientDefinition: {+ id: 'pack-x402-inspect-001',+ name: 'x402_inspect_glb',+ description: 'Inspect a glTF/GLB asset (meshes, materials, animations, extensions) via three.ws MCP.',+ arguments: [+ { name: 'url', type: 'string', description: 'Public URL of the .glb or .gltf file to inspect.' },+ ],+ body:+ `const url = String(args.url || '').trim();+if (!url) throw new Error('url is required (https URL of a .glb / .gltf)');+` + x402PayBody('inspect_model', '({ url })'),+ },+ type: 'function',+ function: {+ name: 'x402_inspect_glb',+ description:+ 'Inspect a glTF/GLB 3D asset and return structural metadata: scenes, nodes, meshes (with vertex / triangle counts), materials, textures, animations and extensions used. Pays $0.001 USDC on Solana mainnet per call via x402.',+ parameters: {+ type: 'object',+ properties: {+ url: { type: 'string', description: 'Public URL of a .glb or .gltf model.' },+ },+ required: ['url'],+ },+ },+ },+ {+ clientDefinition: {+ id: 'pack-x402-optimize-001',+ name: 'x402_optimize_glb',+ description: 'Get optimization suggestions for a glTF/GLB asset via three.ws MCP (paid x402 call).',+ arguments: [+ { name: 'url', type: 'string', description: 'Public URL of the .glb or .gltf file to optimize.' },+ ],+ body:+ `const url = String(args.url || '').trim();+if (!url) throw new Error('url is required (https URL of a .glb / .gltf)');+` + x402PayBody('optimize_model', '({ url })'),+ },+ type: 'function',+ function: {+ name: 'x402_optimize_glb',+ description:+ 'Return actionable optimization suggestions for a glTF/GLB 3D asset (texture compression, draco, instancing, etc.) with severity and estimated savings. Pays $0.001 USDC on Solana mainnet per call via x402.',+ parameters: {+ type: 'object',+ properties: {+ url: { type: 'string', description: 'Public URL of a .glb or .gltf model.' },+ },+ required: ['url'],+ },+ },+ },+ {+ clientDefinition: {+ id: 'pack-x402-search-avatars-001',+ name: 'x402_search_avatars',+ description: 'Search public avatars on three.ws (paid x402 call).',+ arguments: [+ { name: 'q', type: 'string', description: 'Optional free-text query (name, traits, description).' },+ { name: 'limit', type: 'number', description: 'Max number of results (default 12).' },+ ],+ body:+ `const q = args.q != null ? String(args.q).trim() : '';+const limit = Math.max(1, Math.min(48, Number(args.limit || 12)));+const argsObj = q ? { q, limit } : { limit };+` + x402PayBody('search_public_avatars', 'argsObj'),+ },+ type: 'function',+ function: {+ name: 'x402_search_avatars',+ description:+ 'Search the three.ws public-avatar library. Pays $0.001 USDC on Solana mainnet per call via x402 and returns up to `limit` avatars (name, slug, model_url). Use when the user wants to find a 3D character / avatar by name or description.',+ parameters: {+ type: 'object',+ properties: {+ q: { type: 'string', description: 'Free-text query (name, traits, description). Omit to browse.' },+ limit: { type: 'integer', description: 'Max results (1–48, default 12).' },+ },+ required: [],+ },+ },+ },+ ],+ },{id: 'tradingview',name: 'TradingView Charts',diff --git a/chat/vite.config.js b/chat/vite.config.jsindex b5895579f..5eb0652a4 100644--- a/chat/vite.config.js+++ b/chat/vite.config.js@@ -56,7 +56,16 @@ export default defineConfig(function () {},server: {proxy: {- '/api': { target: 'http://localhost:3000', changeOrigin: true },+ // Vercel serverless functions live under /api/* in production but+ // Vite's dev server doesn't run them. Forward /api/* to a real+ // upstream so paid x402 calls, model fetches, and auth all work+ // against the production backend during chat dev unless the user+ // explicitly points DEV_API_PROXY at a local vercel-dev process.+ '/api': {+ target: process.env.DEV_API_PROXY || 'https://three.ws',+ changeOrigin: true,+ secure: true,+ },},},plugins: [diff --git a/home.html b/home.htmlindex afbbe81c8..e9d4bd0e6 100644--- a/home.html+++ b/home.html@@ -150,7 +150,8 @@<ul class="h-standards h-reveal" aria-label="Supported formats and standards"><li>glTF 2.0</li><li>GLB</li>- <li>ERC-8004</li>+ <li>Solana</li>+ <li>Metaplex Core</li><li>A2A</li><li>MCP</li></ul>@@ -185,11 +186,11 @@</article><article class="h-pillar h-reveal"><span class="h-pillar-num">03 / Ownership</span>- <h3>Owned, on-chain, portable</h3>+ <h3>Owned on Solana, portable</h3><p>- Register your agent on 20+ EVM chains via ERC-8004 — a verifiable,- CREATE2-deterministic identity discoverable by any A2A or MCP client.- Your agent. Your keys.+ Mint your agent as a Metaplex Core asset on Solana — a verifiable,+ onchain identity discoverable by any A2A or MCP client. Your agent.+ Your keys.</p></article></div>@@ -337,14 +338,14 @@<div class="h-act-text"><div class="h-act-eyebrow"><span class="h-act-dot h-act-dot--mint"></span>- <span>ERC-8004 native</span>+ <span>Metaplex native</span></div><h2 class="h-act-title h-act-title--mint">One transaction.<br /><em>One identity.</em></h2><p class="h-act-lede">- Register onchain. Get a portable, verifiable agentId discoverable by any A2A- or MCP client.+ Mint onchain on Solana. Get a portable, verifiable agentId discoverable+ by any A2A or MCP client.</p><form class="h-deploy-form" id="home-deploy-form" action="/deploy" method="get">@@ -361,34 +362,28 @@/></div><div class="h-form-row">- <label class="h-form-label" for="chain-home">Chain</label>- <select id="chain-home" name="chain" class="h-form-select">- <option value="8453" selected>Base</option>- <option value="1">Ethereum</option>- <option value="10">Optimism</option>- <option value="137">Polygon</option>- <option value="42161">Arbitrum</option>- <option value="43114">Avalanche</option>- <option value="59144">Linea</option>- <option value="534352">Scroll</option>+ <label class="h-form-label" for="network-home">Network</label>+ <select id="network-home" name="network" class="h-form-select">+ <option value="mainnet-beta" selected>Solana Mainnet</option>+ <option value="devnet">Solana Devnet</option></select></div><div class="h-deploy-stats"><div>- <span class="h-stat-label">Chains</span- ><span class="h-stat-val">20+</span>+ <span class="h-stat-label">Chain</span+ ><span class="h-stat-val">Solana</span></div><div><span class="h-stat-label">Standard</span- ><span class="h-stat-val">ERC-721</span>+ ><span class="h-stat-val">Metaplex Core</span></div><div>- <span class="h-stat-label">Protocol</span- ><span class="h-stat-val">ERC-8004</span>+ <span class="h-stat-label">Fee</span+ ><span class="h-stat-val">~$0.01</span></div></div><button type="submit" class="h-btn-primary h-btn-deploy">- <span>Deploy your agent</span>+ <span>Mint your agent</span><span class="arrow">→</span></button></form>@@ -443,7 +438,7 @@<span class="tag"><agent-3d</span><br /> <span class="attr">agent-id</span>=<spanclass="val"- >"0x3d…"</span+ >"3DAg…uPL"</span><br /><span class="tag">></agent-3d></span></div>@@ -454,13 +449,9 @@<span class="h-bento-tag h-bento-tag--mint">On-chain</span><h3>Verifiable identity.</h3><p>- ERC-8004 registration. One transaction. Discoverable by any A2A or- MCP client on 20+ chains.+ Metaplex Core asset on Solana. One transaction, sub-cent fees.+ Discoverable by any A2A or MCP client.</p>- <div class="h-bento-id">- <span class="h-id-dot h-id-dot--mint" aria-hidden="true"></span>- <span class="h-id-addr">0x3d…a9f · Base</span>- </div></div></div><div class="h-bento-card h-reveal">@@ -530,7 +521,7 @@<span class="c"><!-- 2. Drop the tag --></span><span class="tag"><agent-3d</span>- <span class="attr">agent-id</span>=<span class="val">"0x3d…a9f"</span>+ <span class="attr">agent-id</span>=<span class="val">"3DAg…uPL"</span><span class="attr">kiosk</span><span class="tag">></agent-3d></span></code></pre></div>@@ -688,10 +679,10 @@>GitHub</a><a- href="https://eips.ethereum.org/EIPS/eip-8004"+ href="https://developers.metaplex.com/core"target="_blank"rel="noopener"- >ERC-8004</a+ >Metaplex Core</a></div><div class="h-footer-link-col">@@ -716,9 +707,10 @@// so we default to "capable" when the API is absent.const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;- // Hero viewer is always created (above fold), but we skip all below-fold- // viewers on constrained devices.- const SKIP_OFFSCREEN_GL = LOW_MEMORY || REDUCED_MOTION;+ // Skip GL only on truly constrained devices. Reduced-motion users still+ // see the avatars (without auto-rotate); skipping rendering for them left+ // the bento/Act 2/Act 3 canvases permanently blank.+ const SKIP_OFFSCREEN_GL = LOW_MEMORY;// Scroll reveal — use viewport (root: null) so IntersectionObserver// avoids the perspective transform on .home-parallax breaking intersection math.@@ -1013,7 +1005,7 @@act2Obs.disconnect();initAct2();}- }, { threshold: 0.05 });+ }, { threshold: 0, rootMargin: '600px 0px 600px 0px' });act2Obs.observe(canvas);}})();@@ -1098,7 +1090,7 @@io.disconnect();initViewer();}- }, { threshold: 0.05 });+ }, { threshold: 0, rootMargin: '600px 0px 600px 0px' });io.observe(canvas);}})();@@ -1202,7 +1194,7 @@act3Obs.disconnect();initAct3();}- }, { threshold: 0.05 });+ }, { threshold: 0, rootMargin: '600px 0px 600px 0px' });act3Obs.observe(firstCanvas);}})();diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.htmlindex 5b044a4c4..36806bc83 100644--- a/public/dashboard/agent-pumpfun.html+++ b/public/dashboard/agent-pumpfun.html@@ -141,17 +141,19 @@min-width: 0;}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font: inherit;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;}- .btn:hover {- filter: brightness(1.1);+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;}.btn:disabled {opacity: 0.45;@@ -159,9 +161,13 @@}.btn.ghost {background: transparent;- border: 1px solid var(--border);+ border: 1px solid #22222e;color: #ddd;}+ .btn.ghost:hover:not(:disabled) {+ background: #15151d;+ border-color: #2e2e3e;+ }.btn.danger {background: #3a1d22;color: var(--err);diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 20e95f6ce..ccc950ef5 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -296,7 +296,6 @@ function agentCard(a, onRemoved) {const el = document.createElement('div');el.className = 'card';- const thumbSrc = a.avatar_id ? `/api/avatars/${encodeURIComponent(a.avatar_id)}/thumbnail` : null;const onchainBadge = a.is_registered? `<span class="tag" title="Registered on-chain (ERC-8004)" style="background:rgba(106,92,255,0.18); color:#cfc6ff;">on-chain${a.chain_id ? ' · ' + esc(agentChainName(a.chain_id)) : ''}</span>`: `<span class="tag" title="Not yet registered on-chain">off-chain</span>`;@@ -304,11 +303,7 @@ function agentCard(a, onRemoved) {const wallet = a.wallet_address ? `${a.wallet_address.slice(0, 6)}…${a.wallet_address.slice(-4)}` : '';el.innerHTML = `- <div class="preview">- ${thumbSrc- ? `<img class="thumb" src="${esc(thumbSrc)}" alt="${esc(a.name)} avatar" loading="lazy">`- : `<div class="ph"><div style="font-size:32px;line-height:1;margin-bottom:8px" aria-hidden="true">🤖</div><div>No avatar linked</div></div>`}- </div>+ <div class="preview" data-agent-preview></div><h3>${esc(a.name || 'Agent')}</h3><p class="meta">${skillCount} skill${skillCount === 1 ? '' : 's'}${wallet ? ' · ' + esc(wallet) : ''} · ${new Date(a.created_at).toLocaleDateString()}</p><div class="row" style="gap:6px; margin-bottom:10px; flex-wrap:wrap">${onchainBadge}</div>@@ -323,6 +318,8 @@ function agentCard(a, onRemoved) {</div>`;+ mountAgentAvatarPreview(el.querySelector('[data-agent-preview]'), a);+el.querySelector('[data-del]').addEventListener('click', async () => {if (!confirm(`Delete "${a.name}"? This cannot be undone.`)) return;try {@@ -338,6 +335,74 @@ function agentCard(a, onRemoved) {return el;}+// Mount a 3D model-viewer (or thumbnail fallback) for an agent card.+// Lazy-loads when the card scrolls into view. For private linked avatars,+// fetches a short-lived signed URL via /api/avatars/:id.+function mountAgentAvatarPreview(host, agent) {+ if (!host) return;+ const name = agent?.name || 'Agent';+ const showPlaceholder = () => {+ host.innerHTML = `<div class="ph"><div style="font-size:32px;line-height:1;margin-bottom:8px" aria-hidden="true">🤖</div><div>No avatar linked</div></div>`;+ };+ const showSpinner = () => {+ host.innerHTML = '<div class="spinner" aria-label="Loading preview"></div>';+ };+ const showModel = (url) => {+ host.innerHTML = `<model-viewer src="${attr(url)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" loading="lazy" reveal="auto"></model-viewer>`;+ };+ const showThumb = (url) => {+ host.innerHTML = `<img class="thumb" src="${attr(url)}" alt="${attr(name)} avatar" loading="lazy">`;+ };++ if (!agent?.avatar_id) {+ showPlaceholder();+ return;+ }++ // Seed with the public thumbnail (if any) so the card paints instantly.+ if (agent.avatar_thumbnail_url) showThumb(agent.avatar_thumbnail_url);+ else host.innerHTML = '<div class="ph">Loading preview…</div>';++ let loaded = false;+ const load = async () => {+ if (loaded) return;+ loaded = true;+ if (agent.avatar_model_url) {+ showModel(agent.avatar_model_url);+ return;+ }+ showSpinner();+ try {+ const { avatar } = await api.getAvatar(agent.avatar_id);+ const url = avatar?.url || avatar?.model_url;+ if (url) showModel(url);+ else if (avatar?.thumbnail_url) showThumb(avatar.thumbnail_url);+ else showPlaceholder();+ } catch {+ loaded = false;+ host.innerHTML = `<div class="ph">Preview unavailable<br><button data-retry>Retry</button></div>`;+ host.querySelector('[data-retry]').addEventListener('click', load);+ }+ };++ if ('IntersectionObserver' in window) {+ const io = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ io.disconnect();+ load();+ }+ }+ },+ { rootMargin: '200px' },+ );+ io.observe(host);+ } else {+ load();+ }+}+function openCreateForm(host, listEl) {if (host.querySelector('input[name=agent-name]')) {host.querySelector('input[name=agent-name]').focus();@@ -543,6 +608,188 @@ function mountAvatarWalletSection(host, a) {});}+// ── X (Twitter) panel for the agent edit page ──────────────────────────────+// Renders: connect button | quota meter + composer + draft + schedule | disconnect.+function mountAgentXPanel(host, avatar) {+ if (!host) return;+ host.innerHTML = `+ <div class="card" style="padding:16px">+ <div class="row" style="justify-content:space-between;margin-bottom:10px;align-items:baseline">+ <h3 style="margin:0;font-size:14px">Post to X (Twitter)</h3>+ <span class="muted" style="font-size:11px" data-x-meter>Loading…</span>+ </div>+ <div data-x-body><div class="muted" style="font-size:13px">Loading…</div></div>+ </div>+ `;+ const meterEl = host.querySelector('[data-x-meter]');+ const bodyEl = host.querySelector('[data-x-body]');+ loadXPanel({ host, meterEl, bodyEl, avatar }).catch((err) => {+ bodyEl.innerHTML = `<div style="color:#ffb3b3;font-size:13px">${esc(err.message || 'Failed to load')}</div>`;+ });+}++async function loadXPanel({ host, meterEl, bodyEl, avatar }) {+ const status = await fetch('/api/x/status', { credentials: 'include' }).then((r) => r.json());++ if (!status.connected) {+ meterEl.textContent = '';+ bodyEl.innerHTML = `+ <p class="muted" style="font-size:13px;margin:0 0 10px">Connect your X account to let this agent post tweets. Free tier: 5 posts/month per account.</p>+ <a class="btn" href="/api/auth/x/connect?agent_id=${encodeURIComponent(avatar.agent_id || avatar.id)}">Connect X</a>+ `;+ return;+ }++ const used = status.posts_used;+ const quota = status.quota;+ const remaining = Math.max(0, quota - used);+ meterEl.innerHTML = `@${esc(status.username)} · <span style="color:${remaining === 0 ? '#ffb3b3' : '#9a8cff'}">${used}/${quota} posts</span>`;++ bodyEl.innerHTML = `+ <textarea data-x-text placeholder="What should your agent tweet?" rows="3" maxlength="280" style="width:100%;font-family:inherit"></textarea>+ <div class="row" style="justify-content:space-between;margin-top:6px;font-size:11px">+ <span class="muted"><span data-x-count>0</span>/280</span>+ <span class="muted">Resets ${new Date(status.month_resets_at).toLocaleDateString()}</span>+ </div>+ <div class="row" style="gap:8px;margin-top:10px;flex-wrap:wrap">+ <button class="btn sec" data-x-draft type="button">✨ Draft with AI</button>+ <button class="btn" data-x-post type="button" ${remaining === 0 ? 'disabled' : ''}>Post now</button>+ <button class="btn sec" data-x-schedule type="button" ${remaining === 0 ? 'disabled' : ''}>Schedule…</button>+ <button class="btn sec" data-x-disconnect type="button" style="margin-left:auto;font-size:11px;padding:4px 8px;background:transparent;color:#888">Disconnect</button>+ </div>+ <div data-x-msg style="margin-top:10px;font-size:13px"></div>+ <div data-x-scheduled style="margin-top:14px"></div>+ `;++ const textEl = bodyEl.querySelector('[data-x-text]');+ const countEl = bodyEl.querySelector('[data-x-count]');+ const msgEl = bodyEl.querySelector('[data-x-msg]');+ const draftBtn = bodyEl.querySelector('[data-x-draft]');+ const postBtn = bodyEl.querySelector('[data-x-post]');+ const scheduleBtn = bodyEl.querySelector('[data-x-schedule]');+ const disconnectBtn = bodyEl.querySelector('[data-x-disconnect]');+ const scheduledEl = bodyEl.querySelector('[data-x-scheduled]');++ const setMsg = (text, color = '#9a8cff') => { msgEl.style.color = color; msgEl.innerHTML = text; };+ textEl.addEventListener('input', () => { countEl.textContent = textEl.value.length; });++ draftBtn.addEventListener('click', async () => {+ const original = draftBtn.textContent;+ draftBtn.disabled = true;+ draftBtn.textContent = 'Drafting…';+ try {+ const r = await fetch('/api/x/draft', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agent_id: avatar.agent_id || avatar.id, prompt: textEl.value.trim() }),+ });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || 'draft failed');+ textEl.value = data.text;+ countEl.textContent = data.text.length;+ setMsg('Draft ready — review and post.');+ } catch (err) {+ setMsg(err.message, '#ffb3b3');+ } finally {+ draftBtn.disabled = false;+ draftBtn.textContent = original;+ }+ });++ postBtn.addEventListener('click', async () => {+ const text = textEl.value.trim();+ if (!text) return setMsg('Write something first.', '#ffb3b3');+ postBtn.disabled = true;+ setMsg('Posting…');+ try {+ const r = await fetch('/api/x/post', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text, agent_id: avatar.agent_id || avatar.id }),+ });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || 'post failed');+ setMsg(`Posted: <a href="${data.url}" target="_blank" rel="noopener">${data.url}</a>`);+ textEl.value = '';+ countEl.textContent = 0;+ loadXPanel({ host, meterEl, bodyEl, avatar });+ } catch (err) {+ setMsg(err.message, '#ffb3b3');+ } finally {+ postBtn.disabled = false;+ }+ });++ scheduleBtn.addEventListener('click', async () => {+ const text = textEl.value.trim();+ if (!text) return setMsg('Write something first.', '#ffb3b3');+ const input = prompt('Schedule for (any date — e.g. "tomorrow 9am" or "2026-05-14T15:00"):', new Date(Date.now() + 3600_000).toISOString().slice(0, 16));+ if (!input) return;+ const when = new Date(input);+ if (isNaN(when.getTime())) return setMsg('Could not parse that date.', '#ffb3b3');+ setMsg('Scheduling…');+ try {+ const r = await fetch('/api/x/schedule', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text, scheduled_at: when.toISOString(), agent_id: avatar.agent_id || avatar.id }),+ });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || 'schedule failed');+ setMsg(`Scheduled for ${when.toLocaleString()}.`);+ textEl.value = '';+ countEl.textContent = 0;+ loadScheduledPosts(scheduledEl);+ } catch (err) {+ setMsg(err.message, '#ffb3b3');+ }+ });++ disconnectBtn.addEventListener('click', async () => {+ if (!confirm('Disconnect your X account from three.ws?')) return;+ try {+ await fetch('/api/x/status', { method: 'DELETE', credentials: 'include' });+ loadXPanel({ host, meterEl, bodyEl, avatar });+ } catch (err) {+ setMsg(err.message, '#ffb3b3');+ }+ });++ loadScheduledPosts(scheduledEl);+}++async function loadScheduledPosts(host) {+ if (!host) return;+ try {+ const r = await fetch('/api/x/schedule', { credentials: 'include' });+ const data = await r.json();+ const pending = (data.posts || []).filter((p) => !p.posted_at && !p.error);+ if (!pending.length) { host.innerHTML = ''; return; }+ host.innerHTML = `+ <div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em;margin-bottom:6px">Scheduled</div>+ ${pending.map((p) => `+ <div class="row" style="justify-content:space-between;padding:8px 10px;background:#0f0f17;border:1px solid #22222e;border-radius:8px;margin-bottom:6px;font-size:12px">+ <div style="flex:1;min-width:0">+ <div style="color:#ccc;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(p.text)}</div>+ <div class="muted" style="font-size:11px;margin-top:2px">${new Date(p.scheduled_at).toLocaleString()}</div>+ </div>+ <button class="btn sec" data-cancel="${attr(p.id)}" style="font-size:11px;padding:4px 8px">Cancel</button>+ </div>+ `).join('')}+ `;+ host.querySelectorAll('[data-cancel]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const id = btn.getAttribute('data-cancel');+ await fetch(`/api/x/schedule?id=${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' });+ loadScheduledPosts(host);+ });+ });+ } catch {}+}+// Lazy-load preview when card scrolls into view. For private avatars, fetch// a short-lived signed URL via /api/avatars/:id. Falls back to a thumbnail or// placeholder if no preview is available.@@ -1001,8 +1248,10 @@ async function renderEdit(root, params = []) {</form></div><div data-wallet-host style="margin-top:20px; max-width:560px; margin-left:auto; margin-right:auto"></div>+ <div data-x-host style="margin-top:20px; max-width:560px; margin-left:auto; margin-right:auto"></div>`;mountAvatarWalletSection(body.querySelector('[data-wallet-host]'), avatar);+ mountAgentXPanel(body.querySelector('[data-x-host]'), avatar);const msg = body.querySelector('#emsg');body.querySelector('#ef').addEventListener('submit', async (e) => {diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.htmlindex a3ee42c1f..55c30c421 100644--- a/public/dashboard/embed-policy.html+++ b/public/dashboard/embed-policy.html@@ -152,23 +152,38 @@gap: 12px;}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;}.btn.sec {- background: #222230;+ background: #15151d;color: #ddd;+ border-color: #22222e;+ }+ .btn.sec:hover:not(:disabled) {+ background: #1c1c26;+ border-color: #2e2e3e;}.btn.danger {- background: #3a1f24;+ background: #15151d;+ border-color: rgba(204, 64, 64, 0.4);color: #ff9c9c;}+ .btn.danger:hover:not(:disabled) {+ background: rgba(204, 64, 64, 0.12);+ border-color: rgba(204, 64, 64, 0.6);+ }.muted {color: #888;font-size: 13px;diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 56f299ff1..5fe2088f0 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -192,15 +192,17 @@.preview .ph button {margin-top: 8px;padding: 6px 12px;- border-radius: 7px;- border: 1px solid var(--border);- background: #1a1a24;+ border-radius: 6px;+ border: 1px solid #22222e;+ background: #15151d;color: #ddd;font-size: 12px;cursor: pointer;+ transition: border-color 0.12s ease, background 0.12s ease;}.preview .ph button:hover {- background: #22222e;+ background: #1c1c26;+ border-color: #2e2e3e;}.preview .spinner {width: 22px;@@ -232,9 +234,9 @@}.card .actions .btn,.card .actions a.btn {- padding: 6px 10px;+ padding: 6px 11px;font-size: 12px;- border-radius: 7px;+ border-radius: 6px;font-weight: 500;}.card .actions .danger {@@ -287,16 +289,18 @@padding: 14px 0;}.load-more button {- padding: 9px 18px;- border-radius: 9px;- border: 1px solid var(--border);- background: #1a1a24;+ padding: 8px 18px;+ border-radius: 6px;+ border: 1px solid #22222e;+ background: #15151d;color: #ddd;font-size: 13px;cursor: pointer;+ transition: border-color 0.12s ease, background 0.12s ease;}.load-more button:hover:not(:disabled) {- background: #22222e;+ background: #1c1c26;+ border-color: #2e2e3e;}.load-more button:disabled {opacity: 0.6;@@ -315,18 +319,33 @@color: #ccc;}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;+ filter: none;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;}.btn.sec {- background: #222230;+ background: #15151d;color: #ddd;+ border-color: #22222e;+ }+ .btn.sec:hover:not(:disabled) {+ background: #1c1c26;+ border-color: #2e2e3e;}.empty {text-align: center;@@ -402,21 +421,30 @@/* ── Widgets tab ─────────────────────────────────────────────────────── */.btn-primary {display: inline-block;- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;text-decoration: none;+ transition: border-color 0.12s ease, background 0.12s ease;}.btn-primary:hover {- filter: brightness(1.08);+ border-color: #3d3d52;+ background: #0a0a12;+ filter: none;}.btn-danger {- background: #cc4040;+ background: #15151d;+ border-color: rgba(204, 64, 64, 0.4);+ color: #ffb3b3;+ }+ .btn-danger:hover {+ background: rgba(204, 64, 64, 0.12);+ border-color: rgba(204, 64, 64, 0.6);}.widgets-header {display: flex;diff --git a/public/dashboard/sessions.html b/public/dashboard/sessions.htmlindex 4ae64de80..abdc740d3 100644--- a/public/dashboard/sessions.html+++ b/public/dashboard/sessions.html@@ -67,25 +67,41 @@font-size: 14px;}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;}.btn:disabled {opacity: 0.5;cursor: not-allowed;}.btn.sec {- background: #222230;+ background: #15151d;color: #ddd;+ border-color: #22222e;+ }+ .btn.sec:hover:not(:disabled) {+ background: #1c1c26;+ border-color: #2e2e3e;}.btn.danger {- background: #cc4040;+ background: #15151d;+ border-color: rgba(204, 64, 64, 0.4);+ color: #ffb3b3;+ }+ .btn.danger:hover:not(:disabled) {+ background: rgba(204, 64, 64, 0.12);+ border-color: rgba(204, 64, 64, 0.6);}.btn-group {display: flex;diff --git a/public/dashboard/storage.html b/public/dashboard/storage.htmlindex cc653d25e..b53ae7784 100644--- a/public/dashboard/storage.html+++ b/public/dashboard/storage.html@@ -145,22 +145,32 @@border: 1px solid rgba(255, 220, 92, 0.25);}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;+ }+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;}.btn:disabled {opacity: 0.5;cursor: not-allowed;}.btn.sec {- background: #222230;+ background: #15151d;color: #ddd;+ border-color: #22222e;+ }+ .btn.sec:hover:not(:disabled) {+ background: #1c1c26;+ border-color: #2e2e3e;}.muted {color: #888;diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.htmlindex 1da740689..34a17fcef 100644--- a/public/dashboard/wallets.html+++ b/public/dashboard/wallets.html@@ -69,24 +69,37 @@font-size: 14px;}.btn {- padding: 9px 14px;- border-radius: 9px;- border: 0;+ padding: 8px 14px;+ border-radius: 6px;+ border: 1px solid #2a2a36;font-size: 13px;font-weight: 600;cursor: pointer;- background: var(--accent);+ background: #000;color: #fff;+ transition: border-color 0.12s ease, background 0.12s ease;}- .btn:hover {- filter: brightness(1.08);+ .btn:hover:not(:disabled) {+ border-color: #3d3d52;+ background: #0a0a12;}.btn.sec {- background: #222230;+ background: #15151d;color: #ddd;+ border-color: #22222e;+ }+ .btn.sec:hover:not(:disabled) {+ background: #1c1c26;+ border-color: #2e2e3e;}.btn.danger {- background: #cc4040;+ background: #15151d;+ border-color: rgba(204, 64, 64, 0.4);+ color: #ffb3b3;+ }+ .btn.danger:hover:not(:disabled) {+ background: rgba(204, 64, 64, 0.12);+ border-color: rgba(204, 64, 64, 0.6);}.btn:disabled {opacity: 0.5;diff --git a/public/pay/index.html b/public/pay/index.htmlindex b617e9b59..45bebdb74 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -758,7 +758,8 @@ async function loadAgents() {const withWallet = agents.find(a => a.solana_address);if (withWallet) setSelectedAgent(withWallet);}- } catch {+ } catch (err) {+ console.warn('[pay] loadAgents failed:', err?.message || err);agentLoading.style.display = 'none';agentLoginCta.style.display = 'block';}@@ -1106,7 +1107,11 @@ async function* sseEvents(response) {}if (!dataLines.length) continue;let data = null;- try { data = JSON.parse(dataLines.join('\n')); } catch {}+ try {+ data = JSON.parse(dataLines.join('\n'));+ } catch (err) {+ console.warn('[pay] SSE JSON parse failed:', err?.message || err);+ }yield { event, data };}}@@ -1208,7 +1213,9 @@ async function refreshBalance() {if (updated) { selectedAgent = updated; setSelectedAgent(updated); }renderAgentCards(agents);}- } catch {}+ } catch (err) {+ console.warn('[pay] refreshBalance(agent) failed:', err?.message || err);+ }return;}// Shared demo wallet@@ -1221,7 +1228,10 @@ async function refreshBalance() {} else {walletText.textContent = 'agent wallet (no env)';}- } catch { walletText.textContent = 'agent wallet'; }+ } catch (err) {+ console.warn('[pay] refreshBalance(shared) failed:', err?.message || err);+ walletText.textContent = 'agent wallet';+ }}async function refreshFeed() {@@ -1237,7 +1247,9 @@ async function refreshFeed() {${it.tx ? `· <a href="https://solscan.io/tx/${it.tx}" target="_blank" rel="noopener">${it.tx.slice(0,6)}…</a>` : ''}</span>`).join('');feedStrip.innerHTML = make() + make();- } catch {}+ } catch (err) {+ console.warn('[pay] refreshFeed failed:', err?.message || err);+ }}// ---- Wire up ------------------------------------------------------------@@ -1300,11 +1312,11 @@ for (const [tool, alias] of []) {const url = params.get(alias);if (url) {- setTimeout(() => run({ tool, args: { url } }), 250);+ queueMicrotask(() => run({ tool, args: { url } }));break;}}-if (params.get('list') === '1') setTimeout(() => run({ tool: 'tools/list', args: {} }), 250);+if (params.get('list') === '1') queueMicrotask(() => run({ tool: 'tools/list', args: {} }));promptEl.focus();</script>diff --git a/scripts/smoke-paid-mcp.mjs b/scripts/smoke-paid-mcp.mjsindex 02d365f0c..bd25c826e 100755--- a/scripts/smoke-paid-mcp.mjs+++ b/scripts/smoke-paid-mcp.mjs@@ -50,6 +50,8 @@ async function step1_challenge() {const r = await postMcp();if (r.status !== 402) return bad(`expected 402, got ${r.status}`);ok('returns 402');+ const x402Version = r.json?.x402Version;+ if (x402Version !== 2) bad(`expected x402Version=2 (Coinbase v2), got ${x402Version}`);const accepts = r.json?.accepts;if (!Array.isArray(accepts) || accepts.length === 0)return bad('missing accepts[] in 402 body');@@ -57,10 +59,12 @@ async function step1_challenge() {const tag = `${a.network}/${a.scheme}`;if (!a.payTo) bad(`${tag}: missing payTo`);if (!a.asset) bad(`${tag}: missing asset`);- if (!a.maxAmountRequired) bad(`${tag}: missing maxAmountRequired`);- if (a.network === 'solana' && !a.extra?.feePayer)+ // v2 wire uses `amount`, not `maxAmountRequired`.+ if (!a.amount) bad(`${tag}: missing amount (v2 spec)`);+ if (a.network?.startsWith('solana:') && !a.extra?.feePayer)bad(`${tag}: missing extra.feePayer (clients cannot build tx)`);- else ok(`${tag}: ${a.payTo.slice(0, 8)}… amount=${a.maxAmountRequired}`);+ else if (a.payTo && a.amount)+ ok(`${tag}: ${a.payTo.slice(0, 8)}… amount=${a.amount}`);}return accepts;}@@ -69,31 +73,31 @@ async function step2_verifyReachable(accepts) {console.log('\n[2] facilitator /verify reachability per network');for (const a of accepts) {// Shape-correct but unsigned payload — facilitator should respond with- // a structured invalidReason (not a 5xx network error).- const payload =- a.network === 'solana'- ? {- x402Version: 1,- scheme: 'exact',- network: a.network,- payload: { transaction: 'AAA', payer: '11111111111111111111111111111111' },- }- : {- x402Version: 1,- scheme: 'exact',- network: a.network,- payload: {- signature: '0x' + '00'.repeat(65),- authorization: {- from: '0x' + '00'.repeat(20),- to: a.payTo,- value: a.maxAmountRequired,- validAfter: '0',- validBefore: '99999999999',- nonce: '0x' + '00'.repeat(32),- },+ // a structured invalidReason (not a 5xx network error). v2 wire shape.+ const isSolana = a.network?.startsWith('solana:');+ const payload = isSolana+ ? {+ x402Version: 2,+ scheme: 'exact',+ network: a.network,+ payload: { transaction: 'AAA', payer: '11111111111111111111111111111111' },+ }+ : {+ x402Version: 2,+ scheme: 'exact',+ network: a.network,+ payload: {+ signature: '0x' + '00'.repeat(65),+ authorization: {+ from: '0x' + '00'.repeat(20),+ to: a.payTo,+ value: a.amount,+ validAfter: '0',+ validBefore: '99999999999',+ nonce: '0x' + '00'.repeat(32),},- };+ },+ };const xPayment = Buffer.from(JSON.stringify(payload)).toString('base64');const r = await postMcp({ 'x-payment': xPayment });if (r.status === 502 && /No facilitator registered/i.test(r.text))diff --git a/scripts/verify-x402-endpoints.mjs b/scripts/verify-x402-endpoints.mjsnew file mode 100644index 000000000..0839f670f--- /dev/null+++ b/scripts/verify-x402-endpoints.mjs@@ -0,0 +1,135 @@+#!/usr/bin/env node+// Exercise each x402 HTTP endpoint by invoking the Vercel function handler+// directly against a synthesized req/res pair. Confirms the 402 challenge,+// the Bazaar discovery manifest, and the x402-status probe all return v2+// shapes against the current code — no dev server required.++import { createServer } from 'node:http';+import { once } from 'node:events';++process.env.X402_PAY_TO_SOLANA ??= 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';+process.env.X402_PAY_TO_BASE ??= '0x0C70c0e8453C5667739E41acdF6eC5787B8ff542';+process.env.X402_ASSET_MINT_SOLANA ??= 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_ADDRESS_BASE ??= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+process.env.X402_MAX_AMOUNT_REQUIRED ??= '1000';+process.env.X402_FEE_PAYER_SOLANA ??= '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';+process.env.PUBLIC_APP_ORIGIN ??= 'https://three.ws/';++const failures = [];+const ok = (msg) => console.log(` ok ${msg}`);+const fail = (msg) => {+ console.log(` FAIL ${msg}`);+ failures.push(msg);+};++async function call(handler, { method = 'GET', path = '/', headers = {}, body = null } = {}) {+ const server = createServer((req, res) => {+ req.url = path;+ req.method = method;+ Object.assign(req.headers, headers);+ handler(req, res);+ });+ server.listen(0);+ await once(server, 'listening');+ const { port } = server.address();+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {+ method,+ headers,+ body: body != null ? (typeof body === 'string' ? body : JSON.stringify(body)) : undefined,+ });+ const text = await res.text();+ server.close();+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ // non-JSON response+ }+ return { status: res.status, headers: Object.fromEntries(res.headers.entries()), text, json };+}++console.log('\n[1] POST /api/mcp without X-PAYMENT → 402 v2 challenge');+const { default: mcpHandler } = await import('../api/mcp.js');+const r1 = await call(mcpHandler, {+ method: 'POST',+ path: '/api/mcp',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: { jsonrpc: '2.0', id: 1, method: 'tools/list' },+});+if (r1.status !== 402) fail(`expected 402, got ${r1.status} body=${r1.text.slice(0, 200)}`);+else {+ ok('returns 402');+ if (r1.json?.x402Version !== 2) fail(`x402Version=${r1.json?.x402Version}, expected 2`);+ else ok('x402Version=2');+ if (!Array.isArray(r1.json?.accepts) || r1.json.accepts.length === 0)+ fail('missing accepts[]');+ else+ for (const a of r1.json.accepts) {+ if (!a.amount) fail(`${a.network}: missing 'amount' (v2 field)`);+ else if ('maxAmountRequired' in a) fail(`${a.network}: legacy v1 field present`);+ else ok(`${a.network}/${a.scheme} amount=${a.amount} payTo=${a.payTo?.slice(0, 8)}…`);+ }+ if (!r1.json?.resource?.url) fail('missing top-level resource.url');+ else ok(`resource.url=${r1.json.resource.url}`);+ if (!r1.json?.extensions?.bazaar?.discoverable) fail('bazaar extension missing');+ else ok('bazaar discoverable');+ // payment-required header mirror+ if (!r1.headers['payment-required']) fail('payment-required response header missing');+ else {+ const decoded = JSON.parse(Buffer.from(r1.headers['payment-required'], 'base64').toString('utf8'));+ if (decoded.x402Version === 2) ok('payment-required header mirrors body (v2)');+ else fail(`payment-required header version=${decoded.x402Version}`);+ }+}++console.log('\n[2] GET /.well-known/x402 → Bazaar discovery manifest');+const { default: wkHandler } = await import('../api/wk-x402.js');+const r2 = await call(wkHandler, {+ method: 'GET',+ path: '/.well-known/x402',+});+if (r2.status !== 200) fail(`expected 200, got ${r2.status} body=${r2.text.slice(0, 200)}`);+else {+ ok('returns 200');+ if (!r2.json) fail('non-JSON body');+ else if (r2.json.x402Version !== 2 && !Array.isArray(r2.json.resources) && !Array.isArray(r2.json.accepts))+ fail(`discovery payload missing version/resources/accepts: ${JSON.stringify(r2.json).slice(0, 200)}`);+ else ok(`discovery keys: ${Object.keys(r2.json).join(', ')}`);+}++console.log('\n[3] GET /api/x402-status → facilitator probe');+const { default: statusHandler } = await import('../api/x402-status.js');+const r3 = await call(statusHandler, {+ method: 'GET',+ path: '/api/x402-status',+});+if (r3.status !== 200) fail(`expected 200, got ${r3.status} body=${r3.text.slice(0, 200)}`);+else {+ ok('returns 200');+ if (!r3.json || !Array.isArray(r3.json.facilitators))+ fail('missing facilitators[]');+ else {+ ok(`facilitators=${r3.json.facilitators.length}`);+ for (const f of r3.json.facilitators)+ console.log(` - ${f.network} ${f.ok ? 'OK' : 'NOT OK'} (${f.reason || 'no reason'})`);+ }+}++console.log('\n[4] POST /api/x402-pay (no agentId) without env wallet → 503 wallet_unconfigured');+process.env.NODE_ENV = 'production';+delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;+const { default: payHandler } = await import('../api/x402-pay.js');+const r4 = await call(payHandler, {+ method: 'POST',+ path: '/api/x402-pay',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: { tool: 'tools/list', args: {} },+});+// Either 500 (wallet_unconfigured surfaced via dispatch) or earlier — accept any 4xx/5xx with a clear error.+if (r4.status === 200) fail(`expected error status when wallet unconfigured, got 200`);+else if (!r4.json || (!r4.json.error && !/wallet/.test(r4.text)))+ fail(`response did not surface wallet config error: ${r4.text.slice(0, 200)}`);+else ok(`responds ${r4.status} with ${r4.json?.error || 'wallet error'} (no /home/codespace fallthrough)`);++console.log('\n' + (failures.length === 0 ? 'PASS' : `FAIL (${failures.length})`));+process.exit(failures.length === 0 ? 0 : 1);diff --git a/scripts/verify-x402-wire.mjs b/scripts/verify-x402-wire.mjsnew file mode 100644index 000000000..4ca34049f--- /dev/null+++ b/scripts/verify-x402-wire.mjs@@ -0,0 +1,86 @@+#!/usr/bin/env node+// Local invariant check: server's 402 envelope <-> SDK's payment payload+// share the exact wire shape required by the Coinbase x402 v2 spec.+//+// Asserts (no network calls — pure import smoke):+// 1. paymentRequirements() returns v2-shape `accepts[]` entries+// with `amount` (NOT `maxAmountRequired`).+// 2. build402Body() emits `x402Version: 2`, top-level resource{}, accepts[], extensions.bazaar.+// 3. SDK's PaymentPayload shape carries top-level `scheme` + `network`+// that match the server's selectRequirement() lookup.+// 4. SDK's X-PAYMENT header constant equals what auth.js reads.++import assert from 'node:assert/strict';++process.env.X402_PAY_TO_SOLANA ??= 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';+process.env.X402_PAY_TO_BASE ??= '0x0C70c0e8453C5667739E41acdF6eC5787B8ff542';+process.env.X402_ASSET_MINT_SOLANA ??= 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_ADDRESS_BASE ??= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+process.env.X402_MAX_AMOUNT_REQUIRED ??= '1000';+process.env.X402_FEE_PAYER_SOLANA ??= '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';++const {+ paymentRequirements,+ build402Body,+ X402_VERSION,+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+} = await import('../api/_lib/x402-spec.js');+const { x402: sdkX402 } = await import('../agent-payments-sdk/dist/solana/index.js');+const { X402_HEADER_PAYMENT, X402_HEADER_PAYMENT_RESPONSE } = sdkX402;++console.log('[verify] server constants');+assert.equal(X402_VERSION, 2, 'server X402_VERSION must be 2');+assert.equal(NETWORK_BASE_MAINNET, 'eip155:8453');+assert.equal(+ NETWORK_SOLANA_MAINNET,+ 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+);++console.log('[verify] paymentRequirements() shape');+const reqs = paymentRequirements();+assert.ok(Array.isArray(reqs) && reqs.length >= 1, 'must return at least one accept');+for (const r of reqs) {+ assert.equal(r.scheme, 'exact', `scheme must be 'exact', got ${r.scheme}`);+ assert.ok(r.amount, `v2 spec requires 'amount' (not maxAmountRequired) on ${r.network}`);+ assert.ok(!('maxAmountRequired' in r), `must not emit legacy v1 field on ${r.network}`);+ assert.ok(r.payTo, `${r.network} missing payTo`);+ assert.ok(r.asset, `${r.network} missing asset`);+ assert.ok(r.network.includes(':'), `${r.network} must be CAIP-2`);+ if (r.network.startsWith('solana:'))+ assert.ok(r.extra?.feePayer, `Solana accepts must include extra.feePayer`);+ console.log(` ok ${r.network}/${r.scheme} amount=${r.amount} payTo=${r.payTo.slice(0, 8)}…`);+}++console.log('[verify] build402Body() envelope');+const body = build402Body({+ resourceUrl: 'https://three.ws/api/mcp',+ accepts: reqs,+});+assert.equal(body.x402Version, 2);+assert.equal(typeof body.resource, 'object');+assert.equal(body.resource.url, 'https://three.ws/api/mcp');+assert.ok(Array.isArray(body.accepts));+assert.ok(body.extensions?.bazaar?.discoverable, 'bazaar discovery extension must be present');+console.log(` ok x402Version=${body.x402Version} accepts=${body.accepts.length} bazaar=discoverable`);++console.log('[verify] SDK header constants match server reads');+assert.equal(X402_HEADER_PAYMENT, 'X-PAYMENT', 'SDK must send X-PAYMENT, server reads x-payment');+assert.equal(X402_HEADER_PAYMENT_RESPONSE, 'X-PAYMENT-RESPONSE');+console.log(` ok X-PAYMENT / X-PAYMENT-RESPONSE`);++console.log('[verify] PaymentPayload shape interop (SDK builds → server selectRequirement reads)');+const accept = reqs.find((r) => r.network === NETWORK_SOLANA_MAINNET);+const sdkPayload = {+ x402Version: 2,+ scheme: accept.scheme,+ network: accept.network,+ resource: 'https://three.ws/api/mcp',+ accepted: accept,+ payload: { transaction: 'base64...', payer: '11111111111111111111111111111111' },+};+// Server's selectRequirement reads paymentPayload.network OR paymentPayload.paymentRequirements?.network+assert.equal(sdkPayload.network, accept.network);+console.log(` ok top-level network=${sdkPayload.network} matches server selectRequirement()`);++console.log('\nPASS — server <-> SDK wire shapes are aligned.');diff --git a/scripts/x402-pay-three-ws.mjs b/scripts/x402-pay-three-ws.mjsindex 6ac0dbbbe..b46b0ffcb 100644--- a/scripts/x402-pay-three-ws.mjs+++ b/scripts/x402-pay-three-ws.mjs@@ -56,7 +56,7 @@ const types = {],};-console.log('[x402] signing EIP-3009 transferWithAuthorization (v1 payload)...');+console.log('[x402] signing EIP-3009 transferWithAuthorization (v2 payload)...');const signature = await account.signTypedData({domain,types,@@ -72,7 +72,7 @@ const signature = await account.signTypedData({});const paymentPayload = {- x402Version: 1,+ x402Version: 2,scheme: 'exact',network: 'eip155:8453',payload: { signature, authorization },@@ -81,7 +81,7 @@ console.log(' payload keys:', Object.keys(paymentPayload), ' size:', Buffer.bytconst xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');-console.log('[x402] POST 2 (X-PAYMENT, v1 payload)');+console.log('[x402] POST 2 (X-PAYMENT, v2 payload)');const t0 = Date.now();const paidRes = await fetch(url, {method: 'POST',diff --git a/solana-agent-sdk/src/x402-exact/client.ts b/solana-agent-sdk/src/x402-exact/client.tsindex 9b1d4dfcc..fb9fdc817 100644--- a/solana-agent-sdk/src/x402-exact/client.ts+++ b/solana-agent-sdk/src/x402-exact/client.ts@@ -2,7 +2,7 @@* x402 "exact" scheme client — SPL TransferChecked payment.** Builds a TransferChecked transaction, signs + sends it, and returns the- * tx signature as the proof payload for the PAYMENT-SIGNATURE header.+ * tx signature as the proof payload for the X-PAYMENT header.** Compatible with the x402 v2 spec and the PaymentPayload/PaymentRequirements* types from @pump-fun/agent-payments-sdk/x402.@@ -30,7 +30,7 @@ export interface ExactPaymentProof {/*** Pay using the "exact" x402 scheme.- * Returns the proof to include in the PAYMENT-SIGNATURE header payload.+ * Returns the proof to include in the X-PAYMENT header payload.*/export async function payExact(wallet: WalletProvider,@@ -81,7 +81,11 @@ export async function payExact(/*** Build an x402 PaymentPayload for the "exact" scheme.- * Pass the result to encodePaymentPayload() before attaching to PAYMENT-SIGNATURE header.+ *+ * Pass the result to `encodePaymentPayload()` before attaching to the+ * `X-PAYMENT` request header on the retry. Top-level `scheme` and `network`+ * mirror the chosen `accepts[]` entry so the server's facilitator can route+ * the proof without re-walking the nested `accepted` object.*/export function buildExactPaymentPayload(requirements: ExactPaymentRequirements,@@ -90,6 +94,8 @@ export function buildExactPaymentPayload() {return {x402Version: 2 as const,+ scheme: requirements.scheme,+ network: requirements.network,resource: resourceUrl,accepted: requirements,payload: proof,diff --git a/src/onchain/x402/client.js b/src/onchain/x402/client.jsindex b9fb3fdff..9367f925a 100644--- a/src/onchain/x402/client.js+++ b/src/onchain/x402/client.js@@ -97,17 +97,23 @@ export async function x402Fetch(url, opts = {}) {}async function fetchAgentSnippet(agentId) {- try {- const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {- credentials: 'include',- });- if (!r.ok) return {};- const data = await r.json();- return {- payments: data?.agent?.payments || data?.payments,- meta: { payments: data?.agent?.payments || data?.payments },- };- } catch {- return {};+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {+ credentials: 'include',+ });+ if (!r.ok) {+ throw new Error(+ `x402: failed to load agent ${agentId} (status ${r.status}); cannot route payment without payments config`,+ );+ }+ const data = await r.json();+ const payments = data?.agent?.payments || data?.payments;+ if (!payments) {+ throw new Error(+ `x402: agent ${agentId} has no payments config; cannot route payment`,+ );}+ return {+ payments,+ meta: { payments },+ };}diff --git a/vercel.json b/vercel.jsonindex 25cae025b..3f4eb6907 100644--- a/vercel.json+++ b/vercel.json@@ -1286,6 +1286,10 @@"path": "/api/cron/run-subscriptions","schedule": "0 * * * *"},+ {+ "path": "/api/cron/run-x-scheduled-posts",+ "schedule": "* * * * *"+ },{"path": "/api/cron/pumpfun-signals","schedule": "*/15 * * * *"