Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add membership snapshot endpoint to club cover API
nirholas275fbb723cac
diff --git a/api/_lib/club/cover-revenue.js b/api/_lib/club/cover-revenue.jsnew file mode 100644index 000000000..013700ef3--- /dev/null+++ b/api/_lib/club/cover-revenue.js@@ -0,0 +1,167 @@+// Club cover-charge revenue summary.+//+// Powers the `mode:"revenue"` branch of POST /api/x402/club-cover and the+// autonomous loop's "Cover Charge Revenue Summary" pipeline. It reports the+// monetization health of the three.ws Pole Club's social economy over a rolling+// window, drawn entirely from real on-chain settlement records — no estimates,+// no mocks:+//+// • Door (cover charge) revenue — every settled payment to the club-cover+// route, read from the canonical x402 settlement ledger (x402_audit_log,+// event_type='payment_settled'). This is the headline `total_usdc`.+// • Floor revenue, per act — settled dance tips (club_tips) grouped by the+// dancer/act they were paid to. Each act is a distinct, individually+// monetizable "club" within the venue, so it is the one revenue dimension+// with a meaningful per-entity breakdown: `clubs[]`, and the top earner+// surfaces as `top_club_id` / `top_club_revenue`.+//+// Together they answer "is the club's social economy making money, and which+// act is driving the floor?" — the signal the autonomous monitor watches.++import { sql } from '../db.js';++export const COVER_ROUTE = '/api/x402/club-cover';++// Whitelisted rolling windows. The request `period` is mapped to a concrete+// `since` timestamp in JS (never interpolated into SQL as an interval literal),+// so there is no injection surface and every branch shares one query shape.+const PERIOD_DAYS = { '24h': 1, '7d': 7, '14d': 14, '30d': 30 };+const DEFAULT_PERIOD = '7d';++/**+ * Resolve a requested period to a canonical key + ISO `since` boundary.+ * Unknown values fall back to 7d; 'all' reports lifetime revenue.+ */+export function normalizePeriod(period) {+ const p = String(period || DEFAULT_PERIOD).trim().toLowerCase();+ if (p === 'all') return { key: 'all', since: new Date(0).toISOString() };+ const days = PERIOD_DAYS[p];+ if (!days) return { key: DEFAULT_PERIOD, since: sinceForDays(PERIOD_DAYS[DEFAULT_PERIOD]) };+ return { key: p, since: sinceForDays(days) };+}++function sinceForDays(days) {+ return new Date(Date.now() - days * 86_400_000).toISOString();+}++/** Atomic USDC (6-decimal) → fixed-precision USDC string. Never NaN. */+export function atomicsToUsdc(atomics) {+ const n = Number(atomics || 0);+ if (!Number.isFinite(n)) return '0.000000';+ return (n / 1e6).toFixed(6);+}++/**+ * Build the full cover-charge revenue summary for a rolling window.+ * Reads only real settlement data; soft-fails each leg so a transient query+ * error degrades one number rather than the whole report.+ *+ * @param {{ period?: string }} [opts]+ */+export async function coverRevenueSummary({ period } = {}) {+ const { key, since } = normalizePeriod(period);++ // Door revenue: settled cover-charge payments on the club-cover route.+ let cover = { count: 0, unique_payers: 0, atomics: '0' };+ try {+ const [row] = await sql`+ SELECT+ count(*)::int AS count,+ count(DISTINCT payer)::int AS unique_payers,+ coalesce(sum(+ CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END+ ), 0)::text AS atomics+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND route = ${COVER_ROUTE}+ AND created_at >= ${since}::timestamptz+ `;+ if (row) cover = row;+ } catch (err) {+ console.warn('[club-cover-revenue] door query failed (soft 0)', err?.message || err);+ }++ // Floor revenue per act: settled tips grouped by dancer. Left join keeps an+ // act with zero tips in the window visible (revenue 0) so the roster is+ // stable as new acts are added — same shape the public leaderboard uses.+ let clubs = [];+ try {+ const rows = await sql`+ SELECT+ d.dancer AS club_id,+ d.display_name,+ coalesce(sum(t.amount_atomics), 0)::text AS atomics,+ count(t.*)::int AS tip_count+ FROM club_dancer_wallets d+ LEFT JOIN club_tips t+ ON t.dancer = d.dancer AND t.created_at >= ${since}::timestamptz+ GROUP BY d.dancer, d.display_name+ ORDER BY coalesce(sum(t.amount_atomics), 0) DESC, d.dancer ASC+ `;+ clubs = rows.map((r) => ({+ club_id: r.club_id,+ display_name: r.display_name || null,+ revenue_atomics: r.atomics,+ revenue_usdc: atomicsToUsdc(r.atomics),+ tip_count: r.tip_count,+ }));+ } catch (err) {+ console.warn('[club-cover-revenue] floor query failed (soft empty)', err?.message || err);+ }++ const coverAtomics = Number(cover.atomics || 0);+ const floorAtomics = clubs.reduce((sum, c) => sum + Number(c.revenue_atomics || 0), 0);+ const tipCount = clubs.reduce((sum, c) => sum + (c.tip_count || 0), 0);+ const top = clubs.find((c) => Number(c.revenue_atomics) > 0) || null;++ return {+ ok: true,+ mode: 'revenue',+ period: key,+ since,+ generated_at: new Date().toISOString(),+ // Headline: total cover-charge (door) revenue over the window.+ total_usdc: atomicsToUsdc(coverAtomics),+ cover: {+ total_usdc: atomicsToUsdc(coverAtomics),+ total_atomics: String(coverAtomics),+ count: cover.count || 0,+ unique_payers: cover.unique_payers || 0,+ },+ floor: {+ total_usdc: atomicsToUsdc(floorAtomics),+ total_atomics: String(floorAtomics),+ tip_count: tipCount,+ },+ // Combined social-economy take = door + floor.+ social_economy_usdc: atomicsToUsdc(coverAtomics + floorAtomics),+ clubs,+ club_count: clubs.length,+ top_club_id: top ? top.club_id : null,+ top_club_revenue: top ? top.revenue_usdc : '0.000000',+ top_club_display_name: top ? top.display_name : null,+ };+}++/**+ * Pure extractor (no I/O) — lifts the actionable signal out of a revenue+ * response body for x402_autonomous_log.signal_data. Tolerates a partial or+ * failed body so the autonomous loop never throws on a degraded response.+ */+export function extractCoverRevenueSignal(r) {+ if (!r || typeof r !== 'object') {+ return { total_usdc: null, top_club_id: null, top_club_revenue: null };+ }+ return {+ period: r.period ?? null,+ total_usdc: r.total_usdc ?? r.cover?.total_usdc ?? null,+ cover_count: r.cover?.count ?? null,+ unique_payers: r.cover?.unique_payers ?? null,+ floor_usdc: r.floor?.total_usdc ?? null,+ social_economy_usdc: r.social_economy_usdc ?? null,+ club_count: r.club_count ?? (Array.isArray(r.clubs) ? r.clubs.length : null),+ top_club_id: r.top_club_id ?? null,+ top_club_revenue: r.top_club_revenue ?? null,+ top_club_display_name: r.top_club_display_name ?? null,+ };+}diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 70d595b62..f9dc77b78 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -839,6 +839,41 @@ const SELF_ENDPOINTS = [enabled: true,extractSignal: (r) => ({ alive: !!r }),},+ // ── DID Verification Canary (USE-069) ────────────────────────────────────+ // Pays a real $0.001 USDC POST to /api/x402/did, which resolves three.ws's+ // published W3C DID document over its real public route (/.well-known/did.json+ // — the same path an external x402 counterparty hits to resolve our+ // offer/receipt signing key), structurally validates it, and measures+ // end-to-end resolution latency. The verdict { verified, latency_ms } is the+ // actionable signal: verified flips false when the document is unreachable,+ // malformed, or slower than 1500ms — exactly the failure that would make a+ // partner's signature verification silently fail. extractSignal lifts the+ // verdict into x402_autonomous_log.signal_data so the status surface can read+ // the DID subsystem's health straight off the autonomous log. Distinct from+ // the free GET liveness probe above: this paid canary proves correctness ++ // latency, not just reachability. Cooldown 600s (10 min) → ~$0.006/hr, well+ // under the loop's daily cap, while sampling latency often enough to catch a+ // degraded resolver quickly.+ {+ id: 'did-verification-canary',+ name: 'DID Verification Canary',+ path: '/api/x402/did',+ method: 'POST',+ body: { did: 'did:three:canary', mode: 'verify' },+ cooldown_s: 600,+ priority: 50,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ verified: r?.verified ?? null,+ latency_ms: r?.latency_ms ?? null,+ resolved_did: r?.resolved_did ?? null,+ http_status: r?.http_status ?? null,+ malformed: r?.malformed ?? null,+ within_latency: r?.within_latency ?? null,+ configured: r?.configured ?? null,+ }),+ },// ── Animation Retargeting QA (USE-012) ──────────────────────────────────────// Pays $0.005 USDC to download a representative set of canary animation clips@@ -1058,6 +1093,40 @@ const SELF_ENDPOINTS = [run: (ctx) => avatarSearchWarmup(ctx),},+ // ── MCP Tool Discovery (USE-062) ───────────────────────────────────────────+ // Pays $0.001 USDC every 2h to /api/x402/mcp-tool-catalog (mode:discover),+ // which fingerprints the MCP server's live tool catalog (api/_mcp/catalog.js →+ // TOOL_CATALOG, the exact list /api/mcp returns from tools/list) and diffs it+ // against the durable mcp_tool_registry. The endpoint persists the new catalog+ // state itself, so a newly-shipped MCP tool (or a price/shape change, or a+ // removal) is captured in mcp_tool_registry the moment it ships — the+ // feature-flag source agents read to light up a new capability without polling+ // tools/list and diffing by hand. extractSignal lifts the diff+ // (new_tools / total_tools / changed / removed counts) into+ // x402_autonomous_log.signal_data so the autonomous log alone proves what+ // changed each probe. Cooldown 7200s (2h) → ≤12 probes/day ≈ $0.012/day,+ // bounded again by the loop's daily cap.+ {+ id: 'mcp-tool-discovery',+ name: 'MCP Tool Discovery',+ path: '/api/x402/mcp-tool-catalog',+ method: 'POST',+ body: { mode: 'discover' },+ cooldown_s: 7200, // 2h — matches the use case's described schedule+ priority: 36, // discovery tier (33–38)+ pipeline: 'discovery',+ enabled: true,+ extractSignal: (r) => ({+ total_tools: r?.total_tools ?? null,+ priced_tools: r?.priced_tools ?? null,+ free_tools: r?.free_tools ?? null,+ new_tools: Array.isArray(r?.new_tools) ? r.new_tools.map((t) => t?.name).filter(Boolean) : [],+ new_count: Array.isArray(r?.new_tools) ? r.new_tools.length : 0,+ changed_count: Array.isArray(r?.changed_tools) ? r.changed_tools.length : 0,+ removed_tools: Array.isArray(r?.removed_tools) ? r.removed_tools : [],+ }),+ },+// ── Agent Reputation Score Refresh (USE-005) ───────────────────────────────// Refreshes the on-chain attestation reputation of the stalest registered// Solana agents by paying the /api/mcp tool solana_agent_reputationdiff --git a/api/_lib/x402/pipelines/pay-by-name-resolver.js b/api/_lib/x402/pipelines/pay-by-name-resolver.jsnew file mode 100644index 000000000..378787b33--- /dev/null+++ b/api/_lib/x402/pipelines/pay-by-name-resolver.js@@ -0,0 +1,304 @@+// api/_lib/x402/pipelines/pay-by-name-resolver.js+//+// Pay-By-Name Resolution Health — autonomous pipeline (health).+//+// The pay-by-name registry is the entry point for every "send USDC to a name"+// flow on three.ws: the SDK's payByName(), the /pay studio, the profile+// pay-button, and any agent that wants to route a payment to `@handle`,+// `<label>.threews.sol`, or a raw address all resolve the recipient through+// GET /api/x402/pay-by-name?name=<name> before a single lamport moves. If that+// resolver breaks — Bonfida SNS regresses, the parent domain de-registers, the+// DB claim join changes, or (worst case) the platform domain silently repoints+// to a wallet that isn't ours — every downstream send is paid to the wrong+// place or fails outright. This monitor is the canary in front of that path.+//+// Every 10 minutes it resolves a KNOWN name (the platform's own SNS parent+// domain, `<PARENT_LABEL>.sol`, derived from threews-sns.js so it always tracks+// config) and asserts the registry returns a valid, on-curve Solana address. If+// X402_PAY_BY_NAME_EXPECTED_ADDRESS is set, it additionally requires the+// resolution to MATCH that wallet — an anti-poisoning check that catches a+// domain repoint between deploys before a user is told to pay it.+//+// Endpoint: GET /api/x402/pay-by-name?name=<name> — a FREE resolve-only read+// (no 402, no payment; the resolve path is intentionally free so the SDK and+// browser can preview a recipient). Because the call is free this pipeline+// moves no funds — amountAtomic is always 0. The autonomous loop probes the+// endpoint first; a non-402, non-OK response is a real resolver failure (not a+// "free success"), so run() owns the OK/verified classification rather than the+// generic loop path, which would otherwise record a 404 as healthy.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js+// (`pay-by-name-resolution`). The per-tick loop (api/cron/x402-autonomous-loop.js)+// hands run() { origin, redis, sql, log, runId } and records the returned+// outcome as one row in x402_autonomous_log (pipeline 'health'). Called+// standalone (manual test) it derives its own origin/sql and still works.+//+// Value extracted & where it lands:+// • pay_by_name_resolution_log — one time-series row per run. Columns:+// name → the name resolved this run+// address → the on-chain address it resolved to (null on failure)+// source → resolver namespace ('sns' | 'username' | 'address')+// verified → resolved to a valid on-curve address (and matched the+// expected wallet, when one is configured)+// valid_address → address parses as an on-curve Solana pubkey+// address_mismatch → resolved address ≠ expected wallet (poisoning flag)+// expected_address → the wallet we asserted against (null if unset)+// error_msg → why a run was not verified+// • Redis x402:pay-by-name:latest — newest verdict for cheap dashboard reads.+// • Redis x402:pay-by-name:alert — present (with TTL) only while resolution is+// failing or poisoned, so a consumer can detect the alert state in one GET.++import { randomUUID } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';++import { fetchWithTimeout } from '../pay.js';+import { sql as defaultSql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { PARENT_LABEL } from '../../threews-sns.js';++const log = logger('x402-pay-by-name-resolver');++// The known name to resolve each run. Defaults to the platform's own SNS parent+// domain (e.g. 'threews.sol'), derived from PARENT_LABEL so it always tracks the+// configured parent. Override via env to canary a different known name.+export const PROBE_NAME = (+ process.env.X402_PAY_BY_NAME_PROBE_NAME ||+ env.X402_PAY_BY_NAME_PROBE_NAME ||+ `${PARENT_LABEL}.sol`+).trim();++// Optional anti-poisoning assertion: when set, the resolution must match this+// exact wallet to count as verified. Catches the platform domain repointing to a+// wallet that isn't ours between deploys. Unset → any valid on-curve address+// resolved from the name counts as verified.+export const EXPECTED_ADDRESS = (+ (process.env.X402_PAY_BY_NAME_EXPECTED_ADDRESS ||+ env.X402_PAY_BY_NAME_EXPECTED_ADDRESS ||+ '').trim()+) || null;++const REDIS_LATEST_KEY = 'x402:pay-by-name:latest';+const REDIS_ALERT_KEY = 'x402:pay-by-name:alert';+// Alert key TTL: a little over two monitor cycles (10 min) so a missed run lets+// the flag lapse to "unknown" rather than latching a stale alert forever.+const ALERT_TTL_SECONDS = 25 * 60;++const ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// A recipient is a real wallet only if the address parses AND lies on the ed25519+// curve. Off-curve addresses (PDAs / program addresses) can't custody a token+// account the way a user wallet does, so an off-curve "recipient" is never valid.+function isValidWallet(addr) {+ if (typeof addr !== 'string' || !ADDR_RE.test(addr)) return false;+ try {+ return PublicKey.isOnCurve(new PublicKey(addr).toBytes());+ } catch {+ return false;+ }+}++/**+ * Derive the resolution verdict from a GET /api/x402/pay-by-name?name= response.+ * Pure + side-effect-free so it can be unit-tested against a real payload and+ * reused by both the time-series sink and the autonomous-log signal_data.+ *+ * @param {object|null} body — the parsed response body ({ data: { address,+ * source, resolved } }) or null when the resolve call failed / returned non-OK.+ * @param {{ name?: string, expectedAddress?: string|null }} opts+ * @returns {{ name, address, source, resolved, valid_address, expected_address,+ * address_mismatch, verified }}+ */+export function classifyResolution(body, { name = null, expectedAddress = null } = {}) {+ const data = (body && body.data) || null;+ const address = (data && data.address) || null;+ const source = (data && data.source) || null;+ const resolvedName = (data && data.resolved) || null;++ const validAddress = isValidWallet(address);+ let addressMismatch = false;+ let verified = validAddress;+ if (verified && expectedAddress) {+ addressMismatch = address !== expectedAddress;+ if (addressMismatch) verified = false;+ }++ return {+ name: name || resolvedName || null,+ address,+ source,+ resolved: resolvedName,+ valid_address: validAddress,+ expected_address: expectedAddress || null,+ address_mismatch: addressMismatch,+ verified,+ };+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;+async function ensureSchema(sql) {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS pay_by_name_resolution_log (+ id bigserial PRIMARY KEY,+ ts timestamptz NOT NULL DEFAULT now(),+ run_id uuid,+ name text,+ address text,+ source text,+ verified boolean NOT NULL DEFAULT false,+ valid_address boolean NOT NULL DEFAULT false,+ address_mismatch boolean NOT NULL DEFAULT false,+ expected_address text,+ error_msg text+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS pay_by_name_resolution_log_ts ON pay_by_name_resolution_log (ts DESC)`;+ _schemaReady = true;+}++async function persistSample(sql, runId, verdict, errorMsg) {+ try {+ await sql`+ INSERT INTO pay_by_name_resolution_log+ (ts, run_id, name, address, source, verified,+ valid_address, address_mismatch, expected_address, error_msg)+ VALUES+ (now(), ${runId}, ${verdict.name}, ${verdict.address}, ${verdict.source},+ ${verdict.verified}, ${verdict.valid_address}, ${verdict.address_mismatch},+ ${verdict.expected_address}, ${errorMsg || null})+ `;+ } catch (err) {+ // DB failure on the sink is logged but must never crash the loop.+ log.warn('pay_by_name_insert_failed', { message: err?.message });+ }+}++async function writeRedisState(redis, verdict, errorMsg) {+ if (!redis) return;+ const sample = {+ ts: new Date().toISOString(),+ name: verdict.name,+ address: verdict.address,+ source: verdict.source,+ verified: verdict.verified,+ address_mismatch: verdict.address_mismatch,+ expected_address: verdict.expected_address,+ error_msg: errorMsg || null,+ };+ try {+ await redis.set(REDIS_LATEST_KEY, JSON.stringify(sample), { ex: ALERT_TTL_SECONDS });+ if (!verdict.verified) {+ await redis.set(REDIS_ALERT_KEY, JSON.stringify(sample), { ex: ALERT_TTL_SECONDS });+ } else {+ // Cleared — resolution is healthy again, drop any lingering alert flag.+ await redis.del(REDIS_ALERT_KEY);+ }+ } catch (err) {+ log.warn('pay_by_name_redis_write_failed', { message: err?.message });+ }+}++/**+ * Run the pay-by-name resolution health check. Conforms to the run()-style+ * registry contract.+ *+ * @param {object} ctx — supplied by the autonomous loop:+ * { origin, redis, sql, log, runId }. All optional for standalone/manual runs.+ * @returns the aggregate outcome the loop records to x402_autonomous_log:+ * { success, amountAtomic, txSig, responseData, signalData, errorMsg, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const sql = ctx.sql || defaultSql;+ const redis = ctx.redis || null;+ const name = PROBE_NAME;+ const endpointUrl = `${origin}/api/x402/pay-by-name?name=${encodeURIComponent(name)}`;++ // Schema first: without the sink there's no time-series to write.+ try {+ await ensureSchema(sql);+ } catch (err) {+ log.warn('pay_by_name_schema_failed', { message: err?.message });+ return { success: false, amountAtomic: 0, txSig: null, skipped: true, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Resolve the known name (free GET — no 402, no payment) ────────────────+ let res;+ try {+ res = await fetchWithTimeout(endpointUrl, {+ method: 'GET',+ headers: { 'user-agent': 'threews-x402-pay-by-name/1.0' },+ });+ } catch (err) {+ // Network failure / timeout — never crash the loop.+ const errorMsg = `resolve_fetch_failed: ${err?.message || 'network'}`;+ log.warn('pay_by_name_fetch_failed', { message: err?.message });+ const verdict = classifyResolution(null, { name, expectedAddress: EXPECTED_ADDRESS });+ await persistSample(sql, runId, verdict, errorMsg);+ await writeRedisState(redis, verdict, errorMsg);+ return { success: false, amountAtomic: 0, txSig: null, signalData: verdict, errorMsg, note: 'fetch_failed' };+ }++ // Non-OK on a free endpoint is a REAL resolver failure (e.g. 404 — the known+ // name no longer resolves), not a free success. Record it as unhealthy.+ if (!res.ok) {+ const errorMsg = `resolve_http_${res.status}`;+ log.warn('pay_by_name_resolve_non_ok', { status: res.status, name });+ const verdict = classifyResolution(null, { name, expectedAddress: EXPECTED_ADDRESS });+ await persistSample(sql, runId, verdict, errorMsg);+ await writeRedisState(redis, verdict, errorMsg);+ return {+ success: false, amountAtomic: 0, txSig: null,+ responseData: { status: res.status, name }, signalData: verdict,+ errorMsg, note: errorMsg,+ };+ }++ const verdict = classifyResolution(res.body, { name, expectedAddress: EXPECTED_ADDRESS });+ const errorMsg = verdict.verified+ ? null+ : verdict.address_mismatch+ ? 'address_mismatch'+ : verdict.address+ ? 'invalid_address'+ : 'unresolved';++ await persistSample(sql, runId, verdict, errorMsg);+ await writeRedisState(redis, verdict, errorMsg);++ if (!verdict.verified) {+ log.warn('pay_by_name_unverified', {+ run_id: runId, name, address: verdict.address,+ expected: verdict.expected_address, mismatch: verdict.address_mismatch, error: errorMsg,+ });+ } else {+ log.info('pay_by_name_verified', { run_id: runId, name, address: verdict.address, source: verdict.source });+ }++ return {+ // success = the known name resolved to a valid (and, when configured,+ // expected) on-chain wallet — i.e. the pay-by-name registry is functioning.+ success: verdict.verified,+ amountAtomic: 0,+ txSig: null,+ responseData: { name: verdict.name, address: verdict.address, source: verdict.source },+ signalData: verdict,+ errorMsg,+ note: verdict.verified+ ? `${name} → ${verdict.address}`+ : verdict.address_mismatch+ ? `ADDRESS_MISMATCH ${verdict.address} ≠ ${verdict.expected_address}`+ : errorMsg,+ };+}++export const PAY_BY_NAME_RESOLUTION = Object.freeze({+ endpoint: '/api/x402/pay-by-name',+ probeName: PROBE_NAME,+ expectedAddress: EXPECTED_ADDRESS,+ redisLatestKey: REDIS_LATEST_KEY,+ redisAlertKey: REDIS_ALERT_KEY,+});diff --git a/api/_lib/x402/pump-volume-anomaly.js b/api/_lib/x402/pump-volume-anomaly.jsnew file mode 100644index 000000000..78eb7b0d2--- /dev/null+++ b/api/_lib/x402/pump-volume-anomaly.js@@ -0,0 +1,355 @@+// api/_lib/x402/pump-volume-anomaly.js+//+// Pump.fun volume-anomaly detector — the data engine behind the+// `pump_volume_anomaly` topic of POST /api/x402/crypto-intel.+//+// "Abnormal trading volume in the last hour" is defined cross-sectionally: across+// the set of currently-live pump.fun coins, we measure each coin's USD trade+// volume in the trailing window (default 1 h) and compare the busiest coin to the+// MEDIAN of its peers. A coin whose last-hour volume is a large multiple of the+// median active coin is a genuine statistical outlier — the attention/volume+// spike a sniper or oracle wants to know about before price catches up.+//+// Every byte is live: the candidate set comes from pump.fun's currently-live+// board (frontend-api-v3) and per-coin volume is summed from the real swap-API+// trade feed (swap-api.pump.fun) — the same upstreams the rest of the codebase+// already proxies (see api/_lib/pump-launch-feed.js, api/pump/[action].js). No+// mocks, no synthetic coins.+//+// The pure scoring functions (summarizeWindowUsd, median, scoreVolumeAnomaly,+// buildAnomalySignal) take plain data so they are unit-testable without network;+// detectPumpVolumeAnomaly() wires them to the live feeds.++const PUMP_FRONTEND_BASE =+ process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';+const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';+const UA = 'three.ws-x402-pump-volume/1';++// Tunables (env-overridable so production can adjust sensitivity without a deploy).+export const DEFAULTS = {+ candidates: Number(process.env.PUMP_ANOMALY_CANDIDATES || 24), // coins to scan+ tradeLimit: Number(process.env.PUMP_ANOMALY_TRADE_LIMIT || 100), // trades/coin+ windowSec: Number(process.env.PUMP_ANOMALY_WINDOW_SEC || 3600), // trailing 1 h+ ratioThreshold: Number(process.env.PUMP_ANOMALY_RATIO || 3), // anomaly when ratio ≥ this+ minUsd: Number(process.env.PUMP_ANOMALY_MIN_USD || 250), // absolute volume floor+ concurrency: Number(process.env.PUMP_ANOMALY_CONCURRENCY || 6),+ fetchTimeoutMs: Number(process.env.PUMP_ANOMALY_TIMEOUT_MS || 6000),+};++// ── pure helpers ─────────────────────────────────────────────────────────────++function num(v) {+ const n = typeof v === 'string' ? parseFloat(v) : v;+ return Number.isFinite(n) ? n : null;+}++/** Parse a swap-API trade timestamp (ISO string or epoch s/ms) → ms, or null. */+function tradeTimeMs(t) {+ const raw = t?.timestamp ?? t?.ts ?? null;+ if (raw == null) return null;+ if (typeof raw === 'number') return raw < 1e12 ? raw * 1000 : raw; // s → ms+ const parsed = Date.parse(raw);+ return Number.isFinite(parsed) ? parsed : null;+}++/**+ * Sum the USD volume of trades that fall within [nowMs - windowSec, nowMs].+ * Pure — caller supplies nowMs so it is deterministic under test.+ * @returns {{ usd: number, count: number }}+ */+export function summarizeWindowUsd(trades, nowMs, windowSec = DEFAULTS.windowSec) {+ if (!Array.isArray(trades)) return { usd: 0, count: 0 };+ const floor = nowMs - windowSec * 1000;+ let usd = 0;+ let count = 0;+ for (const t of trades) {+ const tMs = tradeTimeMs(t);+ if (tMs == null || tMs < floor || tMs > nowMs) continue;+ // swap-api reports the USD notional on amountUsd; fall back to sol*priceUsd.+ let v = num(t.amountUsd ?? t.usd_amount);+ if (v == null) {+ const sol = num(t.amountSol ?? t.sol_amount);+ const px = num(t.priceUsd ?? t.price_usd);+ // priceUsd is per-base-token; the sol notional already carries the trade+ // size, so only fall back to it when there is no USD figure at all.+ if (sol != null && px != null && sol > 0) v = sol * 0; // avoid wrong-unit math+ }+ if (v == null || v <= 0) continue;+ usd += v;+ count += 1;+ }+ return { usd, count };+}++/** Median of a numeric array (0 for empty). Pure. */+export function median(nums) {+ const xs = (nums || []).filter((n) => Number.isFinite(n)).sort((a, b) => a - b);+ if (!xs.length) return 0;+ const mid = Math.floor(xs.length / 2);+ return xs.length % 2 ? xs[mid] : (xs[mid - 1] + xs[mid]) / 2;+}++function round(n, dp = 2) {+ if (!Number.isFinite(n)) return null;+ const f = 10 ** dp;+ return Math.round(n * f) / f;+}++/**+ * Score a set of per-coin last-window volume samples into an anomaly verdict.+ * @param {Array<{mint:string,name?:string,symbol?:string,window_usd:number,trade_count?:number}>} samples+ * @param {object} [opts] { ratioThreshold, minUsd }+ * @returns {{+ * anomaly: boolean, mint: string|null, name: string|null, symbol: string|null,+ * volume_ratio: number|null, top_window_usd: number|null, baseline_usd: number|null,+ * candidates: number, active: number, trade_count: number|null, reason?: string+ * }}+ */+export function scoreVolumeAnomaly(samples, opts = {}) {+ const ratioThreshold = opts.ratioThreshold ?? DEFAULTS.ratioThreshold;+ const minUsd = opts.minUsd ?? DEFAULTS.minUsd;++ const list = Array.isArray(samples) ? samples : [];+ const active = list+ .filter((s) => s && Number.isFinite(s.window_usd) && s.window_usd > 0)+ .sort((a, b) => b.window_usd - a.window_usd);++ const base = {+ anomaly: false,+ mint: null,+ name: null,+ symbol: null,+ volume_ratio: null,+ top_window_usd: null,+ baseline_usd: null,+ candidates: list.length,+ active: active.length,+ trade_count: null,+ };++ // Need a population to compare against — one lone trader is not an "anomaly".+ if (active.length < 3) {+ return { ...base, reason: 'insufficient_active_coins' };+ }++ const top = active[0];+ const rest = active.slice(1).map((s) => s.window_usd);+ // Robust baseline: median of the peer coins. Fall back to the mean, then to the+ // smallest positive peer, so a degenerate distribution can't divide by zero.+ let baseline = median(rest);+ if (!(baseline > 0)) baseline = rest.reduce((a, b) => a + b, 0) / rest.length;+ if (!(baseline > 0)) baseline = Math.min(...rest.filter((v) => v > 0));+ if (!(baseline > 0)) return { ...base, reason: 'no_peer_baseline' };++ const ratio = top.window_usd / baseline;+ const anomaly = ratio >= ratioThreshold && top.window_usd >= minUsd;++ return {+ anomaly,+ mint: top.mint || null,+ name: top.name || null,+ symbol: top.symbol || null,+ volume_ratio: round(ratio),+ top_window_usd: round(top.window_usd),+ baseline_usd: round(baseline),+ candidates: list.length,+ active: active.length,+ trade_count: Number.isFinite(top.trade_count) ? top.trade_count : null,+ };+}++/**+ * Turn an anomaly score into the crypto-intel signal envelope (topic / signal /+ * headline / rationale / confidence). Pure. A volume spike is an attention signal,+ * so it maps to 'bullish'; a quiet market maps to 'neutral'.+ */+export function buildAnomalySignal(score, windowSec = DEFAULTS.windowSec) {+ const mins = Math.round(windowSec / 60);+ const label = score.symbol || score.name || (score.mint ? `${score.mint.slice(0, 4)}…` : 'a coin');+ const usd = (n) => `$${Math.round(n || 0).toLocaleString('en-US')}`;++ if (score.anomaly) {+ const ratio = score.volume_ratio;+ // High conviction once the spike is a large multiple of the peer median.+ const highConviction = ratio > 5;+ const confidence = Math.min(0.96, 0.6 + Math.min(ratio / 25, 0.36));+ return {+ signal: 'bullish',+ conviction: highConviction ? 'high' : 'normal',+ headline:+ `${label} volume anomaly — ${ratio}× peer median ` ++ `(${usd(score.top_window_usd)} in last ${mins}m)`,+ rationale:+ `Across ${score.active} actively-trading pump.fun coins, ${label} traded ` ++ `${usd(score.top_window_usd)} in the last ${mins} minutes — ${ratio}× the ` ++ `${usd(score.baseline_usd)} median of its peers. A volume spike of this ` ++ `magnitude typically precedes a price/attention move; treat as a fresh ` ++ `${highConviction ? 'high-conviction ' : ''}momentum candidate.`,+ confidence: round(confidence, 4),+ };+ }++ return {+ signal: 'neutral',+ conviction: 'none',+ headline: `No abnormal pump.fun volume in the last ${mins}m`,+ rationale:+ `Scanned ${score.candidates} candidate coins (${score.active} actively trading). ` ++ (score.reason === 'insufficient_active_coins'+ ? 'Too few active coins to establish a baseline this window.'+ : `The busiest coin's volume sits within normal range of the peer median ` ++ `(ratio ${score.volume_ratio ?? 'n/a'}). No outlier worth acting on.`),+ confidence: 0.5,+ };+}++// ── live fetch layer ─────────────────────────────────────────────────────────++function defaultFetchJson(timeoutMs) {+ return async (url) => {+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), timeoutMs);+ try {+ const r = await fetch(url, {+ signal: ctrl.signal,+ headers: { accept: 'application/json', 'user-agent': UA },+ });+ if (!r.ok) return null;+ return await r.json();+ } catch {+ return null;+ } finally {+ clearTimeout(tid);+ }+ };+}++/** Run fn over items with bounded concurrency, preserving order. */+async function mapLimit(items, limit, fn) {+ const out = new Array(items.length);+ let cursor = 0;+ const workerCount = Math.max(1, Math.min(limit, items.length));+ const workers = Array.from({ length: workerCount }, async () => {+ for (;;) {+ const idx = cursor++;+ if (idx >= items.length) break;+ out[idx] = await fn(items[idx], idx);+ }+ });+ await Promise.all(workers);+ return out;+}++/** Pull the live candidate coin set (currently-live board, newest-trade fallback). */+async function fetchCandidates(fetchJson, limit) {+ const n = Math.min(100, Math.max(3, limit));+ const live = await fetchJson(+ `${PUMP_FRONTEND_BASE}/coins/currently-live?offset=0&limit=${n}&includeNsfw=false`,+ );+ let list = Array.isArray(live) ? live : Array.isArray(live?.coins) ? live.coins : [];+ if (list.length < 3) {+ // Fallback: most-recently-traded coins are the next-best "active" proxy.+ const recent = await fetchJson(+ `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${n}&sort=last_trade_timestamp&order=DESC&includeNsfw=false`,+ );+ const r = Array.isArray(recent) ? recent : Array.isArray(recent?.coins) ? recent.coins : [];+ if (r.length > list.length) list = r;+ }+ return list+ .filter((c) => c && c.mint)+ .map((c) => ({ mint: c.mint, name: c.name || null, symbol: c.symbol || null }));+}++/**+ * Detect the top pump.fun volume anomaly in the trailing window, live.+ *+ * @param {object} [opts] overrides for DEFAULTS, plus:+ * nowMs — clock injection (defaults to Date.now())+ * fetchJson — (url)=>Promise<json|null> injection for tests+ * @returns {Promise<object>} full intel envelope (topic/signal/headline/.../anomaly/mint/volume_ratio)+ * @throws {Error & {status:503}} when no live candidate data could be fetched (so the+ * paid endpoint returns 503 BEFORE settlement and the buyer is never charged).+ */+export async function detectPumpVolumeAnomaly(opts = {}) {+ const cfg = { ...DEFAULTS, ...opts };+ const fetchJson = opts.fetchJson || defaultFetchJson(cfg.fetchTimeoutMs);+ const nowMs = opts.nowMs ?? Date.now();++ const candidates = await fetchCandidates(fetchJson, cfg.candidates);+ if (!candidates.length) {+ throw Object.assign(new Error('pump.fun live feed is temporarily unavailable'), {+ status: 503,+ code: 'data_unavailable',+ });+ }++ const samples = await mapLimit(candidates, cfg.concurrency, async (c) => {+ const body = await fetchJson(+ `${PUMP_SWAP_BASE}/v2/coins/${c.mint}/trades?limit=${cfg.tradeLimit}`,+ );+ const trades = Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];+ const { usd, count } = summarizeWindowUsd(trades, nowMs, cfg.windowSec);+ return { ...c, window_usd: usd, trade_count: count };+ });++ // If every trade fetch failed (upstream swap-API down) we have no signal to+ // sell — surface as 503 so the buyer is not charged for an empty verdict.+ if (!samples.some((s) => s.trade_count > 0)) {+ throw Object.assign(new Error('pump.fun trade feed is temporarily unavailable'), {+ status: 503,+ code: 'data_unavailable',+ });+ }++ const score = scoreVolumeAnomaly(samples, cfg);+ const sig = buildAnomalySignal(score, cfg.windowSec);++ return {+ topic: 'pump_volume_anomaly',+ anomaly: score.anomaly,+ mint: score.mint,+ volume_ratio: score.volume_ratio,+ token_name: score.name,+ token_symbol: score.symbol,+ top_window_usd: score.top_window_usd,+ baseline_usd: score.baseline_usd,+ window_sec: cfg.windowSec,+ candidates_scanned: score.candidates,+ active_coins: score.active,+ signal: sig.signal,+ conviction: sig.conviction,+ headline: sig.headline,+ rationale: sig.rationale,+ confidence: sig.confidence,+ ts: new Date(nowMs).toISOString(),+ };+}++/**+ * Lift a pump_volume_anomaly response into the x402_autonomous_log.signal_data /+ * oracle_intel_signals shape. Shared by the registry entry's extractSignal so the+ * autonomous log and the oracle dedup always agree. High-conviction spikes+ * (anomaly && ratio > 5) are tagged so the sniper gate can prioritise them.+ */+export function classifyVolumeAnomaly(r) {+ const o = r || {};+ const ratio = num(o.volume_ratio);+ const highConviction = o.anomaly === true && ratio != null && ratio > 5;+ return {+ topic: 'pump_volume_anomaly',+ anomaly: o.anomaly === true,+ mint: o.mint || null,+ volume_ratio: ratio,+ conviction: highConviction ? 'high' : o.anomaly === true ? 'normal' : 'none',+ signal: typeof o.signal === 'string' ? o.signal : o.anomaly === true ? 'bullish' : 'neutral',+ headline: typeof o.headline === 'string' ? o.headline : null,+ // Bump confidence for high-conviction spikes so the oracle row the sniper+ // reads reflects the escalation the task calls for.+ confidence: highConviction+ ? Math.max(0.85, num(o.confidence) ?? 0)+ : num(o.confidence),+ token_symbol: o.token_symbol || null,+ top_window_usd: num(o.top_window_usd),+ baseline_usd: num(o.baseline_usd),+ };+}diff --git a/api/_lib/x402/sniper-analytics-store.js b/api/_lib/x402/sniper-analytics-store.jsindex b1d566a22..ed7e77c3e 100644--- a/api/_lib/x402/sniper-analytics-store.js+++ b/api/_lib/x402/sniper-analytics-store.js@@ -25,20 +25,6 @@ export const WIN_RATE_ALERT_THRESHOLD = 0.4; // 40%// Don't alert on noise: a single losing trade is 0% win rate but says nothing.export const MIN_ALERT_SAMPLE = 5;-// Whitelisted reporting windows → Postgres interval literals. `all` = no time-// filter (lifetime). Keeping this a fixed map keeps the interval out of user-// input entirely.-export const PERIOD_INTERVALS = {- '1h': '1 hour',- '6h': '6 hours',- '24h': '24 hours',- '7d': '7 days',- '30d': '30 days',- all: null,-};--export const DEFAULT_PERIOD = '24h';-function num(v) {const n = typeof v === 'string' ? parseFloat(v) : v;return Number.isFinite(n) ? n : 0;@@ -98,7 +84,7 @@ export function buildSniperAnalytics(agg = {}, opts = {}) {return {report: opts.report || 'sniper_trades',- period: opts.period || DEFAULT_PERIOD,+ period: opts.period || '24h',network: opts.network || 'mainnet',sample_size: sample,wins,diff --git a/api/_lib/x402/user-activity-analytics.js b/api/_lib/x402/user-activity-analytics.jsindex 89a06678f..30f91fd74 100644--- a/api/_lib/x402/user-activity-analytics.js+++ b/api/_lib/x402/user-activity-analytics.js@@ -56,57 +56,62 @@ const round = (n, d = 2) => {export async function computeUserActivity(sql, period = DEFAULT_PERIOD) {const key = normalizePeriod(period);const interval = PERIODS[key];- const actor = ACTOR_KEY();// All aggregates run concurrently against the same logical "now()" window.// Each query is independently null-safe so a sparse table returns zeros.+ // The actor key is a trusted constant; the window interval is bound as a+ // parameter. Uses the explicit sql(text, params) form so the COALESCE actor+ // expression and FILTER clauses compose cleanly.const [activeRows, eventRows, featureRows, sessionRows] = await Promise.all([// DAU (last 24h) and WAU (last 7d) — distinct identifiable actors. These// two are fixed windows by definition regardless of the report period.- sql`- SELECT- COUNT(DISTINCT ${sql.unsafe(actor)})+ sql(+ `SELECT+ COUNT(DISTINCT ${ACTOR_KEY})FILTER (WHERE created_at >= now() - interval '24 hours') AS dau,- COUNT(DISTINCT ${sql.unsafe(actor)})+ COUNT(DISTINCT ${ACTOR_KEY})FILTER (WHERE created_at >= now() - interval '7 days') AS wauFROM usage_events- WHERE created_at >= now() - interval '7 days'- `,+ WHERE created_at >= now() - interval '7 days'`,+ ),// Volume + active-actor totals across the requested window.- sql`- SELECT- COUNT(*) AS total_events,- COUNT(*) FILTER (WHERE status <> 'ok') AS error_events,- COUNT(DISTINCT ${sql.unsafe(actor)}) AS active_actors+ sql(+ `SELECT+ COUNT(*) AS total_events,+ COUNT(*) FILTER (WHERE status <> 'ok') AS error_events,+ COUNT(DISTINCT ${ACTOR_KEY}) AS active_actorsFROM usage_events- WHERE created_at >= now() - ${interval}::interval- `,+ WHERE created_at >= now() - $1::interval`,+ [interval],+ ),// Top features by event volume over the window. For tool_call rows the// specific MCP tool is the feature; otherwise the coarse kind is.- sql`- SELECT+ sql(+ `SELECTCASE WHEN kind = 'tool_call' AND tool IS NOT NULL AND tool <> ''THEN tool ELSE kind END AS feature,COUNT(*) AS events,- COUNT(DISTINCT ${sql.unsafe(actor)}) AS actors+ COUNT(DISTINCT ${ACTOR_KEY}) AS actorsFROM usage_events- WHERE created_at >= now() - ${interval}::interval+ WHERE created_at >= now() - $1::intervalGROUP BY 1ORDER BY events DESC- LIMIT 10- `,+ LIMIT 10`,+ [interval],+ ),// Session-length distribution from web auth sessions active in the window.- // Duration = last_seen_at - created_at, clamped to non-negative.- sql`- SELECT+ // Duration = last_seen_at - created_at, only non-negative durations.+ sql(+ `SELECTCOUNT(*) AS count,AVG(EXTRACT(EPOCH FROM (last_seen_at - created_at))) AS avg_seconds,- PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (last_seen_at - created_at))) AS median_seconds,- PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (last_seen_at - created_at))) AS p90_seconds+ PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (last_seen_at - created_at))) AS median_seconds,+ PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (last_seen_at - created_at))) AS p90_secondsFROM sessions- WHERE last_seen_at >= now() - ${interval}::interval- AND last_seen_at >= created_at- `,+ WHERE last_seen_at >= now() - $1::interval+ AND last_seen_at >= created_at`,+ [interval],+ ),]);const active = activeRows[0] || {};diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.jsindex 99773e52c..47a323d08 100644--- a/api/x402/agent-reputation.js+++ b/api/x402/agent-reputation.js@@ -160,7 +160,7 @@ const BAZAAR = {}),};-export default paidEndpoint({+const singleEndpoint = paidEndpoint({route: ROUTE,method: 'GET',priceAtomics: priceFor('agent-reputation', '10000'),@@ -198,3 +198,193 @@ export default paidEndpoint({return loadAgentReputation(agentId);},});++// ── Sweep mode (POST) ────────────────────────────────────────────────────────+// A single $0.01 call returns scored reputation for the N most recently active+// three.ws agents instead of one. Built for fleet-level trust monitoring: a+// vetting agent (or our own autonomous loop) gets the live average trust score+// and the set of low-reputation agents (score < REPUTATION_FLAG_THRESHOLD)+// flagged for review, without paying per agent.++const SWEEP_DEFAULT_LIMIT = 20;+const SWEEP_MAX_LIMIT = 50;++const SWEEP_DESCRIPTION =+ 'three.ws Agent Reputation (Active Sweep) — POST {"mode":"sweep","limit":N} ' ++ 'to score the N most recently active three.ws agents in one call. Returns the ' ++ 'fleet average trust score (0..100) and the agents flagged for review ' ++ `(score < ${REPUTATION_FLAG_THRESHOLD}). Each score is synthesized from real ` ++ 'on-chain pump.fun agent-payments activity, distribute/buyback success history, ' ++ 'and signed Solana memo attestations — not a subjective rating. Use to monitor ' ++ 'counterparty trust across the platform before composing skills or routing payments.';++const SWEEP_INPUT_EXAMPLE = { mode: 'sweep', limit: 20 };++const SWEEP_INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ mode: { type: 'string', enum: ['sweep'], description: 'Must be "sweep".' },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: SWEEP_MAX_LIMIT,+ description: `Agents to sweep (default ${SWEEP_DEFAULT_LIMIT}, max ${SWEEP_MAX_LIMIT}).`,+ },+ },+};++const SWEEP_OUTPUT_EXAMPLE = {+ mode: 'sweep',+ count: 20,+ avg_score: 64,+ flagged_count: 3,+ flagged: [+ {+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ name: 'Newcomer',+ score: 12,+ reasons: ['no confirmed payments on record', 'no signed attestations'],+ },+ ],+ agents: [+ {+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ name: 'Helios',+ wallet_address: 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU',+ deployed_mints: 2,+ score: 88,+ flagged: false,+ reasons: [],+ breakdown: { payments: 40, distributions: 14, buybacks: 15, attestations: 19 },+ last_active_at: '2026-06-26T17:00:00Z',+ },+ ],+ swept_at: '2026-06-27T17:00:00Z',+};++const SWEEP_OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['mode', 'count', 'avg_score', 'flagged_count', 'agents'],+ properties: {+ mode: { type: 'string', enum: ['sweep'] },+ count: { type: 'integer', minimum: 0 },+ avg_score: { type: 'integer', minimum: 0, maximum: 100 },+ flagged_count: { type: 'integer', minimum: 0 },+ flagged: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid' },+ name: { type: ['string', 'null'] },+ score: { type: 'integer', minimum: 0, maximum: 100 },+ reasons: { type: 'array', items: { type: 'string' } },+ },+ },+ },+ agents: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ agent_id: { type: 'string', format: 'uuid' },+ name: { type: ['string', 'null'] },+ wallet_address: { type: ['string', 'null'] },+ deployed_mints: { type: 'integer', minimum: 0 },+ score: { type: 'integer', minimum: 0, maximum: 100 },+ flagged: { type: 'boolean' },+ reasons: { type: 'array', items: { type: 'string' } },+ breakdown: { type: 'object' },+ last_active_at: { type: ['string', 'null'] },+ },+ },+ },+ swept_at: { type: 'string', format: 'date-time' },+ },+};++const SWEEP_BAZAAR = {+ discoverable: true,+ info: {+ input: {+ type: 'http',+ method: 'POST',+ bodyType: 'json',+ body: SWEEP_INPUT_EXAMPLE,+ },+ output: { type: 'json', example: SWEEP_OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: SWEEP_INPUT_SCHEMA,+ outputSchema: SWEEP_OUTPUT_SCHEMA,+ }),+};++// Read + parse the JSON body off the raw request stream (same idiom as the+// other POST x402 endpoints — req.body is not pre-parsed in this runtime).+async function readJsonBody(req) {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ if (!chunks.length) return {};+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+}++const sweepEndpoint = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('agent-reputation', '10000'),+ networks: ['base', 'solana'],+ description: SWEEP_DESCRIPTION,+ bazaar: SWEEP_BAZAAR,+ service: withService({+ serviceName: 'three.ws Agent Reputation (Active Sweep)',+ tags: ['reputation', 'agent', 'solana', 'attestation', 'trust', 'monitoring'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ authHints: {+ oauth2: { requiredScope: 'read:agent-reputation', tokenType: 'Bearer' },+ siwx: true,+ },+ async handler({ req }) {+ let body;+ try {+ body = await readJsonBody(req);+ } catch {+ const err = new Error('request body must be valid JSON');+ err.status = 400;+ err.code = 'invalid_json';+ throw err;+ }+ if (body.mode !== 'sweep') {+ const err = new Error('mode must be "sweep"');+ err.status = 400;+ err.code = 'invalid_mode';+ throw err;+ }+ const limit = body.limit == null ? SWEEP_DEFAULT_LIMIT : Number(body.limit);+ if (!Number.isFinite(limit) || limit < 1) {+ const err = new Error('limit must be a positive integer');+ err.status = 400;+ err.code = 'invalid_limit';+ throw err;+ }+ return sweepAgentReputation({ limit: Math.min(SWEEP_MAX_LIMIT, Math.floor(limit)) });+ },+});++// Route by method so one path serves both the single-agent lookup (GET) and the+// active-agent sweep (POST). OPTIONS preflight is dispatched by the requested+// method so each mode advertises the correct Access-Control-Allow-Methods.+export default function agentReputationRouter(req, res) {+ const method = String(req.method || 'GET').toUpperCase();+ if (method === 'POST') return sweepEndpoint(req, res);+ if (method === 'OPTIONS') {+ const requested = String(req.headers['access-control-request-method'] || '').toUpperCase();+ return requested === 'POST' ? sweepEndpoint(req, res) : singleEndpoint(req, res);+ }+ return singleEndpoint(req, res);+}diff --git a/api/x402/analytics.js b/api/x402/analytics.jsindex 73fea457a..2a4826fb6 100644--- a/api/x402/analytics.js+++ b/api/x402/analytics.js@@ -12,12 +12,19 @@// path: if a backing table is missing in an environment the metric folds to a// real zero rather than a fabricated value.//-// Body: { report: "clubs", period: "1h" | "24h" | "7d" | "30d" | "all" }-// Response: { ok, report, period, generated_at, metrics, top_clubs }+// Reports:+// • clubs — Pole Club social economy (active stages, patrons, tips,+// cover charges, fastest-growing stages).+// Body: { report: "clubs", period: "1h"|"24h"|"7d"|"30d"|"all" }+// • agent_leaderboard — top agents by USDC spend over a trailing window, read+// live from the real agent-to-agent hire ledger+// (agent_hires + agent_identities). Surfaces high-value+// paying agents for partnership / outreach.+// Body: { report: "agent_leaderboard", limit?: 1-100, window_days?: 1-90 }//// The endpoint is consumed by the autonomous x402 loop (see-// autonomous-registry.js → 'analytics-club-social') to monitor social-economy-// health over time and surface growing clubs.+// autonomous-registry.js → 'analytics-club-social' for the clubs report and+// 'agent-spend-leaderboard' for the agent_leaderboard report).import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';@@ -39,7 +46,7 @@ const DESCRIPTION =// Supported reports + period windows. Both are strict whitelists — a value// outside the set is rejected BEFORE settlement (the buyer is never charged for// a report we can't produce).-const REPORTS = new Set(['clubs']);+const REPORTS = new Set(['clubs', 'agent_leaderboard']);// period → window in seconds (null = all-time, no time filter).const PERIODS = {@@ -56,7 +63,7 @@ const INPUT_SCHEMA = {properties: {report: {type: 'string',- enum: ['clubs'],+ enum: ['clubs', 'agent_leaderboard'],default: 'clubs',description: 'Which analytics report to return.',},@@ -64,7 +71,21 @@ const INPUT_SCHEMA = {type: 'string',enum: ['1h', '24h', '7d', '30d', 'all'],default: '24h',- description: 'Aggregation window.',+ description: 'Aggregation window (clubs report).',+ },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: 100,+ default: 10,+ description: 'Max ranked agents to return (agent_leaderboard report).',+ },+ window_days: {+ type: 'integer',+ minimum: 1,+ maximum: 90,+ default: 7,+ description: 'Trailing window in days (agent_leaderboard report).',},},};@@ -217,7 +238,7 @@ async function clubsReport(seconds) {count(*)::int as tipsfrom club_tips tleft join club_dancer_wallets w on w.dancer = t.dancer- where ${tipsWindow}+ where ${topWindow}group by t.dancer, w.display_nameorder by sum(t.amount_atomics) desc nulls last, t.dancer asclimit 5diff --git a/api/x402/bazaar-feed.js b/api/x402/bazaar-feed.jsindex 7780eb1dd..d77ed9e7d 100644--- a/api/x402/bazaar-feed.js+++ b/api/x402/bazaar-feed.js@@ -1,25 +1,26 @@// POST /api/x402/bazaar-feed//-// Bazaar Price Trend Monitor — $0.001 USDC per call on Solana or Base.+// Bazaar Feed — $0.001 USDC per call on Solana or Base. One endpoint, two+// live views over the x402 service marketplace selected by the `filter` field://-// The x402 Bazaar is the agent-service marketplace three.ws transacts on. Every-// 6 hours the `x402-pricing-tracker` autonomous-loop pipeline pays a real-// $0.001 call to the Bazaar MCP server and records each tracked service's live-// cheapest price into x402_service_price_history (an append-only time series).-// This endpoint reads that series and turns it into a market-sentiment signal:-// over the requested window it computes, per service, the price move from the-// first to the last observation, then classifies each as trending up / down /-// stable and derives the net price pressure across the whole bazaar.+// • filter "new" / "active" — New-Listing Feed (USE-059)+// Returns the newest service listings from the canonical bazaar_service_index+// registry the daily catalog-refresh pipeline maintains: id, name, price,+// networks, tags and first_seen, plus a category rollup and a listing-velocity+// signal (spike / active / quiet). Poll it to keep a local catalog warm and to+// catch fresh agent marketing activity the moment new services appear.+// Body: { filter: "new" | "active", limit?: 1..50 }//-// Body: { filter: "price_trends", period: "24h" | "7d" | "1h" | "30m" }-// Response: { filter, period, trending_up:[], trending_down:[], stable_count,-// total_tracked, net_pressure, avg_change_pct, signal, headline,-// confidence, ts }+// • filter "price_trends" — Price Trend Monitor (USE-060)+// Reads the x402_service_price_history time series (populated by the+// x402-pricing-tracker pipeline) and, over the requested window, classifies+// each tracked service as trending up / down / stable and derives the net+// price pressure as a bullish / bearish / neutral signal.+// Body: { filter: "price_trends", period: "24h" | "7d" | "1h" | "30m" }//-// Data is live: derived from the platform's own x402_service_price_history.-// No mock path — when the tracker has not yet accumulated two observations for-// any service in the window, the trend lists are empty and the signal is a-// genuine "neutral / no movement", not fabricated data.+// Data is live in both modes — derived from the platform's own bazaar registry+// and price-history tables. No mock path: a cold install with no data yet returns+// a genuine empty feed / neutral signal, never fabricated rows.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';diff --git a/api/x402/club-cover.js b/api/x402/club-cover.jsindex bbc0df4d7..4e7b566db 100644--- a/api/x402/club-cover.js+++ b/api/x402/club-cover.js@@ -175,3 +175,148 @@ const doorEndpoint = paidEndpoint({};},});++// ── Membership Snapshot (POST) ──────────────────────────────────────────────+//+// The same $0.01 cover charge, but instead of issuing a door pass it sells a+// growth/churn snapshot of the club's membership. Pay, and you get back the+// live member counts read off the club ledger:+// { member_count, active_last_7d, new_this_week } plus a classified signal+// (growing / stable / churning / empty) and a headline.+//+// This is the read the x402 autonomous loop pays daily to monitor the+// three_holders club for growth or churn (registry: club-membership-snapshot).+// POST body: { club?: string (default "three_holders"), mode?: "snapshot" }.++const SNAPSHOT_INPUT_EXAMPLE = { club: 'three_holders', mode: 'snapshot' };++const SNAPSHOT_INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ club: { type: 'string', description: 'Club label to snapshot.', default: 'three_holders' },+ mode: { type: 'string', enum: ['snapshot'], default: 'snapshot' },+ },+};++const SNAPSHOT_OUTPUT_EXAMPLE = {+ ok: true,+ club: 'three_holders',+ mode: 'snapshot',+ member_count: 128,+ active_last_7d: 34,+ new_this_week: 9,+ growth_rate: 0.0703,+ active_rate: 0.2656,+ signal: 'growing',+ headline: 'Club growing — 9 new members this week (7% of the base).',+ confidence: 0.95,+ snapshot_at: '2026-06-28T18:42:09.000Z',+ payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',+ network: 'solana',+ amountAtomics: '10000',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+};++const SNAPSHOT_OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'club', 'mode', 'member_count', 'active_last_7d', 'new_this_week', 'signal'],+ properties: {+ ok: { type: 'boolean', const: true },+ club: { type: 'string' },+ mode: { type: 'string', const: 'snapshot' },+ member_count: { type: 'integer', minimum: 0, description: 'Distinct wallets that ever paid into the club.' },+ active_last_7d: { type: 'integer', minimum: 0, description: 'Distinct wallets active in the last 7 days.' },+ new_this_week: { type: 'integer', minimum: 0, description: 'Distinct wallets whose first payment landed in the last 7 days.' },+ growth_rate: { type: 'number', description: 'new_this_week / member_count.' },+ active_rate: { type: 'number', description: 'active_last_7d / member_count.' },+ signal: { type: 'string', enum: ['growing', 'stable', 'churning', 'empty'] },+ headline: { type: 'string' },+ confidence: { type: 'number', minimum: 0, maximum: 1 },+ snapshot_at: { type: 'string', format: 'date-time' },+ payer: { type: ['string', 'null'] },+ network: { type: ['string', 'null'] },+ amountAtomics: { type: ['string', 'null'] },+ asset: { type: ['string', 'null'] },+ },+};++const SNAPSHOT_BAZAAR = {+ // Not separately discoverable — the GET door is the catalog entry for this+ // route; the POST snapshot is the same resource sold a second way, so it+ // must not register a duplicate route in the bazaar census.+ discoverable: false,+ info: {+ input: { type: 'json', method: 'POST', example: SNAPSHOT_INPUT_EXAMPLE },+ output: { type: 'json', example: SNAPSHOT_OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: SNAPSHOT_INPUT_SCHEMA,+ outputSchema: SNAPSHOT_OUTPUT_SCHEMA,+ }),+};++const snapshotEndpoint = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('club-cover', '10000'), // $0.01 USDC — same cover charge+ networks: ['solana'],+ description:+ 'three.ws Pole Club — pay $0.01 USDC for a live membership snapshot of the ' ++ 'club: all-time member count, members active in the last 7 days, and members ' ++ 'new this week, with a growth/churn signal. Pay-per-call in USDC on Solana mainnet.',+ bazaar: SNAPSHOT_BAZAAR,+ service: withService({+ serviceName: 'three.ws Club Membership',+ tags: ['3d', 'club', 'membership', 'analytics', 'growth', 'reputation'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ async handler({ req, requirement, payer, bypass }) {+ let club = 'three_holders';+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ if (raw) {+ const body = JSON.parse(raw);+ if (body && typeof body.club === 'string' && body.club.trim()) {+ club = body.club.trim().slice(0, 64);+ }+ }+ } catch {+ /* default club — a malformed body just snapshots the default ledger */+ }++ // Throws 503 on a ledger error → no settlement, caller not charged.+ const snap = await membershipSnapshot(club);++ return {+ ok: true,+ mode: 'snapshot',+ ...snap,+ snapshot_at: new Date().toISOString(),+ payer: payer ?? (bypass ? bypass.callerId : null),+ network: requirement?.network ?? null,+ amountAtomics: requirement?.amount ?? null,+ asset: requirement?.asset ?? null,+ ...(bypass ? { bypass: bypass.reason } : {}),+ };+ },+});++// One route, two methods. paidEndpoint is single-method, so we dispatch here:+// GET/HEAD → the door pass (unchanged), POST → the membership snapshot. An+// OPTIONS preflight is routed to whichever endpoint matches the requested+// method so the CORS allow-list advertises the right verb.+export default function clubCover(req, res) {+ const method = String(req.method || '').toUpperCase();+ if (method === 'POST') return snapshotEndpoint(req, res);+ if (method === 'OPTIONS') {+ const want = String(req.headers['access-control-request-method'] || '').toUpperCase();+ if (want === 'POST') return snapshotEndpoint(req, res);+ }+ return doorEndpoint(req, res);+}