Skip to content

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.

feat: add user activity analytics endpoint and related utilities

nirholas2fa132f7d793
diff --git a/api/_lib/club/cover-pass.js b/api/_lib/club/cover-pass.js
index beeb6cab1..296810c9a 100644
--- a/api/_lib/club/cover-pass.js
+++ b/api/_lib/club/cover-pass.js
@@ -60,6 +60,109 @@ export function tierFor(visits) {
return 'newcomer';
}
+// ── Membership snapshot ─────────────────────────────────────────────────────
+//
+// The cover-charge endpoint also sells a *membership snapshot* of the club: a
+// paid read of who actually shows up. There is a single club ledger (club_tips —
+// every settled door/dance payment writes one row), so the snapshot is computed
+// over that ledger and the requested `club` label (e.g. "three_holders") is
+// carried through for the caller's bookkeeping. Three real, growth/churn-
+// actionable counts come straight out of the ledger:
+//
+// member_count — distinct wallets that have ever paid into the club (the
+// all-time membership base).
+// active_last_7d — distinct wallets with a settled payment in the last 7 days
+// (this week's active members).
+// new_this_week — distinct wallets whose FIRST-EVER payment landed in the
+// last 7 days (genuinely new members, not returning ones).
+//
+// One round-trip: group the ledger by wallet to get each wallet's first/last
+// activity, then tally over those per-wallet extents.
+//
+// Fails HARD (throws 503) on a query error so the paid endpoint never charges
+// for a snapshot it couldn't actually compute — a genuinely empty club returns
+// all zeros, which is a real answer and is fine to bill.
+export async function membershipSnapshot(club = 'three_holders') {
+ let row;
+ try {
+ const rows = await sql`
+ with firsts as (
+ select
+ lower(payer) as wallet,
+ min(created_at) as first_seen,
+ max(created_at) as last_seen
+ from club_tips
+ where payer is not null and payer <> ''
+ group by lower(payer)
+ )
+ select
+ count(*)::int as member_count,
+ count(*) filter (where last_seen >= now() - interval '7 days')::int as active_last_7d,
+ count(*) filter (where first_seen >= now() - interval '7 days')::int as new_this_week
+ from firsts
+ `;
+ row = rows?.[0] || {};
+ } catch (err) {
+ throw Object.assign(
+ new Error(`club membership ledger is temporarily unavailable: ${err?.message || err}`),
+ { status: 503, code: 'membership_unavailable' },
+ );
+ }
+ return classifyMembership({
+ club,
+ member_count: Number(row.member_count) || 0,
+ active_last_7d: Number(row.active_last_7d) || 0,
+ new_this_week: Number(row.new_this_week) || 0,
+ });
+}
+
+// Turn the three raw counts into a classified growth/churn signal. Pure — the
+// snapshot endpoint embeds the result in the paid response and the autonomous
+// loop's extractSignal lifts the same fields, so writer and reader never drift.
+//
+// @param {{ club?: string, member_count: number, active_last_7d: number, new_this_week: number }} s
+export function classifyMembership(s) {
+ const member_count = Math.max(0, Math.round(Number(s?.member_count) || 0));
+ const active_last_7d = Math.max(0, Math.round(Number(s?.active_last_7d) || 0));
+ const new_this_week = Math.max(0, Math.round(Number(s?.new_this_week) || 0));
+
+ // Share of the base that is new this week / active this week.
+ const growth_rate = member_count > 0 ? new_this_week / member_count : 0;
+ const active_rate = member_count > 0 ? active_last_7d / member_count : 0;
+
+ let signal, headline;
+ if (member_count === 0) {
+ signal = 'empty';
+ headline = 'No club members yet — the door has seen no settled activity.';
+ } else if (new_this_week >= 1 && growth_rate >= 0.1) {
+ signal = 'growing';
+ headline = `Club growing — ${new_this_week} new member${new_this_week === 1 ? '' : 's'} this week (${Math.round(growth_rate * 100)}% of the base).`;
+ } else if (active_rate < 0.1) {
+ signal = 'churning';
+ headline = `Club churning — only ${active_last_7d} of ${member_count} members active in the last 7 days.`;
+ } else {
+ signal = 'stable';
+ headline = `Club stable — ${active_last_7d} of ${member_count} members active this week, ${new_this_week} new.`;
+ }
+
+ // Confidence grows with the membership base: a 1-member club is a weak
+ // read, a 50+ member club is a confident one. Clamped to [0.3, 0.95].
+ const confidence =
+ member_count === 0 ? 0.3 : Math.min(0.95, Math.max(0.3, member_count / 50));
+
+ return {
+ club: String(s?.club || 'three_holders'),
+ member_count,
+ active_last_7d,
+ new_this_week,
+ growth_rate: Number(growth_rate.toFixed(4)),
+ active_rate: Number(active_rate.toFixed(4)),
+ signal,
+ headline,
+ confidence: Number(confidence.toFixed(2)),
+ };
+}
+
/**
* Run the bouncer over a paid wallet and return its entry pass. The payment is
* assumed already settled on-chain by the caller — this only decides admission
diff --git a/api/_lib/trust/solana-bouncer.js b/api/_lib/trust/solana-bouncer.js
index b91df562d..5919c3c09 100644
--- a/api/_lib/trust/solana-bouncer.js
+++ b/api/_lib/trust/solana-bouncer.js
@@ -175,6 +175,169 @@ function attestationTotal(rep) {
return (a.feedback_count || 0) + (a.validation_count || 0);
}
+// Agents scoring below this are flagged for trust review by the active-agent
+// sweep (api/x402/agent-reputation POST mode → x402_autonomous_log).
+export const REPUTATION_FLAG_THRESHOLD = 30;
+
+/**
+ * Collapse a reputation snapshot into a single 0..100 trust score, derived
+ * purely from settled on-chain behavior. Unproven / inactive agents score low
+ * (and are flagged); agents with real paid demand, honored distribution and
+ * buyback obligations, and signed attestations score high. Deterministic — the
+ * same snapshot always yields the same score, so it is safe to unit-test and to
+ * compare across sweeps.
+ *
+ * Weights (max 100): payments 45 (volume 25 + distinct payers 10 + reliability
+ * 10), distributions 15, buybacks 15, attestations 25.
+ *
+ * @param {object} rep snapshot from loadAgentReputation
+ * @returns {{score:number, flagged:boolean, reasons:string[], breakdown:object}}
+ */
+export function scoreAgentReputation(rep) {
+ const p = (rep && rep.payments) || {};
+ const d = (rep && rep.distributions) || {};
+ const b = (rep && rep.buybacks) || {};
+ const a = (rep && rep.attestations) || {};
+
+ const confirmed = Math.max(0, Number(p.confirmed_count) || 0);
+ const payers = Math.max(0, Number(p.distinct_payers) || 0);
+ const failureRate = Math.min(1, Math.max(0, Number(p.failure_rate) || 0));
+
+ // Payments — proven demand + reliability (45 pts).
+ const volumePts = (Math.min(confirmed, 50) / 50) * 25;
+ const payerPts = (Math.min(payers, 10) / 10) * 10;
+ const reliabilityPts = confirmed > 0 ? (1 - failureRate) * 10 : 0;
+
+ // Distributions — honored payout obligations (15 pts). Neutral when none ran.
+ const distTotal = (Number(d.confirmed) || 0) + (Number(d.failed) || 0);
+ const distPts = distTotal > 0 ? (Number(d.success_rate) || 0) * 15 : 0;
+
+ // Buybacks — follow-through on burn commitments (15 pts).
+ const buyConfirmed = Number(b.confirmed) || 0;
+ const buyTotal = buyConfirmed + (Number(b.failed) || 0);
+ const buyPts = buyTotal > 0 ? (buyConfirmed / buyTotal) * 15 : 0;
+
+ // Attestations — signed peer/validator vouches (25 pts).
+ const attTotal = (Number(a.feedback_count) || 0) + (Number(a.validation_count) || 0);
+ const attPts = (Math.min(attTotal, 10) / 10) * 25;
+
+ const score = Math.round(
+ Math.min(100, Math.max(0, volumePts + payerPts + reliabilityPts + distPts + buyPts + attPts)),
+ );
+
+ const reasons = [];
+ if (confirmed === 0) reasons.push('no confirmed payments on record');
+ if (attTotal === 0) reasons.push('no signed attestations');
+ if (confirmed > 0 && failureRate > 0.2) {
+ reasons.push(`elevated payment failure rate ${(failureRate * 100).toFixed(0)}%`);
+ }
+ if (distTotal > 0 && (Number(d.success_rate) || 0) < 0.5) {
+ reasons.push('distribution success rate below 50%');
+ }
+
+ return {
+ score,
+ flagged: score < REPUTATION_FLAG_THRESHOLD,
+ reasons,
+ breakdown: {
+ payments: Math.round(volumePts + payerPts + reliabilityPts),
+ distributions: Math.round(distPts),
+ buybacks: Math.round(buyPts),
+ attestations: Math.round(attPts),
+ },
+ };
+}
+
+/**
+ * The most recently active three.ws agents — ordered by latest settled payment,
+ * falling back to mint creation for agents that deployed a token but have not
+ * been paid yet. Only agents with at least one pump_agent_mints row qualify
+ * (an agent with no token has no Solana track record to score).
+ *
+ * @param {number} limit rows to return (already clamped by the caller)
+ * @returns {Promise<Array<{id:string,name:string,wallet_address:string,last_active_at:string|null}>>}
+ */
+async function listRecentlyActiveAgents(limit) {
+ const rows = await sql`
+ select ai.id, ai.name, ai.wallet_address,
+ max(coalesce(p.confirmed_at, p.created_at, m.created_at)) as last_active_at
+ from agent_identities ai
+ join pump_agent_mints m on m.agent_id = ai.id
+ left join pump_agent_payments p on p.mint_id = m.id
+ where ai.deleted_at is null
+ group by ai.id, ai.name, ai.wallet_address
+ order by last_active_at desc nulls last
+ limit ${limit}
+ `;
+ return rows.map((r) => ({
+ id: r.id,
+ name: r.name,
+ wallet_address: r.wallet_address || null,
+ last_active_at: r.last_active_at ? new Date(r.last_active_at).toISOString() : null,
+ }));
+}
+
+/**
+ * Sweep the most recently active agents and score each one's Solana behavioral
+ * reputation. Powers the autonomous platform-trust monitor: it returns the live
+ * average trust score and flags low-reputation agents (score <
+ * REPUTATION_FLAG_THRESHOLD) for review. The reads are injectable so the
+ * aggregate logic is unit-testable without a database.
+ *
+ * @param {object} [opts]
+ * @param {number} [opts.limit=20] agents to sweep (clamped 1..50)
+ * @param {(id:string)=>Promise<object>} [opts.read] reputation reader (override in tests)
+ * @param {(limit:number)=>Promise<Array>} [opts.list] active-agent lister (override in tests)
+ * @returns {Promise<object>} aggregate sweep result
+ */
+export async function sweepAgentReputation({
+ limit = 20,
+ read = loadAgentReputation,
+ list = listRecentlyActiveAgents,
+} = {}) {
+ const n = Math.min(50, Math.max(1, Math.floor(Number(limit) || 20)));
+ const active = await list(n);
+
+ const scored = await Promise.all(
+ active.map(async (row) => {
+ const rep = await read(row.id);
+ const s = scoreAgentReputation(rep);
+ return {
+ agent_id: rep.agent_id || row.id,
+ name: rep.name ?? row.name ?? null,
+ wallet_address: rep.wallet_address || row.wallet_address || null,
+ deployed_mints: rep.deployed_mints || 0,
+ score: s.score,
+ flagged: s.flagged,
+ reasons: s.reasons,
+ breakdown: s.breakdown,
+ last_active_at: row.last_active_at || null,
+ };
+ }),
+ );
+
+ const count = scored.length;
+ const flagged = scored.filter((agent) => agent.flagged);
+ const avgScore = count
+ ? Math.round(scored.reduce((sum, agent) => sum + agent.score, 0) / count)
+ : 0;
+
+ return {
+ mode: 'sweep',
+ count,
+ avg_score: avgScore,
+ flagged_count: flagged.length,
+ flagged: flagged.map((agent) => ({
+ agent_id: agent.agent_id,
+ name: agent.name,
+ score: agent.score,
+ reasons: agent.reasons,
+ })),
+ agents: scored,
+ swept_at: new Date().toISOString(),
+ };
+}
+
/**
* Door tier from Solana behavioral reputation. Mirrors club/cover-pass.tierFor
* but reads the whole platform's record instead of club_tips alone. Never
diff --git a/api/_lib/x402/agent-leaderboard-store.js b/api/_lib/x402/agent-leaderboard-store.js
new file mode 100644
index 000000000..1c6373c89
--- /dev/null
+++ b/api/_lib/x402/agent-leaderboard-store.js
@@ -0,0 +1,130 @@
+// api/_lib/x402/agent-leaderboard-store.js
+//
+// Value store for the Agent x402 Spend Leaderboard (USE-043).
+//
+// The x402 autonomous loop pays /api/x402/analytics (report=agent_leaderboard)
+// on a schedule (registry entry `agent-spend-leaderboard`) and snapshots the
+// top agents by x402 spend this week. This module owns the snapshot table so the
+// writer (registry storeValue) and any reader agree on shape, mirroring the
+// three-signal-store.js idiom.
+//
+// Consumer: partnership-outreach tooling reads the latest snapshot to find the
+// highest-value paying agents (top_agent_id + the full ranking) to prioritize
+// for outreach — the actionable signal this pipeline extracts.
+
+function num(v) {
+ const n = typeof v === 'string' ? parseFloat(v) : v;
+ return Number.isFinite(n) ? n : null;
+}
+
+/**
+ * Normalize a /api/x402/analytics (agent_leaderboard) response into the signal
+ * shape stored in x402_autonomous_log.signal_data AND used to drive the snapshot
+ * insert. Shared by the registry's extractSignal and storeValue so both agree.
+ *
+ * @param {object|null} r raw analytics response
+ * @returns {{
+ * topic: string, report: string, window_days: number|null,
+ * agent_count: number, total_spend_usdc: number|null,
+ * top_agent_id: string|null, top_agent_name: string|null,
+ * top_agent_spend_usdc: number|null, signal: string, headline: string|null,
+ * confidence: number, leaderboard: Array<object>
+ * }}
+ */
+export function classifyLeaderboard(r) {
+ const o = r || {};
+ const rows = Array.isArray(o.leaderboard) ? o.leaderboard : [];
+ const top = rows[0] || null;
+ const totalSpend = num(o.total_spend_usdc);
+ const topSpend = top ? num(top.spend_usdc) : null;
+ return {
+ topic: 'agent_leaderboard',
+ report: 'agent_leaderboard',
+ window_days: Number.isFinite(o.window_days) ? o.window_days : 7,
+ agent_count: rows.length,
+ total_spend_usdc: totalSpend,
+ top_agent_id: top ? top.agent_id || null : null,
+ top_agent_name: top ? top.name || null : null,
+ top_agent_spend_usdc: topSpend,
+ // A populated leaderboard with real spend is a "live" intel signal; an
+ // empty week (no paid hires) is "quiet". Confidence scales with breadth.
+ signal: rows.length > 0 ? 'live' : 'quiet',
+ headline: top
+ ? `${top.name || 'Agent'} leads x402 spend at $${(topSpend ?? 0).toFixed(2)} (${rows.length} active)`
+ : 'No agent x402 spend recorded this week',
+ confidence: Math.min(0.95, 0.5 + rows.length * 0.045),
+ leaderboard: rows,
+ };
+}
+
+// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).
+let _schemaReady = false;
+
+/**
+ * Create the snapshot table if absent. Idempotent; safe to call on every write.
+ * @param {Function} sql tagged-template sql client (from api/_lib/db.js)
+ */
+export async function ensureLeaderboardSchema(sql) {
+ if (_schemaReady || !sql) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS agent_spend_leaderboard_snapshots (
+ id bigserial PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ run_id uuid,
+ window_days int,
+ agent_count int,
+ total_spend_usdc double precision,
+ top_agent_id uuid,
+ top_agent_name text,
+ top_agent_spend_usdc double precision,
+ leaderboard jsonb NOT NULL DEFAULT '[]'::jsonb,
+ source text NOT NULL DEFAULT 'x402-autonomous'
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS agent_spend_leaderboard_snapshots_ts_desc
+ ON agent_spend_leaderboard_snapshots (ts DESC)
+ `;
+ _schemaReady = true;
+}
+
+/**
+ * Append one leaderboard snapshot.
+ * @param {Function} sql
+ * @param {object} v a classifyLeaderboard() result
+ * @param {{ runId?: string, source?: string }} [meta]
+ */
+export async function insertLeaderboardSnapshot(sql, v, meta = {}) {
+ if (!sql || !v) return;
+ await ensureLeaderboardSchema(sql);
+ // top_agent_id is a uuid column — never insert a non-uuid; null it if absent.
+ const topId = typeof v.top_agent_id === 'string' && v.top_agent_id ? v.top_agent_id : null;
+ await sql`
+ INSERT INTO agent_spend_leaderboard_snapshots
+ (ts, run_id, window_days, agent_count, total_spend_usdc,
+ top_agent_id, top_agent_name, top_agent_spend_usdc, leaderboard, source)
+ VALUES
+ (now(), ${meta.runId || null}, ${v.window_days ?? 7}, ${v.agent_count ?? 0},
+ ${v.total_spend_usdc}, ${topId}, ${v.top_agent_name},
+ ${v.top_agent_spend_usdc},
+ ${JSON.stringify(v.leaderboard || [])}::jsonb,
+ ${meta.source || 'x402-autonomous'})
+ `;
+}
+
+/**
+ * Latest leaderboard snapshot, or null when none exist. Read by partnership
+ * outreach tooling to prioritize the highest-value paying agents.
+ * @param {Function} sql
+ */
+export async function getLatestLeaderboard(sql) {
+ if (!sql) return null;
+ const rows = await sql`
+ SELECT ts, run_id, window_days, agent_count, total_spend_usdc,
+ top_agent_id, top_agent_name, top_agent_spend_usdc, leaderboard
+ FROM agent_spend_leaderboard_snapshots
+ ORDER BY ts DESC
+ LIMIT 1
+ `;
+ return rows[0] || null;
+}
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index d7d423ac8..70d595b62 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -451,6 +451,47 @@ const SELF_ENDPOINTS = [
extractSignal: (r) => ({ verdict: r?.verdict, confidence: r?.confidence, sources: r?.sources }),
},
+ // ── Bazaar Price Trend Monitor (USE-060) ──────────────────────────────────
+ // Pays $0.001 USDC to /api/x402/bazaar-feed for a 24h read of price movement
+ // across the x402 service marketplace, derived from the platform's own
+ // x402_service_price_history time series (populated by the x402-pricing-tracker
+ // pipeline). The endpoint classifies each tracked service as trending up /
+ // down / stable over the window and derives the net price pressure as a
+ // bullish / bearish / neutral signal. As an `oracle` entry the latest verdict
+ // dedups into oracle_intel_signals (topic 'bazaar_price_trends') so the sniper
+ // gate can fold marketplace cost sentiment into conviction. extractSignal lifts
+ // the directional signal + the mover counts into x402_autonomous_log.signal_data.
+ // Cooldown 900s (15 min) → matches the price feed's volatility without re-reading
+ // the same window every tick; spend ≈ $0.10/day, well under the loop's daily cap.
+ {
+ id: 'bazaar-price-trends',
+ name: 'Bazaar Price Trend Monitor',
+ path: '/api/x402/bazaar-feed',
+ method: 'POST',
+ body: { filter: 'price_trends', period: '24h' },
+ cooldown_s: 900, // 15 min — price-pressure signal volatility
+ priority: 82,
+ pipeline: 'oracle',
+ enabled: true,
+ extractSignal: (r) => ({
+ topic: 'bazaar_price_trends',
+ signal: r?.signal || null,
+ headline: r?.headline || null,
+ confidence: r?.confidence ?? null,
+ net_pressure: r?.net_pressure ?? null,
+ avg_change_pct: r?.avg_change_pct ?? null,
+ trending_up: Array.isArray(r?.trending_up)
+ ? r.trending_up.map((s) => ({ service_key: s.service_key, pct_change: s.pct_change }))
+ : [],
+ trending_down: Array.isArray(r?.trending_down)
+ ? r.trending_down.map((s) => ({ service_key: s.service_key, pct_change: s.pct_change }))
+ : [],
+ stable_count: r?.stable_count ?? 0,
+ total_tracked: r?.total_tracked ?? 0,
+ period: r?.period || '24h',
+ }),
+ },
+
// ── Volume / Activity Feed (keep the live feed alive) ─────────────────────
{
id: 'dance-tip-vol-1',
diff --git a/api/_lib/x402/revenue-analytics.js b/api/_lib/x402/revenue-analytics.js
new file mode 100644
index 000000000..f6ab93487
--- /dev/null
+++ b/api/_lib/x402/revenue-analytics.js
@@ -0,0 +1,185 @@
+// api/_lib/x402/revenue-analytics.js
+//
+// Revenue Dashboard Aggregation — the data layer behind POST /api/x402/analytics
+// ({ report: "revenue", period }). Builds a real, per-endpoint revenue report
+// from the platform's own settled-payment ledger; no estimates of demand, only
+// money that actually moved on-chain.
+//
+// Sources (both real, both already populated by live traffic):
+// • x402_audit_log (event_type = 'payment_settled') — every settled x402 call
+// with its route + atomic USDC amount. This is gross revenue, per endpoint.
+// • cross_chain_cost_comparison — the rolling on-chain settlement cost in USD
+// the cross-chain-cost pipeline measures hourly. Multiplied by the settled
+// payment count it yields the settlement fee the platform actually bears, so
+// net = gross − settlement fees is grounded in measured gas, not a guess.
+//
+// The report shape is consumed by:
+// • POST /api/x402/analytics — the paid x402 endpoint that returns it.
+// • the `platform-revenue-analytics` autonomous-loop entry, whose extractSignal
+// lifts { total_usd, top_endpoint, fee_collected } into oracle_intel_signals
+// (topic 'platform-revenue') so the sniper gate sees live platform health.
+
+import { sql } from '../db.js';
+import { atomicsToUsdc } from '../agent-paid-services.js';
+
+// Supported report periods → lookback in hours (null = all-time).
+const PERIOD_HOURS = {
+ '1h': 1,
+ '6h': 6,
+ '24h': 24,
+ '7d': 24 * 7,
+ '30d': 24 * 30,
+ all: null,
+};
+
+/**
+ * Normalize a requested period string to a canonical key + ISO `since` bound.
+ * Unknown / malformed inputs fall back to 24h (the dashboard default).
+ * @param {string} raw
+ * @returns {{ key: string, hours: number|null, since: string|null }}
+ */
+export function resolvePeriod(raw) {
+ const key = String(raw || '24h').toLowerCase().trim();
+ const hours = key in PERIOD_HOURS ? PERIOD_HOURS[key] : 24;
+ const canonical = key in PERIOD_HOURS ? key : '24h';
+ const since = hours == null ? null : new Date(Date.now() - hours * 3600_000).toISOString();
+ return { key: canonical, hours, since };
+}
+
+// 6-decimal USD string for money fields (matches the audit-log dashboard format).
+function usd(n) {
+ return (Number(n) || 0).toFixed(6);
+}
+
+/**
+ * Mean per-settlement on-chain cost (USD) over the window, from the cross-chain
+ * cost pipeline's measurements. Prefers the windowed average and falls back to
+ * the latest snapshot; returns { perTxUsd, source } where source documents which
+ * measurement was used (or 'none' when the pipeline has no data yet).
+ *
+ * @param {number|null} windowHours lookback for the average (null → all-time)
+ */
+async function settlementCostPerTx(windowHours) {
+ try {
+ const rows = windowHours == null
+ ? await sql`
+ SELECT avg(solana_gas_usd) FILTER (WHERE solana_gas_usd IS NOT NULL) AS avg_usd,
+ count(*) FILTER (WHERE solana_gas_usd IS NOT NULL)::int AS samples
+ FROM cross_chain_cost_comparison`
+ : await sql`
+ SELECT avg(solana_gas_usd) FILTER (WHERE solana_gas_usd IS NOT NULL) AS avg_usd,
+ count(*) FILTER (WHERE solana_gas_usd IS NOT NULL)::int AS samples
+ FROM cross_chain_cost_comparison
+ WHERE checked_at >= now() - (${windowHours} || ' hours')::interval`;
+ const avg = rows?.[0]?.avg_usd;
+ if (avg != null && Number(avg) > 0) {
+ return { perTxUsd: Number(avg), source: 'window_avg', samples: rows[0].samples || 0 };
+ }
+ // Window empty — fall back to the most recent measured settlement cost.
+ const latest = await sql`
+ SELECT solana_gas_usd FROM cross_chain_cost_comparison
+ WHERE solana_gas_usd IS NOT NULL
+ ORDER BY checked_at DESC LIMIT 1`;
+ const last = latest?.[0]?.solana_gas_usd;
+ if (last != null && Number(last) > 0) {
+ return { perTxUsd: Number(last), source: 'latest_snapshot', samples: 1 };
+ }
+ } catch (err) {
+ // Table may not exist in a fresh env — treat as "no cost data".
+ if (!err?.message?.includes('does not exist')) throw err;
+ }
+ return { perTxUsd: 0, source: 'none', samples: 0 };
+}
+
+/**
+ * Build the revenue report for a period.
+ *
+ * @param {object} opts
+ * @param {string} [opts.period='24h']
+ * @returns {Promise<object>} the full report (see the endpoint's OUTPUT_SCHEMA)
+ */
+export async function buildRevenueReport({ period = '24h' } = {}) {
+ const { key, hours, since } = resolvePeriod(period);
+
+ // ── Gross totals over the window (settled payments only). ────────────────
+ const [totals] = await sql`
+ SELECT
+ count(*)::int AS payments,
+ count(DISTINCT payer)::int AS unique_payers,
+ coalesce(sum(
+ CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END
+ ), 0) AS gross_atomics
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
+ `;
+ const payments = totals?.payments || 0;
+ const grossAtomics = Number(totals?.gross_atomics || 0);
+ const grossUsd = atomicsToUsdc(grossAtomics);
+
+ // ── Per-endpoint earnings, highest gross first. ──────────────────────────
+ const routeRows = await sql`
+ SELECT
+ route,
+ count(*)::int AS count,
+ coalesce(sum(
+ CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END
+ ), 0) AS gross_atomics
+ FROM x402_audit_log
+ WHERE event_type = 'payment_settled'
+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
+ GROUP BY route
+ ORDER BY gross_atomics DESC, count DESC
+ `;
+ const byEndpoint = routeRows.map((r) => {
+ const g = atomicsToUsdc(Number(r.gross_atomics || 0));
+ return {
+ endpoint: r.route || 'unknown',
+ count: r.count,
+ gross_usd: usd(g),
+ share: grossUsd > 0 ? Number((g / grossUsd).toFixed(4)) : 0,
+ };
+ });
+ const topEndpoint = byEndpoint[0]
+ ? { endpoint: byEndpoint[0].endpoint, count: byEndpoint[0].count, gross_usd: byEndpoint[0].gross_usd }
+ : null;
+
+ // ── Settlement fee split: measured on-chain cost × settled payment count. ─
+ const cost = await settlementCostPerTx(hours);
+ const settlementFeeUsd = cost.perTxUsd * payments;
+ const netPlatformUsd = Math.max(0, grossUsd - settlementFeeUsd);
+ const effectiveFeeRate = grossUsd > 0 ? Number((settlementFeeUsd / grossUsd).toFixed(6)) : 0;
+
+ const [failed] = await sql`
+ SELECT count(*)::int AS n
+ FROM x402_audit_log
+ WHERE event_type = 'payment_failed'
+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)
+ `;
+
+ return {
+ report: 'revenue',
+ period: key,
+ since,
+ generated_at: new Date().toISOString(),
+ totals: {
+ gross_usd: usd(grossUsd),
+ net_platform_usd: usd(netPlatformUsd),
+ settlement_fee_usd: usd(settlementFeeUsd),
+ total_payments: payments,
+ failed_payments: failed?.n || 0,
+ unique_payers: totals?.unique_payers || 0,
+ avg_payment_usd: usd(payments > 0 ? grossUsd / payments : 0),
+ },
+ fee_splits: {
+ gross_usd: usd(grossUsd),
+ settlement_fee_usd: usd(settlementFeeUsd),
+ net_platform_usd: usd(netPlatformUsd),
+ effective_fee_rate: effectiveFeeRate,
+ fee_per_settlement_usd: usd(cost.perTxUsd),
+ fee_source: cost.source,
+ },
+ by_endpoint: byEndpoint,
+ top_endpoint: topEndpoint,
+ };
+}
diff --git a/api/_lib/x402/sniper-analytics-store.js b/api/_lib/x402/sniper-analytics-store.js
new file mode 100644
index 000000000..b1d566a22
--- /dev/null
+++ b/api/_lib/x402/sniper-analytics-store.js
@@ -0,0 +1,204 @@
+// api/_lib/x402/sniper-analytics-store.js
+//
+// Compute + persistence layer for the Sniper Trade Performance analytics feed.
+//
+// The x402 endpoint POST /api/x402/analytics aggregates the autonomous sniper's
+// own real trade ledger (agent_sniper_positions — closed positions with a signed
+// realized_pnl_lamports) into a performance report: win rate, average profit,
+// worst loss, and total SOL volume snipped over a period. The x402 autonomous
+// loop pays $0.01 USDC for that report on a schedule (registry entry
+// `sniper-trade-analytics`), records it to x402_autonomous_log, and — via the
+// storeValue hook below — appends every snapshot to sniper_trade_analytics and
+// raises a low-win-rate alert the strategy auto-tuner / ops dashboard consumes.
+//
+// Schema + compute ownership lives here so the endpoint (writer of the report),
+// the registry's extractSignal (lifts the headline metrics into signal_data),
+// and the storeValue persistence all agree on the exact shape and the alert rule.
+
+export const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// A sniper "win" is a closed position whose realized PnL is strictly positive.
+// Below this win rate — once there are enough closed trades for the rate to be
+// meaningful — the strategy is underperforming and the loop raises an alert so
+// the auto-tuner can pull back sizing or tighten entry filters.
+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;
+}
+
+function round(v, dp = 6) {
+ const f = 10 ** dp;
+ return Math.round(num(v) * f) / f;
+}
+
+/**
+ * Turn a single aggregate row over agent_sniper_positions into the full
+ * sniper-trade performance report. Pure — the caller supplies the live SOL/USD
+ * price so USD conversions are deterministic and testable.
+ *
+ * @param {object} agg aggregate counts/sums (numbers or numeric strings):
+ * { closed, wins, losses, breakeven, volume_lamports, total_pnl_lamports,
+ * avg_pnl_lamports, worst_loss_lamports, best_win_lamports, avg_pnl_pct }
+ * @param {object} opts
+ * @param {number|null} opts.solUsd live SOL price in USD (null → USD fields null)
+ * @param {string} opts.period period key (echoed back)
+ * @param {string} opts.network 'mainnet' | 'devnet' | 'all'
+ * @param {string} opts.report report id (echoed back)
+ * @param {string} [opts.generatedAt] ISO timestamp (caller stamps it)
+ */
+export function buildSniperAnalytics(agg = {}, opts = {}) {
+ const solUsd = opts.solUsd != null && num(opts.solUsd) > 0 ? num(opts.solUsd) : null;
+ const lamToSol = (l) => round(num(l) / LAMPORTS_PER_SOL, 9);
+ const solToUsd = (s) => (solUsd != null ? round(s * solUsd, 4) : null);
+
+ const sample = Math.round(num(agg.closed));
+ const wins = Math.round(num(agg.wins));
+ const losses = Math.round(num(agg.losses));
+ const breakeven = Math.round(num(agg.breakeven));
+
+ const winRate = sample > 0 ? wins / sample : 0;
+
+ const totalVolumeSol = lamToSol(agg.volume_lamports);
+ const totalPnlSol = lamToSol(agg.total_pnl_lamports);
+ const avgProfitSol = lamToSol(agg.avg_pnl_lamports);
+ const worstLossSol = lamToSol(agg.worst_loss_lamports);
+ const bestWinSol = lamToSol(agg.best_win_lamports);
+
+ const alert =
+ sample >= MIN_ALERT_SAMPLE && winRate < WIN_RATE_ALERT_THRESHOLD
+ ? {
+ type: 'low_win_rate',
+ win_rate: round(winRate, 4),
+ threshold: WIN_RATE_ALERT_THRESHOLD,
+ sample_size: sample,
+ message:
+ `Sniper win rate ${(winRate * 100).toFixed(1)}% is below the ` +
+ `${(WIN_RATE_ALERT_THRESHOLD * 100).toFixed(0)}% floor over ${sample} closed trades — ` +
+ `review entry filters / sizing.`,
+ }
+ : null;
+
+ return {
+ report: opts.report || 'sniper_trades',
+ period: opts.period || DEFAULT_PERIOD,
+ network: opts.network || 'mainnet',
+ sample_size: sample,
+ wins,
+ losses,
+ breakeven,
+ win_rate: round(winRate, 4),
+ win_rate_pct: round(winRate * 100, 2),
+ total_volume_sol: totalVolumeSol,
+ total_volume_usdc: solToUsd(totalVolumeSol),
+ total_pnl_sol: totalPnlSol,
+ total_pnl_usdc: solToUsd(totalPnlSol),
+ avg_profit_sol: avgProfitSol,
+ avg_profit_usdc: solToUsd(avgProfitSol),
+ avg_profit_pct: round(num(agg.avg_pnl_pct), 4),
+ best_win_sol: bestWinSol,
+ best_win_usdc: solToUsd(bestWinSol),
+ worst_loss_sol: worstLossSol,
+ worst_loss_usdc: solToUsd(worstLossSol),
+ sol_price_usd: solUsd,
+ alert,
+ generated_at: opts.generatedAt || null,
+ };
+}
+
+/**
+ * Lift the headline, auto-tuning-actionable metrics out of a report for
+ * x402_autonomous_log.signal_data. Tolerates either a full report or a raw
+ * endpoint response (same field names).
+ */
+export function classifySniperSignal(r) {
+ const o = r || {};
+ return {
+ report: o.report || 'sniper_trades',
+ period: o.period || null,
+ network: o.network || null,
+ win_rate: o.win_rate ?? null,
+ avg_profit_usdc: o.avg_profit_usdc ?? null,
+ total_volume_sol: o.total_volume_sol ?? null,
+ sample_size: o.sample_size ?? null,
+ alert: o.alert || null,
+ };
+}
+
+let _schemaReady = false;
+
+/**
+ * Create the analytics time-series table if absent. Idempotent; the in-process
+ * guard avoids re-issuing the DDL after the first call. Mirrors the loop's
+ * ensureSchema idiom (see api/_lib/x402/three-signal-store.js).
+ */
+export async function ensureSniperAnalyticsSchema(sql) {
+ if (_schemaReady || !sql) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS sniper_trade_analytics (
+ id bigserial PRIMARY KEY,
+ ts timestamptz NOT NULL DEFAULT now(),
+ period text,
+ network text,
+ sample_size int,
+ wins int,
+ losses int,
+ win_rate double precision,
+ total_volume_sol double precision,
+ total_pnl_sol double precision,
+ avg_profit_sol double precision,
+ avg_profit_usdc double precision,
+ worst_loss_sol double precision,
+ sol_price_usd double precision,
+ alert jsonb,
+ run_id uuid,
+ source text NOT NULL DEFAULT 'x402-autonomous'
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS sniper_trade_analytics_ts_desc
+ ON sniper_trade_analytics (ts DESC)
+ `;
+ _schemaReady = true;
+}
+
+/**
+ * Append one analytics snapshot to the time series.
+ * @param {Function} sql
+ * @param {object} report a buildSniperAnalytics() result
+ * @param {{ runId?: string, source?: string }} [meta]
+ */
+export async function insertSniperAnalytics(sql, report, meta = {}) {
+ if (!sql || !report) return;
+ await ensureSniperAnalyticsSchema(sql);
+ await sql`
+ INSERT INTO sniper_trade_analytics
+ (ts, period, network, sample_size, wins, losses, win_rate,
+ total_volume_sol, total_pnl_sol, avg_profit_sol, avg_profit_usdc,
+ worst_loss_sol, sol_price_usd, alert, run_id, source)
+ VALUES
+ (now(), ${report.period}, ${report.network}, ${report.sample_size},
+ ${report.wins}, ${report.losses}, ${report.win_rate},
+ ${report.total_volume_sol}, ${report.total_pnl_sol}, ${report.avg_profit_sol},
+ ${report.avg_profit_usdc}, ${report.worst_loss_sol}, ${report.sol_price_usd},
+ ${report.alert ? JSON.stringify(report.alert) : null},
+ ${meta.runId || null}, ${meta.source || 'x402-autonomous'})
+ `;
+}
diff --git a/api/_lib/x402/user-activity-analytics.js b/api/_lib/x402/user-activity-analytics.js
new file mode 100644
index 000000000..89a06678f
--- /dev/null
+++ b/api/_lib/x402/user-activity-analytics.js
@@ -0,0 +1,164 @@
+// api/_lib/x402/user-activity-analytics.js
+//
+// Real product-analytics computation over the platform's own activity tables.
+// Backs the paid POST /api/x402/analytics endpoint AND the autonomous-loop
+// snapshot persistence, so both always derive identical numbers from one place.
+//
+// Source of truth: usage_events (every API/MCP/render/llm call is metered here
+// by api/_lib/usage.js) and sessions (web auth sessions). No mocks — every
+// figure is a live SQL aggregate. An empty table yields zeros, never fabricated
+// data.
+
+// Supported reporting windows. The autonomous entry uses '7d'; callers may ask
+// for a shorter or longer window. Each maps to a Postgres interval string.
+export const PERIODS = {
+ '24h': '24 hours',
+ '7d': '7 days',
+ '30d': '30 days',
+};
+
+export const DEFAULT_PERIOD = '7d';
+
+// Normalize a caller-supplied period to a supported key (defaults to 7d).
+export function normalizePeriod(period) {
+ const p = String(period || '').toLowerCase().trim();
+ return PERIODS[p] ? p : DEFAULT_PERIOD;
+}
+
+// A stable per-actor identity across the heterogeneous usage_events columns.
+// An anonymous hit (all identity columns null) collapses to NULL and is
+// excluded from DAU/WAU by COUNT(DISTINCT) — DAU/WAU count identifiable actors,
+// not raw traffic. Order: human user → autonomous agent → API key → OAuth
+// client → avatar owner. Trusted constant (no user input) — inlined into the
+// raw SQL text below.
+const ACTOR_KEY = `COALESCE(
+ user_id::text,
+ 'agent:' || agent_id::text,
+ 'apikey:' || api_key_id::text,
+ 'client:' || client_id,
+ 'avatar:' || avatar_id::text
+)`;
+
+// Round to a sensible number of decimals without dragging in a dependency.
+const round = (n, d = 2) => {
+ if (n == null || !Number.isFinite(Number(n))) return null;
+ const f = 10 ** d;
+ return Math.round(Number(n) * f) / f;
+};
+
+/**
+ * Compute the user_activity report over the given window.
+ *
+ * @param {Function} sql neon tagged-template client (api/_lib/db.js)
+ * @param {string} period one of PERIODS keys; coerced via normalizePeriod
+ * @returns {Promise<object>} the full report payload
+ */
+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.
+ 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)})
+ FILTER (WHERE created_at >= now() - interval '24 hours') AS dau,
+ COUNT(DISTINCT ${sql.unsafe(actor)})
+ FILTER (WHERE created_at >= now() - interval '7 days') AS wau
+ FROM usage_events
+ 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
+ FROM usage_events
+ WHERE created_at >= now() - ${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
+ CASE 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
+ FROM usage_events
+ WHERE created_at >= now() - ${interval}::interval
+ GROUP BY 1
+ ORDER BY events DESC
+ LIMIT 10
+ `,
+ // Session-length distribution from web auth sessions active in the window.
+ // Duration = last_seen_at - created_at, clamped to non-negative.
+ sql`
+ SELECT
+ COUNT(*) 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
+ FROM sessions
+ WHERE last_seen_at >= now() - ${interval}::interval
+ AND last_seen_at >= created_at
+ `,
+ ]);
+
+ const active = activeRows[0] || {};
+ const ev = eventRows[0] || {};
+ const sess = sessionRows[0] || {};
+
+ const dau = Number(active.dau || 0);
+ const wau = Number(active.wau || 0);
+ const totalEvents = Number(ev.total_events || 0);
+ const errorEvents = Number(ev.error_events || 0);
+
+ const topFeatures = (featureRows || []).map((r) => ({
+ feature: r.feature || 'unknown',
+ events: Number(r.events || 0),
+ actors: Number(r.actors || 0),
+ share: totalEvents > 0 ? round(Number(r.events) / totalEvents, 4) : 0,
+ }));
+
+ return {
+ report: 'user_activity',
+ period: key,
+ window: interval,
+ // Stickiness: DAU/WAU is the canonical engagement ratio (0..1).
+ dau,
+ wau,
+ stickiness: wau > 0 ? round(dau / wau, 3) : 0,
+ active_actors: Number(ev.active_actors || 0),
+ total_events: totalEvents,
+ error_rate: totalEvents > 0 ? round(errorEvents / totalEvents, 4) : 0,
+ top_features: topFeatures,
+ session_length: {
+ count: Number(sess.count || 0),
+ avg_seconds: round(sess.avg_seconds, 1),
+ median_seconds: round(sess.median_seconds, 1),
+ p90_seconds: round(sess.p90_seconds, 1),
+ },
+ ts: new Date().toISOString(),
+ };
+}
+
+// Lift the headline signal the autonomous loop records into x402_autonomous_log
+// .signal_data and persists into the snapshot table. Tolerates a partial/empty
+// report so a degraded run still records something coherent.
+export function extractActivitySignal(report) {
+ const r = report || {};
+ return {
+ dau: Number(r.dau || 0),
+ wau: Number(r.wau || 0),
+ top_feature: Array.isArray(r.top_features) && r.top_features.length
+ ? r.top_features[0].feature
+ : null,
+ stickiness: r.stickiness ?? null,
+ total_events: Number(r.total_events || 0),
+ };
+}
diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.js
index bb7791495..99773e52c 100644
--- a/api/x402/agent-reputation.js
+++ b/api/x402/agent-reputation.js
@@ -20,7 +20,11 @@ import { priceFor } from '../_lib/x402-prices.js';
import { isUuid } from '../_lib/validate.js';
// Shared with /api/x402/agent-bouncer so the raw reputation snapshot and the
// admit/refuse verdict are computed from one source of truth.
-import { loadAgentReputation } from '../_lib/trust/solana-bouncer.js';
+import {
+ loadAgentReputation,
+ sweepAgentReputation,
+ REPUTATION_FLAG_THRESHOLD,
+} from '../_lib/trust/solana-bouncer.js';
const ROUTE = '/api/x402/agent-reputation';
diff --git a/api/x402/analytics.js b/api/x402/analytics.js
new file mode 100644
index 000000000..73fea457a
--- /dev/null
+++ b/api/x402/analytics.js
@@ -0,0 +1,301 @@
+// POST /api/x402/analytics
+//
+// Social-Economy Analytics Feed — $0.005 USDC per call on Solana or Base.
+//
+// One agent pays another for a live, aggregated view of the three.ws social
+// economy. The first report exposed is the Pole Club's activity: how many
+// stages (clubs) are currently active, how many distinct patrons (members) are
+// participating, the tip throughput, the cover charges collected at the door,
+// and which stages are growing fastest. Every number is read live from the
+// real ledgers — club_tips (the settled tip ledger), club_dancer_wallets (the
+// stage roster) and x402_audit_log (settled cover-charge payments). No mock
+// 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 }
+//
+// 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.
+
+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 { sql } from '../_lib/db.js';
+
+const ROUTE = '/api/x402/analytics';
+
+const DESCRIPTION =
+ 'three.ws Social-Economy Analytics — pay $0.005 USDC per call for a live, ' +
+ 'aggregated view of platform social activity. The "clubs" report returns the ' +
+ 'Pole Club economy over the requested window: active stages, distinct patron ' +
+ 'members, tip count + USDC volume, cover charges collected at the door, and a ' +
+ 'fastest-growing-stage leaderboard. Read live from the on-chain-settled tip + ' +
+ 'cover ledgers. Pay-per-call in USDC on Solana mainnet or Base.';
+
+// 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']);
+
+// period → window in seconds (null = all-time, no time filter).
+const PERIODS = {
+ '1h': 3600,
+ '24h': 86400,
+ '7d': 604800,
+ '30d': 2592000,
+ all: null,
+};
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ report: {
+ type: 'string',
+ enum: ['clubs'],
+ default: 'clubs',
+ description: 'Which analytics report to return.',
+ },
+ period: {
+ type: 'string',
+ enum: ['1h', '24h', '7d', '30d', 'all'],
+ default: '24h',
+ description: 'Aggregation window.',
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok', 'report', 'period', 'generated_at', 'metrics'],
+ properties: {
+ ok: { type: 'boolean', const: true },
+ report: { type: 'string', enum: ['clubs'] },
+ period: { type: 'string' },
+ generated_at: { type: 'string', format: 'date-time' },
+ metrics: {
+ type: 'object',
+ required: ['active_clubs', 'total_clubs', 'members', 'tips', 'cover_charges'],
+ properties: {
+ active_clubs: { type: 'integer', minimum: 0, description: 'Stages that received a tip in the window.' },
+ total_clubs: { type: 'integer', minimum: 0, description: 'Registered stages in the roster.' },
+ members: { type: 'integer', minimum: 0, description: 'Distinct patron wallets active in the window.' },
+ tips: {
+ type: 'object',
+ properties: {
+ count: { type: 'integer', minimum: 0 },
+ volume_atomics: { type: 'string' },
+ volume_usdc: { type: 'number' },
+ },
+ },
+ cover_charges: {
+ type: 'object',
+ properties: {
+ count: { type: 'integer', minimum: 0 },
+ atomics: { type: 'string' },
+ usdc: { type: 'number' },
+ },
+ },
+ },
+ },
+ top_clubs: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ dancer: { type: 'string' },
+ display_name: { type: ['string', 'null'] },
+ volume_atomics: { type: 'string' },
+ volume_usdc: { type: 'number' },
+ tips: { type: 'integer' },
+ },
+ },
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ report: 'clubs',
+ period: '24h',
+ generated_at: '2026-06-27T18:42:09.000Z',
+ metrics: {
+ active_clubs: 3,
+ total_clubs: 4,
+ members: 27,
+ tips: { count: 41, volume_atomics: '410000', volume_usdc: 0.41 },
+ cover_charges: { count: 12, atomics: '120000', usdc: 0.12 },
+ },
+ top_clubs: [
+ { dancer: '1', display_name: 'Nyx', volume_atomics: '190000', volume_usdc: 0.19, tips: 19 },
+ ],
+};
+
+const BAZAAR = {
+ discoverable: true,
+ description: DESCRIPTION,
+ useCases: ['social analytics', 'club economy health', 'agent-to-agent payment'],
+ input: { type: 'json', example: { report: 'clubs', period: '24h' }, schema: INPUT_SCHEMA },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ info: {
+ input: { type: 'json', example: { report: 'clubs', period: '24h' } },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export const BAZAAR_SCHEMA = BAZAAR;
+
+const ROUTE_COVER = '/api/x402/club-cover';
+
+const atomicsToUsd = (atomics) => Math.round((Number(atomics || 0) / 1e6) * 1e6) / 1e6;
+
+// Read the request body without assuming a framework parsed it. Mirrors the
+// crypto-intel idiom so this file works under the same raw-stream dispatch.
+async function readBody(req) {
+ if (req.body && typeof req.body === 'object') return req.body;
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const raw = Buffer.concat(chunks).toString('utf8').trim();
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+// Each aggregate is read independently and fails soft to a zeroed shape, so one
+// missing table (e.g. x402_audit_log not yet migrated in a fresh env) never
+// blanks the whole report — the live tables still report real numbers.
+//
+// The window is a parameterized fragment over created_at; the seconds value is
+// bound, never interpolated, so a hostile `period` can never inject SQL. null
+// seconds → all-time. The top-clubs query joins club_dancer_wallets (which also
+// has a created_at), so it needs the alias-qualified t.created_at variant.
+async function clubsReport(seconds) {
+ const tipsWindow =
+ seconds == null ? sql`true` : sql`created_at >= now() - (${seconds}::int * interval '1 second')`;
+ const auditWindow = tipsWindow; // x402_audit_log: single table, created_at unambiguous
+ const topWindow =
+ seconds == null ? sql`true` : sql`t.created_at >= now() - (${seconds}::int * interval '1 second')`;
+
+ const [tips, roster, covers, topClubs] = await Promise.all([
+ sql`
+ select
+ count(*)::int as tip_count,
+ coalesce(sum(amount_atomics), 0)::text as tip_volume_atomics,
+ count(distinct lower(payer))::int as members,
+ count(distinct dancer)::int as active_clubs
+ from club_tips
+ where ${tipsWindow}
+ `.catch(() => [{}]),
+ sql`select count(*)::int as total_clubs from club_dancer_wallets`.catch(() => [{}]),
+ sql`
+ select
+ count(*)::int as cover_count,
+ coalesce(sum(amount_atomics), 0)::text as cover_atomics
+ from x402_audit_log
+ where route = ${ROUTE_COVER}
+ and event_type = 'payment_settled'
+ and settlement_status = 'success'
+ and ${auditWindow}
+ `.catch(() => [{}]),
+ sql`
+ select
+ t.dancer as dancer,
+ w.display_name as display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as volume_atomics,
+ count(*)::int as tips
+ from club_tips t
+ left join club_dancer_wallets w on w.dancer = t.dancer
+ where ${tipsWindow}
+ group by t.dancer, w.display_name
+ order by sum(t.amount_atomics) desc nulls last, t.dancer asc
+ limit 5
+ `.catch(() => []),
+ ]);
+
+ const tipRow = tips?.[0] || {};
+ const coverRow = covers?.[0] || {};
+
+ return {
+ metrics: {
+ active_clubs: tipRow.active_clubs ?? 0,
+ total_clubs: roster?.[0]?.total_clubs ?? 0,
+ members: tipRow.members ?? 0,
+ tips: {
+ count: tipRow.tip_count ?? 0,
+ volume_atomics: tipRow.tip_volume_atomics ?? '0',
+ volume_usdc: atomicsToUsd(tipRow.tip_volume_atomics),
+ },
+ cover_charges: {
+ count: coverRow.cover_count ?? 0,
+ atomics: coverRow.cover_atomics ?? '0',
+ usdc: atomicsToUsd(coverRow.cover_atomics),
+ },
+ },
+ top_clubs: (topClubs || []).map((r) => ({
+ dancer: r.dancer,
+ display_name: r.display_name ?? null,
+ volume_atomics: r.volume_atomics ?? '0',
+ volume_usdc: atomicsToUsd(r.volume_atomics),
+ tips: r.tips ?? 0,
+ })),
+ };
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('analytics', '5000'), // $0.005 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Social Analytics',
+ tags: ['analytics', 'club', 'social', 'metrics', 'solana'],
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const body = await readBody(req);
+ const report = String(body.report || 'clubs').toLowerCase().trim();
+ const period = String(body.period || '24h').toLowerCase().trim();
+
+ // Validate BEFORE returning — a throw here lands before settlement, so an
+ // unsupported report/period is rejected without charging the buyer.
+ if (!REPORTS.has(report)) {
+ throw Object.assign(new Error(`unknown report "${report}" — supported: ${[...REPORTS].join(', ')}`), {
+ status: 400,
+ code: 'unknown_report',
+ });
+ }
+ if (!(period in PERIODS)) {
+ throw Object.assign(new Error(`unknown period "${period}" — supported: ${Object.keys(PERIODS).join(', ')}`), {
+ status: 400,
+ code: 'unknown_period',
+ });
+ }
+
+ const seconds = PERIODS[period];
+ const { metrics, top_clubs } = await clubsReport(seconds);
+
+ return {
+ ok: true,
+ report,
+ period,
+ generated_at: new Date().toISOString(),
+ metrics,
+ top_clubs,
+ };
+ },
+});
diff --git a/api/x402/bazaar-feed.js b/api/x402/bazaar-feed.js
new file mode 100644
index 000000000..7780eb1dd
--- /dev/null
+++ b/api/x402/bazaar-feed.js
@@ -0,0 +1,301 @@
+// POST /api/x402/bazaar-feed
+//
+// Bazaar Price Trend Monitor — $0.001 USDC per call on Solana or Base.
+//
+// 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.
+//
+// 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 }
+//
+// 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.
+
+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 { sql } from '../_lib/db.js';
+
+const ROUTE = '/api/x402/bazaar-feed';
+
+// Move bands. A service whose cheapest price moved more than ±STABLE_PCT over
+// the window is "trending"; inside the band it is "stable". Env-overridable so
+// ops can tune sensitivity without a redeploy.
+const STABLE_PCT = Math.max(0.5, Number(process.env.X402_BAZAAR_TREND_STABLE_PCT || 5));
+// Net-pressure thresholds for the directional sentiment signal.
+const PRESSURE_PCT = Math.max(0.05, Number(process.env.X402_BAZAAR_TREND_PRESSURE || 0.15));
+// Cap on how many movers to return per side (the long tail isn't actionable).
+const TOP_N = 25;
+
+const DESCRIPTION =
+ 'Bazaar Price Trend Monitor — pay $0.001 USDC per call for a 24h (or custom ' +
+ 'period) read of price movement across the x402 service marketplace: which ' +
+ 'tracked services got more expensive, which got cheaper, how many held steady, ' +
+ 'and the net price pressure as a bullish / bearish / neutral market signal. ' +
+ 'Derived from three.ws’ own live service price history.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ filter: {
+ type: 'string',
+ description: 'Feed filter. Only "price_trends" is supported.',
+ enum: ['price_trends'],
+ default: 'price_trends',
+ },
+ period: {
+ type: 'string',
+ description: 'Lookback window: <n><unit> where unit is m/h/d/w (e.g. 24h, 7d).',
+ default: '24h',
+ },
+ },
+};
+
+const TREND_ITEM_SCHEMA = {
+ type: 'object',
+ required: ['service_key', 'pct_change', 'price_atomic'],
+ properties: {
+ service_key: { type: 'string' },
+ name: { type: ['string', 'null'] },
+ resource: { type: ['string', 'null'] },
+ tool_name: { type: ['string', 'null'] },
+ network: { type: ['string', 'null'] },
+ pct_change: { type: 'number' },
+ price_atomic: { type: 'number' },
+ price_usdc: { type: 'number' },
+ first_price_atomic:{ type: 'number' },
+ observations: { type: 'integer' },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['filter', 'period', 'trending_up', 'trending_down', 'stable_count', 'signal', 'ts'],
+ properties: {
+ filter: { type: 'string' },
+ period: { type: 'string' },
+ trending_up: { type: 'array', items: TREND_ITEM_SCHEMA },
+ trending_down: { type: 'array', items: TREND_ITEM_SCHEMA },
+ stable_count: { type: 'integer' },
+ total_tracked: { type: 'integer' },
+ net_pressure: { type: 'number' },
+ avg_change_pct:{ type: ['number', 'null'] },
+ signal: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },
+ headline: { type: 'string' },
+ confidence: { type: 'number', minimum: 0, maximum: 1 },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['bazaar price trends', 'service cost monitoring', 'market sentiment', 'agent-to-agent intel'],
+ input: {
+ type: 'json',
+ example: { filter: 'price_trends', period: '24h' },
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: {
+ filter: 'price_trends', period: '24h',
+ trending_up: [{ service_key: 'https://svc.example/api#tool', name: 'Example Oracle', pct_change: 33.3, price_atomic: 2000, price_usdc: 0.002, first_price_atomic: 1500, observations: 4 }],
+ trending_down: [], stable_count: 12, total_tracked: 13,
+ net_pressure: 0.08, avg_change_pct: 2.4, signal: 'neutral',
+ headline: 'Bazaar prices steady — 1 up, 0 down, 12 stable over 24h',
+ confidence: 0.66, ts: '2026-06-27T10:00:00Z',
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Parse a period string (e.g. "24h", "7d", "30m", "2w") into a validated
+// Postgres interval string. Defaults to 24 hours. Clamps to [1 minute, 30 days]
+// so a hostile/typo value can never request an unbounded scan.
+const UNIT_TO_PG = { m: 'minutes', h: 'hours', d: 'days', w: 'weeks' };
+const UNIT_TO_MIN = { m: 1, h: 60, d: 1440, w: 10080 };
+export function parsePeriod(raw) {
+ const def = { interval: '24 hours', label: '24h' };
+ if (typeof raw !== 'string') return def;
+ const m = raw.trim().toLowerCase().match(/^(\d{1,5})\s*([mhdw])$/);
+ if (!m) return def;
+ let n = Number(m[1]);
+ const unit = m[2];
+ if (!Number.isFinite(n) || n <= 0) return def;
+ const minutes = n * UNIT_TO_MIN[unit];
+ const MIN = 1, MAX = 30 * 1440; // 1 minute .. 30 days
+ if (minutes < MIN) { n = 1; return { interval: '1 minutes', label: '1m' }; }
+ if (minutes > MAX) return { interval: '30 days', label: '30d' };
+ return { interval: `${n} ${UNIT_TO_PG[unit]}`, label: `${n}${unit}` };
+}
+
+// Derive the directional sentiment from the up/down/stable tally + average move.
+function classify(up, down, stable, avgChange) {
+ const total = up + down + stable;
+ const movers = up + down;
+ const netPressure = total > 0 ? Number(((up - down) / total).toFixed(4)) : 0;
+ let signal = 'neutral';
+ if (netPressure > PRESSURE_PCT) signal = 'bullish';
+ else if (netPressure < -PRESSURE_PCT) signal = 'bearish';
+
+ // Confidence scales with sample size and the strength of the imbalance.
+ let confidence = total === 0
+ ? 0.4
+ : Math.min(0.95, 0.5 + Math.min(total / 20, 0.2) + Math.min(Math.abs(netPressure), 0.3));
+ confidence = Number(confidence.toFixed(2));
+
+ const dir = signal === 'bullish'
+ ? 'rising'
+ : signal === 'bearish'
+ ? 'cooling'
+ : 'steady';
+ const headline = total === 0
+ ? 'Bazaar price trends: no service movement recorded yet'
+ : `Bazaar prices ${dir} — ${up} up, ${down} down, ${stable} stable`;
+
+ return { signal, netPressure, confidence, headline, total, movers };
+}
+
+// Read the price-trend feed from the live service price-history time series.
+export async function readBazaarPriceTrends(periodRaw) {
+ const { interval, label } = parsePeriod(periodRaw);
+
+ let rows = [];
+ try {
+ rows = await sql`
+ SELECT service_key,
+ (array_agg(price_atomic ORDER BY ts ASC))[1] AS first_price,
+ (array_agg(price_atomic ORDER BY ts DESC))[1] AS last_price,
+ (array_agg(name ORDER BY ts DESC))[1] AS name,
+ (array_agg(resource ORDER BY ts DESC))[1] AS resource,
+ (array_agg(tool_name ORDER BY ts DESC))[1] AS tool_name,
+ (array_agg(network ORDER BY ts DESC))[1] AS network,
+ count(*)::int AS observations
+ FROM x402_service_price_history
+ WHERE ts >= now() - ${interval}::interval
+ AND available = true
+ AND price_atomic IS NOT NULL
+ AND price_atomic > 0
+ GROUP BY service_key
+ HAVING count(*) >= 2
+ `;
+ } catch (err) {
+ // Tracker has never run (table absent) — genuine empty feed, not an error.
+ if (/does not exist/i.test(err?.message || '')) rows = [];
+ else throw err;
+ }
+
+ const up = [];
+ const down = [];
+ let stableCount = 0;
+ let changeSum = 0;
+ let changeN = 0;
+
+ for (const r of rows) {
+ const first = Number(r.first_price);
+ const last = Number(r.last_price);
+ if (!Number.isFinite(first) || first <= 0 || !Number.isFinite(last)) continue;
+ const pct = Number((((last - first) / first) * 100).toFixed(2));
+ changeSum += pct;
+ changeN += 1;
+
+ if (Math.abs(pct) < STABLE_PCT) {
+ stableCount += 1;
+ continue;
+ }
+ const item = {
+ service_key: r.service_key,
+ name: r.name || null,
+ resource: r.resource || null,
+ tool_name: r.tool_name || null,
+ network: r.network || null,
+ pct_change: pct,
+ price_atomic: last,
+ price_usdc: Number((last / 1e6).toFixed(6)),
+ first_price_atomic: first,
+ observations: Number(r.observations || 0),
+ };
+ (pct > 0 ? up : down).push(item);
+ }
+
+ up.sort((a, b) => b.pct_change - a.pct_change);
+ down.sort((a, b) => a.pct_change - b.pct_change);
+
+ const avgChange = changeN > 0 ? Number((changeSum / changeN).toFixed(2)) : null;
+ const { signal, netPressure, confidence, headline, total } =
+ classify(up.length, down.length, stableCount, avgChange);
+
+ return {
+ filter: 'price_trends',
+ period: label,
+ trending_up: up.slice(0, TOP_N),
+ trending_down: down.slice(0, TOP_N),
+ stable_count: stableCount,
+ total_tracked: total,
+ net_pressure: netPressure,
+ avg_change_pct: avgChange,
+ signal,
+ headline: `${headline} over ${label}`,
+ confidence,
+ ts: new Date().toISOString(),
+ };
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('bazaar_feed', '1000'), // $0.001 USDC — lightweight read
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Bazaar Feed',
+ tags: ['bazaar', 'price', 'trends', 'market', 'x402'],
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ let filter = 'price_trends';
+ let period = '24h';
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
+ if (typeof body.filter === 'string' && body.filter.trim()) {
+ filter = body.filter.trim().toLowerCase();
+ }
+ if (typeof body.period === 'string' && body.period.trim()) {
+ period = body.period.trim();
+ }
+ } catch { /* defaults */ }
+
+ if (filter !== 'price_trends') {
+ // Reject before settlement so the buyer is not charged for an
+ // unsupported filter.
+ throw Object.assign(new Error(`unsupported filter "${filter}"; only "price_trends" is available`), {
+ status: 400,
+ code: 'unsupported_filter',
+ });
+ }
+
+ return readBazaarPriceTrends(period);
+ },
+});
diff --git a/api/x402/club-cover.js b/api/x402/club-cover.js
index e23456b28..bbc0df4d7 100644
--- a/api/x402/club-cover.js
+++ b/api/x402/club-cover.js
@@ -24,6 +24,7 @@ import {
findBan,
visitsFor,
tierFor,
+ membershipSnapshot,
} from '../_lib/club/cover-pass.js';
const ROUTE = '/api/x402/club-cover';
@@ -107,7 +108,7 @@ const BAZAAR = {
export const BAZAAR_SCHEMA = BAZAAR;
-export default paidEndpoint({
+const doorEndpoint = paidEndpoint({
route: ROUTE,
method: 'GET',
priceAtomics: priceFor('club-cover', '10000'), // $0.01 USDC
diff --git a/api/x402/did.js b/api/x402/did.js
index a91f5898e..ee7c8637b 100644
--- a/api/x402/did.js
+++ b/api/x402/did.js
@@ -1,40 +1,63 @@
-// /.well-known/did.json — W3C DID Document for the x402 Offer & Receipt
-// extension signing key (USE-17).
+// /api/x402/did — dual-mode DID endpoint.
//
-// Verifiers use this to resolve our `kid` back to a public key when checking
-// EIP-712 / JWS signatures on offers and receipts. Per spec §4.5.1, the
-// resolved key is "authorized to sign for the service identified by the
-// payload's resourceUrl" so listing the signer address (eip712) or public JWK
-// (jws) here is the binding between our HTTPS origin and the signing material.
+// GET → /.well-known/did.json — W3C DID Document for the x402 Offer & Receipt
+// signing key (USE-17). Free. Verifiers resolve our `kid` back to a
+// public key here when checking EIP-712 / JWS signatures on offers and
+// receipts. Per spec §4.5.1 the resolved key is "authorized to sign for
+// the service identified by the payload's resourceUrl", so listing the
+// signer address (eip712) or public JWK (jws) here is the binding
+// between our HTTPS origin and the signing material. Routed via
+// vercel.json: /.well-known/did.json → /api/x402/did.
//
-// Routed via `vercel.json`:
-// /.well-known/did.json → /api/x402/did
+// POST → DID Verification Canary (USE-069). Paid $0.001 USDC. Resolves our
+// published DID document over the real public route an external
+// verifier would hit, validates it is a structurally correct W3C DID
+// document with our x402 service binding, and measures end-to-end
+// resolution latency. The verdict ({ verified, latency_ms }) is the
+// actionable signal: a malformed/unreachable document means any
+// counterparty verifying our offer/receipt signatures fails silently,
+// and a slow resolver degrades their settlement path. The autonomous
+// loop pays this canary on a schedule and records the verdict to
+// x402_autonomous_log so the status surface flags a broken or slow DID
+// subsystem before a partner does. Body:
+// { "did": "did:three:canary", "mode": "verify" }
//
-// When no issuer is configured, we return 404 — there's nothing to publish.
+// When no issuer is configured the GET path returns 404 — there's nothing to
+// publish — and the POST canary truthfully reports verified:false (not_configured).
-import { cors, json, method, error } from '../_lib/http.js';
+import { cors, json, error } from '../_lib/http.js';
import { env } from '../_lib/env.js';
import { getIssuer } from '../_lib/x402/offer-receipt-issuer.js';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { priceFor } from '../_lib/x402-prices.js';
-export default async function handler(req, res) {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
+const ROUTE = '/api/x402/did';
- let built;
- try {
- built = await getIssuer();
- } catch (err) {
- console.error('[x402/did] issuer error:', err?.message);
- return error(res, 500, 'issuer_misconfigured', 'signing key configuration error');
- }
- if (!built) {
- return error(
- res,
- 404,
- 'not_configured',
- 'no offer-receipt signing key is configured for this deployment',
- );
- }
+// W3C DID Core v1 context — a conformant DID document MUST list it first.
+const DID_V1_CONTEXT = 'https://www.w3.org/ns/did/v1';
+
+// The canary fails the latency leg above this. A DID document resolution that
+// external verifiers experience should be well under a second; 1500ms leaves
+// generous headroom for a cold serverless route + TLS while still catching a
+// genuinely degraded resolver.
+const MAX_LATENCY_MS = 1500;
+
+// Resolve the origin we publish the DID document on. APP_ORIGIN is always a
+// valid absolute origin (env normalizes it); SERVER_DOMAIN is the bare host.
+function publicOrigin() {
+ return env.APP_ORIGIN || (env.SERVER_DOMAIN ? `https://${env.SERVER_DOMAIN}` : 'https://three.ws');
+}
+
+// Build the W3C DID Document from the configured offer-receipt issuer. Returns
+// null when no signing key is configured (caller emits 404). Shared by the GET
+// publisher and — indirectly, via the public route — the POST canary, so both
+// always agree on the document shape.
+export async function buildDidDocument() {
+ const built = await getIssuer();
+ if (!built) return null;
const domain = env.SERVER_DOMAIN;
const id = `did:web:${domain}`;
@@ -42,14 +65,11 @@ export default async function handler(req, res) {
if (built.format === 'eip712') {
// did:pkh authorization for EIP-712 verifiers. The recovered signer
- // address from any EIP-712 signature MUST match the address embedded
- // in this entry's blockchainAccountId for the offer/receipt to be
- // accepted as originating from this resource server.
+ // address from any EIP-712 signature MUST match the address embedded in
+ // this entry's blockchainAccountId for the offer/receipt to be accepted
+ // as originating from this resource server.
verificationMethod.push({
id: built.kid,
- // EcdsaSecp256k1RecoveryMethod2020 covers Ethereum-style key
- // recovery; verifiers that pin to a specific scheme (e.g. did:pkh
- // resolvers) will accept this without further interpretation.
type: 'EcdsaSecp256k1RecoveryMethod2020',
controller: id,
blockchainAccountId: `eip155:1:${built.signerAddress}`,
@@ -66,9 +86,9 @@ export default async function handler(req, res) {
});
}
- const doc = {
+ return {
'@context': [
- 'https://www.w3.org/ns/did/v1',
+ DID_V1_CONTEXT,
'https://w3id.org/security/suites/jws-2020/v1',
'https://w3id.org/security/suites/secp256k1recovery-2020/v1',
],
@@ -88,9 +108,222 @@ export default async function handler(req, res) {
},
],
};
+}
+
+// Structural validation of a resolved DID document against the subset of W3C
+// DID Core our verifiers depend on, plus our x402 service binding. Returns a
+// per-check breakdown so the canary's signal pinpoints what regressed.
+export function validateDidDocument(doc) {
+ const ctx = doc && doc['@context'];
+ const ctxList = Array.isArray(ctx) ? ctx : ctx ? [ctx] : [];
+ const vm = Array.isArray(doc?.verificationMethod) ? doc.verificationMethod : [];
+ const assertion = Array.isArray(doc?.assertionMethod) ? doc.assertionMethod : [];
+ const services = Array.isArray(doc?.service) ? doc.service : [];
+ const vmIds = new Set(vm.map((m) => m && m.id).filter(Boolean));
+
+ const checks = {
+ is_object: !!doc && typeof doc === 'object' && !Array.isArray(doc),
+ has_did_context: ctxList.includes(DID_V1_CONTEXT),
+ has_did_id: typeof doc?.id === 'string' && /^did:/.test(doc.id),
+ // Every verification method must carry the triple verifiers key off of.
+ has_verification_method:
+ vm.length > 0 &&
+ vm.every((m) => m && typeof m.id === 'string' && typeof m.type === 'string' && typeof m.controller === 'string'),
+ // assertionMethod must reference a real verification method (string ref or
+ // embedded object) — the binding that authorizes the key to sign claims.
+ assertion_resolves:
+ assertion.length > 0 &&
+ assertion.some((a) => (typeof a === 'string' ? vmIds.has(a) : !!a && vmIds.has(a.id))),
+ // Our specific binding: the x402 payment service entry verifiers look for.
+ has_x402_service: services.some(
+ (s) => s && s.type === 'x402PaymentService' && typeof s.serviceEndpoint === 'string',
+ ),
+ };
+ checks.valid = Object.values(checks).every(Boolean);
+ return checks;
+}
+
+// ── GET: publish the DID document (free) ─────────────────────────────────────
+async function handleDidDocument(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ let doc;
+ try {
+ doc = await buildDidDocument();
+ } catch (err) {
+ console.error('[x402/did] issuer error:', err?.message);
+ return error(res, 500, 'issuer_misconfigured', 'signing key configuration error');
+ }
+ if (!doc) {
+ return error(
+ res,
+ 404,
+ 'not_configured',
+ 'no offer-receipt signing key is configured for this deployment',
+ );
+ }
json(res, 200, doc, {
'content-type': 'application/did+json; charset=utf-8',
'cache-control': 'public, max-age=300',
});
}
+
+// ── POST: DID Verification Canary (paid $0.001 USDC) ─────────────────────────
+const DESCRIPTION =
+ 'DID Verification Canary — pay $0.001 USDC to resolve three.ws\'s published ' +
+ 'W3C DID document over its real public route, structurally validate it, and ' +
+ 'measure end-to-end resolution latency. Returns { verified, latency_ms } plus ' +
+ 'a per-check breakdown. verified=false when the document is unreachable, ' +
+ 'malformed, or slower than 1500ms — the same failure an external x402 verifier ' +
+ 'would hit resolving our offer/receipt signing key.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ did: {
+ type: 'string',
+ description: 'DID to verify (echoed for round-trip confirmation).',
+ default: 'did:three:canary',
+ },
+ mode: {
+ type: 'string',
+ enum: ['verify'],
+ description: 'Operation. Only "verify" is supported.',
+ default: 'verify',
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['verified', 'latency_ms', 'did', 'mode', 'ts'],
+ properties: {
+ verified: { type: 'boolean' },
+ latency_ms: { type: 'integer' },
+ did: { type: 'string' },
+ mode: { type: 'string' },
+ resolved_did: { type: ['string', 'null'] },
+ http_status: { type: 'integer' },
+ within_latency: { type: 'boolean' },
+ malformed: { type: 'boolean' },
+ configured: { type: 'boolean' },
+ checks: { type: 'object' },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['DID resolution health', 'offer/receipt signing-key verification', 'identity canary'],
+ input: { type: 'json', example: { did: 'did:three:canary', mode: 'verify' }, schema: INPUT_SCHEMA },
+ output: {
+ type: 'json',
+ example: {
+ verified: true,
+ latency_ms: 142,
+ did: 'did:three:canary',
+ mode: 'verify',
+ resolved_did: 'did:web:three.ws',
+ http_status: 200,
+ within_latency: true,
+ malformed: false,
+ configured: true,
+ checks: {
+ is_object: true,
+ has_did_context: true,
+ has_did_id: true,
+ has_verification_method: true,
+ assertion_resolves: true,
+ has_x402_service: true,
+ valid: true,
+ },
+ ts: '2026-06-27T10:00:00Z',
+ },
+ },
+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+async function readBody(req) {
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const raw = Buffer.concat(chunks).toString('utf8');
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+const verifyCanary = paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('did_verify', '1000'), // $0.001 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws DID Verification Canary',
+ tags: ['did', 'identity', 'health', 'verification', 'x402'],
+ }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const body = await readBody(req);
+ const did = typeof body.did === 'string' && body.did.trim() ? body.did.trim().slice(0, 200) : 'did:three:canary';
+ const mode = typeof body.mode === 'string' && body.mode.trim() ? body.mode.trim().slice(0, 32) : 'verify';
+
+ const url = `${publicOrigin()}/.well-known/did.json`;
+ const t0 = Date.now();
+ let httpStatus = 0;
+ let doc = null;
+ let fetchError = null;
+ try {
+ const r = await fetch(url, {
+ headers: { accept: 'application/did+json, application/json', 'user-agent': 'threews-did-canary/1.0' },
+ signal: AbortSignal.timeout(5000),
+ });
+ httpStatus = r.status;
+ const text = await r.text();
+ try {
+ doc = JSON.parse(text);
+ } catch {
+ doc = null;
+ }
+ } catch (err) {
+ fetchError = err?.message || 'fetch_failed';
+ }
+ const latency_ms = Date.now() - t0;
+
+ // http 404 = issuer not configured (a distinct, known state, not a regression).
+ const configured = httpStatus !== 404;
+ const checks = validateDidDocument(doc);
+ const malformed = httpStatus !== 200 || !checks.valid;
+ const within_latency = latency_ms <= MAX_LATENCY_MS;
+ const verified = !malformed && within_latency;
+
+ return {
+ verified,
+ latency_ms,
+ did,
+ mode,
+ resolved_did: typeof doc?.id === 'string' ? doc.id : null,
+ http_status: httpStatus,
+ within_latency,
+ malformed,
+ configured,
+ checks,
+ ...(fetchError ? { fetch_error: fetchError } : {}),
+ ts: new Date().toISOString(),
+ };
+ },
+});
+
+// ── Dispatch by method ───────────────────────────────────────────────────────
+export default function handler(req, res) {
+ if (req.method === 'POST') return verifyCanary(req, res);
+ // GET / HEAD / OPTIONS → free DID document publisher.
+ return handleDidDocument(req, res);
+}
diff --git a/api/x402/forge.js b/api/x402/forge.js
index ac3a8f3d5..601b8fd46 100644
--- a/api/x402/forge.js
+++ b/api/x402/forge.js
@@ -72,6 +72,7 @@ import {
preferFreeReconstruct,
buildCatalog,
} from '../_lib/forge-tiers.js';
+import { llmComplete } from '../_lib/llm.js';
const ROUTE = '/api/x402/forge';
const REQUIRED_SCOPE = 'x402:bypass';
@@ -85,6 +86,20 @@ const MAX_VIEWS = 4;
// photos) and the text→3D fallback when the free NVIDIA NIM lane is unavailable.
const BACKEND = 'trellis';
+// ── Content-generation health probe (mode:"health_check", type:"text") ─────────
+// A full text→3D job is slow ($0.05, tens of seconds) — too heavy to canary on a
+// tight schedule. This lightweight mode instead exercises the generative AI lane
+// every forge job depends on (the free-first LLM provider chain that drives
+// prompt understanding) with one fast, real text completion. It proves content
+// generation is alive and within its latency budget, returning a measured
+// { generated, latency_ms, token_count } verdict the autonomous loop alerts on.
+// Priced at the floor ($0.001) since it does no reconstruction.
+const HEALTH_CHECK_PRICE_ATOMIC = 1000; // $0.001 USDC
+// The latency SLA the probe asserts. A completion slower than this (or a failure)
+// flips within_budget:false and raises a forge performance alert downstream.
+const HEALTH_CHECK_BUDGET_MS = 5000;
+const HEALTH_CHECK_DEFAULT_PROMPT = 'Write one sentence about Solana.';
+
const ROUTE_DESCRIPTION =
'three.ws Forge — pay-per-call text→3D and image→3D. Submit a prompt (or up ' +
'to four reference views of one object) and get back a job token; poll it for ' +
@@ -119,6 +134,18 @@ const INPUT_SCHEMA = {
},
tier: { type: 'string', enum: [...TIER_IDS], default: DEFAULT_TIER },
aspect_ratio: { type: 'string', enum: [...VALID_ASPECT], default: '1:1' },
+ mode: {
+ type: 'string',
+ enum: ['generate', 'health_check'],
+ default: 'generate',
+ description: 'health_check runs a fast text content-generation canary ($0.001) instead of a 3D job — returns { generated, latency_ms, token_count }.',
+ },
+ type: {
+ type: 'string',
+ enum: ['text'],
+ default: 'text',
+ description: 'Content type for health_check mode (text generation canary).',
+ },
},
};
@@ -425,6 +452,56 @@ async function submitViaReconstruct({ prompt, imageUrls, isImageMode, aspect, ti
};
}
+// Run the content-generation health probe: one fast, real LLM text completion
+// over the platform's free-first provider chain (the same generative lane forge
+// relies on). Measures end-to-end latency and the generated token count, and
+// never throws — a provider outage is the very signal this probe exists to catch,
+// so it returns a settled verdict (generated:false) rather than failing the paid
+// call. The caller paid for a verdict; it always gets one.
+async function runForgeHealthCheck({ prompt }) {
+ const probePrompt = (prompt && prompt.length >= 3 ? prompt : HEALTH_CHECK_DEFAULT_PROMPT);
+ const t0 = Date.now();
+ try {
+ const { text, provider, model, usage } = await llmComplete({
+ system: 'You are a concise assistant. Reply in a single short sentence.',
+ user: probePrompt,
+ maxTokens: 64,
+ // Bound each provider attempt to the SLA so a hung upstream can't stall the
+ // probe; latency_ms still reports the real measured round-trip.
+ timeoutMs: HEALTH_CHECK_BUDGET_MS,
+ track: { tool: 'forge-health-check' },
+ });
+ const latencyMs = Date.now() - t0;
+ const out = (text || '').trim();
+ // Prefer the provider-reported output token count; fall back to a coarse
+ // char/4 estimate only if usage is missing so the field is always populated.
+ const tokenCount = usage?.output ?? Math.ceil(out.length / 4);
+ return {
+ mode: 'health_check',
+ type: 'text',
+ generated: out.length > 0,
+ latency_ms: latencyMs,
+ token_count: tokenCount,
+ within_budget: latencyMs <= HEALTH_CHECK_BUDGET_MS,
+ provider,
+ model,
+ sample: out.slice(0, 200),
+ };
+ } catch (err) {
+ const latencyMs = Date.now() - t0;
+ console.warn(`[x402/forge] health_check generation failed: ${err?.message || err}`);
+ return {
+ mode: 'health_check',
+ type: 'text',
+ generated: false,
+ latency_ms: latencyMs,
+ token_count: 0,
+ within_budget: false,
+ error: err?.code || 'generation_failed',
+ };
+ }
+}
+
// Map a submitGeneration failure onto the right HTTP response. A provider 429 is
// a transient throttle (Replicate's create-prediction limit, tightest when the
// account runs low on credit). Because submit runs BEFORE settle, the payment
@@ -543,7 +620,9 @@ export default wrap(async (req, res) => {
}
const resourceUrl = resolveResourceUrl(req, ROUTE);
- const priceAtomics = priceAtomicsForTier(parsed.tier);
+ // The health-check probe does no reconstruction, so it is priced at the floor
+ // ($0.001) rather than the tier price the 3D generation lanes quote.
+ const priceAtomics = parsed.isHealthCheck ? HEALTH_CHECK_PRICE_ATOMIC : priceAtomicsForTier(parsed.tier);
const requirements = buildRequirements(resourceUrl, priceAtomics);
const service = withService({
serviceName: 'three.ws Forge — text/image → 3D',
@@ -574,10 +653,14 @@ export default wrap(async (req, res) => {
}
if (acResult?.grantAccess) {
let result;
- try {
- result = await submitGeneration(parsed);
- } catch (err) {
- return respondGenerationError(res, err);
+ if (parsed.isHealthCheck) {
+ result = await runForgeHealthCheck(parsed);
+ } else {
+ try {
+ result = await submitGeneration(parsed);
+ } catch (err) {
+ return respondGenerationError(res, err);
+ }
}
if (acResult.headers)
for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
@@ -628,11 +711,18 @@ export default wrap(async (req, res) => {
}
// Submit AFTER verify but BEFORE settle so a failed submit never charges.
+ // The health-check probe is the exception: it never throws and always returns a
+ // verdict (a generator outage is the signal the caller paid for), so it settles
+ // unconditionally rather than refunding on a failed completion.
let result;
- try {
- result = await submitGeneration(parsed);
- } catch (err) {
- return respondGenerationError(res, err);
+ if (parsed.isHealthCheck) {
+ result = await runForgeHealthCheck(parsed);
+ } else {
+ try {
+ result = await submitGeneration(parsed);
+ } catch (err) {
+ return respondGenerationError(res, err);
+ }
}
let settled;
@@ -684,6 +774,16 @@ async function parseRequestFromObject(body) {
const isImageMode = imageUrls.length > 0;
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
+
+ // Health-check mode: a lightweight, real content-generation canary that never
+ // reconstructs a mesh (see runForgeHealthCheck). It supplies its own default
+ // prompt, so it is never an empty "probe" and bypasses the 3–1000 char prompt
+ // rule that gates the 3D lanes. Only the documented type:"text" is supported.
+ const isHealthCheck = body.mode === 'health_check';
+ if (isHealthCheck) {
+ return { prompt, imageUrls: [], isImageMode: false, isProbe: false, isHealthCheck: true, healthType: 'text', tier, aspect };
+ }
+
const isProbe = !prompt && !isImageMode;
if (!isImageMode && !isProbe && (prompt.length < 3 || prompt.length > 1000)) {
diff --git a/api/x402/mcp-tool-catalog.js b/api/x402/mcp-tool-catalog.js
new file mode 100644
index 000000000..06a2ec5c2
--- /dev/null
+++ b/api/x402/mcp-tool-catalog.js
@@ -0,0 +1,294 @@
+// POST /api/x402/mcp-tool-catalog
+//
+// MCP Tool Discovery — $0.001 USDC per call on Solana or Base.
+//
+// Pays to discover newly-registered MCP tools on the three.ws MCP server since
+// the last probe. The server's live tool catalog (api/_mcp/catalog.js →
+// TOOL_CATALOG, the exact list /api/mcp returns from tools/list) is fingerprinted
+// and diffed against a durable registry (mcp_tool_registry). The call returns the
+// tools that are NEW since the caller last probed, the tools whose
+// shape/price/description CHANGED, and the tools that DISAPPEARED — so an agent
+// can feature-flag a new capability the moment it ships without polling
+// tools/list and diffing it by hand.
+//
+// Body: { mode?: "discover" | "list" } (default "discover")
+// discover — diff the live catalog against the durable registry, persist the
+// new state, return { new_tools, changed_tools, removed_tools, ... }.
+// list — return the live catalog snapshot only (no diff, no persistence).
+//
+// Response: { ok, mode, total_tools, new_tools[], changed_tools[],
+// removed_tools[], priced_tools, free_tools, ts }
+//
+// Real catalog, real DB diff — no mock path. The autonomous loop pays this every
+// 2 hours; new tools land in mcp_tool_registry for agent feature flagging.
+
+import { createHash } from 'node:crypto';
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor as x402PriceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+import { TOOL_CATALOG } from '../_mcp/catalog.js';
+import { priceFor as toolPriceFor } from '../_lib/pump-pricing.js';
+
+const ROUTE = '/api/x402/mcp-tool-catalog';
+
+const DESCRIPTION =
+ 'three.ws MCP Tool Discovery — pay $0.001 USDC to discover MCP tools that ' +
+ 'were registered (or whose price/shape changed, or that were removed) on the ' +
+ 'three.ws MCP server since you last probed. Returns the diff against a durable ' +
+ 'tool registry so agents can feature-flag new capabilities the moment they ship ' +
+ 'instead of re-fetching and diffing tools/list themselves.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ mode: {
+ type: 'string',
+ enum: ['discover', 'list'],
+ description:
+ '"discover" (default) diffs the live catalog against the durable registry and ' +
+ 'persists the new state. "list" returns the live catalog snapshot only.',
+ default: 'discover',
+ },
+ },
+ additionalProperties: false,
+};
+
+const TOOL_SUMMARY_SCHEMA = {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ description: { type: 'string' },
+ priced: { type: 'boolean' },
+ price_usdc: { type: ['number', 'null'] },
+ input_fields: { type: 'integer' },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ mode: 'discover',
+ total_tools: 24,
+ priced_tools: 11,
+ free_tools: 13,
+ new_tools: [
+ { name: 'segment_model', description: 'Split a mesh into named parts', priced: true, price_usdc: 0.04, input_fields: 2 },
+ ],
+ changed_tools: [
+ { name: 'render_avatar', change: 'price', price_usdc: 0.005, prev_price_usdc: 0.003 },
+ ],
+ removed_tools: [],
+ ts: '2026-06-27T10:00:00.000Z',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok', 'mode', 'total_tools', 'new_tools', 'ts'],
+ properties: {
+ ok: { type: 'boolean' },
+ mode: { type: 'string', enum: ['discover', 'list'] },
+ total_tools: { type: 'integer' },
+ priced_tools: { type: 'integer' },
+ free_tools: { type: 'integer' },
+ new_tools: { type: 'array', items: TOOL_SUMMARY_SCHEMA },
+ changed_tools: { type: 'array', items: { type: 'object' } },
+ removed_tools: { type: 'array', items: { type: 'string' } },
+ tools: { type: 'array', items: TOOL_SUMMARY_SCHEMA },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['mcp tool discovery', 'agent feature flagging', 'capability registry'],
+ input: { type: 'json', example: { mode: 'discover' }, schema: INPUT_SCHEMA },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+let _schemaReady = false;
+async function ensureSchema() {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS mcp_tool_registry (
+ tool_name text PRIMARY KEY,
+ description text,
+ priced boolean NOT NULL DEFAULT false,
+ price_usdc numeric(12,6),
+ input_fields int NOT NULL DEFAULT 0,
+ fingerprint text NOT NULL,
+ active boolean NOT NULL DEFAULT true,
+ first_seen_at timestamptz NOT NULL DEFAULT now(),
+ last_seen_at timestamptz NOT NULL DEFAULT now(),
+ run_id uuid
+ )
+ `;
+ _schemaReady = true;
+}
+
+// Count the declared input properties of a tool's JSON Schema (0 if none).
+function inputFieldCount(inputSchema) {
+ const props = inputSchema && typeof inputSchema === 'object' ? inputSchema.properties : null;
+ return props && typeof props === 'object' ? Object.keys(props).length : 0;
+}
+
+// Project the live catalog into the comparable shape we persist + diff on. The
+// price comes from the same TOOL_PRICING table the MCP server uses to annotate
+// tools/list, so a price change here is the price change a paying client sees.
+function projectCatalog() {
+ return TOOL_CATALOG.map((t) => {
+ const price = toolPriceFor(t.name);
+ const priced = !!price;
+ const priceUsdc = priced && typeof price.amount_usdc === 'number' ? price.amount_usdc : null;
+ const description = typeof t.description === 'string' ? t.description : '';
+ const inputFields = inputFieldCount(t.inputSchema);
+ // Stable fingerprint: any change to the contract a caller depends on
+ // (description, paid/free, price, input shape) flips it. Sorted input
+ // keys keep it order-independent across server restarts.
+ const inputKeys = t.inputSchema && t.inputSchema.properties
+ ? Object.keys(t.inputSchema.properties).sort().join(',')
+ : '';
+ const fingerprint = createHash('sha256')
+ .update(`${t.name}\n${description}\n${priced ? '1' : '0'}\n${priceUsdc ?? ''}\n${inputKeys}`)
+ .digest('hex')
+ .slice(0, 32);
+ return { name: t.name, description, priced, price_usdc: priceUsdc, input_fields: inputFields, fingerprint };
+ });
+}
+
+function summary(t) {
+ return {
+ name: t.name,
+ description: t.description.length > 200 ? t.description.slice(0, 200) + '…' : t.description,
+ priced: t.priced,
+ price_usdc: t.price_usdc,
+ input_fields: t.input_fields,
+ };
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: x402PriceFor('mcp-tool-catalog', '1000'), // $0.001 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws MCP Tool Discovery',
+ tags: ['mcp', 'discovery', 'tools', 'catalog', 'feature-flag', 'agent'],
+ }),
+
+ async handler({ req }) {
+ let mode = 'discover';
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
+ if (body.mode === 'list') mode = 'list';
+ } catch { /* default mode */ }
+
+ const current = projectCatalog();
+ const priced = current.filter((t) => t.priced).length;
+ const ts = new Date().toISOString();
+
+ if (mode === 'list') {
+ return {
+ ok: true,
+ mode,
+ total_tools: current.length,
+ priced_tools: priced,
+ free_tools: current.length - priced,
+ new_tools: [],
+ changed_tools: [],
+ removed_tools: [],
+ tools: current.map(summary),
+ ts,
+ };
+ }
+
+ await ensureSchema();
+
+ // Snapshot the durable registry BEFORE writing so the diff reflects what
+ // changed since the previous probe.
+ const prevRows = await sql`SELECT tool_name, fingerprint, price_usdc, active FROM mcp_tool_registry`;
+ const prev = new Map(prevRows.map((r) => [r.tool_name, r]));
+ const currentNames = new Set(current.map((t) => t.name));
+
+ const newTools = [];
+ const changedTools = [];
+ for (const t of current) {
+ const before = prev.get(t.name);
+ if (!before) {
+ newTools.push(summary(t));
+ } else if (before.fingerprint !== t.fingerprint) {
+ const prevPrice = before.price_usdc != null ? Number(before.price_usdc) : null;
+ const change = !before.active
+ ? 'reactivated'
+ : prevPrice !== t.price_usdc
+ ? 'price'
+ : 'shape';
+ changedTools.push({
+ name: t.name,
+ change,
+ price_usdc: t.price_usdc,
+ prev_price_usdc: prevPrice,
+ priced: t.priced,
+ });
+ }
+ }
+
+ // Tools present in the registry but gone from the live catalog: mark them
+ // inactive (a removed capability is a feature-flag signal too).
+ const removedTools = prevRows
+ .filter((r) => r.active && !currentNames.has(r.tool_name))
+ .map((r) => r.tool_name);
+
+ // Persist the new catalog state. Upsert every live tool (refresh metadata +
+ // last_seen, preserve first_seen), then deactivate the removed ones.
+ for (const t of current) {
+ await sql`
+ INSERT INTO mcp_tool_registry
+ (tool_name, description, priced, price_usdc, input_fields,
+ fingerprint, active, first_seen_at, last_seen_at)
+ VALUES
+ (${t.name}, ${t.description}, ${t.priced}, ${t.price_usdc},
+ ${t.input_fields}, ${t.fingerprint}, true, ${ts}, ${ts})
+ ON CONFLICT (tool_name) DO UPDATE SET
+ description = EXCLUDED.description,
+ priced = EXCLUDED.priced,
+ price_usdc = EXCLUDED.price_usdc,
+ input_fields = EXCLUDED.input_fields,
+ fingerprint = EXCLUDED.fingerprint,
+ active = true,
+ last_seen_at = EXCLUDED.last_seen_at
+ `;
+ }
+ if (removedTools.length > 0) {
+ await sql`
+ UPDATE mcp_tool_registry
+ SET active = false, last_seen_at = ${ts}
+ WHERE tool_name = ANY(${removedTools})
+ `;
+ }
+
+ return {
+ ok: true,
+ mode,
+ total_tools: current.length,
+ priced_tools: priced,
+ free_tools: current.length - priced,
+ new_tools: newTools,
+ changed_tools: changedTools,
+ removed_tools: removedTools,
+ ts,
+ };
+ },
+});