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
Add ca2x402: paste a contract address, get a payable x402 token-intel endpoint
nirholasd9e772dc369a
diff --git a/api/_lib/token-market.js b/api/_lib/token-market.jsnew file mode 100644index 000000000..83b8faf7f--- /dev/null+++ b/api/_lib/token-market.js@@ -0,0 +1,140 @@+// Generic, coin-agnostic token market reader + signal builder.+//+// The mint is supplied at runtime by the caller — this is the plumbing the+// CA → x402 resolver (/ca2x402) and the generic /api/x402/token-intel service+// share. It is deliberately symbol-aware (no hardcoded ticker) so it works for+// any token a user pastes, while the platform still only ever *promotes*+// $THREE. Data is live DexScreener (no key, no mock path).+//+// The $THREE-specific oracle (/api/x402/three-intel) keeps its own THREE-branded+// copy on purpose — it is pinned to one mint and unit-tested as such.++import { isValidSolanaAddress, isValidEvmAddress } from './validate.js';++const DEXSCREENER_TOKENS = 'https://api.dexscreener.com/latest/dex/tokens/';++/**+ * Is this string a plausible token contract address we can resolve?+ * Accepts Solana base58 mints and EVM 0x addresses — DexScreener indexes both.+ * @param {string} ca+ * @returns {boolean}+ */+export function isResolvableAddress(ca) {+ return isValidSolanaAddress(ca) || isValidEvmAddress(ca);+}++/** Chain family of a contract address, or null if unrecognized. */+export function chainOf(ca) {+ if (isValidEvmAddress(ca)) return 'evm';+ if (isValidSolanaAddress(ca)) return 'solana';+ return null;+}++function num(v) {+ const n = typeof v === 'string' ? parseFloat(v) : v;+ return Number.isFinite(n) ? n : null;+}++/**+ * Fetch live market + identity for any token by contract address.+ *+ * Picks the deepest-liquidity pair across all DEXs/chains DexScreener knows+ * about for the address. Returns null when the token is unknown or upstream is+ * unavailable — callers decide how to surface that (the resolver renders a+ * designed "not found" state; the paid endpoint throws 503 before settling so+ * the buyer is never charged for missing data).+ *+ * @param {string} ca contract address (Solana mint or EVM 0x)+ * @param {{ signal?: AbortSignal }} [opts]+ * @returns {Promise<null | {+ * mint: string, symbol: string|null, name: string|null, image: string|null,+ * chain: string|null, dex: string|null, pair_url: string|null,+ * price_usd: number|null, change_24h: number|null, market_cap_usd: number|null,+ * liquidity_usd: number|null, volume_24h_usd: number|null, pair_created_at: number|null,+ * }>}+ */+export async function fetchTokenMarket(ca, opts = {}) {+ const r = await fetch(`${DEXSCREENER_TOKENS}${encodeURIComponent(ca)}`, {+ headers: { Accept: 'application/json' },+ signal: opts.signal ?? AbortSignal.timeout(6000),+ });+ if (!r.ok) return null;+ const data = await r.json().catch(() => null);+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];+ if (!pairs.length) return null;++ pairs.sort((a, b) => (b.liquidity?.usd ?? 0) - (a.liquidity?.usd ?? 0));+ const p = pairs[0];++ // The address can be either side of a pair; pick the token that matches.+ const lc = ca.toLowerCase();+ const base = p.baseToken || {};+ const quote = p.quoteToken || {};+ const tok = (base.address || '').toLowerCase() === lc ? base+ : (quote.address || '').toLowerCase() === lc ? quote+ : base;+ const info = p.info || {};++ return {+ mint: tok.address || ca,+ symbol: tok.symbol || null,+ name: tok.name || null,+ image: info.imageUrl || null,+ chain: p.chainId || null,+ dex: p.dexId || null,+ pair_url: p.url || null,+ price_usd: num(p.priceUsd),+ change_24h: p.priceChange?.h24 ?? null,+ market_cap_usd: num(p.marketCap) ?? num(p.fdv),+ liquidity_usd: num(p.liquidity?.usd),+ volume_24h_usd: num(p.volume?.h24),+ pair_created_at: num(p.pairCreatedAt),+ };+}++/**+ * Build a bullish/bearish/neutral signal from market data, branded to the+ * token's own symbol. Mirrors the $THREE oracle thresholds so the generated+ * service reads consistently with the in-house one.+ *+ * @param {{ symbol?: string|null, price_usd: number|null, change_24h: number,+ * volume_24h_usd: number|null, liquidity_usd: number|null }} m+ */+export function buildTokenSignal(m) {+ const sym = (m.symbol || 'token').toUpperCase();+ const change = Number(m.change_24h) || 0;+ const fmt = (n) => (n >= 100 ? n.toFixed(2) : n >= 1 ? n.toFixed(3) : n.toFixed(6));+ const pStr = m.price_usd != null ? `$${fmt(m.price_usd)}` : '?';+ const sign = change >= 0 ? '+' : '';+ const cStr = `${sign}${change.toFixed(2)}%`;++ const turnover =+ m.volume_24h_usd != null && m.liquidity_usd ? m.volume_24h_usd / m.liquidity_usd : null;+ const flowLine =+ turnover == null ? 'Flow data is thin; weigh the move accordingly.'+ : turnover > 3 ? 'Volume is running hot against liquidity — high conviction behind the move.'+ : turnover > 1 ? 'Volume is healthy against liquidity; participation is real.'+ : 'Volume is light against liquidity; the move has limited backing so far.';++ let signal, headline;+ if (change > 5) {+ signal = 'bullish';+ headline = `${sym} surges ${cStr} in 24 h — strong momentum`;+ } else if (change > 1) {+ signal = 'bullish';+ headline = `${sym} climbs ${cStr} — moderate upside`;+ } else if (change < -5) {+ signal = 'bearish';+ headline = `${sym} drops ${Math.abs(change).toFixed(2)}% — sellers in control`;+ } else if (change < -1) {+ signal = 'bearish';+ headline = `${sym} slips ${cStr} — mild weakness`;+ } else {+ signal = 'neutral';+ headline = `${sym} flat at ${cStr} — consolidating at ${pStr}`;+ }++ const rationale = `${sym} is ${change >= 0 ? 'up' : 'down'} ${cStr} over 24 h, trading at ${pStr}. ${flowLine}`;+ const confidence = Math.min(0.93, 0.64 + Math.min(Math.abs(change) / 20, 0.29));+ return { signal, headline, rationale, confidence };+}diff --git a/api/ca2x402/resolve.js b/api/ca2x402/resolve.jsnew file mode 100644index 000000000..f606b2f98--- /dev/null+++ b/api/ca2x402/resolve.js@@ -0,0 +1,154 @@+// GET /api/ca2x402/resolve?mint=<contract-address>+//+// The free resolver behind the CA → x402 tool (/ca2x402). Paste any token+// contract address and this returns two things:+//+// 1. token — live identity + market preview (symbol, name, image, price,+// 24 h change, liquidity, volume, a signal) so the page can show+// what it found before anyone pays.+// 2. service — the x402 paid service generated for that exact token: the+// endpoint URL, price, networks, receivers, the bazaar schema,+// and copy-paste call snippets (curl / x402-fetch / agent skill).+//+// The mint is supplied at runtime by the caller — generic, coin-agnostic+// plumbing. This endpoint is free (no payment); the paid data lives behind+// /api/x402/token-intel, which the snippets point at.+//+// Data is live DexScreener. When the token is unknown, we return a clean 404+// the page renders as a designed "not found" state — never a fabricated token.++import { cors, json, error, wrap } from '../_lib/http.js';+import { priceFor } from '../_lib/x402-prices.js';+import { env } from '../_lib/env.js';+import {+ fetchTokenMarket,+ buildTokenSignal,+ isResolvableAddress,+ chainOf,+} from '../_lib/token-market.js';+import { BAZAAR, OUTPUT_SCHEMA } from '../x402/token-intel.js';++const PRICE_ATOMICS = priceFor('token-intel', '10000');+const PRICE_USD = Number(PRICE_ATOMICS) / 1e6; // USDC has 6 decimals+const NETWORKS = ['solana', 'base'];+const ENDPOINT_PATH = '/api/x402/token-intel';++function originOf(req) {+ const proto = (req.headers['x-forwarded-proto'] || 'https').split(',')[0].trim();+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';+ return `${proto}://${host}`;+}++function buildSnippets(endpointUrl) {+ const curl =+ `# 1) See the price (returns HTTP 402 + payment requirements)\n` ++ `curl -i "${endpointUrl}"\n\n` ++ `# 2) Pay & call in one step with the x402 CLI\n` ++ `npx x402-fetch "${endpointUrl}"`;++ const node =+ `import { wrapFetchWithPayment } from 'x402-fetch';\n` ++ `import { createWalletClient, http } from 'viem';\n` ++ `import { privateKeyToAccount } from 'viem/accounts';\n` ++ `import { base } from 'viem/chains';\n\n` ++ `const account = privateKeyToAccount(process.env.PRIVATE_KEY);\n` ++ `const wallet = createWalletClient({ account, chain: base, transport: http() });\n` ++ `const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n\n` ++ `const res = await fetchWithPay('${endpointUrl}');\n` ++ `console.log(await res.json()); // { symbol, price_usd, signal, headline, ... }`;++ const agent =+ `// Inside a three.ws agent — pay from the agent wallet, no keys in code:\n` ++ `const intel = await agent.x402.pay('${endpointUrl}');\n` ++ `agent.log(intel.headline, intel.signal, intel.confidence);`;++ return { curl, node, agent };+}++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const mint = (url.searchParams.get('mint') || '').trim();+ if (!mint) {+ return error(res, 400, 'missing_mint', 'Pass ?mint=<contract-address>.');+ }+ if (!isResolvableAddress(mint)) {+ return error(+ res,+ 422,+ 'invalid_mint',+ 'That does not look like a Solana mint or EVM contract address.',+ );+ }++ let market = null;+ try {+ market = await fetchTokenMarket(mint);+ } catch {+ /* upstream hiccup — fall through to the not-found envelope below */+ }++ if (!market) {+ // Designed "not found": the address is well-formed but no market exists+ // (unlaunched, dead liquidity, or wrong chain). The page tells the user so.+ res.setHeader('cache-control', 'no-store');+ return json(res, 404, {+ ok: false,+ mint,+ chain: chainOf(mint),+ error: 'token_not_found',+ error_description:+ 'No live market found for this address on DexScreener. The token may be unlaunched or have no liquidity yet.',+ });+ }++ const signal = market.change_24h != null ? buildTokenSignal(market) : null;++ const origin = originOf(req);+ const endpointUrl = `${origin}${ENDPOINT_PATH}?mint=${encodeURIComponent(market.mint)}`;++ const token = {+ mint: market.mint,+ symbol: market.symbol,+ name: market.name,+ image: market.image,+ chain: market.chain,+ dex: market.dex,+ pair_url: market.pair_url,+ price_usd: market.price_usd,+ change_24h: market.change_24h,+ market_cap_usd: market.market_cap_usd,+ liquidity_usd: market.liquidity_usd,+ volume_24h_usd: market.volume_24h_usd,+ signal: signal?.signal ?? null,+ headline: signal?.headline ?? null,+ rationale: signal?.rationale ?? null,+ confidence: signal?.confidence ?? null,+ };++ const service = {+ name: 'three.ws Token Oracle',+ endpoint: endpointUrl,+ method: 'GET',+ price_usd: PRICE_USD,+ price_atomics: PRICE_ATOMICS,+ asset: 'USDC',+ networks: NETWORKS,+ pay_to: {+ solana: env.X402_PAY_TO_SOLANA || null,+ base: env.X402_PAY_TO_BASE || null,+ },+ description: BAZAAR.description,+ output_schema: OUTPUT_SCHEMA,+ example_output: { ...BAZAAR.output.example, mint: market.mint, symbol: market.symbol },+ bazaar_discoverable: true,+ snippets: buildSnippets(endpointUrl),+ };++ res.setHeader('cache-control', 'public, max-age=20, stale-while-revalidate=60');+ return json(res, 200, { ok: true, token, service });+}++export default wrap(handler);diff --git a/api/x402/token-intel.js b/api/x402/token-intel.jsnew file mode 100644index 000000000..5047d5d16--- /dev/null+++ b/api/x402/token-intel.js@@ -0,0 +1,149 @@+// GET /api/x402/token-intel?mint=<contract-address>+//+// Generic token oracle — $0.01 USDC per call on Solana or Base. Pass ANY token+// contract address (Solana mint or EVM 0x) and get live market intel for it:+// price, 24 h change, market cap, liquidity, 24 h volume, plus a+// bullish/bearish/neutral signal with a two-sentence rationale.+//+// This is the paid service the CA → x402 resolver (/ca2x402) generates: paste a+// contract address there and it hands you a ready-to-call x402 endpoint pointed+// at that exact token. The mint is supplied at runtime by the caller — generic,+// coin-agnostic plumbing, never an endorsement of any specific non-$THREE coin.+//+// Data is live: DexScreener public API (no key required). No mock path. If live+// data is unavailable, the handler throws BEFORE settlement so the buyer is+// never charged for a missing or fabricated signal.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';+import { fetchTokenMarket, buildTokenSignal, isResolvableAddress } from '../_lib/token-market.js';++const ROUTE = '/api/x402/token-intel';++const DESCRIPTION =+ 'Generic token oracle — pay $0.01 USDC per call for live market intel on ANY ' ++ 'token by contract address: price, 24 h change, market cap, liquidity, 24 h ' ++ 'volume, and a bullish / bearish / neutral signal with a two-sentence ' ++ 'rationale. Pass ?mint=<contract-address> (Solana mint or EVM 0x). Powered ' ++ 'by live DexScreener data.';++export const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['mint'],+ properties: {+ mint: {+ type: 'string',+ description: 'Token contract address — Solana base58 mint or EVM 0x address.',+ minLength: 32,+ maxLength: 64,+ },+ },+};++export const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['mint', 'signal', 'headline', 'rationale', 'confidence', 'ts'],+ properties: {+ mint: { type: 'string' },+ symbol: { type: ['string', 'null'] },+ name: { type: ['string', 'null'] },+ chain: { type: ['string', 'null'] },+ price_usd: { type: ['number', 'null'] },+ change_24h: { type: ['number', 'null'] },+ market_cap_usd: { type: ['number', 'null'] },+ liquidity_usd: { type: ['number', 'null'] },+ volume_24h_usd: { type: ['number', 'null'] },+ signal: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },+ headline: { type: 'string' },+ rationale: { type: 'string' },+ confidence: { type: 'number', minimum: 0, maximum: 1 },+ ts: { type: 'string', format: 'date-time' },+ },+};++export const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['token market signal', 'memecoin due-diligence', 'agent trading intel'],+ input: {+ type: 'query',+ example: { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },+ schema: INPUT_SCHEMA,+ },+ output: {+ type: 'json',+ example: {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ symbol: 'THREE', name: 'three.ws', chain: 'solana',+ price_usd: 0.003685, change_24h: 12.4, market_cap_usd: 3685000,+ liquidity_usd: 412000, volume_24h_usd: 1268079,+ signal: 'bullish',+ headline: 'THREE climbs +12.40% — moderate upside',+ rationale: 'THREE is up +12.40% over 24 h, trading at $0.003685. Volume is healthy against liquidity; participation is real.',+ confidence: 0.86, ts: '2026-06-12T10:00:00Z',+ },+ },+ schema: buildBazaarSchema({+ method: 'GET',+ queryParamsSchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++export default paidEndpoint({+ route: ROUTE,+ method: 'GET',+ priceAtomics: priceFor('token-intel', '10000'), // $0.01 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Token Oracle',+ tags: ['token', 'market', 'signal', 'ca2x402', 'solana', 'base'],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ const mint = new URL(req.url, 'http://x').searchParams.get('mint')?.trim();+ if (!mint || !isResolvableAddress(mint)) {+ // Validation failure is thrown (not settled) so the buyer is not charged+ // for a malformed request — the wrapper maps this to a 422 before settle.+ throw Object.assign(new Error('mint must be a valid Solana or EVM contract address'), {+ status: 422,+ code: 'invalid_mint',+ });+ }++ let live = null;+ try { live = await fetchTokenMarket(mint); } catch { /* upstream hiccup */ }++ if (!live || live.change_24h == null) {+ throw Object.assign(new Error('live market data for this token is temporarily unavailable'), {+ status: 503,+ code: 'data_unavailable',+ });+ }++ const { signal, headline, rationale, confidence } = buildTokenSignal(live);+ return {+ mint: live.mint,+ symbol: live.symbol,+ name: live.name,+ chain: live.chain,+ price_usd: live.price_usd,+ change_24h: live.change_24h,+ market_cap_usd: live.market_cap_usd,+ liquidity_usd: live.liquidity_usd,+ volume_24h_usd: live.volume_24h_usd,+ signal,+ headline,+ rationale,+ confidence,+ ts: new Date().toISOString(),+ };+ },+});diff --git a/pages/ca2x402.html b/pages/ca2x402.htmlnew file mode 100644index 000000000..b29f0b2a2--- /dev/null+++ b/pages/ca2x402.html@@ -0,0 +1,51 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>CA → x402 · three.ws</title>+ <meta+ name="description"+ content="Paste any token contract address and get a live, payable x402 endpoint for its market intel — price, momentum, and a bullish/bearish signal — instantly. Discoverable in the x402 bazaar, callable by any agent for $0.01 USDC."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/ca2x402" />+ <meta property="og:title" content="CA → x402 · three.ws" />+ <meta+ property="og:description"+ content="Turn any contract address into a payable x402 service. Paste a CA → get a live endpoint other agents can pay to query, with copy-paste call snippets and the live 402 challenge."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="CA → x402 · three.ws" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/ca2x402.css" />+ <link rel="stylesheet" href="/footer.css" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/ca2x402" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cx-shell" id="cx-root" aria-labelledby="cx-title">+ <!-- hydrated by /src/ca2x402.js -->+ </main>++ <script type="module" src="/src/ca2x402.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/prompts/wallet-innovation/03-anomaly-guard.md b/prompts/wallet-innovation/03-anomaly-guard.mddeleted file mode 100644index 9282bed84..000000000--- a/prompts/wallet-innovation/03-anomaly-guard.md+++ /dev/null@@ -1,92 +0,0 @@-# 03 — The Self-Defending Wallet: Real-Time Behavioral Anomaly Guard--> Read `00-README.md` first. Obey every rule there. Delete this file only when-> fully done + self-improved.--## The problem worth solving--Static caps (`daily_usd`, `per_tx_usd`) and a manual `frozen` switch protect the-*known* failure modes. They do nothing about the *unknown* one: an agent that-gets prompt-injected, a strategy that goes haywire at 3am, a leaked session that-drains within the daily cap, a sudden burst of payments to a never-seen-counterparty. By the time a human notices, the money is gone.--## The game-changing feature--Give every wallet an **immune system**. The platform continuously learns each-agent's *normal* spending behavior and scores every outbound action in real time;-when something looks anomalous, it **auto-freezes the wallet and pings the owner-with one-tap approve/deny** — before the questionable spend settles, not after.-"Your money defends itself" is a story no agent-wallet competitor can tell.--## What to build (wire all of it, for real)--1. **Behavioral baseline per agent.** Compute, from real `agent_custody_events`- + on-chain history, a per-agent profile: typical spend velocity (count &- $/hour), typical & p95 transaction size, set of known counterparties /- destinations, active hours, asset mix, and token-age distribution for trades.- Recompute incrementally as new events land. Real data only — if an agent has- little history, say so and widen tolerances rather than fake a baseline.-2. **Real-time anomaly score.** On every outbound action (called from- `enforceSpendLimit` / `reserveSpendUsd`, so it covers trade/snipe/x402/withdraw),- score deviation across the dimensions above into an interpretable signal:- each contributing factor named ("3× your largest-ever trade", "first payment- to this address", "20 spends in 2 minutes — 10× your normal velocity",- "first activity outside your agent's usual hours"). Deterministic, fast, no- blocking network call in the hot path.-3. **Graduated response, owner-tunable.** Sensitivity presets (Relaxed / Balanced- / Strict). Below threshold → allow + record the score. Above → **auto-freeze**- (reuse `meta.spend_limits.frozen`; coordinate with the freeze in- `agent-trade-guards.js`) and hold/deny the triggering action, then notify.- Never fail open: if scoring errors, default to the safe side per sensitivity.-4. **One-tap owner adjudication.** The owner gets a real notification (wire web- push / the existing notify channel — `api/_lib/notify.js` — and surface it in- the hub) describing *exactly* why, with **Approve** (unfreeze + allowlist this- pattern so it won't re-trip) and **Deny/Keep frozen** (and optionally one-tap- "sweep funds to safety" → withdraw). Approving must teach the baseline so the- wallet gets smarter, not naggier.-5. **Anomaly timeline.** An owner-facing feed of scored events (allowed +- flagged), each explained in plain language, with the action taken — so the- guard is transparent, never a black box.--## Architecture guidance--- Baseline + scoring in a new module (e.g. `api/_lib/wallet-anomaly.js`); pure,- unit-testable scoring functions fed live numbers by callers. Persist baselines- in `meta` or a new table via migration; never block signing on recompute.-- Hook the score check into the shared guards as an additional predicate- alongside the freeze and caps — additive, minimal, well-commented (shared hot- file; coordinate per `00-README.md`).-- Notifications must be real and timely. If push isn't configured for a user,- degrade to in-app + email/Telegram via whatever the platform already uses —- never silently swallow an alert about someone's money.--## Security & correctness--- The guard must not become an oracle that leaks behavior to attackers via error- text. Owner-only detail; generic refusal to the agent path.-- Avoid false-positive fatigue: every approve should measurably reduce future- false trips for that pattern. Avoid false negatives on the catastrophic cases- (velocity spikes, brand-new high-value destinations) by weighting them hard.-- Idempotent freezes; no thrash (don't freeze→unfreeze→refreeze in a loop).--## Testing--- Unit tests for each anomaly dimension and the combined score; baseline math;- the "low history → wide tolerance" path; totality / fail-safe on bad input.-- A simulated attack scenario (sudden drain within the daily cap to a new- address) that asserts the guard freezes + records + notifies.--## Deliverables--Baseline engine, real-time scorer wired into the shared guards, graduated-auto-freeze + tunable sensitivity, real owner notifications with one-tap-adjudication that trains the baseline, anomaly timeline UI, tests, changelog-(feature/security).--## Before you finish--Then improve it: make the explanation human and specific (not "score 0.82" but-"10× your usual pace, to an address you've never used"), and wire the "sweep to-safety" shortcut so a flagged owner can act in one tap. Verify the attack-scenario in the browser, review your diff, then **delete this prompt file.**diff --git a/src/ca2x402.css b/src/ca2x402.cssnew file mode 100644index 000000000..b2b6d2b88--- /dev/null+++ b/src/ca2x402.css@@ -0,0 +1,348 @@+/* CA → x402 — turn any contract address into a payable x402 service.+ * Uses the platform token system (public/tokens.css). Brand blue marks the+ * x402/service surfaces; semantic green/red only ever mark price movement. */++.cx-shell {+ max-width: 980px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg) var(--space-2xl);+ color: var(--ink);+ font-family: var(--font-body);+}++/* ── hero ─────────────────────────────────────────────────────────────── */+.cx-hero { text-align: center; margin-bottom: var(--space-xl); }+.cx-badge {+ display: inline-block;+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--brand-blue-light, var(--accent));+ background: var(--brand-blue-dim, var(--accent-soft));+ border: 1px solid var(--brand-blue-stroke, var(--stroke));+ border-radius: var(--radius-pill);+ padding: 4px 12px;+ margin-bottom: var(--space-md);+}+.cx-hero h1 {+ font-family: var(--font-display);+ font-weight: 800;+ font-size: clamp(2.4rem, 7vw, 4rem);+ line-height: 1.02;+ margin: 0 0 var(--space-md);+ letter-spacing: -0.02em;+}+.cx-arrow { color: var(--accent); font-weight: 400; }+.cx-sub {+ font-size: var(--text-lg);+ line-height: 1.55;+ color: var(--ink-dim);+ max-width: 60ch;+ margin: 0 auto var(--space-xl);+}+.cx-sub strong { color: var(--ink-bright); font-weight: 600; }++.cx-form {+ display: flex;+ gap: var(--space-sm);+ max-width: 680px;+ margin: 0 auto;+}+.cx-input {+ flex: 1;+ min-width: 0;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ color: var(--ink-bright);+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: 0 var(--space-md);+ height: 52px;+ transition: border-color 0.15s ease, box-shadow 0.15s ease;+}+.cx-input::placeholder { color: var(--ink-faint); font-family: var(--font-body); }+.cx-input:focus {+ outline: none;+ border-color: var(--accent);+ box-shadow: 0 0 0 3px var(--accent-soft);+}+.cx-go {+ flex: none;+ height: 52px;+ padding: 0 var(--space-lg);+ font-family: var(--font-body);+ font-weight: 600;+ font-size: var(--text-sm);+ color: var(--accent-ink, #fff);+ background: var(--accent);+ border: none;+ border-radius: var(--radius-md);+ cursor: pointer;+ transition: transform 0.12s ease, opacity 0.15s ease, filter 0.15s ease;+ white-space: nowrap;+}+.cx-go:hover:not(:disabled) { filter: brightness(1.08); transform: translateY(-1px); }+.cx-go:active:not(:disabled) { transform: translateY(0); }+.cx-go:disabled { opacity: 0.55; cursor: progress; }++.cx-examples {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-xs);+ margin-top: var(--space-md);+ font-size: var(--text-2xs);+ color: var(--ink-faint);+}+.cx-chip {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ color: var(--ink-bright);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-pill);+ padding: 3px 12px;+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;+}+.cx-chip:hover { border-color: var(--accent); background: var(--accent-soft); }+.cx-chip-hint { font-family: var(--font-mono); }++/* ── results / cards ──────────────────────────────────────────────────── */+.cx-results { margin-top: var(--space-xl); display: flex; flex-direction: column; gap: var(--space-lg); }+.cx-card {+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ padding: var(--space-lg);+ animation: cx-in 0.3s ease both;+}+@keyframes cx-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }++/* ── empty state ──────────────────────────────────────────────────────── */+.cx-empty { padding: var(--space-md) 0; }+.cx-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-md); }+.cx-step {+ display: flex;+ gap: var(--space-sm);+ align-items: flex-start;+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-md);+}+.cx-step-n {+ flex: none;+ width: 26px; height: 26px;+ display: grid; place-items: center;+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ color: var(--accent);+ background: var(--accent-soft);+ border-radius: var(--radius-pill);+}+.cx-step-h { font-weight: 600; font-size: var(--text-sm); color: var(--ink-bright); margin-bottom: 2px; }+.cx-step-b { font-size: var(--text-2xs); color: var(--ink-dim); line-height: 1.45; }++/* ── token card ───────────────────────────────────────────────────────── */+.cx-token-head { display: flex; align-items: center; gap: var(--space-md); margin-bottom: var(--space-lg); }+.cx-av {+ flex: none; width: 52px; height: 52px;+ border-radius: var(--radius-pill);+ object-fit: cover;+ border: 1px solid var(--stroke);+ background: var(--surface-2);+}+.cx-av-ph {+ display: grid; place-items: center;+ font-family: var(--font-display); font-weight: 700; font-size: var(--text-md);+ color: var(--ink-dim); text-transform: uppercase;+}+.cx-token-id { flex: 1; min-width: 0; }+.cx-token-sym { display: flex; align-items: center; gap: var(--space-xs); font-family: var(--font-display); font-weight: 700; font-size: var(--text-xl); color: var(--ink-bright); }+.cx-chain {+ font-family: var(--font-mono); font-size: var(--text-2xs);+ text-transform: capitalize; color: var(--ink-dim);+ background: var(--surface-2); border: 1px solid var(--stroke);+ border-radius: var(--radius-pill); padding: 1px 8px;+}+.cx-token-name { font-size: var(--text-sm); color: var(--ink-dim); margin: 2px 0 6px; }+.cx-mint {+ font-family: var(--font-mono); font-size: var(--text-2xs);+ color: var(--ink-faint); background: none; border: none; padding: 0;+ cursor: pointer; display: inline-flex; align-items: center; gap: 5px;+ transition: color 0.15s ease;+}+.cx-mint:hover { color: var(--accent); }+.cx-mint-ic { opacity: 0.7; }++.cx-stats {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: 1px;+ background: var(--stroke);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ overflow: hidden;+}+.cx-stat { background: var(--surface-1); padding: var(--space-sm) var(--space-md); }+.cx-stat-k { font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 3px; }+.cx-stat-v { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-bright); font-weight: 600; }+.cx-pos { color: var(--success); }+.cx-neg { color: var(--danger); }++.cx-pill {+ font-family: var(--font-mono); font-size: var(--text-2xs);+ text-transform: uppercase; letter-spacing: 0.05em;+ border-radius: var(--radius-pill); padding: 3px 11px; font-weight: 600;+}+.cx-bull { color: var(--success); background: rgba(74, 222, 128, 0.12); }+.cx-bear { color: var(--danger); background: rgba(248, 113, 113, 0.12); }+.cx-neu { color: var(--ink-dim); background: var(--surface-2); }++.cx-signal {+ margin-top: var(--space-lg);+ padding: var(--space-md);+ background: var(--surface-2);+ border-radius: var(--radius-md);+ border-left: 2px solid var(--accent);+}+.cx-signal-h { font-weight: 600; font-size: var(--text-sm); color: var(--ink-bright); margin-bottom: 4px; }+.cx-signal-r { font-size: var(--text-2xs); color: var(--ink-dim); line-height: 1.5; }+.cx-dexlink { display: inline-block; margin-top: var(--space-md); font-size: var(--text-2xs); color: var(--accent); text-decoration: none; }+.cx-dexlink:hover { text-decoration: underline; }++/* ── service card ─────────────────────────────────────────────────────── */+.cx-service { border-color: var(--brand-blue-stroke, var(--stroke)); }+.cx-service-label { font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; }+.cx-endpoint {+ display: flex; align-items: center; gap: var(--space-xs);+ width: 100%; text-align: left;+ font-family: var(--font-mono); font-size: var(--text-2xs);+ background: var(--surface-2); border: 1px solid var(--stroke);+ border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md);+ cursor: pointer; color: var(--ink-bright);+ transition: border-color 0.15s ease;+}+.cx-endpoint:hover { border-color: var(--accent); }+.cx-method { color: var(--accent); font-weight: 700; flex: none; }+.cx-url { flex: 1; min-width: 0; overflow-wrap: anywhere; }++.cx-service-meta {+ display: flex; flex-wrap: wrap; gap: var(--space-lg);+ margin: var(--space-md) 0 var(--space-lg);+ padding-bottom: var(--space-md);+ border-bottom: 1px solid var(--stroke);+}+.cx-meta { display: flex; flex-direction: column; gap: 3px; }+.cx-meta-k { font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; }+.cx-meta-v { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-bright); font-weight: 600; }+.cx-meta-v em { font-style: normal; color: var(--ink-dim); font-weight: 400; font-size: var(--text-2xs); }+.cx-nets { display: flex; gap: 5px; }+.cx-net { font-family: var(--font-mono); font-size: var(--text-2xs); text-transform: capitalize; border-radius: var(--radius-pill); padding: 2px 9px; border: 1px solid var(--stroke); color: var(--ink-dim); }+.cx-net-solana { color: #9945ff; border-color: rgba(153, 69, 255, 0.4); }+.cx-net-base { color: #0052ff; border-color: rgba(0, 82, 255, 0.4); }+.cx-ok { color: var(--success); }++/* ── snippets ─────────────────────────────────────────────────────────── */+.cx-tabs { display: flex; gap: 4px; margin-bottom: var(--space-sm); }+.cx-tab {+ font-family: var(--font-body); font-size: var(--text-2xs); font-weight: 600;+ color: var(--ink-dim); background: none;+ border: 1px solid transparent; border-radius: var(--radius-md);+ padding: 5px 12px; cursor: pointer; transition: all 0.15s ease;+}+.cx-tab:hover { color: var(--ink-bright); }+.cx-tab-on { color: var(--ink-bright); background: var(--surface-2); border-color: var(--stroke); }+.cx-code-wrap { position: relative; }+.cx-code {+ font-family: var(--font-mono); font-size: var(--text-2xs); line-height: 1.6;+ color: var(--ink-bright); background: var(--surface-2);+ border: 1px solid var(--stroke); border-radius: var(--radius-md);+ padding: var(--space-md); margin: 0; overflow-x: auto; white-space: pre;+}+.cx-code-sm { margin-top: var(--space-sm); max-height: 360px; overflow: auto; }+.cx-copy {+ position: absolute; top: 8px; right: 8px;+ font-family: var(--font-body); font-size: var(--text-2xs); font-weight: 600;+ color: var(--ink-dim); background: var(--surface-1);+ border: 1px solid var(--stroke); border-radius: var(--radius-md);+ padding: 3px 10px; cursor: pointer; transition: all 0.15s ease;+}+.cx-copy:hover { color: var(--ink-bright); border-color: var(--accent); }+.cx-copied { color: var(--success) !important; border-color: var(--success) !important; }++/* ── live 402 challenge ───────────────────────────────────────────────── */+.cx-challenge { margin-top: var(--space-lg); padding-top: var(--space-md); border-top: 1px solid var(--stroke); }+.cx-challenge-btn {+ font-family: var(--font-body); font-size: var(--text-2xs); font-weight: 600;+ color: var(--accent); background: var(--accent-soft);+ border: 1px solid var(--brand-blue-stroke, var(--stroke)); border-radius: var(--radius-md);+ padding: 7px 14px; cursor: pointer; transition: all 0.15s ease;+}+.cx-challenge-btn:hover:not(:disabled) { filter: brightness(1.1); }+.cx-challenge-btn:disabled { opacity: 0.6; cursor: progress; }+.cx-challenge-hint { display: block; margin-top: 8px; font-size: var(--text-2xs); color: var(--ink-faint); line-height: 1.5; }+.cx-challenge-out { margin-top: var(--space-md); animation: cx-in 0.25s ease both; }+.cx-challenge-status { font-size: var(--text-2xs); color: var(--ink-dim); margin-bottom: 6px; }+.cx-challenge-status strong { color: var(--accent); font-family: var(--font-mono); }+.cx-challenge-err { color: var(--danger); font-size: var(--text-2xs); }++/* ── error / skeleton ─────────────────────────────────────────────────── */+.cx-error { text-align: center; padding: var(--space-2xl) var(--space-lg); }+.cx-error-ic {+ width: 46px; height: 46px; margin: 0 auto var(--space-md);+ display: grid; place-items: center;+ font-family: var(--font-mono); font-size: var(--text-xl); font-weight: 700;+ color: var(--ink-dim); background: var(--surface-2);+ border: 1px solid var(--stroke); border-radius: var(--radius-pill);+}+.cx-error h2 { font-size: var(--text-lg); margin: 0 0 var(--space-xs); color: var(--ink-bright); }+.cx-error p { font-size: var(--text-sm); color: var(--ink-dim); max-width: 44ch; margin: 0 auto var(--space-lg); line-height: 1.5; }+.cx-retry {+ font-family: var(--font-body); font-size: var(--text-sm); font-weight: 600;+ color: var(--ink-bright); background: var(--surface-2);+ border: 1px solid var(--stroke); border-radius: var(--radius-md);+ padding: 9px 18px; cursor: pointer; transition: all 0.15s ease;+}+.cx-retry:hover { border-color: var(--accent); }++.cx-skeleton .cx-sk { background: var(--surface-2); border-radius: var(--radius-md); position: relative; overflow: hidden; }+.cx-skeleton .cx-sk::after {+ content: ''; position: absolute; inset: 0;+ background: linear-gradient(90deg, transparent, var(--surface-3, rgba(255,255,255,0.06)), transparent);+ animation: cx-shimmer 1.3s infinite;+}+@keyframes cx-shimmer { 100% { transform: translateX(100%); } }+.cx-sk-row { display: flex; gap: var(--space-md); align-items: center; margin-bottom: var(--space-lg); }+.cx-sk-av { width: 52px; height: 52px; border-radius: var(--radius-pill); flex: none; }+.cx-sk-lines { flex: 1; display: flex; flex-direction: column; gap: 8px; }+.cx-sk-l1 { height: 18px; width: 40%; }+.cx-sk-l2 { height: 12px; width: 60%; }+.cx-sk-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm); }+.cx-sk-cell { height: 52px; }++/* ── focus visibility (a11y) ──────────────────────────────────────────── */+.cx-go:focus-visible, .cx-chip:focus-visible, .cx-tab:focus-visible,+.cx-copy:focus-visible, .cx-retry:focus-visible, .cx-challenge-btn:focus-visible,+.cx-mint:focus-visible, .cx-endpoint:focus-visible, .cx-dexlink:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, var(--accent));+ outline-offset: var(--focus-ring-offset, 2px);+}++/* ── responsive ───────────────────────────────────────────────────────── */+@media (max-width: 720px) {+ .cx-steps { grid-template-columns: 1fr; }+ .cx-stats { grid-template-columns: repeat(2, 1fr); }+ .cx-sk-grid { grid-template-columns: repeat(2, 1fr); }+ .cx-form { flex-direction: column; }+ .cx-go { width: 100%; }+}++@media (prefers-reduced-motion: reduce) {+ .cx-card, .cx-challenge-out { animation: none; }+ .cx-skeleton .cx-sk::after { animation: none; }+ .cx-go:hover:not(:disabled) { transform: none; }+}diff --git a/src/ca2x402.js b/src/ca2x402.jsnew file mode 100644index 000000000..85d187533--- /dev/null+++ b/src/ca2x402.js@@ -0,0 +1,354 @@+// CA → x402 — frontend surface.+//+// Paste any token contract address; get a live, payable x402 endpoint for that+// token's market intel. The page is a thin shell over two real endpoints:+// • GET /api/ca2x402/resolve — free: token identity + the generated service+// • GET /api/x402/token-intel — the paid x402 service the snippets call+//+// Nothing here is sampled. When a CA has no market, we render a designed+// "not found" state; when the resolver is down we say so and offer a retry.++import { apiFetch } from './api.js';++const root = document.getElementById('cx-root');++// The platform coin is the canonical example — $THREE is the only coin three.ws+// promotes (CA pinned in CLAUDE.md). The tool itself accepts any address.+const EXAMPLE_CA = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const state = {+ ca: '',+ loading: false,+ result: null, // { token, service }+ error: null, // { code, message }+ challenge: null, // raw 402 body from the live endpoint+ challengeState: 'idle', // idle | loading | done | error+ tab: 'curl',+};++// ── utilities ─────────────────────────────────────────────────────────────────+function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function shortCa(m) { return m ? `${m.slice(0, 4)}…${m.slice(-4)}` : ''; }+function fmtUsd(n) {+ if (n == null || !Number.isFinite(Number(n))) return '—';+ const v = Number(n);+ if (v === 0) return '$0';+ if (v < 0.0001) return `$${v.toExponential(2)}`;+ if (v < 1) return `$${v.toPrecision(3)}`;+ return `$${v.toLocaleString('en-US', { maximumFractionDigits: 2 })}`;+}+function fmtCompact(n) {+ if (n == null || !Number.isFinite(Number(n))) return '—';+ return `$${Number(n).toLocaleString('en-US', { notation: 'compact', maximumFractionDigits: 2 })}`;+}+function fmtPct(n) {+ if (n == null || !Number.isFinite(Number(n))) return '—';+ const v = Number(n);+ return `${v >= 0 ? '+' : ''}${v.toFixed(2)}%`;+}+function pctClass(n) { const v = Number(n); return v > 0 ? 'cx-pos' : v < 0 ? 'cx-neg' : ''; }+function looksLikeCa(s) {+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s) || /^0x[a-fA-F0-9]{40}$/.test(s);+}++async function copy(text, btn) {+ try {+ await navigator.clipboard.writeText(text);+ if (btn) {+ const prev = btn.textContent;+ btn.textContent = 'Copied';+ btn.classList.add('cx-copied');+ setTimeout(() => { btn.textContent = prev; btn.classList.remove('cx-copied'); }, 1400);+ }+ } catch { /* clipboard blocked — no-op, the value is still visible */ }+}++// ── data ──────────────────────────────────────────────────────────────────────+async function resolve(ca) {+ state.loading = true;+ state.error = null;+ state.result = null;+ state.challenge = null;+ state.challengeState = 'idle';+ render();+ try {+ const r = await apiFetch(`/api/ca2x402/resolve?mint=${encodeURIComponent(ca)}`);+ const body = await r.json().catch(() => null);+ if (!r.ok || !body?.ok) {+ state.error = {+ code: body?.error || 'error',+ message: body?.error_description || 'Could not resolve that address.',+ };+ } else {+ state.result = body;+ }+ } catch {+ state.error = { code: 'network', message: 'Network error reaching the resolver. Check your connection and retry.' };+ } finally {+ state.loading = false;+ render();+ }+}++async function fetchChallenge() {+ const ep = state.result?.service?.endpoint;+ if (!ep) return;+ state.challengeState = 'loading';+ render();+ try {+ // Hit the real paid endpoint with no payment header — it answers 402 with+ // the exact payment requirements. This is the live proof, not a mock.+ const r = await fetch(ep, { headers: { Accept: 'application/json' } });+ const body = await r.json().catch(() => null);+ state.challenge = { status: r.status, body };+ state.challengeState = 'done';+ } catch {+ state.challengeState = 'error';+ }+ render();+}++// ── views ───────────────────────────────────────────────────────────────────+function hero() {+ return `+ <section class="cx-hero">+ <div class="cx-badge">x402 · agent-payable</div>+ <h1 id="cx-title">CA <span class="cx-arrow">→</span> x402</h1>+ <p class="cx-sub">+ Paste any token contract address. Get a live, payable <strong>x402 endpoint</strong>+ for its market intel — price, momentum, and a bullish/bearish signal — that any agent+ can call for <strong>$0.01 USDC</strong>. Discoverable in the bazaar. No keys, no backend.+ </p>+ <form class="cx-form" id="cx-form" autocomplete="off">+ <input+ id="cx-input"+ class="cx-input"+ type="text"+ inputmode="text"+ spellcheck="false"+ placeholder="Paste a token contract address (Solana mint or 0x…)"+ aria-label="Token contract address"+ value="${esc(state.ca)}"+ />+ <button class="cx-go" type="submit" ${state.loading ? 'disabled' : ''}>+ ${state.loading ? 'Resolving…' : 'Resolve →'}+ </button>+ </form>+ <div class="cx-examples">+ <span>Try it:</span>+ <button class="cx-chip" data-ca="${EXAMPLE_CA}" type="button">$THREE</button>+ <span class="cx-chip-hint">${shortCa(EXAMPLE_CA)}</span>+ </div>+ </section>`;+}++function emptyState() {+ const steps = [+ ['Paste', 'Any Solana mint or EVM contract address.'],+ ['Resolve', 'We pull its live market from DexScreener and brand a signal to its ticker.'],+ ['Ship', 'You get a payable x402 endpoint + copy-paste snippets, live in the bazaar.'],+ ];+ return `+ <section class="cx-empty">+ <div class="cx-steps">+ ${steps.map(([h, b], i) => `+ <div class="cx-step">+ <div class="cx-step-n">${i + 1}</div>+ <div><div class="cx-step-h">${esc(h)}</div><div class="cx-step-b">${esc(b)}</div></div>+ </div>`).join('')}+ </div>+ </section>`;+}++function loadingState() {+ return `+ <section class="cx-card cx-skeleton" aria-busy="true" aria-label="Resolving">+ <div class="cx-sk-row"><div class="cx-sk cx-sk-av"></div><div class="cx-sk-lines"><div class="cx-sk cx-sk-l1"></div><div class="cx-sk cx-sk-l2"></div></div></div>+ <div class="cx-sk-grid">${Array.from({ length: 4 }).map(() => '<div class="cx-sk cx-sk-cell"></div>').join('')}</div>+ </section>`;+}++function errorState() {+ const e = state.error;+ const isNotFound = e.code === 'token_not_found';+ return `+ <section class="cx-card cx-error">+ <div class="cx-error-ic" aria-hidden="true">${isNotFound ? '∅' : '!'}</div>+ <h2>${isNotFound ? 'No market found for that address' : 'Could not resolve'}</h2>+ <p>${esc(e.message)}</p>+ <button class="cx-retry" id="cx-retry" type="button">Try another address</button>+ </section>`;+}++function signalPill(sig) {+ if (!sig) return '';+ const map = { bullish: 'cx-bull', bearish: 'cx-bear', neutral: 'cx-neu' };+ return `<span class="cx-pill ${map[sig] || 'cx-neu'}">${esc(sig)}</span>`;+}++function tokenCard(t) {+ const chain = t.chain ? `<span class="cx-chain">${esc(t.chain)}</span>` : '';+ const avatar = t.image+ ? `<img class="cx-av" src="${esc(t.image)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'cx-av cx-av-ph',textContent:'${esc((t.symbol || '?').slice(0, 2))}'}))" />`+ : `<div class="cx-av cx-av-ph">${esc((t.symbol || '?').slice(0, 2))}</div>`;+ const stats = [+ ['Price', fmtUsd(t.price_usd)],+ ['24h', `<span class="${pctClass(t.change_24h)}">${fmtPct(t.change_24h)}</span>`],+ ['Market cap', fmtCompact(t.market_cap_usd)],+ ['Liquidity', fmtCompact(t.liquidity_usd)],+ ['24h volume', fmtCompact(t.volume_24h_usd)],+ ];+ return `+ <section class="cx-card cx-token">+ <div class="cx-token-head">+ ${avatar}+ <div class="cx-token-id">+ <div class="cx-token-sym">${esc(t.symbol || 'Unknown')} ${chain}</div>+ <div class="cx-token-name">${esc(t.name || '')}</div>+ <button class="cx-mint" type="button" data-copy="${esc(t.mint)}" title="Copy contract address">+ ${shortCa(t.mint)} <span class="cx-mint-ic">⧉</span>+ </button>+ </div>+ ${t.signal ? `<div class="cx-token-sig">${signalPill(t.signal)}</div>` : ''}+ </div>+ <div class="cx-stats">+ ${stats.map(([k, v]) => `<div class="cx-stat"><div class="cx-stat-k">${k}</div><div class="cx-stat-v">${v}</div></div>`).join('')}+ </div>+ ${t.headline ? `<div class="cx-signal"><div class="cx-signal-h">${esc(t.headline)}</div><div class="cx-signal-r">${esc(t.rationale || '')}</div></div>` : ''}+ ${t.pair_url ? `<a class="cx-dexlink" href="${esc(t.pair_url)}" target="_blank" rel="noopener">View pair on ${esc(t.dex || 'DEX')} ↗</a>` : ''}+ </section>`;+}++function serviceCard(s) {+ const nets = (s.networks || []).map((n) => `<span class="cx-net cx-net-${esc(n)}">${esc(n)}</span>`).join('');+ const tabs = [['curl', 'cURL'], ['node', 'Node'], ['agent', 'Agent']];+ const snippet = s.snippets?.[state.tab] || '';+ return `+ <section class="cx-card cx-service">+ <div class="cx-service-top">+ <div>+ <div class="cx-service-label">Your x402 endpoint</div>+ <button class="cx-endpoint" type="button" data-copy="${esc(s.endpoint)}" title="Copy endpoint URL">+ <span class="cx-method">GET</span>+ <span class="cx-url">${esc(s.endpoint)}</span>+ <span class="cx-mint-ic">⧉</span>+ </button>+ </div>+ </div>+ <div class="cx-service-meta">+ <div class="cx-meta"><span class="cx-meta-k">Price</span><span class="cx-meta-v">${fmtUsd(s.price_usd)} <em>${esc(s.asset || 'USDC')}</em></span></div>+ <div class="cx-meta"><span class="cx-meta-k">Networks</span><span class="cx-meta-v cx-nets">${nets}</span></div>+ <div class="cx-meta"><span class="cx-meta-k">Discovery</span><span class="cx-meta-v">${s.bazaar_discoverable ? '<span class="cx-ok">● in bazaar</span>' : '—'}</span></div>+ </div>++ <div class="cx-snippets">+ <div class="cx-tabs" role="tablist" aria-label="Call snippets">+ ${tabs.map(([id, label]) => `<button class="cx-tab ${state.tab === id ? 'cx-tab-on' : ''}" role="tab" aria-selected="${state.tab === id}" data-tab="${id}" type="button">${label}</button>`).join('')}+ </div>+ <div class="cx-code-wrap">+ <button class="cx-copy" type="button" data-copy="${esc(snippet)}">Copy</button>+ <pre class="cx-code"><code>${esc(snippet)}</code></pre>+ </div>+ </div>++ <div class="cx-challenge">+ <button class="cx-challenge-btn" id="cx-challenge-btn" type="button" ${state.challengeState === 'loading' ? 'disabled' : ''}>+ ${state.challengeState === 'loading' ? 'Fetching…' : 'Fetch the live 402 challenge'}+ </button>+ <span class="cx-challenge-hint">Calls the real endpoint with no payment — see the exact requirements an agent would settle.</span>+ ${renderChallenge()}+ </div>+ </section>`;+}++function renderChallenge() {+ if (state.challengeState === 'idle') return '';+ if (state.challengeState === 'error') {+ return `<div class="cx-challenge-out cx-challenge-err">Endpoint unreachable. Retry in a moment.</div>`;+ }+ if (state.challengeState === 'done' && state.challenge) {+ const { status, body } = state.challenge;+ const pretty = JSON.stringify(body, null, 2);+ return `+ <div class="cx-challenge-out">+ <div class="cx-challenge-status">HTTP <strong>${status}</strong> ${status === 402 ? 'Payment Required — exactly what a buyer settles against' : ''}</div>+ <pre class="cx-code cx-code-sm"><code>${esc(pretty)}</code></pre>+ </div>`;+ }+ return '';+}++function render() {+ let body;+ if (state.loading) body = loadingState();+ else if (state.error) body = errorState();+ else if (state.result) body = tokenCard(state.result.token) + serviceCard(state.result.service);+ else body = emptyState();++ root.innerHTML = hero() + `<div class="cx-results">${body}</div>`;+ wire();+}++// ── events ──────────────────────────────────────────────────────────────────+function wire() {+ const form = document.getElementById('cx-form');+ const input = document.getElementById('cx-input');+ form?.addEventListener('submit', (e) => {+ e.preventDefault();+ const ca = (input.value || '').trim();+ if (!ca) return;+ if (!looksLikeCa(ca)) {+ state.error = { code: 'invalid_mint', message: 'That does not look like a Solana mint or 0x contract address.' };+ state.result = null;+ render();+ return;+ }+ state.ca = ca;+ syncUrl(ca);+ resolve(ca);+ });++ root.querySelectorAll('.cx-chip').forEach((c) => c.addEventListener('click', () => {+ const ca = c.dataset.ca;+ state.ca = ca;+ if (input) input.value = ca;+ syncUrl(ca);+ resolve(ca);+ }));++ root.querySelectorAll('[data-copy]').forEach((b) => b.addEventListener('click', () => copy(b.dataset.copy, b.classList.contains('cx-copy') ? b : null)));++ root.querySelectorAll('.cx-tab').forEach((t) => t.addEventListener('click', () => {+ state.tab = t.dataset.tab;+ render();+ }));++ document.getElementById('cx-retry')?.addEventListener('click', () => {+ state.error = null;+ state.ca = '';+ syncUrl('');+ render();+ document.getElementById('cx-input')?.focus();+ });++ document.getElementById('cx-challenge-btn')?.addEventListener('click', fetchChallenge);+}++function syncUrl(ca) {+ const u = new URL(window.location.href);+ if (ca) u.searchParams.set('ca', ca);+ else u.searchParams.delete('ca');+ window.history.replaceState(null, '', u);+}++// ── boot ──────────────────────────────────────────────────────────────────────+const initial = new URL(window.location.href).searchParams.get('ca');+if (initial && looksLikeCa(initial.trim())) {+ state.ca = initial.trim();+ render();+ resolve(state.ca);+} else {+ render();+}diff --git a/vercel.json b/vercel.jsonindex 735d18b24..e6aeac3e9 100644--- a/vercel.json+++ b/vercel.json@@ -500,6 +500,10 @@"src": "/agi/?","dest": "/agi.html"},+ {+ "src": "/ca2x402/?",+ "dest": "/ca2x402.html"+ },{"src": "/api/billing/receipts","dest": "/api/billing/receipts"diff --git a/vite.config.js b/vite.config.jsindex c5a740a58..b2a27e0b3 100644--- a/vite.config.js+++ b/vite.config.js@@ -386,6 +386,7 @@ const appConfig = {radar: resolve(__dirname, 'pages/radar.html'),oracle: resolve(__dirname, 'pages/oracle.html'),arm: resolve(__dirname, 'pages/arm.html'),+ ca2x402: resolve(__dirname, 'pages/ca2x402.html'),activity: resolve(__dirname, 'pages/activity.html'),'coin-intel': resolve(__dirname, 'pages/coin-intel.html'),trending: resolve(__dirname, 'pages/trending.html'),@@ -839,6 +840,8 @@ support: resolve(__dirname, 'pages/support.html'),'/oracle/arm/': resolve(root, 'pages/arm.html'),'/arm': resolve(root, 'pages/arm.html'),'/arm/': resolve(root, 'pages/arm.html'),+ '/ca2x402': resolve(root, 'pages/ca2x402.html'),+ '/ca2x402/': resolve(root, 'pages/ca2x402.html'),'/activity': resolve(root, 'pages/activity.html'),'/activity/': resolve(root, 'pages/activity.html'),'/trending': resolve(root, 'pages/trending.html'),