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
refactor: consolidate Solana payment endpoints and remove deprecated files
nirholas64bffbe3ca35
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.jsnew file mode 100644index 000000000..4daf6d49c--- /dev/null+++ b/api/_lib/pumpfun-ws-feed.js@@ -0,0 +1,122 @@+// Pump.fun public WebSocket feed — no Redis or Solana RPC required.+// Uses pump.fun's Socket.IO endpoint for live mint events and polls+// their REST API for graduation (migration) events.++import WebSocket from 'ws';++const PUMP_WS = 'wss://frontend-api.pump.fun/socket.io/?EIO=4&transport=websocket';+const PUMP_REST = 'https://frontend-api.pump.fun';+const GRAD_POLL_MS = 5_000;++/**+ * Connect to the pump.fun public feed.+ * @param {{ onEvent: Function, signal?: AbortSignal, kind?: string }} opts+ * kind: 'all' | 'mint' | 'graduation' (default 'all')+ * onEvent: ({ kind, data }) => void+ * @returns {Function} cleanup — call to stop everything early+ */+export function connectPumpFunFeed({ onEvent, signal, kind = 'all' }) {+ let active = true;+ let ws = null;+ let pollTimer = null;+ const seenGrad = new Set();++ function stop() {+ active = false;+ clearTimeout(pollTimer);+ if (ws) try { ws.close(); } catch {}+ }++ signal?.addEventListener('abort', stop);++ // Socket.IO WebSocket for real-time mint events+ if (kind === 'all' || kind === 'mint') {+ ws = new WebSocket(PUMP_WS, {+ headers: { Origin: 'https://pump.fun', 'User-Agent': 'Mozilla/5.0' },+ });++ ws.on('open', () => {+ ws.send('40'); // Engine.IO → Socket.IO connect+ });++ ws.on('message', (raw) => {+ if (!active) return;+ const str = raw.toString();++ if (str === '2') { ws.send('3'); return; } // ping → pong++ if (str.startsWith('40')) {+ // Socket.IO connected — subscribe to new tokens+ ws.send('42["subscribeNewToken"]');+ return;+ }++ if (!str.startsWith('42')) return;+ let msg;+ try { msg = JSON.parse(str.slice(2)); } catch { return; }+ const [event, data] = msg;++ if (event === 'newCoinCreated' && data?.mint) {+ onEvent({ kind: 'mint', data: normalizeMint(data) });+ }+ });++ ws.on('error', (err) => console.error('[pumpfun-ws] error:', err?.message));+ }++ // REST polling for graduations (pump.fun doesn't emit these on Socket.IO)+ if (kind === 'all' || kind === 'graduation') {+ const pollGrads = async () => {+ if (!active) return;+ try {+ const r = await fetch(`${PUMP_REST}/coins/migrated?limit=20`, {+ headers: { 'User-Agent': 'Mozilla/5.0' },+ signal: signal ?? undefined,+ });+ if (r.ok) {+ const coins = await r.json();+ const list = Array.isArray(coins) ? coins : (coins?.coins ?? []);+ for (const coin of list) {+ const id = coin.tx_hash || coin.mint;+ if (seenGrad.has(id)) continue;+ seenGrad.add(id);+ if (seenGrad.size > 500) {+ const oldest = seenGrad.values().next().value;+ seenGrad.delete(oldest);+ }+ onEvent({ kind: 'graduation', data: normalizeGrad(coin) });+ }+ }+ } catch {}+ if (active) pollTimer = setTimeout(pollGrads, GRAD_POLL_MS);+ };+ pollGrads();+ }++ return stop;+}++function normalizeMint(d) {+ return {+ mint: d.mint,+ name: d.name,+ symbol: d.symbol,+ image_uri: d.image_uri,+ creator: d.creator,+ created_timestamp: d.created_timestamp,+ usd_market_cap: d.usd_market_cap,+ description: d.description,+ };+}++function normalizeGrad(d) {+ return {+ tx_signature: d.tx_hash || null,+ signature: d.tx_hash || null,+ mint: d.mint,+ name: d.name,+ symbol: d.symbol,+ usd_market_cap: d.usd_market_cap,+ raydium_pool: d.raydium_pool,+ };+}diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 1c2b5211c..526576d41 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -30,16 +30,8 @@ export default wrap(async function handler(req, res) {if (sub === 'wallet') return handleWallet(req, res, id);if (sub === 'solana') {- if (action === 'activity') {- const mod = await import('./solana-activity.js');- return mod.default(req, res, id);- }- if (action === 'airdrop') {- const mod = await import('./solana-airdrop.js');- return mod.default(req, res, id);- }const mod = await import('./solana-wallet.js');- return mod.default(req, res, id);+ return mod.default(req, res, id, action);}if (sub === 'sns') {diff --git a/api/agents/pumpfun-feed.js b/api/agents/pumpfun-feed.jsindex 774a44adf..1cb5ac70f 100644--- a/api/agents/pumpfun-feed.js+++ b/api/agents/pumpfun-feed.js@@ -1,23 +1,23 @@/*** GET /api/agents/pumpfun-feed* ---------------------------------- * Live pump.fun activity feed for Solana agents. Streams `claim` and- * `graduation` events as Server-Sent Events.+ * Live pump.fun activity feed. Streams `mint`, `graduation`, and `claim`+ * events as Server-Sent Events.** Auth: session OR bearer (scope `mcp` or `profile`).- * Query: ?kind=claims|graduations|all (default all)- * ?minTier=notable|influencer|mega (claim filter, optional)+ * Query: ?kind=all|mint|graduation|claims (default all)+ * ?minTier=notable|influencer|mega (claim filter, optional)*- * Implementation: serverless functions cannot hold long-lived connections- * efficiently, so we run a bounded poll loop (every 4s, up to 90s) and let- * the browser EventSource auto-reconnect. Each tick fetches `claimsSince`- * from the upstream pumpfun-claims-bot and emits new events.+ * Sources (in priority order):+ * 1. pump.fun public WebSocket (always available — mint + graduation)+ * 2. Redis/pumpfun-bot (optional — adds claim events when configured)*/import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { cors, method, error, wrap } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';+import { limits } from '../_lib/rate-limit.js';import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';+import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';const POLL_MS = 4000;const MAX_DURATION_MS = 90_000;@@ -50,58 +50,64 @@ export default wrap(async (req, res) => {res.setHeader('x-accel-buffering', 'no');res.flushHeaders?.();- // When the upstream feed isn't provisioned, open the SSE stream and close- // it cleanly — a 503 here would trigger EventSource auto-reconnect storms.- if (!pumpfunBotEnabled()) {- writeSse(res, 'disabled', { reason: 'pumpfun feed not configured' });- writeSse(res, 'close', { reason: 'not_configured' });- res.end();- return;- }+ const started = Date.now();+ let active = true;+ req.on('close', () => { active = false; });++ const wsAbort = new AbortController();+ req.on('close', () => wsAbort.abort());- writeSse(res, 'open', { kind, minTier: minTierParam || null });+ // Event queue fed by the pump.fun WebSocket+ const queue = [];+ const wsKind = kind === 'claims' ? 'graduation' : kind; // claims come from bot only+ const stopWs = connectPumpFunFeed({+ kind: wsKind,+ signal: wsAbort.signal,+ onEvent: ({ kind: evKind, data }) => {+ if (active) queue.push({ evKind, data });+ },+ });++ writeSse(res, 'open', { kind, minTier: minTierParam || null, source: 'websocket' });+ // Optional: also poll Redis/bot for claim events if configuredconst seen = new Set();let lastSig = null;- const started = Date.now();- let active = true;- req.on('close', () => {- active = false;- });- const tick = async () => {- const tasks = [];- if (kind === 'claims' || kind === 'all') {- tasks.push(pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 }).then((r) => ({ t: 'claim', r })));- }- if (kind === 'graduations' || kind === 'all') {- tasks.push(pumpfunMcp.graduations({ limit: 10 }).then((r) => ({ t: 'graduation', r })));- }- const results = await Promise.all(tasks);- for (const { t, r } of results) {- if (!r.ok) continue;- const items = Array.isArray(r.data) ? r.data : r.data?.items || [];- for (const ev of items) {- const id = ev.tx_signature || ev.signature || ev.id;- if (!id || seen.has(id)) continue;- seen.add(id);- if (t === 'claim') {+ const tickClaims = pumpfunBotEnabled()+ ? async () => {+ if (kind !== 'claims' && kind !== 'all') return;+ const r = await pumpfunMcp.claimsSince({ sinceSig: lastSig, limit: 25 });+ if (!r.ok) return;+ const items = Array.isArray(r.data) ? r.data : r.data?.items || [];+ for (const ev of items) {+ const id = ev.tx_signature || ev.signature || ev.id;+ if (!id || seen.has(id)) continue;+ seen.add(id);if (minTier && TIER_RANK[(ev.tier || '').toLowerCase()] < minTier) continue;lastSig = id;+ writeSse(res, 'claim', ev);}- writeSse(res, t, ev);- }- }- };+ }+ : null;while (active && Date.now() - started < MAX_DURATION_MS) {- try {- await tick();- } catch {}+ // Drain WebSocket event queue+ while (queue.length > 0 && active) {+ const { evKind, data } = queue.shift();+ writeSse(res, evKind, data);+ }++ // Pull claim events from Redis/bot if available+ if (tickClaims) {+ try { await tickClaims(); } catch {}+ }+writeSse(res, 'ping', { t: Date.now() });await sleep(POLL_MS);}+ stopWs();writeSse(res, 'close', { reason: 'duration_limit' });res.end();});diff --git a/api/agents/solana-activity.js b/api/agents/solana-activity.jsdeleted file mode 100644index 486ec6f78..000000000--- a/api/agents/solana-activity.js+++ /dev/null@@ -1,96 +0,0 @@-// /api/agents/:id/solana/activity?network=mainnet|devnet&limit=20-//-// Returns recent on-chain activity for the agent's Solana wallet:-// • signatures (most-recent first), with slot, blockTime, success/failure,-// SOL delta from this address's perspective, and a short description.-// Owner-only.--import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';-import { cors, json, method, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { solanaConnection } from '../_lib/agent-pumpfun.js';-import { PublicKey } from '@solana/web3.js';--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}--export default async function handler(req, res, id) {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const [row] = await sql`- SELECT id, user_id, meta FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- `;- if (!row) return error(res, 404, 'not_found', 'agent not found');- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');-- const address = row.meta?.solana_address;- if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');-- const url = new URL(req.url, 'http://x');- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';- const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10) || 20, 50);-- let signatures = [];- try {- const conn = solanaConnection(network);- const pk = new PublicKey(address);- const sigs = await conn.getSignaturesForAddress(pk, { limit });-- // Fetch parsed details in batches to compute SOL deltas.- const parsed = await conn.getParsedTransactions(- sigs.map((s) => s.signature),- { maxSupportedTransactionVersion: 0, commitment: 'confirmed' },- );-- signatures = sigs.map((s, i) => {- const tx = parsed[i];- let lamportDelta = null;- let summary = null;- if (tx?.meta && tx?.transaction) {- const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());- const idx = keys.indexOf(address);- if (idx >= 0 && tx.meta.preBalances && tx.meta.postBalances) {- lamportDelta = tx.meta.postBalances[idx] - tx.meta.preBalances[idx];- }- const ix = tx.transaction.message.instructions?.[0];- if (ix?.parsed?.type) summary = ix.parsed.type;- else if (ix?.programId) summary = `program ${ix.programId.toString().slice(0, 6)}…`;- }- return {- signature: s.signature,- slot: s.slot,- block_time: s.blockTime ?? null,- success: !s.err && !tx?.meta?.err,- error: s.err || tx?.meta?.err || null,- lamport_delta: lamportDelta,- sol_delta: lamportDelta == null ? null : lamportDelta / 1e9,- summary,- };- });- } catch (err) {- console.error('[agents/solana-activity] RPC fetch failed', err);- return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');- }-- return json(res, 200, {- data: {- address,- network,- signatures,- },- });-}diff --git a/api/agents/solana-airdrop.js b/api/agents/solana-airdrop.jsdeleted file mode 100644index a6228ec3f..000000000--- a/api/agents/solana-airdrop.js+++ /dev/null@@ -1,77 +0,0 @@-// /api/agents/:id/solana/airdrop (POST, devnet only)-//-// Owner-only. Requests a 1 SOL devnet airdrop to the agent's wallet.-// Mainnet rejected — there's no mainnet faucet.-// Heavily rate-limited to avoid faucet abuse.--import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';-import { cors, json, method, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { solanaConnection } from '../_lib/agent-pumpfun.js';-import { PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';-import { recordEvent } from '../_lib/usage.js';--const AIRDROP_LAMPORTS = LAMPORTS_PER_SOL; // 1 SOL--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}--export default async function handler(req, res, id) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const [row] = await sql`- SELECT id, user_id, meta FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL- `;- if (!row) return error(res, 404, 'not_found', 'agent not found');- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');-- const address = row.meta?.solana_address;- if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');-- let signature;- try {- const conn = solanaConnection('devnet');- signature = await conn.requestAirdrop(new PublicKey(address), AIRDROP_LAMPORTS);- await conn.confirmTransaction(signature, 'confirmed');- } catch (err) {- console.error('[agents/solana-airdrop] failed', err);- // Devnet faucet often runs dry — surface as 502 not 500.- return error(res, 502, 'faucet_unavailable',- err?.message?.includes('429') || err?.message?.includes('limit')- ? 'Devnet faucet is rate-limited — try again in a minute.'- : `Devnet airdrop failed: ${err?.message || 'unknown'}`);- }-- recordEvent({- userId: auth.userId,- agentId: id,- kind: 'solana_airdrop',- tool: 'devnet',- status: 'ok',- meta: { address, signature, lamports: AIRDROP_LAMPORTS },- });-- return json(res, 200, {- data: {- signature,- address,- network: 'devnet',- lamports: AIRDROP_LAMPORTS,- sol: AIRDROP_LAMPORTS / 1e9,- },- });-}diff --git a/api/agents/solana-attest-event.js b/api/agents/solana-attest-event.jsdeleted file mode 100644index d52a241f7..000000000--- a/api/agents/solana-attest-event.js+++ /dev/null@@ -1,145 +0,0 @@-// Pumpkit -> attestation bridge.-// Receives a signed webhook from a pumpkit monitor and emits a-// threews.* SPL Memo on Solana, then mirrors it into solana_attestations-// so reputation reflects the event without waiting for the crawler.-//-// Webhook contract:-// POST /api/agents/solana-attest-event-// headers:-// x-pumpkit-timestamp: <unix seconds>-// x-pumpkit-signature: hex(hmac_sha256(secret, "<ts>.<raw-body>"))-// body: { event_id, event_type, agent_asset, network, token_mint, task_id, detail? }-//-// Idempotency: each (agent_asset, payload.event_id) pair is emitted at most once.-// Replay: rejects timestamps outside REPLAY_WINDOW_SECS.--import crypto from 'node:crypto';-import { z } from 'zod';--import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { parse } from '../_lib/validate.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { recordEvent } from '../_lib/usage.js';-import {- mintAttestation,- loadAttesterKeypair,- taskHash as _taskHash,- buildPayload as _buildPayload,-} from '../_lib/attest-event.js';--const REPLAY_WINDOW_SECS = 5 * 60;-const MAX_BODY_BYTES = 64_000;--const bodySchema = z.object({- event_id: z.string().min(1).max(128),- event_type: z.enum(['graduation', 'fee_claim', 'whale_trade', 'cto_detected']),- agent_asset: z.string().min(32).max(44),- network: z.enum(['mainnet', 'devnet']),- token_mint: z.string().min(32).max(44),- task_id: z.string().min(1).max(128),- detail: z.record(z.unknown()).optional(),-});--// -- Pure helpers (re-exported for tests, backed by the shared core) -------export const taskHash = _taskHash;-export const buildPayload = _buildPayload;--// Signed message is `${timestamp}.${raw}` — binds body to its declared time-// so a captured signature can't be replayed against a fresh body.-export function verifyPumpkitSignature({ secret, timestamp, signature, raw, nowSecs = Math.floor(Date.now() / 1000) }) {- if (!secret || !timestamp || !signature) return { ok: false, reason: 'missing' };- const ts = Number(timestamp);- if (!Number.isFinite(ts)) return { ok: false, reason: 'bad_timestamp' };- if (Math.abs(nowSecs - ts) > REPLAY_WINDOW_SECS) return { ok: false, reason: 'stale' };-- const expect = crypto.createHmac('sha256', secret)- .update(`${ts}.`).update(raw).digest();- let got;- try { got = Buffer.from(signature, 'hex'); }- catch { return { ok: false, reason: 'bad_signature' }; }- if (got.length !== expect.length) return { ok: false, reason: 'bad_signature' };- return { ok: crypto.timingSafeEqual(got, expect), reason: 'ok' };-}--// -- Handler ---------------------------------------------------------------async function readBuffered(req) {- const chunks = [];- let total = 0;- for await (const c of req) {- chunks.push(c);- total += c.length;- if (total > MAX_BODY_BYTES) throw Object.assign(new Error('payload too large'), { status: 413 });- }- return Buffer.concat(chunks);-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;- if (!method(req, res, ['POST'])) return;-- const startedAt = Date.now();-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const secret = process.env.PUMPKIT_WEBHOOK_SECRET;- if (!secret) return error(res, 500, 'internal', 'webhook secret not configured');-- const raw = await readBuffered(req);- const verdict = verifyPumpkitSignature({- secret,- timestamp: req.headers['x-pumpkit-timestamp'],- signature: req.headers['x-pumpkit-signature'],- raw,- });- if (!verdict.ok) return error(res, 401, 'unauthorized', `invalid webhook signature (${verdict.reason})`);-- let parsed;- try { parsed = JSON.parse(raw.toString('utf8')); }- catch { return error(res, 400, 'validation_error', 'invalid JSON'); }- const body = parse(bodySchema, parsed);-- const [agent] = await sql`- select id, user_id from agent_identities- where meta->'onchain'->>'sol_asset' = ${body.agent_asset}- or meta->>'sol_mint_address' = ${body.agent_asset}- limit 1- `;- if (!agent) return error(res, 404, 'not_found', 'agent_asset not registered');-- const result = await mintAttestation({- event_id: body.event_id,- event_type: body.event_type,- source: `pumpkit.${body.event_type === 'cto_detected' ? 'cto' : body.event_type === 'whale_trade' ? 'whale' : body.event_type}`,- agent_asset: body.agent_asset,- network: body.network,- token_mint: body.token_mint,- task_id: body.task_id,- detail: body.detail,- attester: loadAttesterKeypair(),- });-- const baseLog = {- userId: agent.user_id,- agentId: agent.id,- kind: 'attest_event',- tool: `pumpkit.${body.event_type}`,- latencyMs: Date.now() - startedAt,- meta: { network: body.network, event_id: body.event_id, signature: result.signature },- };-- if (result.status === 'minted') {- recordEvent({ ...baseLog, status: 'ok', meta: { ...baseLog.meta, kind: result.kind } });- return json(res, 201, { data: { signature: result.signature, kind: result.kind, deduped: false } });- }- if (result.status === 'deduped') {- recordEvent({ ...baseLog, status: 'deduped' });- return json(res, 200, { data: { signature: result.signature, deduped: true } });- }- // in_progress- recordEvent({ ...baseLog, status: 'in_progress' });- return json(res, 202, { data: { deduped: true, status: 'in_progress' } });-});diff --git a/api/agents/solana-attestations.js b/api/agents/solana-attestations.jsdeleted file mode 100644index 667e5cbbb..000000000--- a/api/agents/solana-attestations.js+++ /dev/null@@ -1,89 +0,0 @@-/**- * GET /api/agents/solana-attestations?asset=<pubkey>&kind=feedback|validation|task|accept|revoke|dispute|all&network=devnet|mainnet- *- * Reads three.ws ERC-8004-style attestations about a Solana agent from the- * indexer cache. Falls back to a live RPC crawl + upsert when the cache is- * cold for a given agent (first read warms it).- *- * Schema discovery: /.well-known/agent-attestation-schemas- */--import { sql } from '../_lib/db.js';-import { PublicKey } from '@solana/web3.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { KIND_MAP, crawlAgentAttestations } from '../_lib/solana-attestations.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const asset = url.searchParams.get('asset');- const kindArg = url.searchParams.get('kind') || 'all';- const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';- const limit = Math.min(Number(url.searchParams.get('limit') || 100), 500);- const includeRevoked = url.searchParams.get('include_revoked') === '1';-- if (!asset) return error(res, 400, 'validation_error', 'asset query param required');- try { new PublicKey(asset); }- catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }-- const wantKind = kindArg === 'all' ? null : KIND_MAP[kindArg];- if (kindArg !== 'all' && !wantKind) {- return error(res, 400, 'validation_error',- 'kind must be one of: feedback, validation, task, accept, revoke, dispute, all');- }-- // Cold-cache warm-up: if this agent has never been crawled, do it inline once.- const [cursor] = await sql`- select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1- `;- if (!cursor) {- const [agent] = await sql`- select wallet_address as owner from agent_identities- where meta->>'sol_mint_address' = ${asset} and deleted_at is null- limit 1- `;- try {- await crawlAgentAttestations({- agentAsset: asset, network,- ownerWallet: agent?.owner || null,- });- } catch (e) {- // don't fail the read; cache will be empty until cron runs- }- }-- const rows = wantKind- ? await sql`- select signature, slot, block_time, attester, kind, payload,- verified, revoked, disputed- from solana_attestations- where agent_asset = ${asset} and network = ${network} and kind = ${wantKind}- and (${includeRevoked} or revoked = false)- order by slot desc- limit ${limit}- `- : await sql`- select signature, slot, block_time, attester, kind, payload,- verified, revoked, disputed- from solana_attestations- where agent_asset = ${asset} and network = ${network}- and (${includeRevoked} or revoked = false)- order by slot desc- limit ${limit}- `;-- return json(res, 200, {- data: rows,- agent: asset,- network,- kind: kindArg,- count: rows.length,- last_indexed_at: cursor?.last_indexed_at || null,- });-});diff --git a/api/agents/solana-card.js b/api/agents/solana-card.jsdeleted file mode 100644index 528488b20..000000000--- a/api/agents/solana-card.js+++ /dev/null@@ -1,145 +0,0 @@-/**- * GET /api/agents/solana-card?asset=<pubkey>- *- * A2A-compatible agent discovery card for a Solana-registered agent.- * Same role as ERC-8004's agent manifest: any third-party agent can fetch- * this URL, learn the agent's identity + skills + how to attest about it.- *- * Also served at /a/sol/<asset>/.well-known/agent-card.json (see vercel.json).- */--import { sql } from '../_lib/db.js';-import { PublicKey } from '@solana/web3.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { env } from '../_lib/env.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const url = new URL(req.url, `http://${req.headers.host}`);- const asset = url.searchParams.get('asset');- if (!asset) return error(res, 400, 'validation_error', 'asset required');- try {- new PublicKey(asset);- } catch {- return error(res, 400, 'validation_error', 'invalid asset pubkey');- }-- const [a] = await sql`- select id, name, description, skills, wallet_address as owner, meta, avatar_id- from agent_identities- where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1- `;- if (!a) return error(res, 404, 'not_found', 'agent not found');-- const network = a.meta?.network || 'mainnet';- const origin = env.APP_ORIGIN;-- // Pump.fun off-chain signals — most-recent + per-kind counts. Best-effort:- // the table is optional and may not exist in every deployment.- let pumpfun = null;- try {- const rows = await sql`- select kind, count(*)::int as n, max(seen_at) as last_seen- from pumpfun_signals- where agent_asset = ${asset}- group by kind- `;- if (rows.length > 0) {- const byKind = {};- let total = 0;- let last = null;- for (const r of rows) {- byKind[r.kind] = { count: r.n, last_seen: r.last_seen };- total += r.n;- if (!last || (r.last_seen && r.last_seen > last)) last = r.last_seen;- }- pumpfun = {- signal_count: total,- by_kind: byKind,- last_seen: last,- feed_url: `${origin}/api/agents/pumpfun-feed`,- };- }- } catch {- // pumpfun_signals table not present — omit the block entirely.- }-- // Live token stats from the pump-agent-stats cron snapshot. Joined to- // pump_agent_mints so we only return data for mints we actually track.- let token_stats = null;- try {- const [s] = await sql`- select s.graduated, s.bonding_curve, s.amm,- s.last_signature, s.last_signature_at,- s.recent_tx_count, s.refreshed_at, m.mint, m.network- from pump_agent_stats s- join pump_agent_mints m on m.id = s.mint_id- where m.mint = ${asset} limit 1- `;- if (s) {- token_stats = {- mint: s.mint,- network: s.network,- graduated: s.graduated,- bonding_curve: s.bonding_curve,- amm: s.amm,- last_signature: s.last_signature,- last_signature_at: s.last_signature_at,- recent_tx_count: s.recent_tx_count,- refreshed_at: s.refreshed_at,- };- }- } catch {- // table missing — skip- }-- return json(- res,- 200,- {- schema_version: '1.0',- // A2A core- name: a.name,- description: a.description,- // three.ws extensions- identity: {- chain: 'solana',- network,- asset_pubkey: asset, // Metaplex Core NFT = agent ID- owner: a.owner,- passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,- ...(a.meta?.vanity_prefix ? { vanity_prefix: a.meta.vanity_prefix } : {}),- ...(a.meta?.solana_address ? {- operator_wallet: {- address: a.meta.solana_address,- ...(a.meta.solana_vanity_prefix ? { vanity_prefix: a.meta.solana_vanity_prefix } : {}),- ...(a.meta.solana_wallet_source ? { source: a.meta.solana_wallet_source } : {}),- },- } : {}),- },- skills: a.skills || [],- endpoints: {- chat: `${origin}/api/agents/${a.id}/chat`,- attestations: `${origin}/api/agents/solana-attestations?asset=${asset}&network=${network}`,- reputation: `${origin}/api/agents/solana-reputation?asset=${asset}&network=${network}`,- ...(token_stats- ? {- quote: `${origin}/api/pump/quote?mint=${asset}&network=${network}`,- price_history: `${origin}/api/agents/solana-price-history?asset=${asset}&network=${network}`,- }- : {}),- },- attestation: {- schemas_url: `${origin}/.well-known/agent-attestation-schemas`,- transport: 'spl-memo',- memo_program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',- usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',- },- ...(pumpfun ? { pumpfun } : {}),- ...(token_stats ? { token_stats } : {}),- },- { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' },- );-});diff --git a/api/agents/solana-price-history.js b/api/agents/solana-price-history.jsdeleted file mode 100644index ca2b1c04d..000000000--- a/api/agents/solana-price-history.js+++ /dev/null@@ -1,47 +0,0 @@-// GET /api/agents/solana-price-history?asset=<mint>&network=mainnet|devnet&hours=24-//-// Returns sparkline-friendly price points for an agent's pump.fun mint.--import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const url = new URL(req.url, `http://${req.headers.host}`);- const asset = url.searchParams.get('asset');- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';- const hours = Math.max(1, Math.min(720, Number(url.searchParams.get('hours') || 24)));- if (!asset) return error(res, 400, 'validation_error', 'asset required');-- const [mintRow] = await sql`- select id from pump_agent_mints where mint=${asset} and network=${network} limit 1- `;- if (!mintRow) return error(res, 404, 'not_found', 'mint not tracked');-- const points = await sql`- select ts, sol_per_token, market_cap_lamports, source- from pump_agent_price_points- where mint_id=${mintRow.id} and ts > now() - (${hours} || ' hours')::interval- order by ts asc- `;-- return json(- res,- 200,- {- mint: asset,- network,- hours,- point_count: points.length,- points: points.map((p) => ({- ts: p.ts,- sol_per_token: p.sol_per_token,- market_cap_lamports: p.market_cap_lamports?.toString?.() ?? p.market_cap_lamports,- source: p.source,- })),- },- { 'cache-control': 'public, max-age=60', 'access-control-allow-origin': '*' },- );-});diff --git a/api/agents/solana-register-confirm.js b/api/agents/solana-register-confirm.jsdeleted file mode 100644index 88e5a68bc..000000000--- a/api/agents/solana-register-confirm.js+++ /dev/null@@ -1,135 +0,0 @@-/**- * POST /api/agents/solana-register-confirm- *- * Confirms that the Metaplex Core NFT was successfully minted on Solana,- * then stores the agent identity linked to the NFT mint address.- */--import { z } from 'zod';-import { Connection } from '@solana/web3.js';-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';-import { env } from '../_lib/env.js';--const bodySchema = z.object({- tx_signature: z.string().min(80).max(100),- asset_pubkey: z.string().min(32).max(44), // Metaplex Core asset address (base58)- wallet_address: z.string().min(32).max(44),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),- // Optional overrides- name: z.string().trim().min(1).max(60).optional(),- description: z.string().trim().max(280).optional(),- avatar_id: z.string().uuid().optional(),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { tx_signature, asset_pubkey, wallet_address, network } = body;-- // Verify wallet is linked to user.- const [walletRow] = await sql`- select id from user_wallets- where user_id=${user.id} and address=${wallet_address} and chain_type='solana'- limit 1- `;- if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');-- // Verify transaction on-chain.- const rpcEndpoint = network === 'devnet'- ? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')- : (process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');-- const connection = new Connection(rpcEndpoint, 'confirmed');-- let tx;- try {- tx = await connection.getParsedTransaction(tx_signature, {- maxSupportedTransactionVersion: 0,- commitment: 'confirmed',- });- } catch {- return error(res, 422, 'tx_not_found', 'transaction not found — try again after a few seconds');- }- if (!tx) return error(res, 422, 'tx_not_found', 'transaction not found');- if (tx.meta?.err) return error(res, 422, 'tx_failed', 'transaction failed on-chain');-- // Confirm the asset_pubkey appears as a writable account in the tx- // (it was created — its balance went from 0 to > 0).- const accountKeys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());- const assetInTx = accountKeys.includes(asset_pubkey);- if (!assetInTx) {- return error(res, 422, 'asset_not_in_tx',- 'The asset pubkey was not found in the transaction accounts');- }-- // Check if agent identity already exists for this mint.- const [existing] = await sql`- select id from agent_identities- where (meta->>'sol_mint_address') = ${asset_pubkey} and deleted_at is null- limit 1- `;- if (existing) return error(res, 409, 'conflict', 'agent already registered for this mint');-- // Resolve name/description from pending record or body.- const [pending] = await sql`- select payload from agent_registrations_pending- where user_id=${user.id} and payload->>'asset_pubkey'=${asset_pubkey}- and expires_at > now()- order by created_at desc limit 1- `;- const payload = pending?.payload || {};- const name = body.name || payload.name || `Agent ${asset_pubkey.slice(0, 6)}`;- const description = body.description || payload.description || '';- const avatar_id = body.avatar_id || payload.avatar_id || null;-- // Create agent identity record.- const [agent] = await sql`- insert into agent_identities- (user_id, name, description, avatar_id, wallet_address, meta)- values (- ${user.id},- ${name},- ${description},- ${avatar_id},- ${wallet_address},- ${JSON.stringify({- chain_type: 'solana',- network,- sol_mint_address: asset_pubkey,- tx_signature,- ...(payload.vanity_prefix ? { vanity_prefix: payload.vanity_prefix } : {}),- })}::jsonb- )- returning id, name, description, wallet_address, meta, created_at- `;-- // Clean up pending record.- await sql`- delete from agent_registrations_pending- where user_id=${user.id} and payload->>'asset_pubkey'=${asset_pubkey}- `;-- const appOrigin = env.APP_ORIGIN;- return json(res, 201, {- ok: true,- agent: {- ...agent,- home_url: `${appOrigin}/agent/${agent.id}`,- },- sol_mint_address: asset_pubkey,- tx_signature,- network,- });-});diff --git a/api/agents/solana-register-prep.js b/api/agents/solana-register-prep.jsdeleted file mode 100644index 728b88570..000000000--- a/api/agents/solana-register-prep.js+++ /dev/null@@ -1,163 +0,0 @@-/**- * POST /api/agents/solana-register-prep- *- * Builds a Metaplex Core NFT creation transaction for a Solana agent identity.- * The server constructs the unsigned transaction; the user's wallet signs and submits it.- * Returns: base64-encoded serialized transaction + prepId for the confirm step.- *- * Mirrors register-prep.js (EVM ERC-8004) but targets Solana / Metaplex Core.- */--import { z } from 'zod';-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { mplCore, createV1, fetchAsset } from '@metaplex-foundation/mpl-core';-import {- generateSigner,- publicKey as umiPublicKey,- signerIdentity,- createNoopSigner,-} from '@metaplex-foundation/umi';-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';-import { randomToken } from '../_lib/crypto.js';-import { env } from '../_lib/env.js';--const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';--// Base58 alphabet excluding 0/O/I/l. Mirrors src/solana/vanity/validation.js.-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;-// Vanity prefixes >= this length require a paid plan.-const VANITY_FREE_THRESHOLD = 5;--const bodySchema = z.object({- name: z.string().trim().min(1).max(60),- description: z.string().trim().max(280).default(''),- avatar_id: z.string().uuid().optional(),- wallet_address: z.string().min(32).max(44), // Solana base58 pubkey- metadata_uri: z.string().url().optional(), // pre-pinned IPFS or HTTPS URI- network: z.enum(['mainnet', 'devnet']).default('mainnet'),- // Optional client-grinded vanity asset pubkey. When provided, the server- // builds the tx against this pubkey (noop signer) and the client must- // sign the tx with the matching keypair before submitting.- asset_pubkey: z.string().min(32).max(44).optional(),- vanity_prefix: z.string().min(1).max(6).optional(),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { name, description, avatar_id, wallet_address, network, asset_pubkey, vanity_prefix } = body;-- // Verify wallet belongs to this user.- const [walletRow] = await sql`- select id from user_wallets- where user_id = ${user.id} and address = ${wallet_address} and chain_type = 'solana'- limit 1- `;- if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');-- // If avatar_id provided, verify ownership.- if (avatar_id) {- const [av] = await sql`select id from avatars where id=${avatar_id} and owner_id=${user.id} and deleted_at is null limit 1`;- if (!av) return error(res, 404, 'not_found', 'avatar not found');- }-- // Vanity validation + paywall. Both fields are optional but must agree- // when present (we don't trust the client to honestly report length).- if (vanity_prefix && !asset_pubkey) {- return error(res, 400, 'validation_error', 'vanity_prefix requires asset_pubkey');- }- if (asset_pubkey) {- if (!BASE58_RE.test(asset_pubkey)) {- return error(res, 400, 'validation_error', 'asset_pubkey is not valid base58');- }- if (vanity_prefix) {- if (!BASE58_RE.test(vanity_prefix)) {- return error(res, 400, 'validation_error', 'vanity_prefix is not valid base58');- }- if (!asset_pubkey.startsWith(vanity_prefix)) {- return error(res, 400, 'validation_error', 'asset_pubkey does not start with vanity_prefix');- }- if (vanity_prefix.length >= VANITY_FREE_THRESHOLD && (user.plan ?? 'free') === 'free') {- return error(res, 402, 'payment_required',- `vanity prefixes of ${VANITY_FREE_THRESHOLD}+ characters require a paid plan`);- }- }- }-- const rpcEndpoint = network === 'devnet'- ? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')- : SOLANA_RPC;-- // Build Umi instance. We use a noop signer since the user's wallet will sign.- const umi = createUmi(rpcEndpoint).use(mplCore());- const ownerPubkey = umiPublicKey(wallet_address);- // Asset signer: either the client-supplied vanity pubkey (noop — client signs)- // or a freshly-generated server-side throwaway keypair.- const assetSigner = asset_pubkey- ? createNoopSigner(umiPublicKey(asset_pubkey))- : generateSigner(umi);- // Set the owner as a noop signer so Umi treats them as a required signer.- umi.use(signerIdentity(createNoopSigner(ownerPubkey)));-- // Build the metadata URI: use provided one or synthesize from our app.- const appOrigin = env.APP_ORIGIN;- const metadataUri = body.metadata_uri || `${appOrigin}/api/agents/solana-metadata?name=${encodeURIComponent(name)}&desc=${encodeURIComponent(description)}`;-- // Build the createV1 (Metaplex Core NFT creation) instruction.- const builder = createV1(umi, {- asset: assetSigner,- owner: ownerPubkey,- name,- uri: metadataUri,- // No collection — standalone asset for agent identity- });-- // Serialize the transaction as base64 for the frontend. buildAndSign returns- // a Transaction object — use the Umi transaction factory to get raw bytes.- const tx = await builder.buildAndSign(umi);- const txBytes = umi.transactions.serialize(tx);- const txBase64 = Buffer.from(txBytes).toString('base64');-- // Store prep record.- const prepId = await randomToken(24);- const expiresAt = new Date(Date.now() + 30 * 60 * 1000);-- await sql`- insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at)- values (- ${user.id},- ${assetSigner.publicKey},- ${metadataUri},- ${JSON.stringify({- name, description, avatar_id, wallet_address,- asset_pubkey: assetSigner.publicKey,- network,- prep_id: prepId,- vanity_prefix: vanity_prefix || null,- })}::jsonb,- ${expiresAt}- )- `;-- return json(res, 201, {- prep_id: prepId,- asset_pubkey: assetSigner.publicKey,- tx_base64: txBase64,- network,- metadata_uri: metadataUri,- expires_at: expiresAt.toISOString(),- instructions: 'Sign and submit the transaction with your Solana wallet, then call /api/agents/solana-register-confirm with the tx signature.',- });-});diff --git a/api/agents/solana-reputation-history.js b/api/agents/solana-reputation-history.jsdeleted file mode 100644index 1ddd60473..000000000--- a/api/agents/solana-reputation-history.js+++ /dev/null@@ -1,101 +0,0 @@-/**- * GET /api/agents/solana-reputation-history?asset=<pubkey>&network=devnet|mainnet&days=30- *- * Daily reputation buckets for sparkline rendering. Each bucket is the- * average feedback score for that UTC day. Days with no feedback are- * elided — the client should render gaps appropriately.- *- * Returns the strongest available tier per bucket (credentialed >- * verified > event-attested > raw) so the line reflects the same trust- * model as the headline grade on the passport.- */--import { sql } from '../_lib/db.js';-import { PublicKey } from '@solana/web3.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';--const MAX_DAYS = 90;--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const asset = url.searchParams.get('asset');- const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';- const days = Math.min(Math.max(Number(url.searchParams.get('days') || 30), 1), MAX_DAYS);-- if (!asset) return error(res, 400, 'validation_error', 'asset query param required');- try { new PublicKey(asset); }- catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }-- const rows = await sql`- with feedback as (- select- date_trunc('day', f.block_time) as day,- f.attester,- (f.payload->>'score')::int as score,- exists (- select 1 from solana_attestations a- where a.agent_asset = f.agent_asset- and a.kind = 'threews.accept.v1'- and a.payload->>'task_id' = f.payload->>'task_id'- and a.verified = true- and f.payload->>'task_id' is not null- ) as task_accepted,- exists (- select 1 from solana_credentials c- where c.subject = f.attester- and c.network = f.network- and c.kind = 'threews.verified-client.v1'- and c.closed = false- and (c.expiry is null or c.expiry > f.block_time)- ) as credentialed,- (f.payload->>'source' like 'pumpkit.%') as event_attested- from solana_attestations f- where f.agent_asset = ${asset}- and f.network = ${network}- and f.kind = 'threews.feedback.v1'- and f.revoked = false- and f.block_time >= now() - (${days} || ' days')::interval- )- select- day,- count(*)::int as n,- coalesce(avg(score) filter (where credentialed), 0)::float as score_credentialed,- coalesce(avg(score) filter (where task_accepted), 0)::float as score_verified,- coalesce(avg(score) filter (where event_attested), 0)::float as score_event,- coalesce(avg(score), 0)::float as score_raw,- count(*) filter (where credentialed)::int as n_credentialed,- count(*) filter (where task_accepted)::int as n_verified,- count(*) filter (where event_attested)::int as n_event- from feedback- group by day- order by day asc- `;-- const series = rows.map((r) => {- const tier =- r.n_credentialed > 0 ? { tier: 'credentialed', score: r.score_credentialed, n: r.n_credentialed } :- r.n_verified > 0 ? { tier: 'verified', score: r.score_verified, n: r.n_verified } :- r.n_event > 0 ? { tier: 'event', score: r.score_event, n: r.n_event } :- { tier: 'community', score: r.score_raw, n: r.n };- return {- day: r.day instanceof Date ? r.day.toISOString().slice(0, 10) : String(r.day).slice(0, 10),- tier: tier.tier,- score: Number(tier.score.toFixed(3)),- n: tier.n,- };- });-- return json(res, 200, {- agent: asset,- network,- days,- series,- });-});diff --git a/api/agents/solana-reputation.js b/api/agents/solana-reputation.jsdeleted file mode 100644index 6be100c16..000000000--- a/api/agents/solana-reputation.js+++ /dev/null@@ -1,231 +0,0 @@-/**- * GET /api/agents/solana-reputation?asset=<pubkey>&network=devnet|mainnet- *- * Computed reputation summary for a Solana agent, derived from indexed- * attestations. Returns:- * - total / verified / disputed / revoked counts- * - score_avg (1..5) overall and verified-only- * - validation pass/fail counts- * - recent task acceptances and disputes- *- * "Verified" feedback is feedback whose task_id has a matching threews.accept.v1- * from the agent owner — i.e. the agent confirmed it actually did this work.- */--import { sql } from '../_lib/db.js';-import { PublicKey } from '@solana/web3.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const asset = url.searchParams.get('asset');- const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';-- if (!asset) return error(res, 400, 'validation_error', 'asset query param required');- try {- new PublicKey(asset);- } catch {- return error(res, 400, 'validation_error', 'invalid asset pubkey');- }-- // One pass: feedback aggregates split by verified-task-acceptance, by- // SAS credentialing, and by event-attested provenance. Trust layers:- // 1. Raw — every memo feedback counts equally.- // 2. Verified — feedback whose task_id has a matching task.accepted.- // 3. Credentialed — feedback from attesters holding a- // threews.verified-client.v1 SAS credential.- // 4. Event-attested — feedback whose payload.source is a recognised- // on-chain event monitor (e.g. "pumpkit.*"). Sybil-resistant via- // the underlying on-chain event, not via the attester identity.- const [fb] = await sql`- with feedback as (- select- f.signature, f.attester, f.disputed, f.revoked,- (f.payload->>'score')::int as score,- f.payload->>'task_id' as task_id,- exists (- select 1 from solana_attestations a- where a.agent_asset = f.agent_asset- and a.kind = 'threews.accept.v1'- and a.payload->>'task_id' = f.payload->>'task_id'- and a.verified = true- and f.payload->>'task_id' is not null- ) as task_accepted,- exists (- select 1 from solana_credentials c- where c.subject = f.attester- and c.network = f.network- and c.kind = 'threews.verified-client.v1'- and c.closed = false- and (c.expiry is null or c.expiry > now())- ) as credentialed,- (f.payload->>'source' like 'pumpkit.%' or f.payload->>'source' like 'pumpfun.%') as event_attested- from solana_attestations f- where f.agent_asset = ${asset}- and f.network = ${network}- and f.kind = 'threews.feedback.v1'- and f.revoked = false- ),- per_attester as (- select attester, avg(score)::float as score_avg,- bool_or(task_accepted) as any_verified,- bool_or(credentialed) as any_credentialed,- bool_or(event_attested) as any_event_attested- from feedback group by attester- )- select- (select count(*)::int from feedback) as total,- (select count(*) filter (where task_accepted)::int from feedback) as verified,- (select count(*) filter (where credentialed)::int from feedback) as credentialed,- (select count(*) filter (where event_attested)::int from feedback) as event_attested,- (select count(*) filter (where disputed)::int from feedback) as disputed,- (select coalesce(avg(score), 0)::float from feedback) as score_avg,- (select coalesce(avg(score) filter (where task_accepted), 0)::float from feedback) as score_avg_verified,- (select coalesce(avg(score) filter (where credentialed), 0)::float from feedback) as score_avg_credentialed,- (select coalesce(avg(score) filter (where event_attested), 0)::float from feedback) as score_avg_event_attested,- (select count(*)::int from per_attester) as unique_attesters,- (select count(*) filter (where any_verified)::int from per_attester) as unique_verified_attesters,- (select count(*) filter (where any_credentialed)::int from per_attester) as unique_credentialed_attesters,- (select coalesce(avg(score_avg), 0)::float from per_attester) as score_avg_weighted,- (select coalesce(avg(score_avg) filter (where any_verified), 0)::float from per_attester) as score_avg_weighted_verified,- (select coalesce(avg(score_avg) filter (where any_credentialed), 0)::float from per_attester) as score_avg_weighted_credentialed- `;-- const [val] = await sql`- select- count(*) filter (where (payload->>'passed')::bool)::int as passed,- count(*) filter (where not (payload->>'passed')::bool)::int as failed,- count(*) filter (where (payload->>'passed')::bool- and (payload->>'source' like 'pumpkit.%' or payload->>'source' like 'pumpfun.%'))::int as event_passed,- count(*) filter (where not (payload->>'passed')::bool- and (payload->>'source' like 'pumpkit.%' or payload->>'source' like 'pumpfun.%'))::int as event_failed- from solana_attestations- where agent_asset = ${asset} and network = ${network}- and kind = 'threews.validation.v1' and revoked = false- `;-- // Audited validations from authorized validators (SAS-credentialed).- const [auditedVal] = await sql`- select- count(*) filter (where (data->>'passed')::bool)::int as passed,- count(*) filter (where not (data->>'passed')::bool)::int as failed- from solana_credentials- where subject = ${asset} and network = ${network}- and kind = 'threews.audited-validation.v1'- and closed = false and (expiry is null or expiry > now())- `;-- const [counts] = await sql`- select- count(*) filter (where kind = 'threews.task.v1')::int as tasks_offered,- count(*) filter (where kind = 'threews.accept.v1' and verified)::int as tasks_accepted,- count(*) filter (where kind = 'threews.dispute.v1' and verified)::int as disputes_filed,- count(*) filter (where revoked)::int as revoked_count- from solana_attestations- where agent_asset = ${asset} and network = ${network}- `;-- const [cursor] = await sql`- select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1- `;-- // Pump.fun off-chain signals (claim/graduation activity).- const pumpfunRows = await sql`- select kind, count(*)::int as n, coalesce(sum(weight), 0)::float as w- from pumpfun_signals- where agent_asset = ${asset}- group by kind- `;- const pumpfunByKind = {};- let pumpfunTotal = 0, pumpfunWeight = 0;- for (const r of pumpfunRows) {- pumpfunByKind[r.kind] = { count: r.n, weight: Number(r.w.toFixed(3)) };- pumpfunTotal += r.n;- pumpfunWeight += r.w;- }- const pumpfunSignals = {- count: pumpfunTotal,- weight: Number(pumpfunWeight.toFixed(3)),- by_kind: pumpfunByKind,- };-- // Pump.fun token activity (graduation + recent tx + trade counts).- const [actRow] = await sql`- select s.graduated, s.recent_tx_count,- (select count(*)::int from pump_agent_trades t where t.mint_id = m.id) as trade_count- from pump_agent_stats s- join pump_agent_mints m on m.id = s.mint_id- where m.mint = ${asset} and m.network = ${network}- limit 1- `;- const tokenActivity = actRow ? {- graduated: !!actRow.graduated,- recent_tx_count: actRow.recent_tx_count || 0,- trade_count: actRow.trade_count || 0,- weight: Number((- (actRow.graduated ? 0.3 : 0)- + Math.min(0.4, (actRow.recent_tx_count || 0) * 0.005)- + Math.min(0.3, (actRow.trade_count || 0) * 0.01)- ).toFixed(3)),- } : { graduated: false, recent_tx_count: 0, trade_count: 0, weight: 0 };-- // Pump.fun agent-payments signal: confirmed acceptPayment receipts.- const [payRow] = await sql`- select- count(*) filter (where p.status='confirmed')::int as confirmed_count,- count(distinct p.payer_wallet) filter (where p.status='confirmed')::int as unique_payers,- coalesce(sum(p.amount_atomics) filter (where p.status='confirmed'), 0)::text as total_atomics- from pump_agent_payments p- join pump_agent_mints m on m.id = p.mint_id- join agent_identities a on a.id = m.agent_id- where (a.meta->>'sol_mint_address') = ${asset} and m.network = ${network}- `;- const pumpPayments = payRow || { confirmed_count: 0, unique_payers: 0, total_atomics: '0' };-- return json(res, 200, {- agent: asset,- network,- pump_payments: pumpPayments,- pumpfun_signals: pumpfunSignals,- token_activity: tokenActivity,- feedback: {- total: fb.total,- verified: fb.verified,- credentialed: fb.credentialed,- event_attested: fb.event_attested,- disputed: fb.disputed,- unique_attesters: fb.unique_attesters,- unique_verified_attesters: fb.unique_verified_attesters,- unique_credentialed_attesters: fb.unique_credentialed_attesters,- score_avg: Number(fb.score_avg.toFixed(3)),- score_avg_verified: Number(fb.score_avg_verified.toFixed(3)),- score_avg_credentialed: Number(fb.score_avg_credentialed.toFixed(3)),- score_avg_event_attested: Number(fb.score_avg_event_attested.toFixed(3)),- score_avg_weighted: Number(fb.score_avg_weighted.toFixed(3)),- score_avg_weighted_verified: Number(fb.score_avg_weighted_verified.toFixed(3)),- score_avg_weighted_credentialed: Number(fb.score_avg_weighted_credentialed.toFixed(3)),- },- validation: {- self_passed: val.passed,- self_failed: val.failed,- event_passed: val.event_passed,- event_failed: val.event_failed,- audited_passed: auditedVal.passed,- audited_failed: auditedVal.failed,- },- tasks: {- offered: counts.tasks_offered,- accepted: counts.tasks_accepted,- },- disputes_filed: counts.disputes_filed,- revoked_count: counts.revoked_count,- last_indexed_at: cursor?.last_indexed_at || null,- });-});diff --git a/api/auth/forgot-password.js b/api/auth/forgot-password.jsdeleted file mode 100644index 2c4b8e6ad..000000000--- a/api/auth/forgot-password.js+++ /dev/null@@ -1,46 +0,0 @@-import { sql } from '../_lib/db.js';-import { randomToken, sha256 } from '../_lib/crypto.js';-import { cors, json, method, readJson, wrap } from '../_lib/http.js';-import { limits } from '../_lib/rate-limit.js';-import { parse, email } from '../_lib/validate.js';-import { sendPasswordResetEmail } from '../_lib/email.js';-import { z } from 'zod';--const bodySchema = z.object({ email });--const APP_ORIGIN = process.env.APP_ORIGIN || 'https://three.ws';-const EXPIRES_MINUTES = 60;--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const body = parse(bodySchema, await readJson(req));-- // Per-email rate limit (anti-enumeration: still respond success on limit hit).- const rl = await limits.forgotPasswordEmail(body.email);- if (!rl.success) return json(res, 200, { success: true });-- const rows =- await sql`select id from users where email = ${body.email} and deleted_at is null limit 1`;- const user = rows[0];-- if (user) {- const token = randomToken(32);- const tokenHash = await sha256(token);- const expiresAt = new Date(Date.now() + EXPIRES_MINUTES * 60_000);- await sql`- insert into password_resets (user_id, token_hash, expires_at)- values (${user.id}, ${tokenHash}, ${expiresAt.toISOString()})- `;- const resetUrl = `${APP_ORIGIN}/reset-password?token=${encodeURIComponent(token)}`;- // Fire-and-forget; don't await on the critical path.- sendPasswordResetEmail({- to: body.email,- resetUrl,- expiresInMinutes: EXPIRES_MINUTES,- }).catch(() => {});- }-- return json(res, 200, { success: true });-});diff --git a/api/auth/login.js b/api/auth/login.jsdeleted file mode 100644index 5c303cc3a..000000000--- a/api/auth/login.js+++ /dev/null@@ -1,37 +0,0 @@-import { sql } from '../_lib/db.js';-import { verifyPassword, createSession, sessionCookie, destroySession } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse, loginBody } from '../_lib/validate.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const ip = clientIp(req);- const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');-- const body = parse(loginBody, await readJson(req));-- const isEmail = body.email.includes('@');- const rows = isEmail- ? await sql`select id, email, password_hash, display_name, plan, avatar_url from users where email = ${body.email} and deleted_at is null limit 1`- : await sql`select id, email, password_hash, display_name, plan, avatar_url from users where display_name ilike ${body.email} and deleted_at is null limit 1`;- const user = rows[0];- const ok = user && (await verifyPassword(body.password, user.password_hash));- if (!ok) return error(res, 401, 'invalid_credentials', 'invalid username/email or password');-- // Invalidate any pre-existing session tied to the incoming cookie before- // minting a new one. Defends against session fixation via planted cookies.- await destroySession(req);-- const token = await createSession({- userId: user.id,- userAgent: req.headers['user-agent'],- ip,- });- res.setHeader('set-cookie', sessionCookie(token));- const { password_hash: _p, ...safe } = user;- return json(res, 200, { user: safe });-});diff --git a/api/auth/logout-everywhere.js b/api/auth/logout-everywhere.jsdeleted file mode 100644index 1a9745f79..000000000--- a/api/auth/logout-everywhere.js+++ /dev/null@@ -1,45 +0,0 @@-// Revoke every session AND every OAuth refresh token for the caller, including-// the current session, and clear the cookie. This fully signs the user out on-// every device and invalidates any OAuth tokens issued to third-party clients.-// Different from DELETE /api/auth/sessions (which keeps the current session).--import { sql } from '../_lib/db.js';-import { getSessionUser, sessionCookie } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';--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, 'unauthenticated', 'not signed in');-- const ip = clientIp(req);- const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- // Revoke all active sessions across every device.- const sessionResult = await sql`- update sessions- set revoked_at = now()- where user_id = ${user.id}- and revoked_at is null- `;-- // Revoke all OAuth refresh tokens so third-party clients can no longer- // obtain new access tokens on behalf of this user.- await sql`- update oauth_refresh_tokens- set revoked_at = now()- where user_id = ${user.id}- and revoked_at is null- `;-- const clearCookies = sessionCookie('', { clear: true });- const existing = res.getHeader('set-cookie') || [];- const arr = Array.isArray(existing) ? existing : [existing];- res.setHeader('set-cookie', [...arr, ...clearCookies]);-- return json(res, 200, { ok: true, revoked: sessionResult.count });-});diff --git a/api/auth/logout.js b/api/auth/logout.jsdeleted file mode 100644index 0e7f32981..000000000--- a/api/auth/logout.js+++ /dev/null@@ -1,10 +0,0 @@-import { destroySession, sessionCookie } from '../_lib/auth.js';-import { cors, json, method, wrap } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;- await destroySession(req);- res.setHeader('set-cookie', sessionCookie('', { clear: true }));- return json(res, 200, { ok: true });-});diff --git a/api/auth/me.js b/api/auth/me.jsdeleted file mode 100644index e9d187b7d..000000000--- a/api/auth/me.js+++ /dev/null@@ -1,10 +0,0 @@-import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthenticated', 'not signed in');- return json(res, 200, { user });-});diff --git a/api/auth/profile.js b/api/auth/profile.jsdeleted file mode 100644index af8243f48..000000000--- a/api/auth/profile.js+++ /dev/null@@ -1,48 +0,0 @@-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';-import { parse, username as usernameValidator, displayName } from '../_lib/validate.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { z } from 'zod';--const bodySchema = z- .object({- username: usernameValidator.optional(),- display_name: displayName.optional(),- })- .refine((b) => b.username !== undefined || b.display_name !== undefined, {- message: 'at least one field required',- });--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;- if (!method(req, res, ['PATCH'])) return;-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthenticated', 'not signed in');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));-- if (body.username) {- const taken = await sql`- select id from users- where lower(username) = ${body.username.toLowerCase()} and id != ${user.id} and deleted_at is null- limit 1- `;- if (taken[0]) return error(res, 409, 'conflict', 'username already taken');- }-- const [updated] = await sql`- update users set- username = coalesce(${body.username ?? null}, username),- display_name = coalesce(${body.display_name ?? null}, display_name),- updated_at = now()- where id = ${user.id} and deleted_at is null- returning id, display_name, username- `;-- return json(res, 200, { user: updated });-});diff --git a/api/auth/register.js b/api/auth/register.jsdeleted file mode 100644index 0ccc17498..000000000--- a/api/auth/register.js+++ /dev/null@@ -1,57 +0,0 @@-import { sql } from '../_lib/db.js';-import { hashPassword, createSession, sessionCookie, destroySession } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse, registerBody, usernameRegisterBody } from '../_lib/validate.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const ip = clientIp(req);- const rl = await limits.registerIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many signups from this IP');-- const raw = await readJson(req);- let email, displayName, password;-- if (raw.username && !raw.email) {- // Username-only registration — synthetic email kept internal, never shown.- const body = parse(usernameRegisterBody, raw);- const safe = body.username.toLowerCase().replace(/[^a-z0-9_-]/g, '_');- email = `${safe}@users.three.ws.local`;- displayName = body.username;- password = body.password;-- const existing =- await sql`select id from users where display_name ilike ${body.username} and deleted_at is null limit 1`;- if (existing[0]) return error(res, 409, 'conflict', 'email or username already in use');- } else {- const body = parse(registerBody, raw);- email = body.email;- displayName = body.display_name ?? null;- password = body.password;-- const existing =- await sql`select id from users where email = ${email} and deleted_at is null limit 1`;- if (existing[0]) return error(res, 409, 'conflict', 'email or username already in use');- }-- const hash = await hashPassword(password);- const [user] = await sql`- insert into users (email, password_hash, display_name)- values (${email}, ${hash}, ${displayName})- returning id, display_name, plan, created_at- `;-- // Kill any pre-existing planted session cookie before issuing the real one.- await destroySession(req);-- const token = await createSession({- userId: user.id,- userAgent: req.headers['user-agent'],- ip,- });- res.setHeader('set-cookie', sessionCookie(token));- return json(res, 201, { user });-});diff --git a/api/auth/resend-verification.js b/api/auth/resend-verification.jsdeleted file mode 100644index 88c6320fd..000000000--- a/api/auth/resend-verification.js+++ /dev/null@@ -1,50 +0,0 @@-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { sha256 } from '../_lib/crypto.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits } from '../_lib/rate-limit.js';-import { sendVerificationEmail } from '../_lib/email.js';--const EXPIRES_MINUTES = 30;--function generateCode() {- // 6-digit numeric, zero-padded.- const n = Math.floor(Math.random() * 1_000_000);- return n.toString().padStart(6, '0');-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const session = await getSessionUser(req, res);- if (!session) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.resendVerifyUser(session.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'please wait before requesting again');-- const rows =- await sql`select email, email_verified from users where id = ${session.id} and deleted_at is null limit 1`;- const user = rows[0];- if (!user) return error(res, 401, 'unauthorized', 'sign in required');- if (user.email_verified) return json(res, 200, { success: true, already_verified: true });-- // Invalidate any prior unconsumed codes so only the latest one works.- await sql`update email_verifications set consumed_at = now() where user_id = ${session.id} and consumed_at is null`;-- const code = generateCode();- const codeHash = await sha256(code);- const expiresAt = new Date(Date.now() + EXPIRES_MINUTES * 60_000);- await sql`- insert into email_verifications (user_id, code_hash, expires_at)- values (${session.id}, ${codeHash}, ${expiresAt.toISOString()})- `;-- sendVerificationEmail({- to: user.email,- code,- expiresInMinutes: EXPIRES_MINUTES,- }).catch(() => {});-- return json(res, 200, { success: true });-});diff --git a/api/auth/reset-password.js b/api/auth/reset-password.jsdeleted file mode 100644index 0079a1bd3..000000000--- a/api/auth/reset-password.js+++ /dev/null@@ -1,46 +0,0 @@-import { sql } from '../_lib/db.js';-import { hashPassword } from '../_lib/auth.js';-import { sha256 } from '../_lib/crypto.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse, password } from '../_lib/validate.js';-import { z } from 'zod';--const bodySchema = z.object({- token: z.string().min(16).max(256),- password,-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- // Reuse generic auth IP limiter — same shape as login/register.- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');-- const body = parse(bodySchema, await readJson(req));- const tokenHash = await sha256(body.token);-- const rows = await sql`- select r.id, r.user_id- from password_resets r- join users u on u.id = r.user_id- where r.token_hash = ${tokenHash}- and r.consumed_at is null- and r.expires_at > now()- and u.deleted_at is null- limit 1- `;- const row = rows[0];- if (!row) return error(res, 400, 'invalid_token', 'reset link is invalid or has expired');-- const hash = await hashPassword(body.password);- await sql`update users set password_hash = ${hash}, updated_at = now() where id = ${row.user_id}`;- await sql`update password_resets set consumed_at = now() where id = ${row.id}`;-- // Revoke all existing sessions for safety after a password reset.- await sql`update sessions set revoked_at = now() where user_id = ${row.user_id} and revoked_at is null`;-- return json(res, 200, { success: true });-});diff --git a/api/auth/verify-email.js b/api/auth/verify-email.jsdeleted file mode 100644index 4c7a40121..000000000--- a/api/auth/verify-email.js+++ /dev/null@@ -1,43 +0,0 @@-import { sql } from '../_lib/db.js';-import { sha256 } from '../_lib/crypto.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';-import { z } from 'zod';--const bodySchema = z.object({- code: z- .string()- .trim()- .regex(/^\d{6}$/, '6-digit code required'),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const ip = clientIp(req);- const rl = await limits.verifyEmailIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');-- const body = parse(bodySchema, await readJson(req));- const codeHash = await sha256(body.code);-- const rows = await sql`- select v.id, v.user_id- from email_verifications v- join users u on u.id = v.user_id- where v.code_hash = ${codeHash}- and v.consumed_at is null- and v.expires_at > now()- and u.deleted_at is null- limit 1- `;- const row = rows[0];- if (!row) return error(res, 400, 'invalid_code', 'invalid or expired verification code');-- await sql`update email_verifications set consumed_at = now() where id = ${row.id}`;- await sql`update users set email_verified = true, updated_at = now() where id = ${row.user_id}`;-- return json(res, 200, { success: true });-});diff --git a/api/kol/import-gmgn.js b/api/kol/import-gmgn.jsdeleted file mode 100644index 8a15b8b63..000000000--- a/api/kol/import-gmgn.js+++ /dev/null@@ -1,57 +0,0 @@-// POST /api/kol/import-gmgn-// body: { rawJson: <string|object> }-// → { imported: <number>, wallets: [...] }-//-// Merges parsed wallets into src/kol/wallets.json by wallet address (latest wins).-// No auth required; rate-limited by IP.--import { readFile, writeFile } from 'node:fs/promises';-import path from 'node:path';-import { fileURLToPath } from 'node:url';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { parseGmgnSmartWallets } from '../../src/kol/gmgn-parser.js';--const WALLETS_PATH = path.resolve(- path.dirname(fileURLToPath(import.meta.url)),- '../../src/kol/wallets.json',-);--async function loadWallets() {- try {- return JSON.parse(await readFile(WALLETS_PATH, 'utf8'));- } catch {- return [];- }-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['POST'])) return;-- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = await readJson(req);- if (!body || body.rawJson == null) {- return error(res, 400, 'validation_error', 'body.rawJson is required');- }-- let parsed;- try {- parsed = parseGmgnSmartWallets(body.rawJson);- } catch (err) {- return error(res, 400, 'validation_error', err.message);- }-- const existing = await loadWallets();- const byWallet = new Map(existing.map((w) => [w.wallet, w]));- for (const entry of parsed) {- byWallet.set(entry.wallet, entry);- }- const merged = [...byWallet.values()];-- await writeFile(WALLETS_PATH, JSON.stringify(merged, null, '\t') + '\n', 'utf8');-- return json(res, 200, { imported: parsed.length, wallets: merged });-});diff --git a/api/kol/leaderboard.js b/api/kol/leaderboard.jsdeleted file mode 100644index 941bba07e..000000000--- a/api/kol/leaderboard.js+++ /dev/null@@ -1,33 +0,0 @@-// GET /api/kol/leaderboard?window=7d&limit=25-// → { items: [{ wallet, pnlUsd, winRate, trades, rank }] }-//-// Public read-only endpoint; no auth required. Rate-limited by IP.-// window ∈ '24h' | '7d' | '30d' (default '7d')-// limit ∈ 1..100 (default 25, capped at 100)--import { cors, json, method, wrap, error } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { getLeaderboard } from '../../src/kol/leaderboard.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const url = new URL(req.url, `http://${req.headers.host}`);- const window = url.searchParams.get('window') || '7d';- const limitRaw = url.searchParams.get('limit');- const limit = limitRaw != null ? Number(limitRaw) : 25;-- let items;- try {- items = await getLeaderboard({ window, limit });- } catch (err) {- if (err.status === 400) return error(res, 400, err.code || 'validation_error', err.message);- throw err;- }-- return json(res, 200, { items });-});diff --git a/api/kol/trades.js b/api/kol/trades.jsdeleted file mode 100644index b9610836a..000000000--- a/api/kol/trades.js+++ /dev/null@@ -1,30 +0,0 @@-// GET /api/kol/trades?mint=<mint>&limit=<n>-//-// Returns recent trades for a Solana token mint filtered to smart-money wallets.-// Wallet qualification rule: minimum $10 000 cumulative realised P&L (see-// src/kol/wallets.js).-//-// TODO: wire up a real trade source (Helius enriched-transactions, Birdeye,-// or a self-hosted indexer). Today the trades array is always empty.--import { cors, error, json, method, wrap } from '../_lib/http.js';-import { KOL_WALLETS } from '../../src/kol/wallets.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;-- const url = new URL(req.url, 'http://x');- const mint = url.searchParams.get('mint');- const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') || '20')));-- if (!mint) return error(res, 400, 'validation_error', 'mint is required');-- // TODO: query enriched transactions for `mint` from indexer, filter to- // KOL_WALLETS addresses, map to the trade shape below.- // Trade shape: { time: ISO8601, side: 'buy'|'sell', wallet: string,- // usd: number, source: 'kol'|'whale'|'smart-money' }- const trades = [];-- return json(res, 200, { mint, trades, wallets: KOL_WALLETS.length });-});diff --git a/api/oauth/authorize.js b/api/oauth/authorize.jsdeleted file mode 100644index 7af97e9fc..000000000--- a/api/oauth/authorize.js+++ /dev/null@@ -1,206 +0,0 @@-// OAuth 2.1 authorization endpoint.-// GET → renders consent page (or redirects to login if no session)-// POST → user accepted; issues an authorization code and redirects back.-//-// PKCE is mandatory (S256). No implicit flow. No password grant.--import { sql } from '../_lib/db.js';-import { getSessionUser, csrfTokenFor, verifyCsrfToken, isSameSiteOrigin } from '../_lib/auth.js';-import { randomToken } from '../_lib/crypto.js';-import { cors, method, wrap, error, redirect, readForm } from '../_lib/http.js';-import { env } from '../_lib/env.js';--const CODE_TTL_SEC = 60;--// OAuth 2.1 §3.1.2.2 — exact match on protocol/host/port/pathname.-// Request URI must carry no extra query params or fragment.-function redirectUriMatches(requested, registered) {- let reqUrl;- try {- reqUrl = new URL(requested);- } catch {- return false;- }- if (reqUrl.hash) return false;- if (reqUrl.search) return false;- return registered.some((entry) => {- let regUrl;- try {- regUrl = new URL(entry);- } catch {- return false;- }- return (- reqUrl.protocol === regUrl.protocol &&- reqUrl.host === regUrl.host &&- reqUrl.port === regUrl.port &&- reqUrl.pathname === regUrl.pathname- );- });-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET', 'POST'])) return;-- const params = req.method === 'POST' ? await readForm(req) : parseQuery(req.url);- const {- response_type,- client_id,- redirect_uri,- scope,- state,- code_challenge,- code_challenge_method,- resource,- } = params;-- if (response_type !== 'code')- return error(res, 400, 'unsupported_response_type', 'only response_type=code supported');- if (!client_id) return error(res, 400, 'invalid_request', 'client_id required');- if (!redirect_uri) return error(res, 400, 'invalid_request', 'redirect_uri required');- if (!code_challenge)- return error(res, 400, 'invalid_request', 'code_challenge required (PKCE)');- if (!code_challenge_method)- return error(res, 400, 'invalid_request', 'code_challenge_method required (must be S256)');- if (code_challenge_method !== 'S256')- return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');-- const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;- const client = rows[0];- if (!client) return error(res, 400, 'invalid_client', 'unknown client');- if (!redirectUriMatches(redirect_uri, client.redirect_uris)) {- return error(res, 400, 'invalid_redirect_uri', 'redirect_uri not registered');- }-- const user = await getSessionUser(req);- if (!user) {- // Bounce to login, preserving the consent URL.- const next = encodeURIComponent(`/oauth/consent?${new URLSearchParams(params).toString()}`);- return redirect(res, `/login?next=${next}`);- }-- if (req.method === 'GET') {- // Render a simple consent page. Kept server-side to avoid shipping extra JS.- const csrf = await csrfTokenFor(req);- return renderConsent(res, { client, user, params, csrf });- }-- // POST — user confirmed consent. Reject cross-site POSTs (Origin check) and- // forged submissions (CSRF token bound to the session cookie).- if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');- if (!(await verifyCsrfToken(req, params.csrf)))- return error(res, 403, 'forbidden', 'invalid csrf token');-- if (params.decision !== 'allow') {- const denied = new URL(redirect_uri);- denied.searchParams.set('error', 'access_denied');- if (state) denied.searchParams.set('state', state);- return redirect(res, denied.toString());- }-- const code = randomToken(24);- const grantedScope = intersectScopes(scope || client.scope, client.scope);- await sql`- insert into oauth_auth_codes (code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method, expires_at)- values (${code}, ${client_id}, ${user.id}, ${redirect_uri}, ${grantedScope}, ${resource ?? env.MCP_RESOURCE},- ${code_challenge}, 'S256', now() + ${`${CODE_TTL_SEC} seconds`}::interval)- `;-- const back = new URL(redirect_uri);- back.searchParams.set('code', code);- if (state) back.searchParams.set('state', state);- return redirect(res, back.toString());-});--function parseQuery(url) {- const q = new URL(url, 'http://x').searchParams;- return Object.fromEntries(q);-}--function intersectScopes(requested, allowed) {- const a = new Set(allowed.split(/\s+/).filter(Boolean));- return (- requested- .split(/\s+/)- .filter((s) => a.has(s))- .join(' ') || allowed- );-}--function renderConsent(res, { client, user, params, csrf }) {- res.statusCode = 200;- res.setHeader('content-type', 'text/html; charset=utf-8');- res.setHeader('cache-control', 'no-store');- // Harden the consent page against clickjacking, mixed content, and- // extension/CDN script injection. form-action restricts where the form- // can POST; frame-ancestors blocks iframing of the consent UI.- res.setHeader(- 'content-security-policy',- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",- );- res.setHeader('x-frame-options', 'DENY');- res.setHeader('x-content-type-options', 'nosniff');- res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');- res.setHeader('strict-transport-security', 'max-age=63072000; includeSubDomains; preload');- const scope = params.scope || client.scope;- const scopeList = scope.split(/\s+/).filter(Boolean);- res.end(`<!doctype html>-<html lang="en"><head>-<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">-<title>Authorize ${esc(client.name)} · three.ws</title>-<style>- :root { color-scheme: light dark; }- body { font: 16px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; background:#0b0b10; color:#eee; margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; }- .card { background:#14141c; border:1px solid #2a2a36; border-radius:16px; padding:28px 28px 24px; max-width:440px; width:100%; box-shadow:0 10px 40px rgba(0,0,0,.4); }- h1 { font-size:20px; margin:0 0 8px; }- .sub { color:#aaa; margin:0 0 20px; }- .who { display:flex; align-items:center; gap:10px; margin-bottom:16px; padding:10px 12px; background:#1b1b25; border-radius:10px; }- .dot { width:32px; height:32px; border-radius:50%; background:linear-gradient(135deg,#6a5cff,#ff5ca8); display:grid; place-items:center; color:#fff; font-weight:600; }- ul { margin:12px 0 20px; padding-left:0; list-style:none; }- li { padding:8px 0; border-bottom:1px solid #22222e; display:flex; gap:10px; }- li:last-child { border:0; }- li::before { content:"✓"; color:#6a5cff; }- .actions { display:flex; gap:10px; }- button { flex:1; padding:12px 16px; border-radius:10px; border:0; font-size:15px; font-weight:600; cursor:pointer; }- .allow { background:#6a5cff; color:#fff; }- .deny { background:transparent; color:#aaa; border:1px solid #2a2a36; }- .foot { margin-top:16px; font-size:12px; color:#777; }- a { color:#9a8cff; }-</style>-</head><body><form class="card" method="post" action="/api/oauth/authorize">- <h1>Authorize <b>${esc(client.name)}</b></h1>- <p class="sub">Grant this application access to your three.ws account.</p>- <div class="who"><div class="dot">${esc((user.display_name || user.email)[0].toUpperCase())}</div><div><div>${esc(user.display_name || user.email)}</div><div style="color:#888;font-size:13px">${esc(user.email)}</div></div></div>- <p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p>- <ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul>- <input type="hidden" name="csrf" value="${esc(csrf || '')}">- ${Object.entries(params)- .filter(([k]) => k !== 'csrf' && k !== 'decision')- .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)- .join('')}- <div class="actions">- <button class="deny" type="submit" name="decision" value="deny">Cancel</button>- <button class="allow" type="submit" name="decision" value="allow">Authorize</button>- </div>- <p class="foot">You can revoke access any time from your <a href="/dashboard/connections">dashboard</a>.</p>-</form></body></html>`);-}--function scopeLabel(s) {- const labels = {- 'avatars:read': 'Read your avatars',- 'avatars:write': 'Create and update avatars',- 'avatars:delete': 'Delete your avatars',- profile: 'See your name and email',- offline_access: 'Stay signed in across sessions',- };- return labels[s] || esc(s);-}--function esc(s) {- return String(s).replace(- /[&<>"']/g,- (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],- );-}diff --git a/api/oauth/introspect.js b/api/oauth/introspect.jsdeleted file mode 100644index 585db2651..000000000--- a/api/oauth/introspect.js+++ /dev/null@@ -1,68 +0,0 @@-// RFC 7662 — OAuth 2.0 Token Introspection-// Minimal: authenticated clients can check if a token is active.--import { sql } from '../_lib/db.js';-import { authenticateBearer, verifyAccessToken } from '../_lib/auth.js';-import { sha256, constantTimeEquals } from '../_lib/crypto.js';-import { cors, method, readForm, wrap, json, error } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;- if (!method(req, res, ['POST'])) return;-- const form = await readForm(req);- const { token, client_id, client_secret } = form;- if (!token || !client_id)- return error(res, 400, 'invalid_request', 'token and client_id required');-- const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;- const client = rows[0];- if (!client) return json(res, 200, { active: false });-- if (client.client_type === 'confidential') {- const hash = await sha256(client_secret ?? '');- if (!client.client_secret_hash || !constantTimeEquals(hash, client.client_secret_hash)) {- return error(res, 401, 'invalid_client', 'bad client credentials');- }- }-- try {- const payload = await verifyAccessToken(token);- // Only the issuing client can introspect its own access tokens. Prevents- // any registered client from probing arbitrary tokens for user identity- // or scope (especially relevant given open dynamic registration).- if (payload.client_id && payload.client_id !== client_id) {- // RFC 7662 §2.2: response for "not issued to this client" must be- // indistinguishable from "token not found" so clients can't probe- // token ownership. Both return identical {active: false} at 200.- return json(res, 200, { active: false });- }- return json(res, 200, {- active: true,- scope: payload.scope,- client_id: payload.client_id,- sub: payload.sub,- aud: payload.aud,- iss: payload.iss,- exp: payload.exp,- iat: payload.iat,- token_type: 'Bearer',- });- } catch {- // Maybe it's a refresh token.- const h = await sha256(token);- const r = await sql`select user_id, scope, expires_at, revoked_at from oauth_refresh_tokens- where token_hash = ${h} and client_id = ${client_id} limit 1`;- const row = r[0];- if (!row || row.revoked_at || new Date(row.expires_at) < new Date()) {- return json(res, 200, { active: false });- }- return json(res, 200, {- active: true,- scope: row.scope,- client_id,- sub: row.user_id,- token_type: 'refresh_token',- });- }-});diff --git a/api/oauth/register.js b/api/oauth/register.jsdeleted file mode 100644index 770f469a3..000000000--- a/api/oauth/register.js+++ /dev/null@@ -1,90 +0,0 @@-// RFC 7591 — OAuth 2.0 Dynamic Client Registration-// MCP clients (including Claude) call this at first connect to register themselves.--import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';-import { randomToken, sha256 } from '../_lib/crypto.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { z } from 'zod';-import { parse } from '../_lib/validate.js';--const registerSchema = z.object({- redirect_uris: z.array(z.string().url()).min(1).max(10),- client_name: z.string().trim().min(1).max(120).optional(),- client_uri: z.string().url().optional(),- logo_uri: z.string().url().optional(),- scope: z.string().max(500).optional(),- grant_types: z.array(z.string()).optional(),- response_types: z.array(z.string()).optional(),- token_endpoint_auth_method: z- .enum(['none', 'client_secret_basic', 'client_secret_post'])- .optional(),- software_id: z.string().max(120).optional(),- software_version: z.string().max(60).optional(),-});--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;- if (!method(req, res, ['POST'])) return;-- // RFC 7591 dynamic registration is unauthenticated by design, so cap per-IP- // to deter DB flooding and mass minting of throwaway clients for CSRF / abuse.- const rl = await limits.oauthRegisterIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many registrations from this IP');-- const body = parse(registerSchema, await readJson(req));-- // Security: only allow http redirect URIs for localhost (dev), per OAuth 2.1.- for (const uri of body.redirect_uris) {- const u = new URL(uri);- if (u.protocol === 'http:' && !/^localhost$|^127\.0\.0\.1$/.test(u.hostname)) {- return error(- res,- 400,- 'invalid_redirect_uri',- 'non-https redirect URIs only allowed for localhost',- );- }- }-- const authMethod = body.token_endpoint_auth_method ?? 'none';- const clientType = authMethod === 'none' ? 'public' : 'confidential';-- const clientId = `mcp_${randomToken(18)}`;- let clientSecret = null;- let secretHash = null;- if (clientType === 'confidential') {- clientSecret = randomToken(32);- secretHash = await sha256(clientSecret);- }-- const scope = body.scope ?? 'avatars:read';- const grantTypes = body.grant_types ?? ['authorization_code', 'refresh_token'];- const responseTypes = body.response_types ?? ['code'];-- await sql`- insert into oauth_clients (- client_id, client_secret_hash, client_type, name, logo_uri, client_uri,- redirect_uris, grant_types, response_types, token_endpoint_auth, scope,- software_id, software_version, dynamically_registered- ) values (- ${clientId}, ${secretHash}, ${clientType},- ${body.client_name ?? 'MCP Client'},- ${body.logo_uri ?? null}, ${body.client_uri ?? null},- ${body.redirect_uris}, ${grantTypes}, ${responseTypes}, ${authMethod}, ${scope},- ${body.software_id ?? null}, ${body.software_version ?? null}, true- )- `;-- return json(res, 201, {- client_id: clientId,- ...(clientSecret ? { client_secret: clientSecret } : {}),- client_id_issued_at: Math.floor(Date.now() / 1000),- token_endpoint_auth_method: authMethod,- redirect_uris: body.redirect_uris,- grant_types: grantTypes,- response_types: responseTypes,- scope,- client_name: body.client_name ?? 'MCP Client',- });-});diff --git a/api/oauth/revoke.js b/api/oauth/revoke.jsdeleted file mode 100644index b004d6df8..000000000--- a/api/oauth/revoke.js+++ /dev/null@@ -1,34 +0,0 @@-// RFC 7009 — OAuth 2.0 Token Revocation--import { sql } from '../_lib/db.js';-import { revokeRefreshToken } from '../_lib/auth.js';-import { sha256, constantTimeEquals } from '../_lib/crypto.js';-import { cors, method, readForm, wrap, json, error } from '../_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;- if (!method(req, res, ['POST'])) return;-- const form = await readForm(req);- const { token, token_type_hint, client_id, client_secret } = form;- if (!token || !client_id)- return error(res, 400, 'invalid_request', 'token and client_id required');-- const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;- const client = rows[0];- if (!client) return json(res, 200, {}); // RFC: respond 200 even if unknown, to prevent enumeration-- if (client.client_type === 'confidential') {- const hash = await sha256(client_secret ?? '');- if (!client.client_secret_hash || !constantTimeEquals(hash, client.client_secret_hash)) {- return error(res, 401, 'invalid_client', 'bad client credentials');- }- }-- // Only refresh tokens are revocable server-side; access tokens are JWTs with short TTL.- if (token_type_hint !== 'access_token') {- await revokeRefreshToken(token, client_id);- }-- return json(res, 200, {});-});diff --git a/api/oauth/token.js b/api/oauth/token.jsdeleted file mode 100644index 8718f267d..000000000--- a/api/oauth/token.js+++ /dev/null@@ -1,172 +0,0 @@-// OAuth 2.1 token endpoint.-// Grants supported:-// - authorization_code (with PKCE)-// - refresh_token (rotation + reuse detection)--import { sql } from '../_lib/db.js';-import { mintAccessToken, issueRefreshToken, rotateRefreshToken } from '../_lib/auth.js';-import { sha256, sha256Base64Url, constantTimeEquals } from '../_lib/crypto.js';-import { cors, method, readForm, wrap, error, json } from '../_lib/http.js';-import { limits } from '../_lib/rate-limit.js';-import { env } from '../_lib/env.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;- if (!method(req, res, ['POST'])) return;-- const form = await readForm(req);- const clientId = form.client_id || basicAuthUser(req);- if (!clientId) return error(res, 400, 'invalid_client', 'client_id required');-- const rl = await limits.oauthToken(clientId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many token requests');-- const rows = await sql`select * from oauth_clients where client_id = ${clientId} limit 1`;- const client = rows[0];- if (!client) return error(res, 400, 'invalid_client', 'unknown client');-- if (client.client_type === 'confidential') {- const secret = form.client_secret || basicAuthPass(req) || '';- const providedHash = await sha256(secret);- if (- !client.client_secret_hash ||- !constantTimeEquals(providedHash, client.client_secret_hash)- ) {- return error(res, 401, 'invalid_client', 'bad client credentials');- }- }-- const grantType = form.grant_type;- if (grantType === 'authorization_code') return handleAuthCode(res, client, form);- if (grantType === 'refresh_token') return handleRefresh(res, client, form);- return error(res, 400, 'unsupported_grant_type', `grant_type=${grantType} not supported`);-});--async function handleAuthCode(res, client, form) {- const { code, redirect_uri, code_verifier } = form;- if (!code || !redirect_uri || !code_verifier) {- return error(res, 400, 'invalid_request', 'code, redirect_uri, code_verifier required');- }-- const rows = await sql`- select * from oauth_auth_codes where code = ${code} limit 1- `;- const row = rows[0];- if (!row) return error(res, 400, 'invalid_grant', 'unknown code');- if (row.consumed_at) {- await sql`update oauth_refresh_tokens set revoked_at = now()- where user_id = ${row.user_id} and client_id = ${client.client_id} and revoked_at is null`;- return error(res, 400, 'invalid_grant', 'authorization code already used');- }- if (new Date(row.expires_at) < new Date())- return error(res, 400, 'invalid_grant', 'code expired');- if (row.client_id !== client.client_id)- return error(res, 400, 'invalid_grant', 'client mismatch');- if (row.redirect_uri !== redirect_uri)- return error(res, 400, 'invalid_grant', 'redirect_uri mismatch');-- const computed = await sha256Base64Url(code_verifier);- if (computed !== row.code_challenge)- return error(res, 400, 'invalid_grant', 'PKCE verification failed');-- await sql`update oauth_auth_codes set consumed_at = now() where code = ${code}`;-- const accessToken = await mintAccessToken({- userId: row.user_id,- clientId: client.client_id,- scope: row.scope,- resource: row.resource || env.MCP_RESOURCE,- });-- const wantsRefresh = client.grant_types.includes('refresh_token');- const refresh = wantsRefresh- ? await issueRefreshToken({- userId: row.user_id,- clientId: client.client_id,- scope: row.scope,- resource: row.resource,- })- : null;-- return json(res, 200, {- access_token: accessToken,- token_type: 'Bearer',- expires_in: 3600,- scope: row.scope,- ...(refresh ? { refresh_token: refresh.token } : {}),- });-}--async function handleRefresh(res, client, form) {- const { refresh_token, scope } = form;- if (!refresh_token) return error(res, 400, 'invalid_request', 'refresh_token required');-- let result;- try {- result = await rotateRefreshToken({- oldSecret: refresh_token,- clientId: client.client_id,- // Narrow the rotated refresh token to the requested subset so a caller- // can't re-widen back to the full grant on a later refresh. When no- // scope is sent, preserve the stored scope. When scope is sent, it- // must be a strict subset of the stored scope — reject otherwise so- // the intersect fallback never silently upgrades to stored.- narrowScope: (stored) => {- if (!scope) return stored;- if (!isSubsetScope(scope, stored)) {- throw Object.assign(new Error('requested scope exceeds granted scope'), {- status: 400,- code: 'invalid_scope',- });- }- return scope.split(/\s+/).filter(Boolean).join(' ');- },- });- } catch (err) {- return error(res, err.status || 400, err.code || 'invalid_grant', err.message);- }-- const accessToken = await mintAccessToken({- userId: result.userId,- clientId: client.client_id,- scope: result.scope,- resource: result.resource || env.MCP_RESOURCE,- });-- return json(res, 200, {- access_token: accessToken,- token_type: 'Bearer',- expires_in: 3600,- scope: result.scope,- refresh_token: result.next.token,- });-}--function isSubsetScope(requested, stored) {- const allowed = new Set(stored.split(/\s+/).filter(Boolean));- const asked = requested.split(/\s+/).filter(Boolean);- if (asked.length === 0) return false;- return asked.every((s) => allowed.has(s));-}--function basicAuthUser(req) {- const h = req.headers.authorization || '';- if (!h.toLowerCase().startsWith('basic ')) return null;- try {- const decoded = Buffer.from(h.slice(6), 'base64').toString('utf8');- return decoded.split(':')[0];- } catch {- return null;- }-}--function basicAuthPass(req) {- const h = req.headers.authorization || '';- if (!h.toLowerCase().startsWith('basic ')) return null;- try {- const decoded = Buffer.from(h.slice(6), 'base64').toString('utf8');- return decoded.split(':').slice(1).join(':');- } catch {- return null;- }-}diff --git a/api/payments/evm/checkout.js b/api/payments/evm/checkout.jsdeleted file mode 100644index 23b05c6c3..000000000--- a/api/payments/evm/checkout.js+++ /dev/null@@ -1,68 +0,0 @@-// POST /api/payments/evm/checkout-// Creates a payment intent for an EVM USDC subscription payment.-// Returns the recipient address, exact USDC amount, and a nonce to include in calldata.-// The frontend completes the on-chain transfer, then calls /confirm with the tx hash.--import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';-import { randomToken } from '../../_lib/crypto.js';-import { PLANS, EVM_USDC, getEvmRecipient, INTENT_TTL_MINUTES } from '../_config.js';--const bodySchema = z.object({- plan: z.enum(['pro', 'team', 'enterprise']),- chain_id: z.number().int().positive(),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { plan, chain_id } = body;-- if (!EVM_USDC[chain_id]) {- return error(res, 400, 'unsupported_chain', `chain ${chain_id} is not supported for payments`);- }-- const recipient = getEvmRecipient(chain_id);- if (!recipient) {- return error(res, 503, 'not_configured', 'payment recipient not configured for this chain');- }-- const planConfig = PLANS[plan];- const amountUsdc = planConfig.price_usd; // USD = USDC 1:1- const nonce = await randomToken(16);- const expiresAt = new Date(Date.now() + INTENT_TTL_MINUTES * 60 * 1000);-- const [intent] = await sql`- insert into plan_payment_intents- (user_id, plan, chain_type, chain_id, amount_usdc, recipient, nonce, expires_at)- values- (${user.id}, ${plan}, 'evm', ${chain_id}, ${amountUsdc}, ${recipient.toLowerCase()}, ${nonce}, ${expiresAt})- returning id, nonce, amount_usdc, recipient, expires_at- `;-- return json(res, 201, {- intent_id: intent.id,- plan,- chain_id,- usdc_address: EVM_USDC[chain_id],- recipient: recipient,- amount_usdc: amountUsdc,- // amount in smallest unit (6 decimals) for the frontend to pass to the contract- amount_atomics: String(BigInt(Math.round(amountUsdc * 1_000_000))),- nonce,- expires_at: intent.expires_at,- instructions: `Transfer exactly ${amountUsdc} USDC to ${recipient} on chain ${chain_id}. Include nonce "${nonce}" in memo/calldata if possible, then call /api/payments/evm/confirm.`,- });-});diff --git a/api/payments/evm/confirm.js b/api/payments/evm/confirm.jsdeleted file mode 100644index b2c69bde4..000000000--- a/api/payments/evm/confirm.js+++ /dev/null@@ -1,132 +0,0 @@-// POST /api/payments/evm/confirm-// Verifies an on-chain EVM USDC transfer and activates the subscription.-// Checks: tx exists, to = recipient, from = user wallet, token = USDC, value >= expected.--import { z } from 'zod';-import { createPublicClient, http, parseAbi, formatUnits } from 'viem';-import { mainnet, base, optimism, arbitrum, polygon, sepolia, baseSepolia } from 'viem/chains';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';-import { env } from '../../_lib/env.js';-import { sendSubscriptionConfirmEmail } from '../../_lib/email.js';-import { PLANS, EVM_USDC } from '../_config.js';--const CHAINS = { 1: mainnet, 8453: base, 10: optimism, 42161: arbitrum, 137: polygon, 11155111: sepolia, 84532: baseSepolia };--const ERC20_ABI = parseAbi([- 'event Transfer(address indexed from, address indexed to, uint256 value)',-]);--const bodySchema = z.object({- intent_id: z.string().uuid(),- tx_hash: z.string().regex(/^0x[a-fA-F0-9]{64}$/),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { intent_id, tx_hash } = body;-- // Load and validate intent.- const [intent] = await sql`- select * from plan_payment_intents- where id = ${intent_id} and user_id = ${user.id}- limit 1- `;- if (!intent) return error(res, 404, 'not_found', 'intent not found');- if (intent.status === 'confirmed') return error(res, 409, 'already_confirmed', 'payment already confirmed');- if (intent.status === 'expired' || new Date(intent.expires_at) < new Date()) {- await sql`update plan_payment_intents set status='expired' where id=${intent_id}`;- return error(res, 410, 'intent_expired', 'payment session expired — start a new checkout');- }-- const chainId = intent.chain_id;- const chain = CHAINS[chainId];- if (!chain) return error(res, 400, 'unsupported_chain', `chain ${chainId} not supported`);-- const rpcUrl = env.getRpcUrl(chainId);- const client = createPublicClient({ chain, transport: http(rpcUrl || undefined) });-- // Fetch and verify transaction receipt.- let receipt;- try {- receipt = await client.getTransactionReceipt({ hash: tx_hash });- } catch {- return error(res, 422, 'tx_not_found', 'transaction not found on chain — may need more confirmations');- }- if (receipt.status !== 'success') {- return error(res, 422, 'tx_failed', 'transaction reverted');- }-- // Parse ERC-20 Transfer events from the USDC contract.- const usdcAddress = EVM_USDC[chainId]?.toLowerCase();- const logs = await client.getLogs({- address: usdcAddress,- event: ERC20_ABI[0],- fromBlock: receipt.blockNumber,- toBlock: receipt.blockNumber,- });-- const expectedRecipient = intent.recipient.toLowerCase();- const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));-- const matchingLog = logs.find((log) =>- log.transactionHash?.toLowerCase() === tx_hash.toLowerCase() &&- log.args.to?.toLowerCase() === expectedRecipient &&- BigInt(log.args.value ?? 0) >= expectedAtomics- );-- if (!matchingLog) {- return error(res, 422, 'transfer_not_found',- `No USDC transfer of ${intent.amount_usdc} USDC to ${expectedRecipient} found in tx`);- }-- // Confirm intent and activate subscription.- await sql`- update plan_payment_intents- set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now()- where id=${intent_id}- `;-- const planConfig = PLANS[intent.plan];- const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);-- await sql`- insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until)- values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil})- on conflict (user_id) where status='active'- do update set- plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id,- token_address=excluded.token_address, tx_hash=excluded.tx_hash,- amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()- `;-- // Upgrade user plan.- await sql`update users set plan=${intent.plan} where id=${user.id}`;-- // Fire-and-forget confirmation email.- queueMicrotask(() => sendSubscriptionConfirmEmail({- to: user.email,- plan: intent.plan,- chain: `EVM chain ${chainId}`,- txId: tx_hash,- }));-- return json(res, 200, {- ok: true,- plan: intent.plan,- active_until: activeUntil.toISOString(),- tx_hash,- });-});diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].jsnew file mode 100644index 000000000..1169088c8--- /dev/null+++ b/api/payments/solana/[action].js@@ -0,0 +1,130 @@+// Consolidated Solana payment endpoints (checkout + confirm).++import { z } from 'zod';+import { Connection } from '@solana/web3.js';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';+import { randomToken } from '../../_lib/crypto.js';+import { sendSubscriptionConfirmEmail } from '../../_lib/email.js';+import { PLANS, SOLANA_USDC_MINT, getSolanaRecipient, INTENT_TTL_MINUTES } from '../_config.js';++const SOLANA_RPC_MAINNET = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';++// ── checkout ──────────────────────────────────────────────────────────────────++const checkoutSchema = z.object({+ plan: z.enum(['pro', 'team', 'enterprise']),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+});++async function handleCheckout(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 rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const body = parse(checkoutSchema, await readJson(req));+ const { plan, network } = body;+ const recipient = getSolanaRecipient();+ if (!recipient) return error(res, 503, 'not_configured', 'Solana payment recipient not configured');+ const planConfig = PLANS[plan];+ const amountUsdc = planConfig.price_usd;+ const nonce = await randomToken(16);+ const expiresAt = new Date(Date.now() + INTENT_TTL_MINUTES * 60 * 1000);+ const usdcMint = network === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : SOLANA_USDC_MINT;+ const [intent] = await sql`insert into plan_payment_intents (user_id, plan, chain_type, amount_usdc, recipient, nonce, memo, expires_at) values (${user.id}, ${plan}, 'solana', ${amountUsdc}, ${recipient}, ${nonce}, ${nonce}, ${expiresAt}) returning id, nonce, amount_usdc, recipient, expires_at`;+ const solanaPay = new URL(`solana:${recipient}`);+ solanaPay.searchParams.set('amount', String(amountUsdc));+ solanaPay.searchParams.set('spl-token', usdcMint);+ solanaPay.searchParams.set('memo', nonce);+ solanaPay.searchParams.set('label', 'three.ws');+ solanaPay.searchParams.set('message', `${planConfig.label} plan subscription`);+ return json(res, 201, { intent_id: intent.id, plan, network, solana_pay_url: solanaPay.toString(), recipient, usdc_mint: usdcMint, amount_usdc: amountUsdc, nonce, expires_at: intent.expires_at });+}++// ── confirm ───────────────────────────────────────────────────────────────────++const confirmSchema = z.object({+ intent_id: z.string().uuid(),+ tx_signature: z.string().min(80).max(100),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+});++async function handleConfirm(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 rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const body = parse(confirmSchema, await readJson(req));+ const { intent_id, tx_signature, network } = body;+ const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} and chain_type = 'solana' limit 1`;+ if (!intent) return error(res, 404, 'not_found', 'intent not found');+ if (intent.status === 'confirmed') return error(res, 409, 'already_confirmed', 'payment already confirmed');+ if (intent.status === 'expired' || new Date(intent.expires_at) < new Date()) {+ await sql`update plan_payment_intents set status='expired' where id=${intent_id}`;+ return error(res, 410, 'intent_expired', 'payment session expired');+ }+ const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;+ const connection = new Connection(rpcUrl, 'confirmed');+ const usdcMint = network === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : SOLANA_USDC_MINT;+ let tx;+ try { tx = await connection.getParsedTransaction(tx_signature, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' }); }+ catch { return error(res, 422, 'tx_not_found', 'transaction not found — may need more confirmations'); }+ if (!tx) return error(res, 422, 'tx_not_found', 'transaction not found');+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'transaction failed on-chain');+ const memoIx = tx.transaction.message.instructions.find((ix) => ix.programId?.toString() === 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+ const memo = memoIx?.parsed;+ if (memo && memo !== intent.nonce) return error(res, 422, 'memo_mismatch', 'transaction memo does not match intent nonce');+ const expectedRecipient = intent.recipient;+ const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));+ const tokenBalances = tx.meta?.postTokenBalances || [];+ const preBalances = tx.meta?.preTokenBalances || [];+ const matchingTransfer = tx.transaction.message.instructions.find((ix) => {+ if (ix.programId?.toString() !== 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') return false;+ const parsed = ix.parsed;+ if (parsed?.type !== 'transferChecked' && parsed?.type !== 'transfer') return false;+ const info = parsed.info;+ const mintMatch = !info.mint || info.mint === usdcMint;+ const amount = BigInt(info.tokenAmount?.amount ?? info.amount ?? '0');+ return mintMatch && amount >= expectedAtomics && (info.destination === expectedRecipient || info.destinationOwner === expectedRecipient);+ });+ let verifiedViaBalance = false;+ if (!matchingTransfer) {+ for (const post of tokenBalances) {+ if (post.mint !== usdcMint) continue;+ const pre = preBalances.find((p) => p.accountIndex === post.accountIndex);+ const delta = BigInt(post.uiTokenAmount.amount) - BigInt(pre?.uiTokenAmount?.amount ?? '0');+ if (delta >= expectedAtomics) {+ const accountKeys = tx.transaction.message.accountKeys;+ const owner = accountKeys[post.accountIndex]?.pubkey?.toString();+ if (owner === expectedRecipient || post.owner === expectedRecipient) { verifiedViaBalance = true; break; }+ }+ }+ }+ if (!matchingTransfer && !verifiedViaBalance) return error(res, 422, 'transfer_not_found', `No USDC transfer of ${intent.amount_usdc} to ${expectedRecipient} found in tx`);+ await sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now() where id=${intent_id}`;+ const planConfig = PLANS[intent.plan];+ const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);+ await sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;+ await sql`update users set plan=${intent.plan} where id=${user.id}`;+ queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `Solana ${network}`, txId: tx_signature }));+ return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_signature });+}++// ── dispatcher ────────────────────────────────────────────────────────────────++const DISPATCH = { checkout: handleCheckout, confirm: handleConfirm };++export default wrap(async (req, res) => {+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();+ const fn = DISPATCH[action];+ if (!fn) return error(res, 404, 'not_found', `unknown solana payment action: ${action}`);+ return fn(req, res);+});diff --git a/api/payments/solana/checkout.js b/api/payments/solana/checkout.jsdeleted file mode 100644index 8e3e95c74..000000000--- a/api/payments/solana/checkout.js+++ /dev/null@@ -1,74 +0,0 @@-// POST /api/payments/solana/checkout-// Creates a Solana Pay payment request for USDC subscription.-// Returns a Solana Pay URL (solana:<recipient>?amount=X&spl-token=USDC&memo=<nonce>)-// and raw fields for the frontend to construct a transaction manually.--import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';-import { randomToken } from '../../_lib/crypto.js';-import { PLANS, SOLANA_USDC_MINT, getSolanaRecipient, INTENT_TTL_MINUTES } from '../_config.js';--const bodySchema = z.object({- plan: z.enum(['pro', 'team', 'enterprise']),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { plan, network } = body;-- const recipient = getSolanaRecipient();- if (!recipient) {- return error(res, 503, 'not_configured', 'Solana payment recipient not configured');- }-- const planConfig = PLANS[plan];- const amountUsdc = planConfig.price_usd;- const nonce = await randomToken(16);- const expiresAt = new Date(Date.now() + INTENT_TTL_MINUTES * 60 * 1000);- const usdcMint = network === 'devnet'- ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'- : SOLANA_USDC_MINT;-- const [intent] = await sql`- insert into plan_payment_intents- (user_id, plan, chain_type, amount_usdc, recipient, nonce, memo, expires_at)- values- (${user.id}, ${plan}, 'solana', ${amountUsdc}, ${recipient}, ${nonce}, ${nonce}, ${expiresAt})- returning id, nonce, amount_usdc, recipient, expires_at- `;-- // Build Solana Pay URL per spec:- // solana:<recipient>?amount=<usdc>&spl-token=<mint>&memo=<nonce>&label=three.ws&message=<plan>- const solanaPay = new URL(`solana:${recipient}`);- solanaPay.searchParams.set('amount', String(amountUsdc));- solanaPay.searchParams.set('spl-token', usdcMint);- solanaPay.searchParams.set('memo', nonce);- solanaPay.searchParams.set('label', 'three.ws');- solanaPay.searchParams.set('message', `${planConfig.label} plan subscription`);-- return json(res, 201, {- intent_id: intent.id,- plan,- network,- solana_pay_url: solanaPay.toString(),- recipient,- usdc_mint: usdcMint,- amount_usdc: amountUsdc,- nonce,- expires_at: intent.expires_at,- });-});diff --git a/api/payments/solana/confirm.js b/api/payments/solana/confirm.jsdeleted file mode 100644index 71f688dba..000000000--- a/api/payments/solana/confirm.js+++ /dev/null@@ -1,157 +0,0 @@-// POST /api/payments/solana/confirm-// Verifies a Solana USDC transfer on-chain and activates the subscription.-// Checks: tx confirmed, memo matches nonce, SPL transfer to recipient >= expected amount.--import { z } from 'zod';-import { Connection, PublicKey } from '@solana/web3.js';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';-import { sendSubscriptionConfirmEmail } from '../../_lib/email.js';-import { PLANS, SOLANA_USDC_MINT } from '../_config.js';--const SOLANA_RPC_MAINNET = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';-const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';--const bodySchema = z.object({- intent_id: z.string().uuid(),- tx_signature: z.string().min(80).max(100), // base58 Solana tx signature- network: z.enum(['mainnet', 'devnet']).default('mainnet'),-});--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 rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- const body = parse(bodySchema, await readJson(req));- const { intent_id, tx_signature, network } = body;-- // Load intent.- const [intent] = await sql`- select * from plan_payment_intents- where id = ${intent_id} and user_id = ${user.id} and chain_type = 'solana'- limit 1- `;- if (!intent) return error(res, 404, 'not_found', 'intent not found');- if (intent.status === 'confirmed') return error(res, 409, 'already_confirmed', 'payment already confirmed');- if (intent.status === 'expired' || new Date(intent.expires_at) < new Date()) {- await sql`update plan_payment_intents set status='expired' where id=${intent_id}`;- return error(res, 410, 'intent_expired', 'payment session expired');- }-- const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;- const connection = new Connection(rpcUrl, 'confirmed');- const usdcMint = network === 'devnet'- ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'- : SOLANA_USDC_MINT;-- // Fetch transaction.- let tx;- try {- tx = await connection.getParsedTransaction(tx_signature, {- maxSupportedTransactionVersion: 0,- commitment: 'confirmed',- });- } catch {- return error(res, 422, 'tx_not_found', 'transaction not found — may need more confirmations');- }- if (!tx) return error(res, 422, 'tx_not_found', 'transaction not found');- if (tx.meta?.err) return error(res, 422, 'tx_failed', 'transaction failed on-chain');-- // Check memo matches nonce.- const memoIx = tx.transaction.message.instructions.find(- (ix) => ix.programId?.toString() === 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',- );- const memo = memoIx?.parsed;- if (memo && memo !== intent.nonce) {- return error(res, 422, 'memo_mismatch', 'transaction memo does not match intent nonce');- }-- // Find SPL token transfer to recipient.- const expectedRecipient = intent.recipient;- const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));-- const tokenBalances = tx.meta?.postTokenBalances || [];- const preBalances = tx.meta?.preTokenBalances || [];-- // Build a map of account index → token balance change.- const matchingTransfer = tx.transaction.message.instructions.find((ix) => {- if (ix.programId?.toString() !== 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') return false;- const parsed = ix.parsed;- if (parsed?.type !== 'transferChecked' && parsed?.type !== 'transfer') return false;- const info = parsed.info;- // destination owner should be recipient- const destOwner = info.destination || info.destinationOwner || '';- const mintMatch = !info.mint || info.mint === usdcMint;- const amount = BigInt(info.tokenAmount?.amount ?? info.amount ?? '0');- return mintMatch && amount >= expectedAtomics &&- (destOwner === expectedRecipient || info.destination === expectedRecipient);- });-- // Fallback: check token balance deltas.- let verifiedViaBalance = false;- if (!matchingTransfer) {- for (const post of tokenBalances) {- if (post.mint !== usdcMint) continue;- const pre = preBalances.find((p) => p.accountIndex === post.accountIndex);- const delta = BigInt(post.uiTokenAmount.amount) - BigInt(pre?.uiTokenAmount?.amount ?? '0');- if (delta >= expectedAtomics) {- // Check the account owner is the recipient- const accountKeys = tx.transaction.message.accountKeys;- const owner = accountKeys[post.accountIndex]?.pubkey?.toString();- if (owner === expectedRecipient || post.owner === expectedRecipient) {- verifiedViaBalance = true;- break;- }- }- }- }-- if (!matchingTransfer && !verifiedViaBalance) {- return error(res, 422, 'transfer_not_found',- `No USDC transfer of ${intent.amount_usdc} to ${expectedRecipient} found in tx`);- }-- // Confirm intent.- await sql`- update plan_payment_intents- set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now()- where id=${intent_id}- `;-- const planConfig = PLANS[intent.plan];- const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);-- await sql`- insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until)- values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil})- on conflict (user_id) where status='active'- do update set- plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address,- tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()- `;-- await sql`update users set plan=${intent.plan} where id=${user.id}`;-- queueMicrotask(() => sendSubscriptionConfirmEmail({- to: user.email,- plan: intent.plan,- chain: `Solana ${network}`,- txId: tx_signature,- }));-- return json(res, 200, {- ok: true,- plan: intent.plan,- active_until: activeUntil.toISOString(),- tx_signature,- });-});diff --git a/api/wk-agent-attestation-schemas.js b/api/wk-agent-attestation-schemas.jsdeleted file mode 100644index cad28cfd4..000000000--- a/api/wk-agent-attestation-schemas.js+++ /dev/null@@ -1,97 +0,0 @@-// /.well-known/agent-attestation-schemas — three.ws Solana agent attestation schema registry.-//-// Machine-readable schemas for the SPL Memo-based ERC-8004 analog. Other agents-// and indexers consume this to validate payloads they discover via-// getSignaturesForAddress(<agent_asset>).--import { cors, json, method, wrap } from './_lib/http.js';--const COMMON = {- v: { type: 'integer', const: 1 },- kind: { type: 'string' },- agent: { type: 'string', description: 'Metaplex Core asset pubkey (base58)' },- ts: { type: 'integer', description: 'Unix seconds when attestation was created' },-};--const SCHEMAS = {- 'threews.feedback.v1': {- description: 'Client → agent feedback. Verified iff a matching task.accepted exists from this agent for the same task_id.',- required: ['v', 'kind', 'agent', 'score'],- properties: {- ...COMMON,- score: { type: 'integer', minimum: 1, maximum: 5 },- task_id: { type: 'string' },- uri: { type: 'string', format: 'uri' },- },- },- 'threews.validation.v1': {- description: 'Validator attestation about an agent task result.',- required: ['v', 'kind', 'agent', 'task_hash', 'passed'],- properties: {- ...COMMON,- task_hash: { type: 'string' },- passed: { type: 'boolean' },- uri: { type: 'string', format: 'uri' },- },- },- 'threews.task.v1': {- description: 'Client posts a task offer to an agent. Counterpart to task.accepted.',- required: ['v', 'kind', 'agent', 'task_id', 'scope_hash'],- properties: {- ...COMMON,- task_id: { type: 'string' },- scope_hash: { type: 'string', description: 'Hash of off-chain task brief' },- uri: { type: 'string', format: 'uri' },- },- },- 'threews.accept.v1': {- description: 'Agent accepts a task. Must be signed by the agent owner. Required for feedback to be verified.',- required: ['v', 'kind', 'agent', 'task_id'],- properties: {- ...COMMON,- task_id: { type: 'string' },- },- },- 'threews.revoke.v1': {- description: 'Revoke a previous attestation. Only honored when signed by the original attester.',- required: ['v', 'kind', 'agent', 'target_signature'],- properties: {- ...COMMON,- target_signature: { type: 'string', description: 'Signature of the attestation being revoked' },- reason: { type: 'string' },- },- },- 'threews.dispute.v1': {- description: 'Agent owner disputes a feedback or validation. Does not delete; flags disputed=true.',- required: ['v', 'kind', 'agent', 'target_signature'],- properties: {- ...COMMON,- target_signature: { type: 'string' },- reason: { type: 'string' },- uri: { type: 'string', format: 'uri' },- },- },-};--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;- return json(- res,- 200,- {- version: 1,- transport: {- type: 'spl-memo',- program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',- note: 'Each attestation is a signed memo tx with the agent asset pubkey as a non-signer key.',- },- schemas: SCHEMAS,- discovery: {- list_endpoint: '/api/agents/solana-attestations?asset=<pubkey>&kind=...',- reputation_endpoint: '/api/agents/solana-reputation?asset=<pubkey>',- },- },- { 'cache-control': 'public, max-age=300' },- );-});diff --git a/api/wk-oauth-authorization-server.js b/api/wk-oauth-authorization-server.jsdeleted file mode 100644index 2bd0b73fb..000000000--- a/api/wk-oauth-authorization-server.js+++ /dev/null@@ -1,47 +0,0 @@-// RFC 8414 — OAuth 2.0 Authorization Server Metadata-// https://datatracker.ietf.org/doc/html/rfc8414-//-// Served at /.well-known/oauth-authorization-server via vercel.json rewrite.-// The file lives outside a dot-prefixed directory because Vercel's build-// pipeline excludes `api/.well-known/**` from function deployment.--import { env } from './_lib/env.js';-import { cors, json, method, wrap } from './_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;- const base = env.APP_ORIGIN;- return json(- res,- 200,- {- issuer: base,- authorization_endpoint: `${base}/oauth/authorize`,- token_endpoint: `${base}/api/oauth/token`,- registration_endpoint: `${base}/api/oauth/register`,- revocation_endpoint: `${base}/api/oauth/revoke`,- introspection_endpoint: `${base}/api/oauth/introspect`,- response_types_supported: ['code'],- grant_types_supported: ['authorization_code', 'refresh_token'],- code_challenge_methods_supported: ['S256'],- token_endpoint_auth_methods_supported: [- 'none',- 'client_secret_basic',- 'client_secret_post',- ],- scopes_supported: [- 'avatars:read',- 'avatars:write',- 'avatars:delete',- 'profile',- 'offline_access',- ],- service_documentation: `${base}/docs/mcp`,- ui_locales_supported: ['en'],- },- {- 'cache-control': 'public, max-age=300',- },- );-});diff --git a/api/wk-oauth-protected-resource.js b/api/wk-oauth-protected-resource.jsdeleted file mode 100644index 97425c6a4..000000000--- a/api/wk-oauth-protected-resource.js+++ /dev/null@@ -1,27 +0,0 @@-// RFC 9728 — OAuth 2.0 Protected Resource Metadata-// Served at /.well-known/oauth-protected-resource and at-// /api/mcp/.well-known/oauth-protected-resource via vercel.json rewrites.-// Kept outside dot-prefixed dirs: Vercel excludes `api/.well-known/**` from-// function deployment.--import { env } from './_lib/env.js';-import { cors, json, method, wrap } from './_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;- return json(- res,- 200,- {- resource: env.MCP_RESOURCE,- authorization_servers: [env.APP_ORIGIN],- bearer_methods_supported: ['header'],- resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,- scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile'],- },- {- 'cache-control': 'public, max-age=300',- },- );-});diff --git a/api/wk-x402.js b/api/wk-x402.jsdeleted file mode 100644index fdce4d411..000000000--- a/api/wk-x402.js+++ /dev/null@@ -1,24 +0,0 @@-// /.well-known/x402 — x402 resource discovery (fallback; /openapi.json is preferred)-// Spec: https://x402scan.com/discovery--import { cors, json, method, wrap } from './_lib/http.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;- return json(- res,- 200,- {- version: 1,- resources: ['POST /api/mcp'],- schemes: ['solana-pay', 'evm-erc20', 'pump-agent-payments'],- pump_agent_payments: {- prep: '/api/pump/accept-payment-prep',- confirm: '/api/pump/accept-payment-confirm',- balances: '/api/pump/balances',- },- },- { 'cache-control': 'public, max-age=300' },- );-});diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex 797bda201..38da15180 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -79,8 +79,9 @@<input id="ctl-mint" type="text" placeholder="Filter mint…" size="18" /><select id="ctl-kind" title="Event type"><option value="all">All events</option>+ <option value="mint">New tokens</option>+ <option value="graduation">Graduations</option><option value="claims">Claims only</option>- <option value="graduations">Graduations only</option></select><select id="ctl-tier" title="Minimum tier"><option value="">Any tier</option>@@ -116,7 +117,7 @@const params = {asset: url.searchParams.get('asset') || '',mint: url.searchParams.get('mint') || '',- kind: url.searchParams.get('kind') || 'graduations',+ kind: url.searchParams.get('kind') || 'all',minTier: url.searchParams.get('minTier') || '',network: url.searchParams.get('network') || 'mainnet',narrate: url.searchParams.get('narrate') !== '0',@@ -226,6 +227,16 @@</div>`;}+ function renderMint(ev) {+ const cap = ev.usd_market_cap != null ? `$${Number(ev.usd_market_cap).toLocaleString(undefined,{maximumFractionDigits:0})}` : '';+ return `<div class="evt">+ <div class="evt-row"><span class="evt-kind">🌱 new token</span><span class="evt-time">${cap}</span></div>+ <div class="evt-who">${escapeHtml(ev.name || ev.symbol || ev.mint || '—')}</div>+ ${ev.symbol ? `<div class="evt-amt">$${escapeHtml(ev.symbol)}</div>` : ''}+ ${ev.description ? `<div class="evt-take">${escapeHtml(ev.description.slice(0,80))}</div>` : ''}+ </div>`;+ }+function pushEvent(html) {const feed = $('feed');if (feed.querySelector('.empty')) feed.innerHTML = '';@@ -253,6 +264,10 @@const ev = safeJson(msg.data); if (!ev || !eventMatchesMint(ev)) return;pushEvent(renderGraduation(ev));});+ es.addEventListener('mint', (msg) => {+ const ev = safeJson(msg.data); if (!ev || !eventMatchesMint(ev)) return;+ pushEvent(renderMint(ev));+ });}function safeJson(s) { try { return JSON.parse(s); } catch { return null; } }@@ -291,17 +306,7 @@$('ctl-asset').addEventListener('change', onFilterChange);// Initial load- fetch('/api/agents/pumpfun?op=claims&limit=1', { credentials: 'include' }).then((r) => {- if (r.status === 503) {- const w = document.createElement('div');- w.className = 'warn';- w.innerHTML = 'Pump.fun feed is not configured on this server. Set <code>PUMPFUN_BOT_URL</code> to enable. See <a href="/docs/solana-pumpfun.md">solana-pumpfun.md</a>.';- document.querySelector('header').insertAdjacentElement('afterend', w);- setStatus('down', 'unconfigured');- return;- }- connectFeed();- }).catch(() => connectFeed());+ connectFeed();mountAgent();</script>diff --git a/tests/api/solana-attest-event.test.js b/tests/api/solana-attest-event.test.jsindex d8d753d64..cc2613ffc 100644--- a/tests/api/solana-attest-event.test.js+++ b/tests/api/solana-attest-event.test.js@@ -5,7 +5,7 @@ import {buildPayload,taskHash,verifyPumpkitSignature,-} from '../../api/agents/solana-attest-event.js';+} from '../../api/agents/solana/_handlers.js';const SECRET = 'test-secret';const AGENT = 'AgentAssetPubkey1111111111111111111111111111';diff --git a/tests/api/solana-register-prep.test.js b/tests/api/solana-register-prep.test.jsindex 4dd2ae7d3..2aa5b3f2b 100644--- a/tests/api/solana-register-prep.test.js+++ b/tests/api/solana-register-prep.test.js@@ -60,7 +60,7 @@ vi.mock('@metaplex-foundation/umi', () => ({createNoopSigner: vi.fn((pk) => ({ publicKey: pk })),}));-const { default: handler } = await import('../../api/agents/solana-register-prep.js');+const { handleRegisterPrep: handler } = await import('../../api/agents/solana/_handlers.js');// ── Helpers ──────────────────────────────────────────────────────────────diff --git a/vercel.json b/vercel.jsonindex ef7e9db08..f4dad7a9d 100644--- a/vercel.json+++ b/vercel.json@@ -6,39 +6,31 @@"src": "/openapi\\.json","dest": "/api/openapi-json"},- {- "src": "/\\.well-known/x402",- "dest": "/api/wk-x402"- },- {- "src": "/\\.well-known/agent-attestation-schemas",- "dest": "/api/wk-agent-attestation-schemas"- },- {- "src": "/a/sol/([^/]+)/\\.well-known/agent-card\\.json",- "dest": "/api/agents/solana-card?asset=$1"- },- {- "src": "/\\.well-known/oauth-authorization-server",- "dest": "/api/wk-oauth-authorization-server"- },- {- "src": "/\\.well-known/oauth-protected-resource",- "dest": "/api/wk-oauth-protected-resource"- },- {- "src": "/api/mcp/\\.well-known/oauth-protected-resource",- "dest": "/api/wk-oauth-protected-resource"- },+ { "src": "/\\.well-known/x402", "dest": "/api/wk?name=x402" },+ { "src": "/\\.well-known/agent-attestation-schemas", "dest": "/api/wk?name=agent-attestation-schemas" },+ { "src": "/\\.well-known/oauth-authorization-server", "dest": "/api/wk?name=oauth-authorization-server" },+ { "src": "/\\.well-known/oauth-protected-resource", "dest": "/api/wk?name=oauth-protected-resource" },+ { "src": "/api/mcp/\\.well-known/oauth-protected-resource", "dest": "/api/wk?name=oauth-protected-resource" },++ { "src": "/a/sol/([^/]+)/\\.well-known/agent-card\\.json", "dest": "/api/agents/solana/[action]?action=card&asset=$1" },++ { "src": "/api/agents/solana-attestations", "dest": "/api/agents/solana/[action]?action=attestations" },+ { "src": "/api/agents/solana-attest-event", "dest": "/api/agents/solana/[action]?action=attest-event" },+ { "src": "/api/agents/solana-card", "dest": "/api/agents/solana/[action]?action=card" },+ { "src": "/api/agents/solana-price-history", "dest": "/api/agents/solana/[action]?action=price-history" },+ { "src": "/api/agents/solana-register-prep", "dest": "/api/agents/solana/[action]?action=register-prep" },+ { "src": "/api/agents/solana-register-confirm", "dest": "/api/agents/solana/[action]?action=register-confirm" },+ { "src": "/api/agents/solana-reputation", "dest": "/api/agents/solana/[action]?action=reputation" },+ { "src": "/api/agents/solana-reputation-history", "dest": "/api/agents/solana/[action]?action=reputation-history" },{ "src": "/api/newsletter/subscribe", "dest": "/api/newsletter-subscribe" },- { "src": "/oauth/authorize", "dest": "/api/oauth/authorize" },- { "src": "/oauth/consent", "dest": "/api/oauth/authorize" },- { "src": "/oauth/token", "dest": "/api/oauth/token" },- { "src": "/oauth/register", "dest": "/api/oauth/register" },- { "src": "/oauth/revoke", "dest": "/api/oauth/revoke" },- { "src": "/oauth/introspect", "dest": "/api/oauth/introspect" },+ { "src": "/oauth/authorize", "dest": "/api/oauth/[action]?action=authorize" },+ { "src": "/oauth/consent", "dest": "/api/oauth/[action]?action=authorize" },+ { "src": "/oauth/token", "dest": "/api/oauth/[action]?action=token" },+ { "src": "/oauth/register", "dest": "/api/oauth/[action]?action=register" },+ { "src": "/oauth/revoke", "dest": "/api/oauth/[action]?action=revoke" },+ { "src": "/oauth/introspect", "dest": "/api/oauth/[action]?action=introspect" },{ "src": "/login", "dest": "/login.html" },{ "src": "/register", "dest": "/register.html" },@@ -192,11 +184,6 @@{ "src": "/admin/", "dest": "/admin/index.html" },{ "src": "/admin/(.*)", "dest": "/admin/$1" },- { "src": "/api/auth/logout-everywhere", "dest": "/api/auth/logout-everywhere" },- { "src": "/api/auth/verify-email", "dest": "/api/auth/verify-email" },- { "src": "/api/auth/forgot-password", "dest": "/api/auth/forgot-password" },- { "src": "/api/auth/reset-password", "dest": "/api/auth/reset-password" },- { "src": "/api/auth/resend-verification", "dest": "/api/auth/resend-verification" },{ "src": "/api/llm/anthropic", "dest": "/api/llm/anthropic.js" },{ "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]/usage?id=$1" },