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: implement cross-network payment circuit breaker for x402 payment stack liveness

nirholas209355dc5650
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5a7dbf5a8..2d24c8f71 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Task input on Agent Screen — send your agent a task and watch it work** — You can now type any task directly into the Agent Screen page and your agent picks it up in real time. The live screen panel has a new command bar at the bottom: type what you want your agent to do (research, browse, shop, monitor, trade) and hit send. The task is queued via /api/agent-task and the running worker executes it with Stagehand, streaming every browser action back to the live screen as it happens. The worker automatically checks for new tasks every 3 seconds and runs them in priority order, falling back to its autonomous loop when the queue is empty. (`/agent-screen`) `[feature, improvement]`
- **The launcher now reads Know Your Meme** — The autonomous coin launcher gained a new culture feed: Know Your Meme. It reads the freshly-confirmed meme entries and the live meme newsfeed, fuses them with the platform's on-chain signals, and rides the strongest wave when an agent coins its next launch — so new launches track the memes actually entering culture right now, not stale themes. As always, only the cultural THEME is mined; names and tickers are invented fresh, never copied, and every coin stays avatar-fronted and $THREE-aligned. `[feature, improvement]`
- **Top Performers podium on marketplace — oracle-ranked agent leaderboard** — The marketplace now surfaces the top 3 oracle-performing agents in trophy-style cards above the agent grid. Each card shows oracle win rate, W/L record, and realized PnL. Rank 1 gets gold, rank 2 silver, rank 3 bronze. Cards shimmer while loading and disappear cleanly when no oracle data exists. Links directly to each agent's profile. (`/marketplace`) `[feature, improvement]`
+- **Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint** — The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured. `[feature, infra]`
- **Walk-Browse the Marketplace is now monochrome and agent-readable** — The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner. (`/marketplace-walk`) `[improvement]`
- **Wallet sign-in fixed and a cleaner, monochrome login** — Restored Ethereum (SIWE) and Solana (SIWS) wallet sign-in and the active-sessions controls, which had been unreachable due to missing API route mappings. Also refined the sign-in and sign-up screens to a crisp monochrome palette — neutral chain icons, calmer focus and hover states — for a faster, more focused first impression. `[fix, improvement]`
- **x402 payments dashboards refined to the monochrome system** — The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console. (`/dashboard/x402`) `[improvement]`
diff --git a/api/_lib/pump-pricing.js b/api/_lib/pump-pricing.js
index 0baf5b726..b4620c2d5 100644
--- a/api/_lib/pump-pricing.js
+++ b/api/_lib/pump-pricing.js
@@ -37,6 +37,10 @@ export const TOOL_PRICING = Object.freeze({
// per search; authenticated OAuth callers bypass payment entirely (they hold a
// bearer token, so authenticateRequest never issues the x402 challenge).
search_public_avatars: { amount_usdc: 0.001, description: 'Per call — public avatar gallery search' },
+ // On-chain agent reputation summary — a cheap indexed read, priced so the
+ // autonomous reputation-refresh pipeline exercises it as a real x402 call and
+ // external agents pay the going rate to vet a counterparty.
+ solana_agent_reputation: { amount_usdc: 0.001, description: 'Per call — on-chain agent reputation summary' },
// Discovery / lookups (incl. list_animations) — free
});
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 056ff9d2e..1d77bc73a 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -34,6 +34,7 @@
// discovery warmup sweeping 15 categories per run).
import { run as bazaarDiscoveryWarmup } from './pipelines/bazaar-warmup.js';
+import { run as avatarSearchWarmup } from './pipelines/avatar-search-warmup.js';
import { run as reputationRefresh } from './pipelines/reputation-refresh.js';
import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';
import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';
@@ -658,6 +659,27 @@ const SELF_ENDPOINTS = [
enabled: true,
extractSignal: (r) => ({ count: r?.audits?.length, top_score: r?.audits?.[0]?.score }),
},
+ // Token Intel Pre-Snipe Gate (USE-023) — pays the $0.01 USDC Token Oracle
+ // (/api/x402/token-intel) for the freshest pump.fun mints the sniper is about
+ // to consider, turning the due-diligence risk.score into a 0..100 rugpull
+ // sub-score. run() owns the batch sequence + per-mint recording; the loop
+ // records one summary row. Verdicts upsert to token_intel_risk keyed by
+ // (mint, network). Cooldown 1200s (20 min) → ~3 batches/hour, ~$0.09/hr at the
+ // default batch of 3 — bounded again by the loop's daily cap.
+ // Downstream consumer: workers/agent-sniper/oracle-gate.js auto-rejects any
+ // mint with a fresh `rejected = true` verdict before committing SOL.
+ {
+ id: 'token-intel-presnipe-gate',
+ name: 'Token Intel Pre-Snipe Gate',
+ path: '/api/x402/token-intel',
+ method: 'GET',
+ body: null,
+ cooldown_s: 1200,
+ priority: 78,
+ pipeline: 'sniper',
+ enabled: true,
+ run: (ctx) => tokenIntelPreSnipeGate(ctx),
+ },
// ── Identity / DID ─────────────────────────────────────────────────────────
{
@@ -800,6 +822,28 @@ const SELF_ENDPOINTS = [
run: (ctx) => bazaarDiscoveryWarmup(ctx),
},
+ // ── Avatar Search Index Warmup (USE-003) ───────────────────────────────────
+ // Fires ~20 common gallery queries (human, robot, anime, warrior, …) through
+ // the MCP server (/api/mcp → search_public_avatars) at $0.001/call, proving the
+ // full search path returns ranked results WITH resolved thumbnails on a cold
+ // start. run() owns the 20-call sequence and per-call recording; the loop
+ // records one summary row. Cooldown 21600s (every 6h) → ~20 calls/run ≈
+ // $0.08/day. Each query's ranked, thumbnail-resolved slice is upserted into
+ // avatar_search_warm_cache; GET /api/avatars/popular-searches reads it to power
+ // the gallery's popular-search chips and instant cached results.
+ {
+ id: 'avatar-search-index-warmup',
+ name: 'Avatar Search Index Warmup',
+ path: '/api/mcp',
+ method: 'POST',
+ body: null,
+ cooldown_s: 21600,
+ priority: 38,
+ pipeline: 'discovery',
+ enabled: true,
+ run: (ctx) => avatarSearchWarmup(ctx),
+ },
+
// ── Agent Reputation Score Refresh (USE-005) ───────────────────────────────
// Refreshes the on-chain attestation reputation of the stalest registered
// Solana agents by paying the /api/mcp tool solana_agent_reputation
@@ -851,6 +895,36 @@ const SELF_ENDPOINTS = [
run: (ctx) => volumeBootstrapLoop(ctx),
},
+ // ── Live Payment Feed Seeder (USE-025) ─────────────────────────────────────
+ // Keeps the homepage "live payment feed" (the /pay page, the in-world
+ // jumbotron and the exchange NPCs — all polling GET /api/x402-pay?feed=1)
+ // populated with recent activity. The Redis ring that feed renders
+ // (x402:pay:feed) is written ONLY by real /api/x402-pay demo payments, so
+ // with no organic traffic it goes stale and a visitor sees a dead system.
+ // run() makes ONE real on-chain $0.001 USDC demo payment per tick through the
+ // platform-wallet demo flow (signed by X402_AGENT_SOLANA_SECRET_BASE58
+ // server-side), rotating across MCP tools (avatar search / model inspect /
+ // validate / optimize / capability discovery) so the feed shows variety, not
+ // one repeated call. The demo call pushes the receipt onto the Redis ring
+ // (the hot path) and run() mirrors it durably into x402_demo_feed. Cooldown
+ // 300s → one fresh feed entry every 5-min tick ≈ $0.29/day, bounded again by
+ // the loop's daily cap. Value sink: x402_demo_feed (durable activity history +
+ // Redis-eviction backstop). Downstream consumer: the homepage/jumbotron/NPC
+ // live feed via /api/x402-pay?feed=1.
+ {
+ id: 'live-feed-seeder',
+ name: 'Live Payment Feed Seeder',
+ // path is informational — run() rotates the demo-call set against /api/x402-pay.
+ path: '/api/x402-pay',
+ method: 'POST',
+ body: null,
+ cooldown_s: 300,
+ priority: 72,
+ pipeline: 'feed',
+ enabled: true,
+ run: (ctx) => liveFeedSeeder(ctx),
+ },
+
// ── Model Metadata Enrichment (USE-016) ────────────────────────────────────
// Finds public avatars with no tags and pays inspect_model ($0.01/call via
// /api/mcp) to parse each GLB, then derives searchable feature tags + a model
diff --git a/api/_lib/x402/circuit-breaker.js b/api/_lib/x402/pipelines/circuit-breaker.js
similarity index 100%
rename from api/_lib/x402/circuit-breaker.js
rename to api/_lib/x402/pipelines/circuit-breaker.js
diff --git a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
index d20dc6592..9c9ebcac7 100644
--- a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
+++ b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
@@ -52,7 +52,7 @@ import {
payX402,
fetchWithTimeout,
parseSolanaAccept,
-} from '../solana-payer.js';
+} from '../pay.js';
const log = logger('x402-cosmetic-pricing-audit');
diff --git a/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
new file mode 100644
index 000000000..a4391837b
--- /dev/null
+++ b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
@@ -0,0 +1,425 @@
+// api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
+//
+// Payment Proof Idempotency Audit — autonomous pipeline (self/idempotency).
+//
+// A run()-style registry entry (autonomous-registry.js → `payment-proof-idempotency-audit`)
+// the per-tick spend loop invokes once a day. It is the platform's anti-fraud
+// canary: it proves the x402 idempotency store actually prevents a replayed
+// payment proof from settling twice.
+//
+// Why a run() pipeline and not a declarative entry: the audit makes ONE real
+// $0.001 payment and then deliberately submits the SAME signed X-PAYMENT proof a
+// second time, inspecting response headers across both calls. The declarative
+// probe+pay path builds a fresh tx per call and can't replay an identical proof,
+// so this needs to own its full sequence.
+//
+// On each run it:
+// 1. Probes GET /api/x402/model-check (the cheapest idempotent, payment-
+// identifier-aware endpoint, $0.001) for the live 402 challenge.
+// 2. Builds ONE real Solana USDC payment proof — signed with the platform seed
+// wallet via ../pay.js, never mocked — carrying a client payment-identifier
+// (the USE-15 idempotency extension) so the named store is exercised, not
+// just the always-on proof-hash fallback.
+// 3. Fires the paid request once → expects 200 + on-chain settlement (tx_A).
+// 4. Submits the IDENTICAL X-PAYMENT header again (retried briefly to let the
+// cross-replica idempotency cache write land). A correct store either
+// replays the cached 200 (`x-x402-idempotent: replay`) or rejects with a
+// 409 conflict / in-flight — in every case carrying NO new on-chain
+// settlement. The audit fails only if the second call settles a NEW,
+// distinct tx (a real double-settlement).
+// 5. Records the verdict to `x402_idempotency_audit` and raises an ops alert if
+// a double-settlement is ever observed.
+//
+// Recording: the loop records one x402_autonomous_log row per run (the returned
+// signalData lands in signal_data, amountAtomic reflects ONLY the single first
+// charge). The dedicated value sink is the `x402_idempotency_audit` table written
+// here — one row per audit with the full two-call evidence and the pass/fail
+// verdict.
+//
+// Downstream consumer: api/ops/health.js reads the latest `x402_idempotency_audit`
+// row and folds a confirmed double-settlement into the platform health verdict
+// (alongside the cross-network circuit breaker), so the status page / on-call
+// surface a broken anti-replay guard immediately.
+
+import { randomUUID } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ getMint,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import {
+ PAYMENT_IDENTIFIER,
+ generatePaymentId,
+} from '@x402/extensions/payment-identifier';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { sendOpsAlert } from '../../alerts.js';
+import { solanaConnection } from '../../solana/connection.js';
+import {
+ loadSeedKeypair,
+ parseSolanaAccept,
+ buildPaymentTx,
+ fetchWithTimeout,
+ USDC_MINT,
+ SOLANA_RPC,
+} from '../pay.js';
+
+const log = logger('x402-idempotency-audit');
+
+// The audit target: the cheapest endpoint that hand-rolls the x402 dance AND
+// wires the USE-15 idempotency cache (checkCache → writeCachedResponse). $0.001,
+// GET, deterministic. fox.glb is a tiny public canary the server fetches behind
+// its SSRF guard; pinned to the canonical public origin (not the loop's runtime
+// origin) so model-check always has a real public asset to inspect.
+const AUDIT_ROUTE = '/api/x402/model-check';
+const CANARY_GLB = 'https://three.ws/avatars/fox.glb';
+
+// The second (replay) submission can land before the first call's storeResponse
+// write has propagated across Upstash replicas. Retry the replay a few times,
+// spaced out, breaking as soon as the idempotency store answers — this makes the
+// cache-hit path deterministic without guessing a single magic delay. Each miss
+// is harmless: an identical, already-settled Solana tx cannot re-settle on-chain,
+// so a cache miss degrades to an on-chain-blocked settle, never a double charge.
+const REPLAY_ATTEMPTS = 4;
+const REPLAY_BACKOFF_MS = 600;
+
+const usdcMint = () => USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Pull the settled on-chain tx signature out of an X-PAYMENT-RESPONSE header.
+function txFromResponse(headers) {
+ const xpr = headers?.get?.('x-payment-response');
+ if (!xpr) return null;
+ try {
+ const settled = JSON.parse(Buffer.from(xpr, 'base64').toString('utf8'));
+ return settled?.transaction || null;
+ } catch {
+ // Header present but unparseable — settlement happened, signature unknown.
+ return null;
+ }
+}
+
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_idempotency_audit (
+ id bigserial PRIMARY KEY,
+ ts timestamptz DEFAULT now(),
+ run_id uuid,
+ route text NOT NULL,
+ payment_id text,
+ first_status int,
+ first_tx text,
+ first_settled boolean NOT NULL DEFAULT false,
+ second_status int,
+ second_tx text,
+ second_marker text,
+ replay_attempts int,
+ verdict text NOT NULL,
+ double_settled boolean NOT NULL DEFAULT false,
+ pass boolean NOT NULL,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ duration_ms int,
+ error_msg text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_idempotency_audit_ts ON x402_idempotency_audit (ts DESC)`;
+ _schemaReady = true;
+}
+
+async function storeAudit(sql, runId, row) {
+ try {
+ await ensureSchema(sql);
+ await sql`
+ INSERT INTO x402_idempotency_audit
+ (run_id, route, payment_id, first_status, first_tx, first_settled,
+ second_status, second_tx, second_marker, replay_attempts, verdict,
+ double_settled, pass, amount_atomic, duration_ms, error_msg)
+ VALUES
+ (${runId || null}, ${row.route}, ${row.payment_id || null},
+ ${row.first_status}, ${row.first_tx || null}, ${row.first_settled},
+ ${row.second_status}, ${row.second_tx || null}, ${row.second_marker || null},
+ ${row.replay_attempts}, ${row.verdict}, ${row.double_settled}, ${row.pass},
+ ${row.amount_atomic || 0}, ${row.duration_ms}, ${row.error_msg || null})
+ `;
+ } catch (err) {
+ // A DB fault must never crash the loop — log and move on.
+ log.warn('idempotency_audit_insert_failed', { message: err?.message });
+ }
+}
+
+/**
+ * Run the payment-proof idempotency audit. Self-contained: builds its own Solana
+ * payment context when one isn't supplied, so it can be invoked directly (manual
+ * test / standalone) or handed the per-tick loop's shared blockhash + keypair.
+ *
+ * @param {object} [ctx] — supplied by the loop:
+ * { origin, buyer, conn, blockhash, mintInfo, redis, sql, log, runId, remainingCap }
+ * @returns {Promise<{success:boolean, amountAtomic:number, txSig:string|null,
+ * responseData:object|null, signalData:object, errorMsg:string|null,
+ * skipped?:boolean, note?:string}>} the outcome the loop records to
+ * x402_autonomous_log.
+ */
+export async function runIdempotencyAudit(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const sql = ctx.sql || defaultSql;
+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+ const endpointUrl = `${origin}${AUDIT_ROUTE}?url=${encodeURIComponent(CANARY_GLB)}`;
+ const t0 = Date.now();
+
+ const fail = (errorMsg, extra = {}) => ({
+ success: false,
+ amountAtomic: 0,
+ txSig: null,
+ responseData: null,
+ signalData: { audited: false, route: AUDIT_ROUTE, error: errorMsg },
+ errorMsg,
+ ...extra,
+ });
+
+ // ── Wallet pre-flight: exit gracefully (logged) if unconfigured ────────────
+ let buyer = ctx.buyer;
+ if (!buyer) {
+ try {
+ buyer = loadSeedKeypair();
+ } catch (err) {
+ log.info('idempotency_audit_skipped', { reason: err.message });
+ return fail(`wallet_unconfigured: ${err.message}`, { skipped: true });
+ }
+ }
+
+ // ── Solana payment context (reuse loop's, else build our own) ──────────────
+ let conn = ctx.conn;
+ let blockhash = ctx.blockhash;
+ let mintInfo = ctx.mintInfo;
+ if (!conn || !blockhash || !mintInfo) {
+ try {
+ conn = conn || solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ const [bh, mi] = await Promise.all([
+ blockhash ? Promise.resolve({ blockhash }) : conn.getLatestBlockhash('confirmed'),
+ mintInfo ? Promise.resolve(mintInfo) : getMint(conn, new PublicKey(usdcMint())),
+ ]);
+ blockhash = blockhash || bh.blockhash;
+ mintInfo = mintInfo || mi;
+ } catch (err) {
+ log.warn('idempotency_audit_solana_preflight_failed', { message: err?.message });
+ return fail(`solana_preflight_failed: ${err?.message}`, { skipped: true });
+ }
+ }
+
+ // ── Step 1: probe for the 402 challenge ────────────────────────────────────
+ let probe;
+ try {
+ probe = await fetchWithTimeout(endpointUrl, {
+ method: 'GET',
+ headers: { 'user-agent': 'threews-x402-autonomous/1.0' },
+ });
+ } catch (err) {
+ return fail(`probe_failed: ${err?.message || 'network'}`);
+ }
+ if (probe.status !== 402) return fail(`unexpected_probe_status: ${probe.status}`);
+ const accept = parseSolanaAccept(probe.body);
+ if (!accept) return fail('no_solana_accept');
+ if (accept.asset !== usdcMint()) return fail(`unexpected_asset: ${accept.asset}`);
+ if (!accept.extra?.feePayer) return fail('missing_fee_payer');
+
+ const amountAtomic = Number(accept.amount || 0);
+ if (!(amountAtomic > 0)) return fail('zero_price');
+ if (amountAtomic > remainingCap) return fail('cap_would_exceed', { skipped: true });
+
+ // ── Step 2: build ONE signed payment proof carrying a payment-identifier ───
+ // The same base64 header is replayed verbatim in step 4 — that single proof
+ // is the whole point of the audit. The payment-identifier (USE-15) keys the
+ // named idempotency store; the raw-header hash is the always-on fallback. Both
+ // must point a replay at the cached response, never a second settlement.
+ const paymentId = generatePaymentId();
+ let xPayment;
+ try {
+ const receiverAta = getAssociatedTokenAddressSync(
+ new PublicKey(accept.asset), new PublicKey(accept.payTo),
+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);
+ const txBase64 = buildPaymentTx({
+ accept, buyer, blockhash, mintInfo, receiverAtaExists: receiverAtaInfo !== null,
+ });
+ xPayment = Buffer.from(JSON.stringify({
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: endpointUrl, mimeType: 'application/json' },
+ payload: { transaction: txBase64 },
+ accepted: accept,
+ // USE-15 idempotency extension — server reads info.id as the cache key.
+ extensions: { [PAYMENT_IDENTIFIER]: { info: { required: false, id: paymentId } } },
+ })).toString('base64');
+ } catch (err) {
+ return fail(`build_payment_failed: ${err?.message || 'unknown'}`);
+ }
+
+ const paidHeaders = {
+ 'user-agent': 'threews-x402-autonomous/1.0',
+ 'x-payment': xPayment,
+ };
+
+ // ── Step 3: first paid submission → expect a real on-chain settlement ──────
+ let first;
+ try {
+ first = await fetchWithTimeout(endpointUrl, { method: 'GET', headers: paidHeaders });
+ } catch (err) {
+ return fail(`first_call_failed: ${err?.message || 'network'}`);
+ }
+ const firstTx = first.ok ? txFromResponse(first.headers) : null;
+ const firstSettled = !!(first.ok && firstTx);
+ const firstMarker = first.headers?.get?.('x-x402-idempotent') || null;
+
+ // The first call must actually settle for there to be anything to double-spend.
+ // A 402 (payment rejected), a non-settling 200, or a first call that itself
+ // replays an earlier proof leaves nothing to audit — record inconclusive, no
+ // spend booked.
+ if (!firstSettled) {
+ const why = first.status === 402
+ ? 'first_call_402_rejected'
+ : firstMarker
+ ? `first_call_replayed:${firstMarker}`
+ : `first_call_not_settled:http_${first.status}`;
+ const durationMs = Date.now() - t0;
+ await storeAudit(sql, runId, {
+ route: AUDIT_ROUTE, payment_id: paymentId,
+ first_status: first.status, first_tx: firstTx, first_settled: false,
+ second_status: null, second_tx: null, second_marker: null,
+ replay_attempts: 0, verdict: 'inconclusive', double_settled: false,
+ pass: false, amount_atomic: 0, duration_ms: durationMs, error_msg: why,
+ });
+ log.info('idempotency_audit_inconclusive', { run_id: runId, reason: why, status: first.status });
+ return {
+ success: false, amountAtomic: 0, txSig: firstTx,
+ responseData: { first_status: first.status },
+ signalData: { audited: false, route: AUDIT_ROUTE, verdict: 'inconclusive', reason: why },
+ errorMsg: why, note: why,
+ };
+ }
+
+ // ── Step 4: replay the IDENTICAL proof → must NOT settle a second time ─────
+ let second = null;
+ let secondTx = null;
+ let secondMarker = null;
+ let doubleSettled = false;
+ let attempts = 0;
+ for (let i = 0; i < REPLAY_ATTEMPTS; i++) {
+ attempts = i + 1;
+ // Let the first call's cross-replica cache write land before each attempt.
+ await sleep(REPLAY_BACKOFF_MS);
+ try {
+ second = await fetchWithTimeout(endpointUrl, { method: 'GET', headers: paidHeaders });
+ } catch (err) {
+ second = { ok: false, status: 0, headers: null, body: { error: err?.message || 'network' } };
+ continue;
+ }
+ secondMarker = second.headers?.get?.('x-x402-idempotent') || null;
+ secondTx = second.ok ? txFromResponse(second.headers) : null;
+ // A distinct, freshly-settled tx on the replay is the one failure mode that
+ // matters: the anti-replay guard let the same proof settle twice.
+ if (secondTx && secondTx !== firstTx) {
+ doubleSettled = true;
+ break;
+ }
+ // The idempotency store answered (replay / conflict / in-flight) → done.
+ if (secondMarker) break;
+ // No marker and no new settlement: a cache miss that the on-chain layer
+ // blocked (already-processed tx). Retry to give the store time to populate.
+ }
+
+ const durationMs = Date.now() - t0;
+
+ // ── Step 5: classify the verdict ───────────────────────────────────────────
+ // pass = the second submission produced NO new on-chain settlement. The store
+ // proves it via a replay/conflict/in-flight marker; absent a marker, the audit
+ // still passes only because no distinct tx settled (on-chain backstop), but
+ // that path is flagged so a silently-degraded cache store is visible.
+ let verdict;
+ if (doubleSettled) {
+ verdict = 'double_settled';
+ } else if (secondMarker === 'replay') {
+ verdict = 'idempotent_replay';
+ } else if (secondMarker === 'conflict') {
+ verdict = 'idempotent_conflict';
+ } else if (secondMarker === 'in-flight') {
+ verdict = 'idempotent_inflight';
+ } else if (second && !second.ok && !secondTx) {
+ // Second submission failed to settle (e.g. on-chain rejected the duplicate
+ // tx) without the store ever answering — no double-spend, but the store
+ // didn't demonstrably catch it.
+ verdict = 'settle_blocked_no_marker';
+ } else {
+ verdict = 'no_double_settle_no_marker';
+ }
+ const pass = !doubleSettled;
+ const errorMsg = doubleSettled
+ ? `double_settlement: first=${firstTx} second=${secondTx}`
+ : verdict.endsWith('no_marker')
+ ? `replay_unconfirmed:${verdict}`
+ : null;
+
+ const signalData = {
+ audited: true,
+ route: AUDIT_ROUTE,
+ verdict,
+ pass,
+ double_settled: doubleSettled,
+ payment_id: paymentId,
+ first_tx: firstTx,
+ second_marker: secondMarker,
+ second_status: second?.status ?? null,
+ replay_attempts: attempts,
+ };
+
+ await storeAudit(sql, runId, {
+ route: AUDIT_ROUTE, payment_id: paymentId,
+ first_status: first.status, first_tx: firstTx, first_settled: true,
+ second_status: second?.status ?? null, second_tx: secondTx, second_marker: secondMarker,
+ replay_attempts: attempts, verdict, double_settled: doubleSettled,
+ pass, amount_atomic: amountAtomic, duration_ms: durationMs, error_msg: errorMsg,
+ });
+
+ if (doubleSettled) {
+ // Fire-and-forget: a confirmed double-settlement is a fraud-critical event.
+ sendOpsAlert(
+ 'x402 idempotency store FAILED — double settlement',
+ `${AUDIT_ROUTE}: the same payment proof settled twice — ` +
+ `first tx ${firstTx}, second tx ${secondTx} (payment-id ${paymentId}). ` +
+ 'The anti-replay guard is not protecting paid endpoints.',
+ { signature: 'x402-idempotency:double-settle' },
+ ).catch(() => {});
+ }
+
+ log.info('idempotency_audit_complete', {
+ run_id: runId, verdict, pass, double_settled: doubleSettled,
+ first_tx: firstTx, second_marker: secondMarker, attempts, duration_ms: durationMs,
+ });
+
+ // amountAtomic reflects ONLY the single legitimate first charge — a correct
+ // audit moves USDC exactly once. txSig is that first settlement.
+ return {
+ success: pass,
+ amountAtomic,
+ txSig: firstTx,
+ responseData: {
+ first: { status: first.status, tx: firstTx },
+ second: { status: second?.status ?? null, tx: secondTx, marker: secondMarker },
+ },
+ signalData,
+ errorMsg,
+ note: verdict,
+ };
+}
+
+// Alias matching the pipelines convention (bazaar-warmup exports `run`).
+export { runIdempotencyAudit as run };
diff --git a/api/x402/glb-optimization-report.js b/api/x402/glb-optimization-report.js
new file mode 100644
index 000000000..32a52e13b
--- /dev/null
+++ b/api/x402/glb-optimization-report.js
@@ -0,0 +1,52 @@
+// GET /api/x402/glb-optimization-report — GLB Size Optimizer catalog feed.
+//
+// Free operational read (parity with /api/x402/mcp-perf): surfaces what the
+// `glb-size-optimizer` autonomous-loop entry (api/_lib/x402/autonomous-registry.js)
+// has measured. That loop pays a real x402 optimize_model call against /api/mcp
+// every 6 hours for the heaviest un-analyzed public GLB over the 5 MB budget,
+// then writes the original size, projected post-optimization size, and load-time
+// improvement to glb_optimizations. This endpoint is the downstream consumer: it
+// reports the catalog-wide average savings + load-time improvement, the total
+// bytes the catalog would shed, and the remaining backlog of heavy GLBs.
+//
+// Query: ?window=<days> (default 90, max 365) — the rolling analysis window.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { readCatalogOptimizationSummary } from '../_lib/x402/glb-size-optimizer.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let windowDays = 90;
+ try {
+ const u = new URL(req.url, 'http://localhost');
+ const w = Number(u.searchParams.get('window'));
+ if (Number.isFinite(w) && w > 0) windowDays = Math.min(Math.max(w, 1), 365);
+ } catch { /* default window */ }
+
+ try {
+ const summary = await readCatalogOptimizationSummary({ windowDays });
+ // 200 always — the dashboard renders the state itself; a non-2xx here would
+ // be indistinguishable from the endpoint being down.
+ return json(res, 200, { ...summary, generated_at: new Date().toISOString() });
+ } catch (err) {
+ // Table absent (loop never ran) or DB hiccup — report empty-but-ok so the
+ // dashboard shows "no data yet" instead of an error void.
+ const noData = /does not exist/i.test(err?.message || '');
+ return json(res, noData ? 200 : 503, {
+ ok: noData,
+ window_days: windowDays,
+ analyzed_count: 0,
+ backlog_count: 0,
+ total_savings_bytes: 0,
+ total_savings_mb: 0,
+ avg_savings_pct: 0,
+ avg_load_improvement_pct: 0,
+ models: [],
+ note: noData ? 'no_optimizations_yet' : undefined,
+ error: noData ? undefined : 'report_read_failed',
+ generated_at: new Date().toISOString(),
+ });
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index 726333e9d..ae5eb5e18 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -7,6 +7,12 @@
"summary": "The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions.",
"tags": ["feature", "infra"]
},
+ {
+ "date": "2026-06-27",
+ "title": "Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint",
+ "summary": "The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured.",
+ "tags": ["feature", "infra"]
+ },
{
"date": "2026-06-27",
"title": "MCP Tool Latency Monitor — live SLA health for every MCP tool",
diff --git a/public/changelog.json b/public/changelog.json
index ad8a4a7ce..33ebfd4fe 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:09:05.881Z",
+ "generated_at": "2026-06-27T23:09:27.459Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -516,6 +516,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint",
+ "summary": "The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 07954d0bb..88698e7aa 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -390,6 +390,14 @@
<category>feature</category>
<description>The marketplace now surfaces the top 3 oracle-performing agents in trophy-style cards above the agent grid. Each card shows oracle win rate, W/L record, and realized PnL. Rank 1 gets gold, rank 2 silver, rank 3 bronze. Cards shimmer while loading and disappear cleanly when no oracle data exists. Links directly to each agent's profile.</description>
</item>
+ <item>
+ <title>Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured.</description>
+ </item>
<item>
<title>Walk-Browse the Marketplace is now monochrome and agent-readable</title>
<link>https://three.ws/marketplace-walk</link>
diff --git a/public/features.json b/public/features.json
index 53fff8313..421e38238 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:09:05.819Z",
+ "generated_at": "2026-06-27T23:09:27.441Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/three-signal-feed.test.js b/tests/three-signal-feed.test.js
new file mode 100644
index 000000000..4c97053fe
--- /dev/null
+++ b/tests/three-signal-feed.test.js
@@ -0,0 +1,154 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ classifyThreeSignal,
+ usdToThreeTokens,
+ insertThreeSignal,
+ getThreeSignalHistory,
+ THREE_DECIMALS,
+} from '../api/_lib/x402/three-signal-store.js';
+import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+// A live three-intel response (DexScreener-backed shape).
+const SAMPLE = {
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ symbol: 'THREE',
+ price_usd: 0.003685,
+ change_24h: 12.4,
+ market_cap_usd: 3685000,
+ liquidity_usd: 412000,
+ volume_24h_usd: 1268079,
+ signal: 'bullish',
+ headline: 'THREE climbs +12.40% — moderate upside',
+ rationale: 'THREE gained +12.40% over 24 h.',
+ confidence: 0.86,
+ ts: '2026-06-27T10:00:00Z',
+};
+
+// Minimal mock of the tagged-template `sql` client: records every query's text
+// and interpolated values so we can assert on what the store wrote.
+function mockSql() {
+ const calls = [];
+ const fn = (strings, ...values) => {
+ calls.push({ text: strings.join('?').replace(/\s+/g, ' ').trim(), values });
+ return Promise.resolve([]);
+ };
+ fn.calls = calls;
+ return fn;
+}
+
+describe('three-signal-store — classifyThreeSignal', () => {
+ it('carries the full market shape through', () => {
+ const v = classifyThreeSignal(SAMPLE);
+ expect(v.mint).toBe(SAMPLE.mint);
+ expect(v.symbol).toBe('THREE');
+ expect(v.price_usd).toBe(0.003685);
+ expect(v.change_24h).toBe(12.4);
+ expect(v.market_cap_usd).toBe(3685000);
+ expect(v.liquidity_usd).toBe(412000);
+ expect(v.volume_24h_usd).toBe(1268079);
+ expect(v.signal).toBe('bullish');
+ expect(v.confidence).toBe(0.86);
+ expect(v.ts).toBe('2026-06-27T10:00:00Z');
+ });
+
+ it('coerces string numerics and defaults symbol to THREE', () => {
+ const v = classifyThreeSignal({ price_usd: '0.0042', change_24h: '-3.1' });
+ expect(v.price_usd).toBeCloseTo(0.0042, 10);
+ expect(v.change_24h).toBeCloseTo(-3.1, 10);
+ expect(v.symbol).toBe('THREE');
+ });
+
+ it('degrades missing/garbage fields to null, never throws', () => {
+ const v = classifyThreeSignal(null);
+ expect(v.price_usd).toBeNull();
+ expect(v.signal).toBeNull();
+ expect(v.ts).toBeNull();
+ const g = classifyThreeSignal({ price_usd: 'not-a-number' });
+ expect(g.price_usd).toBeNull();
+ });
+});
+
+describe('three-signal-store — usdToThreeTokens', () => {
+ it('converts USD to $THREE tokens + atomics at the given price', () => {
+ const r = usdToThreeTokens(1, 0.002);
+ expect(r.tokens).toBe(500);
+ expect(r.atomics).toBe(500 * 10 ** THREE_DECIMALS);
+ });
+
+ it('returns null for unusable prices (zero, negative, missing)', () => {
+ expect(usdToThreeTokens(1, 0)).toBeNull();
+ expect(usdToThreeTokens(1, -0.5)).toBeNull();
+ expect(usdToThreeTokens(1, null)).toBeNull();
+ expect(usdToThreeTokens(null, 0.002)).toBeNull();
+ });
+});
+
+describe('three-signal-store — insertThreeSignal', () => {
+ it('ensures schema then inserts the snapshot with run metadata', async () => {
+ const sql = mockSql();
+ await insertThreeSignal(sql, classifyThreeSignal(SAMPLE), { runId: 'run-1', source: 'x402-autonomous' });
+ // ensure (table + index) may already be cached from a prior test → assert the
+ // INSERT happened regardless, carrying our values.
+ const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain(SAMPLE.mint);
+ expect(insert.values).toContain(0.003685);
+ expect(insert.values).toContain('run-1');
+ expect(insert.values).toContain('x402-autonomous');
+ });
+
+ it('is a no-op without a sql client', async () => {
+ await expect(insertThreeSignal(null, classifyThreeSignal(SAMPLE))).resolves.toBeUndefined();
+ });
+});
+
+describe('three-signal-store — getThreeSignalHistory', () => {
+ it('clamps the limit into [1, 500]', async () => {
+ const sql = mockSql();
+ await getThreeSignalHistory(sql, 9999);
+ await getThreeSignalHistory(sql, 0);
+ const limits = sql.calls.map((c) => c.values[c.values.length - 1]);
+ expect(limits).toContain(500);
+ expect(limits).toContain(1);
+ });
+});
+
+describe('autonomous registry — three-intel entry', () => {
+ const entry = getSelfRegistry().find((e) => e.id === 'three-intel');
+
+ it('exists, is enabled, GET, oracle pipeline, 15-min cooldown', () => {
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.method).toBe('GET');
+ expect(entry.pipeline).toBe('oracle');
+ expect(entry.cooldown_s).toBe(900);
+ expect(entry.path).toBe('/api/x402/three-intel');
+ });
+
+ it('extractSignal tags topic=three and carries the market shape', () => {
+ const sig = entry.extractSignal(SAMPLE);
+ expect(sig.topic).toBe('three');
+ expect(sig.price_usd).toBe(0.003685);
+ expect(sig.signal).toBe('bullish');
+ });
+
+ it('storeValue persists a valid snapshot to the time series', async () => {
+ const sql = mockSql();
+ await entry.storeValue({ sql, responseBody: SAMPLE, signalData: null, runId: 'run-2' });
+ const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain('run-2');
+ });
+
+ it('storeValue skips an empty/failed snapshot (no price → no row)', async () => {
+ const sql = mockSql();
+ await entry.storeValue({ sql, responseBody: { signal: 'neutral' }, signalData: null, runId: 'run-3' });
+ const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
+ expect(insert).toBeFalsy();
+ });
+
+ it('storeValue never throws when sql is missing', async () => {
+ await expect(entry.storeValue({ sql: null, responseBody: SAMPLE })).resolves.toBeUndefined();
+ });
+});