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(x402): implement closed-loop agent economy with self-hosted facilitator

qbdzc057dd7f24c5
diff --git a/.gitignore b/.gitignore
index 3d6f14efe..d4c837031 100644
--- a/.gitignore
+++ b/.gitignore
@@ -309,3 +309,6 @@ pump-launch-wallets*.zip
.preview/
launch-studio-catalog.png
launch-studio-preview.png
+
+# x402 ring wallet secrets (never commit)
+.x402-ring-secrets.json
diff --git a/api/_lib/migrations/2026-07-01-x402-ring-economy.sql b/api/_lib/migrations/2026-07-01-x402-ring-economy.sql
new file mode 100644
index 000000000..0719c0c51
--- /dev/null
+++ b/api/_lib/migrations/2026-07-01-x402-ring-economy.sql
@@ -0,0 +1,73 @@
+-- 2026-07-01-x402-ring-economy.sql
+--
+-- Closed-loop agent-to-agent x402 economy — schema.
+--
+-- three.ws runs a self-contained x402 economy: platform-controlled agent wallets
+-- pay platform-controlled paid endpoints in real USDC, settled by the platform's
+-- OWN facilitator (api/x402-facilitator) — no external facilitator, no user funds,
+-- no wallet outside three.ws. These tables are the durable audit trail. Every row
+-- is a real on-chain settlement or transfer; there are no synthetic rows.
+--
+-- Tables:
+-- x402_self_facilitator_log — every /verify and /settle the self-hosted
+-- facilitator processes, with the exact SOL fee
+-- the sponsor paid and the reject reason on refusal.
+-- This is the "log everything" settlement trail and
+-- the source of the cumulative SOL-burn meter.
+-- x402_ring_ledger — the economic flow: one row per settled payment
+-- (kind='settle') and per treasury→payer rebalance
+-- (kind='sweep'/'fund'). Drives the net-position
+-- report (gross volume, tx count, SOL burned).
+-- x402_ring_wallets — the registry of platform-controlled wallets in
+-- the ring (role: payer | treasury | sponsor). Only
+-- pubkeys live here; secrets stay in env/Vercel.
+
+CREATE TABLE IF NOT EXISTS x402_self_facilitator_log (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ ts timestamptz NOT NULL DEFAULT now(),
+ action text NOT NULL, -- 'verify' | 'settle'
+ network text,
+ payer text, -- buyer pubkey
+ pay_to text, -- recipient pubkey (must be allowlisted)
+ mint text,
+ amount_atomic bigint,
+ tx_sig text, -- settlement signature (settle only)
+ fee_lamports bigint, -- SOL the sponsor burned on this settle
+ ok boolean NOT NULL DEFAULT false,
+ reject_reason text, -- why a verify/settle was refused
+ idempotency_key text,
+ run_id uuid
+);
+
+CREATE INDEX IF NOT EXISTS x402_self_facilitator_log_ts ON x402_self_facilitator_log (ts DESC);
+CREATE INDEX IF NOT EXISTS x402_self_facilitator_log_sig ON x402_self_facilitator_log (tx_sig);
+CREATE INDEX IF NOT EXISTS x402_self_facilitator_log_action_ok ON x402_self_facilitator_log (action, ok, ts DESC);
+
+CREATE TABLE IF NOT EXISTS x402_ring_ledger (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ ts timestamptz NOT NULL DEFAULT now(),
+ kind text NOT NULL, -- 'settle' | 'sweep' | 'fund'
+ from_wallet text,
+ to_wallet text,
+ endpoint text, -- route paid (settle) or null (sweep)
+ mint text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ tx_sig text,
+ fee_lamports bigint NOT NULL DEFAULT 0,
+ run_id uuid
+);
+
+CREATE INDEX IF NOT EXISTS x402_ring_ledger_ts ON x402_ring_ledger (ts DESC);
+CREATE INDEX IF NOT EXISTS x402_ring_ledger_kind_ts ON x402_ring_ledger (kind, ts DESC);
+CREATE INDEX IF NOT EXISTS x402_ring_ledger_sig ON x402_ring_ledger (tx_sig);
+
+CREATE TABLE IF NOT EXISTS x402_ring_wallets (
+ pubkey text PRIMARY KEY,
+ label text,
+ role text NOT NULL DEFAULT 'payer', -- 'payer' | 'treasury' | 'sponsor'
+ enabled boolean NOT NULL DEFAULT true,
+ note text,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS x402_ring_wallets_role ON x402_ring_wallets (role, enabled);
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 5d3ef4fac..e628419da 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -44,6 +44,7 @@ import { run as reputationRefresh } from './pipelines/reputation-refresh.js';
import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';
import { run as sniperIntelEnrich } from './pipelines/sniper-intel-enrich.js';
import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';
+import { run as ringRebalance } from './pipelines/ring-rebalance.js';
import { run as liveFeedSeeder } from './pipelines/live-feed-seeder.js';
import { run as feeCalculationValidator } from './pipelines/fee-calculation-validator.js';
import { run as crossChainCostComparison } from './pipelines/cross-chain-cost.js';
@@ -2657,6 +2658,28 @@ const SELF_ENDPOINTS = [
run: (ctx) => volumeBootstrapLoop(ctx),
},
+ // ── Ring Rebalancer ────────────────────────────────────────────────────────
+ // Recirculates the closed-loop float: sweeps USDC from the treasury
+ // (X402_PAY_TO_SOLANA) back to the ring payer so the same money cycles
+ // indefinitely instead of the payer draining and the loop halting. Between
+ // platform-controlled wallets only; the sponsor pays the SOL fee so burn
+ // stays on one wallet. Recirculation, not spend — returns amountAtomic:0, so
+ // it never consumes the daily spend cap. No-op until X402_TREASURY_SECRET_BASE58
+ // is set. Value sink: x402_ring_ledger (kind='sweep'). See
+ // pipelines/ring-rebalance.js.
+ {
+ id: 'ring-rebalance',
+ name: 'Ring Rebalancer',
+ path: '/api/x402/ring-settle',
+ method: 'POST',
+ body: null,
+ cooldown_s: 300,
+ priority: 20,
+ pipeline: 'volume',
+ enabled: true,
+ run: (ctx) => ringRebalance(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)
diff --git a/api/_lib/x402/pipelines/ring-rebalance.js b/api/_lib/x402/pipelines/ring-rebalance.js
new file mode 100644
index 000000000..6c38aa703
--- /dev/null
+++ b/api/_lib/x402/pipelines/ring-rebalance.js
@@ -0,0 +1,191 @@
+// api/_lib/x402/pipelines/ring-rebalance.js
+//
+// Ring rebalancer — recirculate the closed-loop float so it never drains.
+//
+// In the closed agent economy, ring payer wallets pay USDC to the treasury
+// (X402_PAY_TO_SOLANA). Left alone the payer drains and the treasury fills, and
+// the loop halts on insufficient balance. This pipeline sweeps USDC from the
+// treasury BACK to the payer so the same float cycles indefinitely — which is
+// what makes "thousands in gross volume" cost only network fees instead of
+// thousands in principal.
+//
+// Every transfer is between platform-controlled wallets only (treasury → payer).
+// The sponsor (X402_FEE_PAYER_SECRET_BASE58) pays the Solana fee so all SOL burn
+// stays on ONE monitored wallet; if the sponsor key is absent the treasury
+// self-pays. Recorded in x402_ring_ledger (kind='sweep'). It moves OUR money in a
+// circle — it is NOT spend, so it returns amountAtomic:0 and never consumes the
+// autonomous loop's daily spend cap.
+//
+// OFF unless X402_TREASURY_SECRET_BASE58 is set (the treasury signing key). Until
+// then run() is a graceful no-op.
+
+import bs58 from 'bs58';
+import {
+ PublicKey, Keypair, TransactionMessage, VersionedTransaction, ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, getAccount, getMint,
+ createTransferCheckedInstruction, createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { solanaConnection } from '../../solana/connection.js';
+import { loadSeedKeypair, USDC_MINT } from '../pay.js';
+
+const log = logger('x402-ring-rebalance');
+
+function loadKp(b58) {
+ const raw = bs58.decode(b58);
+ if (raw.length !== 64) throw new Error(`keypair expected 64 bytes, got ${raw.length}`);
+ return Keypair.fromSecretKey(raw);
+}
+
+// Keep this much USDC in the treasury after a sweep (default 0 — sweep all).
+const TREASURY_BUFFER_ATOMIC = BigInt(process.env.X402_RING_TREASURY_BUFFER_ATOMIC || 0);
+// Don't bother sweeping dust — default $0.10 minimum.
+const MIN_SWEEP_ATOMIC = BigInt(process.env.X402_RING_MIN_SWEEP_ATOMIC || 100_000);
+
+async function confirmSignature(conn, signature, timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const st = value?.[0];
+ if (st) {
+ if (st.err) return { confirmed: false, err: JSON.stringify(st.err) };
+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') {
+ return { confirmed: true };
+ }
+ }
+ if (Date.now() > deadline) return { confirmed: false, err: 'confirm_timeout' };
+ await new Promise((r) => setTimeout(r, 1200));
+ }
+}
+
+export async function run(ctx = {}) {
+ const sql = ctx.sql || defaultSql;
+ const runId = ctx.runId || null;
+
+ const treasurySecret = process.env.X402_TREASURY_SECRET_BASE58;
+ if (!treasurySecret) return { success: true, skipped: true, amountAtomic: 0, note: 'treasury_secret_unset' };
+ if (!USDC_MINT) return { success: true, skipped: true, amountAtomic: 0, note: 'usdc_mint_unset' };
+
+ let treasury;
+ try {
+ treasury = loadKp(treasurySecret);
+ } catch (err) {
+ return { success: false, amountAtomic: 0, errorMsg: `bad_treasury_key:${err.message}` };
+ }
+ if (env.X402_PAY_TO_SOLANA && treasury.publicKey.toBase58() !== env.X402_PAY_TO_SOLANA) {
+ return {
+ success: false,
+ amountAtomic: 0,
+ errorMsg: `treasury_pubkey_mismatch:${treasury.publicKey.toBase58()}!=${env.X402_PAY_TO_SOLANA}`,
+ };
+ }
+
+ let payerKp;
+ try {
+ payerKp = loadSeedKeypair();
+ } catch {
+ return { success: true, skipped: true, amountAtomic: 0, note: 'payer_unset' };
+ }
+ const payerPub = payerKp.publicKey;
+
+ const conn = ctx.conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const mint = new PublicKey(USDC_MINT);
+ const treasuryAta = getAssociatedTokenAddressSync(mint, treasury.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+
+ let balance = 0n;
+ try {
+ const acc = await getAccount(conn, treasuryAta);
+ balance = acc.amount;
+ } catch {
+ return { success: true, skipped: true, amountAtomic: 0, note: 'treasury_ata_empty' };
+ }
+
+ if (balance <= TREASURY_BUFFER_ATOMIC) {
+ return { success: true, skipped: true, amountAtomic: 0, note: `below_buffer:${balance}` };
+ }
+ const sweep = balance - TREASURY_BUFFER_ATOMIC;
+ if (sweep < MIN_SWEEP_ATOMIC) {
+ return { success: true, skipped: true, amountAtomic: 0, note: `below_min_sweep:${sweep}` };
+ }
+
+ // Sponsor pays the fee so SOL burn stays on one wallet; else treasury self-pays.
+ let feePayerKp = treasury;
+ const sponsorSecret = process.env.X402_FEE_PAYER_SECRET_BASE58;
+ if (sponsorSecret) {
+ try {
+ feePayerKp = loadKp(sponsorSecret);
+ } catch {
+ feePayerKp = treasury;
+ }
+ }
+
+ const payerAta = getAssociatedTokenAddressSync(mint, payerPub, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const payerAtaInfo = await conn.getAccountInfo(payerAta).catch(() => null);
+ const mintInfo = await getMint(conn, mint);
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),
+ ];
+ if (!payerAtaInfo) {
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(
+ feePayerKp.publicKey, payerAta, payerPub, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ));
+ }
+ ixs.push(createTransferCheckedInstruction(
+ treasuryAta, mint, payerAta, treasury.publicKey, sweep, mintInfo.decimals, [], TOKEN_PROGRAM_ID,
+ ));
+
+ const msg = new TransactionMessage({
+ payerKey: feePayerKp.publicKey,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ const signers = feePayerKp.publicKey.equals(treasury.publicKey)
+ ? [treasury]
+ : [feePayerKp, treasury];
+ vtx.sign(signers);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 5 });
+ } catch (err) {
+ return { success: false, amountAtomic: 0, errorMsg: `sweep_broadcast_failed:${String(err?.message || err).slice(0, 200)}` };
+ }
+
+ const conf = await confirmSignature(conn, signature);
+ if (!conf.confirmed) {
+ return { success: false, amountAtomic: 0, txSig: signature, errorMsg: `sweep_not_confirmed:${conf.err}` };
+ }
+
+ try {
+ await sql`
+ INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)
+ VALUES ('sweep', ${treasury.publicKey.toBase58()}, ${payerPub.toBase58()},
+ ${USDC_MINT}, ${Number(sweep)}, ${signature}, ${runId})
+ `;
+ } catch (err) {
+ log.warn('sweep_ledger_write_failed', { message: err?.message });
+ }
+
+ log.info('ring_rebalance_swept', {
+ amount_atomic: Number(sweep),
+ to: payerPub.toBase58(),
+ tx: signature,
+ });
+
+ return {
+ success: true,
+ amountAtomic: 0, // recirculation, not spend — cap-neutral
+ txSig: signature,
+ note: `swept ${Number(sweep) / 1e6} USDC treasury→payer`,
+ };
+}
diff --git a/api/_lib/x402/pipelines/volume-bootstrap-loop.js b/api/_lib/x402/pipelines/volume-bootstrap-loop.js
index 571293142..ad1344644 100644
--- a/api/_lib/x402/pipelines/volume-bootstrap-loop.js
+++ b/api/_lib/x402/pipelines/volume-bootstrap-loop.js
@@ -68,6 +68,12 @@ export const VOLUME_PER_RUN_CAP_ATOMIC = Math.max(
// metrics ledger pick it up automatically. The volume loop itself is never listed
// (it is not an HTTP endpoint; no self-recursion).
export const VOLUME_ENDPOINTS = [
+ // Ring-settle is the price-configurable, INTERNAL settlement primitive — the
+ // fee-optimal way to move real volume (fewer, larger payments). By default
+ // ($0.10) it is skipped when the per-run cap is the stock $0.05; raise
+ // X402_PRICE_RING_SETTLE + the caps to make it the volume engine. See
+ // api/x402/ring-settle.js.
+ { key: 'ring-settle', name: 'Ring Settlement', path: '/api/x402/ring-settle', method: 'POST', body: { note: 'ring-cycle' } },
{ key: 'dance-tip', name: 'Dance Tip', path: '/api/x402/dance-tip', method: 'POST', body: { dancer: '1', dance: 'hiphop' } },
{ key: 'crypto-intel', name: 'Crypto Intel', path: '/api/x402/crypto-intel', method: 'POST', body: { topic: 'solana' } },
{ key: 'three-intel', name: '$THREE Signal Feed', path: '/api/x402/three-intel', method: 'POST', body: {} },
diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.js
new file mode 100644
index 000000000..761c85f8c
--- /dev/null
+++ b/api/_lib/x402/self-facilitator.js
@@ -0,0 +1,449 @@
+// api/_lib/x402/self-facilitator.js
+//
+// three.ws SELF-HOSTED x402 facilitator — Solana verify + settle, fully in-house.
+//
+// Why this exists: the default settle path delegates to an EXTERNAL facilitator
+// (PayAI) that co-signs the fee-payer and broadcasts. For the closed-loop
+// agent-to-agent economy the platform runs against its OWN endpoints, we do not
+// want any third party touching settlement or holding the sponsor key. This
+// module IS the facilitator: it validates the buyer-signed Solana USDC transfer,
+// co-signs it with OUR fee-payer key, broadcasts it over OUR RPC, and records the
+// exact SOL fee burned. Point X402_FACILITATOR_URL_SOLANA at /api/x402-facilitator
+// and no money, metadata, or signing authority ever leaves three.ws.
+//
+// SECURITY — the co-signing drain vector. The fee payer signs the WHOLE
+// transaction, so a naive facilitator that blind-signs whatever /settle receives
+// would let anyone drain the sponsor's SOL (submit a tx that SystemProgram-
+// transfers the fee payer's lamports out, or sets an enormous priority fee).
+// Defense: validateRingTransaction() refuses to co-sign anything whose program
+// set is not EXACTLY {ComputeBudget, optional ATA-create for OUR recipient, one
+// USDC TransferChecked to an allowlisted payTo}. No System instructions, capped
+// compute-unit price, recipient must be a platform-controlled wallet. That single
+// gate enforces BOTH "only our wallets settle here" and "the sponsor can't be
+// drained".
+
+import bs58 from 'bs58';
+import { PublicKey, Keypair, VersionedTransaction } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { env } from '../env.js';
+import { solanaConnection } from '../solana/connection.js';
+
+const COMPUTE_BUDGET_PROGRAM_ID = new PublicKey(
+ 'ComputeBudget111111111111111111111111111111',
+);
+const SYSTEM_PROGRAM_ID = new PublicKey('11111111111111111111111111111111');
+
+// SPL Token instruction tag for TransferChecked. Plain Transfer (3) is rejected —
+// TransferChecked commits the mint + decimals, so we can trust the decoded mint.
+const SPL_TRANSFER_CHECKED = 12;
+// ComputeBudget instruction tags.
+const CB_SET_UNIT_LIMIT = 2;
+const CB_SET_UNIT_PRICE = 3;
+
+// Fee-drain guards. A malicious priority fee is paid by the SPONSOR, so cap it.
+// The honest ring builder (pay.js) uses ≤1001 µlamports × 60k CU ≈ 60 lamports;
+// these ceilings sit far above that but bound any adversarial submission.
+const MAX_CU_LIMIT = Number(process.env.X402_SELF_FAC_MAX_CU_LIMIT || 300_000);
+const MAX_CU_PRICE_MICROLAMPORTS = Number(
+ process.env.X402_SELF_FAC_MAX_CU_PRICE || 100_000,
+);
+const MAX_PRIORITY_LAMPORTS = Number(
+ process.env.X402_SELF_FAC_MAX_PRIORITY_LAMPORTS || 20_000,
+);
+// Rent an idempotent ATA-create locks on the sponsor for a NEW recipient token
+// account (~0.00204 SOL). Reclaimable by closing the ATA. Bounded, one-time.
+const ATA_RENT_LAMPORTS = 2_039_280;
+
+export const SELF_FACILITATOR_ENABLED =
+ String(process.env.X402_SELF_FACILITATOR_ENABLED || '').toLowerCase() === 'true';
+
+// Sponsor SOL floor — the hard stop that keeps the loop from draining our SOL.
+// Below this the facilitator refuses to settle (returns success:false), which
+// pauses the paying loop until the sponsor is topped up. Default 0.02 SOL.
+export const SPONSOR_SOL_FLOOR_LAMPORTS = Number(
+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS || 20_000_000,
+);
+
+let _feePayerCache = null;
+// Load the sponsor (fee-payer) keypair the facilitator co-signs with. Its public
+// key MUST equal env.X402_FEE_PAYER_SOLANA (the address the 402 challenge
+// advertises) or endpoints would advertise a fee payer we cannot actually sign.
+export function loadFeePayerKeypair() {
+ if (_feePayerCache) return _feePayerCache;
+ const b58 = process.env.X402_FEE_PAYER_SECRET_BASE58;
+ if (!b58) {
+ throw new Error(
+ 'self-facilitator: X402_FEE_PAYER_SECRET_BASE58 not set (the sponsor key that co-signs + pays SOL)',
+ );
+ }
+ const raw = bs58.decode(b58);
+ if (raw.length !== 64) {
+ throw new Error(`self-facilitator: fee-payer key expected 64 bytes, got ${raw.length}`);
+ }
+ const kp = Keypair.fromSecretKey(raw);
+ const advertised = env.X402_FEE_PAYER_SOLANA;
+ if (advertised && kp.publicKey.toBase58() !== advertised) {
+ throw new Error(
+ `self-facilitator: fee-payer secret pubkey ${kp.publicKey.toBase58()} != advertised X402_FEE_PAYER_SOLANA ${advertised}`,
+ );
+ }
+ _feePayerCache = kp;
+ return kp;
+}
+
+// The set of recipient (payTo) addresses this facilitator will settle to. ONLY
+// platform-controlled wallets belong here — that is what keeps every settled
+// dollar inside three.ws. Defaults to X402_PAY_TO_SOLANA; add ring treasuries via
+// X402_SELF_FACILITATOR_PAYTO_ALLOWLIST (comma-separated).
+export function payToAllowlist() {
+ const out = new Set();
+ if (env.X402_PAY_TO_SOLANA) out.add(env.X402_PAY_TO_SOLANA);
+ const extra = String(process.env.X402_SELF_FACILITATOR_PAYTO_ALLOWLIST || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ for (const a of extra) out.add(a);
+ return out;
+}
+
+function readU32LE(data, offset) {
+ return (
+ data[offset] |
+ (data[offset + 1] << 8) |
+ (data[offset + 2] << 16) |
+ (data[offset + 3] << 24)
+ ) >>> 0;
+}
+
+function readU64LE(data, offset) {
+ let v = 0n;
+ for (let i = 7; i >= 0; i--) v = (v << 8n) | BigInt(data[offset + i]);
+ return v;
+}
+
+// Decode + STRICTLY validate a buyer-signed ring payment transaction. Returns
+// { ok:true, decoded } when it is a clean single-USDC-transfer to an allowlisted
+// recipient with a bounded sponsor fee, or { ok:false, reason } otherwise. Never
+// throws on adversarial input — a bad tx is a clean refusal, not a 5xx.
+export function validateRingTransaction({ txBase64, requirement, feePayerPubkey, allowlist }) {
+ let tx;
+ try {
+ tx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));
+ } catch (err) {
+ return { ok: false, reason: `deserialize_failed:${err.message}` };
+ }
+ const msg = tx.message;
+
+ // Address-table lookups would hide accounts we can't statically resolve.
+ // The ring builder never uses them; reject to keep validation total.
+ if (msg.addressTableLookups && msg.addressTableLookups.length > 0) {
+ return { ok: false, reason: 'address_table_lookups_forbidden' };
+ }
+
+ const keys = msg.staticAccountKeys;
+ if (!keys || keys.length === 0) return { ok: false, reason: 'no_account_keys' };
+
+ // Fee payer is always account index 0.
+ const feePayer = keys[0];
+ if (feePayerPubkey && feePayer.toBase58() !== feePayerPubkey) {
+ return {
+ ok: false,
+ reason: `fee_payer_mismatch:${feePayer.toBase58()}!=${feePayerPubkey}`,
+ };
+ }
+
+ const mint = new PublicKey(requirement.asset);
+ const requiredAmount = BigInt(requirement.amount);
+ const payTo = new PublicKey(requirement.payTo);
+
+ if (!allowlist.has(payTo.toBase58())) {
+ return { ok: false, reason: `pay_to_not_allowlisted:${payTo.toBase58()}` };
+ }
+
+ const expectedReceiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+
+ let transferCount = 0;
+ let payer = null;
+ let transferAmount = 0n;
+ let cuLimit = 200_000; // Solana default when unset
+ let cuPrice = 0n;
+ let ataCreatePresent = false;
+
+ const ixs = msg.compiledInstructions;
+ for (const ix of ixs) {
+ const programId = keys[ix.programIdIndex];
+ const data = ix.data; // Uint8Array
+ const accts = ix.accountKeyIndexes;
+
+ if (programId.equals(SYSTEM_PROGRAM_ID)) {
+ // A top-level System instruction could move the sponsor's SOL. Never allow.
+ return { ok: false, reason: 'system_instruction_forbidden' };
+ }
+
+ if (programId.equals(COMPUTE_BUDGET_PROGRAM_ID)) {
+ const tag = data[0];
+ if (tag === CB_SET_UNIT_LIMIT) {
+ cuLimit = readU32LE(data, 1);
+ } else if (tag === CB_SET_UNIT_PRICE) {
+ cuPrice = readU64LE(data, 1);
+ }
+ // Other compute-budget tags carry no fund movement; ignore.
+ continue;
+ }
+
+ if (programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID)) {
+ // Only permit creating OUR recipient's ATA, funded by the sponsor.
+ // Accounts: [funder, ata, owner, mint, systemProgram, tokenProgram].
+ const funder = keys[accts[0]];
+ const ata = keys[accts[1]];
+ const owner = keys[accts[2]];
+ const ixMint = keys[accts[3]];
+ if (!ata.equals(expectedReceiverAta)) {
+ return { ok: false, reason: 'ata_create_wrong_account' };
+ }
+ if (!owner.equals(payTo)) return { ok: false, reason: 'ata_create_wrong_owner' };
+ if (!ixMint.equals(mint)) return { ok: false, reason: 'ata_create_wrong_mint' };
+ if (!funder.equals(feePayer)) return { ok: false, reason: 'ata_create_wrong_funder' };
+ ataCreatePresent = true;
+ continue;
+ }
+
+ if (programId.equals(TOKEN_PROGRAM_ID)) {
+ // The ONLY value-moving instruction we permit: one TransferChecked of
+ // the required USDC from the buyer to OUR recipient ATA.
+ // Accounts: [source, mint, destination, authority].
+ if (data[0] !== SPL_TRANSFER_CHECKED) {
+ return { ok: false, reason: `token_ix_not_transfer_checked:${data[0]}` };
+ }
+ transferCount += 1;
+ if (transferCount > 1) return { ok: false, reason: 'multiple_transfers' };
+
+ const source = keys[accts[0]];
+ const ixMint = keys[accts[1]];
+ const dest = keys[accts[2]];
+ const authority = keys[accts[3]];
+
+ if (!ixMint.equals(mint)) return { ok: false, reason: 'transfer_wrong_mint' };
+ if (!dest.equals(expectedReceiverAta)) {
+ return { ok: false, reason: 'transfer_wrong_destination' };
+ }
+ // The buyer (authority) must own the source ATA and must be a signer.
+ const expectedSource = getAssociatedTokenAddressSync(
+ mint, authority, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ if (!source.equals(expectedSource)) {
+ return { ok: false, reason: 'transfer_source_not_authority_ata' };
+ }
+ // authority must never be the sponsor — the sponsor pays fees, not USDC.
+ if (authority.equals(feePayer)) return { ok: false, reason: 'authority_is_fee_payer' };
+ // authority must be a required signer (index < numRequiredSignatures).
+ const authIndex = accts[3];
+ if (authIndex >= msg.header.numRequiredSignatures) {
+ return { ok: false, reason: 'authority_not_signer' };
+ }
+
+ // TransferChecked data: [12, u64 amount, u8 decimals].
+ transferAmount = readU64LE(data, 1);
+ payer = authority.toBase58();
+ continue;
+ }
+
+ // Any other program touching this transaction is disallowed.
+ return { ok: false, reason: `program_not_allowed:${programId.toBase58()}` };
+ }
+
+ if (transferCount !== 1) return { ok: false, reason: 'no_usdc_transfer' };
+ if (transferAmount < requiredAmount) {
+ return {
+ ok: false,
+ reason: `amount_below_required:${transferAmount}<${requiredAmount}`,
+ };
+ }
+
+ // Bound the sponsor's priority fee.
+ if (cuLimit > MAX_CU_LIMIT) return { ok: false, reason: `cu_limit_too_high:${cuLimit}` };
+ if (cuPrice > BigInt(MAX_CU_PRICE_MICROLAMPORTS)) {
+ return { ok: false, reason: `cu_price_too_high:${cuPrice}` };
+ }
+ const priorityLamports = Number((cuPrice * BigInt(cuLimit)) / 1_000_000n);
+ if (priorityLamports > MAX_PRIORITY_LAMPORTS) {
+ return { ok: false, reason: `priority_fee_too_high:${priorityLamports}` };
+ }
+
+ const baseFee = 5000 * msg.header.numRequiredSignatures;
+ const estFeeLamports = baseFee + priorityLamports + (ataCreatePresent ? ATA_RENT_LAMPORTS : 0);
+
+ return {
+ ok: true,
+ decoded: {
+ tx,
+ payer,
+ payTo: payTo.toBase58(),
+ mint: mint.toBase58(),
+ amountAtomic: Number(transferAmount),
+ estFeeLamports,
+ ataCreatePresent,
+ },
+ };
+}
+
+// Extract the base64 signed transaction from an x402 payment payload.
+export function txBase64FromPayload(paymentPayload) {
+ return (
+ paymentPayload?.payload?.transaction ||
+ paymentPayload?.transaction ||
+ null
+ );
+}
+
+// ── Sponsor SOL guard ────────────────────────────────────────────────────────
+// Cache the sponsor SOL balance briefly so a high-throughput settle stream does
+// not hit getBalance on every payment. The floor check is the hard stop that
+// keeps the loop from ever draining our SOL: below the floor, settle refuses and
+// the paying loop stalls until the sponsor is topped up.
+let _solCache = { lamports: null, at: 0 };
+const SOL_CACHE_MS = 20_000;
+
+export async function sponsorSolLamports(conn, feePayerPubkey, now = Date.now()) {
+ if (_solCache.lamports != null && now - _solCache.at < SOL_CACHE_MS) {
+ return _solCache.lamports;
+ }
+ const lamports = await conn.getBalance(feePayerPubkey, 'confirmed');
+ _solCache = { lamports, at: now };
+ return lamports;
+}
+
+// Invalidate the cache right after a settle so the next check sees the debit
+// promptly as the balance approaches the floor.
+function bumpSolCache(deltaLamports) {
+ if (_solCache.lamports != null) _solCache.lamports = Math.max(0, _solCache.lamports - deltaLamports);
+}
+
+async function confirmSignature(conn, signature, timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const st = value?.[0];
+ if (st) {
+ if (st.err) return { confirmed: false, err: JSON.stringify(st.err) };
+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') {
+ return { confirmed: true };
+ }
+ }
+ if (Date.now() > deadline) return { confirmed: false, err: 'confirm_timeout' };
+ await new Promise((r) => setTimeout(r, 1200));
+ }
+}
+
+// Settle a validated ring payment: co-sign with the sponsor, broadcast over our
+// RPC, confirm. Returns the x402-wire settle shape { success, transaction,
+// network, payer } plus feeLamports for the burn meter. Never throws for a
+// rejected payment — a refusal is a clean { success:false, reason }.
+export async function settleRingPayment({ paymentPayload, requirement, conn, feePayer }) {
+ const network = requirement.network;
+ const connection = conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const sponsor = feePayer || loadFeePayerKeypair();
+
+ const txBase64 = txBase64FromPayload(paymentPayload);
+ if (!txBase64) return { success: false, reason: 'missing_transaction' };
+
+ const validation = validateRingTransaction({
+ txBase64,
+ requirement,
+ feePayerPubkey: sponsor.publicKey.toBase58(),
+ allowlist: payToAllowlist(),
+ });
+ if (!validation.ok) return { success: false, reason: validation.reason };
+ const decoded = validation.decoded;
+ const { tx, payer, estFeeLamports } = decoded;
+
+ // Hard stop: never settle if the sponsor is below its SOL floor.
+ const solLamports = await sponsorSolLamports(connection, sponsor.publicKey);
+ if (solLamports < SPONSOR_SOL_FLOOR_LAMPORTS) {
+ return {
+ success: false,
+ reason: `sponsor_sol_below_floor:${solLamports}<${SPONSOR_SOL_FLOOR_LAMPORTS}`,
+ sponsorSolLamports: solLamports,
+ };
+ }
+
+ // Co-sign as the fee payer (buyer already signed) and broadcast.
+ try {
+ tx.sign([sponsor]);
+ } catch (err) {
+ return { success: false, reason: `cosign_failed:${err.message}` };
+ }
+
+ let signature;
+ try {
+ signature = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 5,
+ });
+ } catch (err) {
+ const m = String(err?.message || err);
+ // A resent settle (idempotent replay) hits "already processed" — the prior
+ // broadcast landed. Recover the signature from the tx and report success.
+ if (/already been processed|AlreadyProcessed|already processed/i.test(m)) {
+ const sig = tx.signatures?.[0] ? bs58.encode(tx.signatures[0]) : null;
+ if (sig) {
+ return {
+ success: true,
+ transaction: sig,
+ network,
+ payer,
+ feeLamports: estFeeLamports,
+ replayed: true,
+ };
+ }
+ }
+ return { success: false, reason: `broadcast_failed:${m}`.slice(0, 300) };
+ }
+
+ const conf = await confirmSignature(connection, signature);
+ if (!conf.confirmed) {
+ return { success: false, reason: `not_confirmed:${conf.err}`, transaction: signature };
+ }
+
+ bumpSolCache(estFeeLamports);
+
+ // Best-effort: read the real network fee for accurate burn accounting.
+ let feeLamports = estFeeLamports;
+ try {
+ const parsed = await connection.getParsedTransaction(signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (parsed?.meta?.fee != null) {
+ feeLamports = parsed.meta.fee + (decoded.ataCreatePresent ? ATA_RENT_LAMPORTS : 0);
+ }
+ } catch { /* estimate stands */ }
+
+ return { success: true, transaction: signature, network, payer, feeLamports };
+}
+
+// Verify shape for /verify — validate without broadcasting.
+export function verifyRingPayment({ paymentPayload, requirement, feePayerPubkey }) {
+ const txBase64 = txBase64FromPayload(paymentPayload);
+ if (!txBase64) return { isValid: false, invalidReason: 'missing_transaction' };
+ const validation = validateRingTransaction({
+ txBase64,
+ requirement,
+ feePayerPubkey: feePayerPubkey || (env.X402_FEE_PAYER_SOLANA || null),
+ allowlist: payToAllowlist(),
+ });
+ if (!validation.ok) return { isValid: false, invalidReason: validation.reason };
+ return {
+ isValid: true,
+ network: requirement.network,
+ asset: validation.decoded.mint,
+ payer: validation.decoded.payer,
+ };
+}
diff --git a/api/x402-facilitator/[action].js b/api/x402-facilitator/[action].js
new file mode 100644
index 000000000..6adce5d2a
--- /dev/null
+++ b/api/x402-facilitator/[action].js
@@ -0,0 +1,174 @@
+// POST /api/x402-facilitator/verify
+// POST /api/x402-facilitator/settle
+// GET /api/x402-facilitator/supported
+//
+// three.ws SELF-HOSTED x402 facilitator (Solana). This is the in-house
+// replacement for an external facilitator (e.g. PayAI): it validates a
+// buyer-signed USDC transfer, co-signs it with OUR sponsor (fee-payer) key,
+// broadcasts it over OUR RPC, and logs the exact SOL fee burned. Point
+// X402_FACILITATOR_URL_SOLANA at https://three.ws/api/x402-facilitator and no
+// third party ever touches settlement of the closed-loop agent economy.
+//
+// OFF BY DEFAULT. Requires X402_SELF_FACILITATOR_ENABLED=true plus the sponsor
+// secret X402_FEE_PAYER_SECRET_BASE58. Only settles payments whose payTo is in
+// the platform allowlist (X402_PAY_TO_SOLANA + X402_SELF_FACILITATOR_PAYTO_ALLOWLIST)
+// and whose transaction is a single clean USDC transfer — see self-facilitator.js
+// validateRingTransaction() for the anti-drain gate.
+//
+// Wire format matches the x402 v2 facilitator contract consumed by
+// api/_lib/x402-spec.js callFacilitator():
+// /verify → { isValid, network, asset, payer } | { isValid:false, invalidReason }
+// /settle → { success:true, transaction, network, payer } | { success:false, errorReason }
+
+import { cors, json, method, wrap, readJson } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { env } from '../_lib/env.js';
+import { NETWORK_SOLANA_MAINNET, X402_VERSION } from '../_lib/x402-spec.js';
+import {
+ SELF_FACILITATOR_ENABLED,
+ verifyRingPayment,
+ settleRingPayment,
+ loadFeePayerKeypair,
+} from '../_lib/x402/self-facilitator.js';
+
+function actionFrom(req) {
+ const q = req.query?.action;
+ if (q) return String(q).toLowerCase();
+ const path = String(req.url || '').split('?')[0];
+ const seg = path.split('/').filter(Boolean).pop();
+ return String(seg || '').toLowerCase();
+}
+
+// Fire-and-forget settlement audit. A DB hiccup must never fail a settle the
+// buyer already funded — the ledger backfill (x402_ring_ledger) is the economic
+// source of truth; this table is the per-op facilitator trail.
+function logOp(row) {
+ sql`
+ INSERT INTO x402_self_facilitator_log
+ (action, network, payer, pay_to, mint, amount_atomic, tx_sig,
+ fee_lamports, ok, reject_reason, idempotency_key)
+ VALUES
+ (${row.action}, ${row.network || null}, ${row.payer || null},
+ ${row.payTo || null}, ${row.mint || null}, ${row.amountAtomic ?? null},
+ ${row.txSig || null}, ${row.feeLamports ?? null}, ${row.ok},
+ ${row.reason || null}, ${row.idempotencyKey || null})
+ `.catch((err) => console.error('[self-facilitator] log failed', err?.message || err));
+}
+
+async function getBody(req) {
+ if (req.body && typeof req.body === 'object') return req.body;
+ try {
+ return await readJson(req);
+ } catch {
+ return null;
+ }
+}
+
+export default wrap(async (req, res) => {
+ cors(req, res, { origins: '*', methods: 'GET,POST,OPTIONS' });
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ const action = actionFrom(req);
+
+ // /supported is a public capability probe (no payment, no secret needed) so
+ // api/x402-status.js probeFacilitators() can confirm we advertise exact/solana.
+ if (action === 'supported') {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ return json(res, 200, {
+ kinds: [
+ { x402Version: X402_VERSION, scheme: 'exact', network: NETWORK_SOLANA_MAINNET },
+ ],
+ });
+ }
+
+ if (!method(req, res, ['POST'])) return;
+
+ if (!SELF_FACILITATOR_ENABLED) {
+ return json(res, 503, {
+ isValid: false,
+ success: false,
+ errorReason: 'self_facilitator_disabled',
+ invalidReason: 'self_facilitator_disabled',
+ });
+ }
+
+ const body = await getBody(req);
+ const paymentPayload = body?.paymentPayload;
+ const requirement = body?.paymentRequirements;
+ if (!paymentPayload || !requirement) {
+ return json(res, 400, {
+ isValid: false,
+ success: false,
+ errorReason: 'missing paymentPayload/paymentRequirements',
+ invalidReason: 'missing paymentPayload/paymentRequirements',
+ });
+ }
+
+ // This facilitator settles Solana only. EVM/other networks are not ours here.
+ if (!String(requirement.network || '').startsWith('solana')) {
+ return json(res, 400, {
+ isValid: false,
+ success: false,
+ errorReason: `unsupported_network:${requirement.network}`,
+ invalidReason: `unsupported_network:${requirement.network}`,
+ });
+ }
+
+ if (action === 'verify') {
+ const result = verifyRingPayment({ paymentPayload, requirement });
+ logOp({
+ action: 'verify',
+ network: requirement.network,
+ payer: result.payer,
+ payTo: requirement.payTo,
+ mint: requirement.asset,
+ amountAtomic: Number(requirement.amount) || null,
+ ok: result.isValid,
+ reason: result.invalidReason,
+ });
+ // 200 either way — callFacilitator inspects isValid; verifyPayment maps a
+ // false result to a clean 402 for the paying client.
+ return json(res, 200, result);
+ }
+
+ if (action === 'settle') {
+ let feePayer;
+ try {
+ feePayer = loadFeePayerKeypair();
+ } catch (err) {
+ logOp({ action: 'settle', network: requirement.network, ok: false, reason: `no_sponsor_key:${err.message}` });
+ return json(res, 200, { success: false, errorReason: 'sponsor_key_unconfigured' });
+ }
+ const result = await settleRingPayment({ paymentPayload, requirement, feePayer });
+ logOp({
+ action: 'settle',
+ network: requirement.network,
+ payer: result.payer,
+ payTo: requirement.payTo,
+ mint: requirement.asset,
+ amountAtomic: Number(requirement.amount) || null,
+ txSig: result.transaction,
+ feeLamports: result.feeLamports,
+ ok: result.success,
+ reason: result.reason,
+ idempotencyKey: req.headers?.['idempotency-key'] || null,
+ });
+ if (!result.success) {
+ // 200 + success:false → settlePayment throws a clean settle_failed without
+ // the transient-5xx retry path.
+ return json(res, 200, { success: false, errorReason: result.reason });
+ }
+ return json(res, 200, {
+ success: true,
+ transaction: result.transaction,
+ network: result.network,
+ payer: result.payer,
+ });
+ }
+
+ return json(res, 404, { error: `unknown_action:${action}` });
+});
diff --git a/api/x402-ring.js b/api/x402-ring.js
new file mode 100644
index 000000000..b3d17bcf3
--- /dev/null
+++ b/api/x402-ring.js
@@ -0,0 +1,205 @@
+// GET /api/x402-ring — net-position report for the closed-loop agent economy.
+//
+// The honest scoreboard for the self-cycled x402 ring: how much gross volume the
+// platform-controlled wallets moved through the platform's own endpoints, how
+// many transactions that took, and — the number that actually matters — how much
+// SOL the sponsor burned to do it. Because every wallet is ours, the principal
+// recirculates; this report exists to prove at a glance that the only real cost
+// is network fees, and that no money left three.ws.
+//
+// GET /api/x402-ring — 24h window
+// GET /api/x402-ring?period=all — lifetime
+// GET /api/x402-ring?period=7d
+//
+// Reads x402_self_facilitator_log (settlements + fees) and x402_ring_ledger
+// (sweeps), plus live on-chain balances for the treasury / payer / sponsor. Every
+// row is a real settled payment — if the ring is idle the report is honestly
+// empty. This is internal/dogfooding volume and is labeled as such; it is NOT the
+// public organic-revenue feed (see /api/x402-revenue).
+
+import { cors, json, method, wrap } from './_lib/http.js';
+import { sql, isDbUnavailableError } from './_lib/db.js';
+import { env } from './_lib/env.js';
+import { PublicKey } from '@solana/web3.js';
+import { getAccount, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from '@solana/spl-token';
+import { solanaConnection } from './_lib/solana/connection.js';
+import { loadSeedKeypair, USDC_MINT } from './_lib/x402/pay.js';
+import { SELF_FACILITATOR_ENABLED, SPONSOR_SOL_FLOOR_LAMPORTS } from './_lib/x402/self-facilitator.js';
+
+const PERIOD_HOURS = { '24h': 24, '7d': 168, '30d': 720 };
+
+// Resolve ?period= to an ISO cutoff (or null for lifetime). Returned as a bound
+// parameter — the Neon tagged template does NOT compose SQL fragments, so the
+// window is a value, not injected SQL.
+function sinceFor(periodKey) {
+ const hours = PERIOD_HOURS[periodKey];
+ if (!hours) return null;
+ return new Date(Date.now() - hours * 3600 * 1000).toISOString();
+}
+
+function usdc(atomic) {
+ if (atomic == null) return null;
+ return Number(atomic) / 1e6;
+}
+
+function sol(lamports) {
+ if (lamports == null) return null;
+ return Number(lamports) / 1e9;
+}
+
+// Best-effort live SOL price for a USD figure on the burn — never blocks the
+// report if the quote is unreachable.
+async function solUsd() {
+ try {
+ const r = await fetch(
+ 'https://api.geckoterminal.com/api/v2/simple/networks/solana/token_price/So11111111111111111111111111111111111111112',
+ { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(4000) },
+ );
+ if (!r.ok) return null;
+ const d = await r.json();
+ const p = d?.data?.attributes?.token_prices?.So11111111111111111111111111111111111111112;
+ return p ? Number(p) : null;
+ } catch {
+ return null;
+ }
+}
+
+async function usdcBalance(conn, ownerB58) {
+ if (!ownerB58 || !USDC_MINT) return null;
+ try {
+ const owner = new PublicKey(ownerB58);
+ const mint = new PublicKey(USDC_MINT);
+ const ata = getAssociatedTokenAddressSync(mint, owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const acc = await getAccount(conn, ata);
+ return usdc(acc.amount);
+ } catch {
+ return 0;
+ }
+}
+
+async function solBalance(conn, ownerB58) {
+ if (!ownerB58) return null;
+ try {
+ return sol(await conn.getBalance(new PublicKey(ownerB58), 'confirmed'));
+ } catch {
+ return null;
+ }
+}
+
+export default wrap(async (req, res) => {
+ cors(req, res, { origins: '*', methods: 'GET,OPTIONS' });
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+ if (!method(req, res, ['GET'])) return;
+
+ const periodKey = String(req.query?.period || '24h').toLowerCase();
+ const since = sinceFor(periodKey); // ISO string, or null = lifetime
+
+ let settlements = { count: 0, gross_usdc: 0, avg_call_usdc: null };
+ let fees = { tx_count: 0, sol_burned_lamports: 0, sol_burned: 0, per_tx_avg_lamports: null };
+ let sweeps = { count: 0, swept_usdc: 0 };
+ let recent = [];
+ let dbOk = true;
+
+ try {
+ const [s] = await sql`
+ SELECT count(*)::int AS n,
+ COALESCE(sum(amount_atomic), 0)::bigint AS gross,
+ COALESCE(sum(fee_lamports), 0)::bigint AS fee
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ok = true
+ AND (${since}::timestamptz IS NULL OR ts >= ${since}::timestamptz)
+ `;
+ settlements = {
+ count: s.n,
+ gross_usdc: usdc(s.gross),
+ avg_call_usdc: s.n > 0 ? usdc(Number(s.gross) / s.n) : null,
+ };
+ fees = {
+ tx_count: s.n,
+ sol_burned_lamports: Number(s.fee),
+ sol_burned: sol(s.fee),
+ per_tx_avg_lamports: s.n > 0 ? Math.round(Number(s.fee) / s.n) : null,
+ };
+
+ const [w] = await sql`
+ SELECT count(*)::int AS n, COALESCE(sum(amount_atomic), 0)::bigint AS swept
+ FROM x402_ring_ledger
+ WHERE kind = 'sweep'
+ AND (${since}::timestamptz IS NULL OR ts >= ${since}::timestamptz)
+ `;
+ sweeps = { count: w.n, swept_usdc: usdc(w.swept) };
+
+ recent = await sql`
+ SELECT ts, payer, pay_to, amount_atomic, tx_sig, fee_lamports
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ok = true
+ ORDER BY ts DESC
+ LIMIT 20
+ `;
+ } catch (err) {
+ if (isDbUnavailableError(err)) {
+ dbOk = false;
+ } else {
+ throw err;
+ }
+ }
+
+ // Live balances (best-effort) prove the float is intact.
+ const conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const treasuryAddr = env.X402_PAY_TO_SOLANA || null;
+ const sponsorAddr = env.X402_FEE_PAYER_SOLANA || null;
+ let payerAddr = null;
+ try {
+ payerAddr = loadSeedKeypair().publicKey.toBase58();
+ } catch { /* payer key not configured in this env */ }
+
+ const [treasuryUsdc, payerUsdc, sponsorSol, price] = await Promise.all([
+ usdcBalance(conn, treasuryAddr),
+ usdcBalance(conn, payerAddr),
+ solBalance(conn, sponsorAddr),
+ solUsd(),
+ ]);
+
+ const ringFloat = (treasuryUsdc || 0) + (payerUsdc || 0);
+ const burnedUsd = price != null ? Number((fees.sol_burned * price).toFixed(4)) : null;
+
+ return json(res, 200, {
+ ok: true,
+ self_hosted_facilitator: SELF_FACILITATOR_ENABLED,
+ internal: true,
+ note: 'Self-cycled internal ring volume — dogfooding, not organic third-party demand.',
+ period: since ? periodKey : 'all',
+ db_available: dbOk,
+ settlements,
+ fees: { ...fees, sol_usd: price, burned_usd: burnedUsd },
+ sweeps,
+ wallets: {
+ treasury: { address: treasuryAddr, usdc: treasuryUsdc },
+ payer: { address: payerAddr, usdc: payerUsdc },
+ sponsor: {
+ address: sponsorAddr,
+ sol: sponsorSol,
+ floor_sol: sol(SPONSOR_SOL_FLOOR_LAMPORTS),
+ below_floor: sponsorSol != null ? sponsorSol < sol(SPONSOR_SOL_FLOOR_LAMPORTS) : null,
+ },
+ },
+ net: {
+ ring_float_usdc: ringFloat,
+ gross_volume_usdc: settlements.gross_usdc,
+ real_cost_usdc: burnedUsd,
+ note: 'Principal recirculates between platform wallets; real cost = SOL fees only.',
+ },
+ recent: recent.map((r) => ({
+ ts: r.ts,
+ payer: r.payer,
+ pay_to: r.pay_to,
+ usdc: usdc(r.amount_atomic),
+ tx: r.tx_sig,
+ fee_lamports: r.fee_lamports != null ? Number(r.fee_lamports) : null,
+ })),
+ });
+});
diff --git a/api/x402/ring-settle.js b/api/x402/ring-settle.js
new file mode 100644
index 000000000..40a99bb58
--- /dev/null
+++ b/api/x402/ring-settle.js
@@ -0,0 +1,124 @@
+// POST /api/x402/ring-settle
+//
+// Internal settlement primitive for the closed-loop agent-to-agent economy.
+//
+// The platform's ring payer wallets pay THIS endpoint (recipient = our treasury,
+// X402_PAY_TO_SOLANA) in real USDC, settled by the self-hosted facilitator
+// (api/x402-facilitator). It exists so ring volume can use a SINGLE, price-
+// configurable call instead of raising the price of real product endpoints:
+//
+// FEE ECONOMICS — the Solana network fee is ~flat per transaction (~$0.002),
+// independent of payment size, so ring cost scales with tx COUNT, not volume.
+// To generate $X of gross volume for the least SOL, make FEWER, LARGER payments.
+// Tune the per-call size with X402_PRICE_RING_SETTLE (atomics, 6dp). Default is
+// a deliberately large $0.10 so a handful of calls, not thousands, move real
+// money. At $1.00/call, $10k of volume costs ~$20 of SOL; at $0.001/call the
+// same $10k would cost ~$20,000 of SOL. Bigger calls, smaller burn.
+//
+// discoverable:false — this is an INTERNAL primitive. It is deliberately NOT
+// advertised on the public x402 bazaar / agentic.market catalog: ring volume is
+// dogfooding, not organic third-party demand, and must not masquerade as such.
+//
+// The settled response is a real receipt (a signed economic tick) so the call is
+// a genuine paid service invocation, not a naked money move.
+
+import crypto from 'node:crypto';
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { priceFor } from '../_lib/x402-prices.js';
+
+const ROUTE = '/api/x402/ring-settle';
+
+// Default $0.10. Raise via X402_PRICE_RING_SETTLE to move more per call (fewer
+// txs → less SOL burned for the same gross volume).
+const DEFAULT_PRICE_ATOMICS = '100000';
+
+const DESCRIPTION =
+ 'three.ws internal ring-settlement primitive. Platform-controlled agent ' +
+ 'wallets pay this endpoint in USDC to cycle the closed-loop agent economy; ' +
+ 'the settled response is a signed economic tick receipt. Price is operator-' +
+ 'configurable (X402_PRICE_RING_SETTLE) so ring volume uses fewer, larger ' +
+ 'payments and burns minimal SOL. Not a public service.';
+
+const INPUT_EXAMPLE = { note: 'ring-cycle', seq: 1 };
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ note: { type: 'string', description: 'Optional label echoed into the receipt.' },
+ seq: { type: 'integer', description: 'Optional caller sequence number, echoed back.' },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ kind: 'ring-tick',
+ receiptId: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',
+ note: 'ring-cycle',
+ seq: 1,
+ payer: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',
+ network: 'solana',
+ amountAtomics: '100000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ settledAt: '2026-07-01T18:42:09.000Z',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok', 'kind', 'receiptId', 'settledAt'],
+ properties: {
+ ok: { type: 'boolean', const: true },
+ kind: { type: 'string', const: 'ring-tick' },
+ receiptId: { type: 'string', format: 'uuid' },
+ note: { type: ['string', 'null'] },
+ seq: { type: ['integer', 'null'] },
+ payer: { type: ['string', 'null'] },
+ network: { type: ['string', 'null'] },
+ amountAtomics: { type: ['string', 'null'] },
+ asset: { type: ['string', 'null'] },
+ settledAt: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: false,
+ info: {
+ input: { type: 'http', method: 'POST', body: INPUT_EXAMPLE },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('ring-settle', DEFAULT_PRICE_ATOMICS),
+ networks: ['solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ // No SIWX free-retrigger: every ring call must be a real settled payment, or
+ // the volume would be a signature bypass instead of an on-chain cycle.
+ async handler({ req, requirement, payer }) {
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
+ return {
+ ok: true,
+ kind: 'ring-tick',
+ receiptId: crypto.randomUUID(),
+ note: typeof body.note === 'string' ? body.note.slice(0, 120) : null,
+ seq: Number.isInteger(body.seq) ? body.seq : null,
+ payer: payer ?? null,
+ network: requirement?.network ?? null,
+ amountAtomics: requirement?.amount ?? null,
+ asset: requirement?.asset ?? null,
+ settledAt: new Date().toISOString(),
+ };
+ },
+});
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
new file mode 100644
index 000000000..61116680a
--- /dev/null
+++ b/docs/x402-ring-economy.md
@@ -0,0 +1,142 @@
+# Closed-loop x402 ring economy
+
+A self-contained agent-to-agent payment loop: **three.ws-controlled wallets pay
+three.ws's own x402 endpoints in real USDC, settled by three.ws's own
+facilitator.** No user funds, no external facilitator, no wallet outside the
+platform. It exists to dogfood and load-test the agent economy end to end —
+proving every paid endpoint settles real money, continuously — while costing only
+Solana network fees, because the principal recirculates between wallets you
+control.
+
+> **This is internal/dogfooding volume, and it is labeled as such.** The report
+> endpoint tags it `internal: true`, and the ring settlement endpoint is
+> `discoverable: false` (never advertised on the public x402 bazaar /
+> agentic.market catalog). Do **not** present self-cycled ring volume as organic
+> third-party demand — that is the one thing this system is deliberately built
+> *not* to do. The public organic-revenue feed is a separate surface
+> ([/api/x402-revenue](../api/x402-revenue.js)).
+
+## The one number that matters: SOL fee scales with tx COUNT, not volume
+
+Every Solana settlement costs a ~flat network fee (~$0.002), regardless of the
+payment size. So to move `$X` of gross volume for the least SOL, make **fewer,
+larger payments**:
+
+| $10,000 gross via | per-call | # txs | SOL burned | fee cost |
+|---|---|---|---|---|
+| tiny micro-payments | $0.001 | 10,000,000 | ~100 SOL | **~$20,000** |
+| moderate | $1.00 | 10,000 | ~0.1 SOL | **~$20** |
+| large | $10.00 | 1,000 | ~0.01 SOL | **~$2** |
+
+Same volume, 1000× difference in cost. Tune per-call size with
+`X402_PRICE_RING_SETTLE`. Bigger calls, smaller burn.
+
+## Architecture
+
+```
+ ring payer wallet ──(1) pay USDC──▶ /api/x402/ring-settle (recipient = treasury)
+ ▲ │
+ │ (2) self-hosted facilitator
+ │ /api/x402-facilitator co-signs
+ │ with the sponsor + broadcasts
+ │ │
+ │ ▼
+ │ treasury (X402_PAY_TO_SOLANA)
+ └────────(4) rebalancer sweeps treasury→payer──────┘
+ (ring-rebalance pipeline)
+ sponsor (X402_FEE_PAYER_SOLANA) pays all SOL fees — one wallet to watch (3)
+```
+
+The three roles are all platform-controlled:
+
+| Role | Receives / does | Public env | Secret env | Fund with |
+|---|---|---|---|---|
+| **payer** | pays the ring | (derived) | `X402_SEED_SOLANA_SECRET_BASE58` | USDC float (recirculates) |
+| **treasury** | receives payments | `X402_PAY_TO_SOLANA` | `X402_TREASURY_SECRET_BASE58` | nothing (fills, gets swept back) |
+| **sponsor** | pays SOL fees | `X402_FEE_PAYER_SOLANA` | `X402_FEE_PAYER_SECRET_BASE58` | SOL for fees only |
+
+## Components
+
+- **Self-hosted facilitator** — [api/x402-facilitator/[action].js](../api/x402-facilitator/[action].js),
+ core in [api/_lib/x402/self-facilitator.js](../api/_lib/x402/self-facilitator.js).
+ Drop-in `/verify` + `/settle` matching the x402 v2 facilitator contract.
+ Validates the buyer-signed USDC transfer, co-signs with the sponsor key,
+ broadcasts over our RPC, logs the exact SOL fee. Point
+ `X402_FACILITATOR_URL_SOLANA` at `https://three.ws/api/x402-facilitator` and no
+ third party ever touches settlement.
+ - **Anti-drain gate.** The sponsor signs the whole transaction, so the
+ facilitator refuses to co-sign anything that is not exactly `{compute-budget,
+ optional ATA-create for OUR treasury, one USDC TransferChecked to an
+ allowlisted payTo}`. No System instructions (no SOL transfer out), capped
+ priority fee, recipient must be allowlisted. This blocks the "anyone drains
+ the sponsor" attack **and** enforces "only our wallets settle here".
+ - **SOL floor.** Below `X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) the
+ facilitator refuses to settle, pausing the loop before it can drain your SOL.
+- **Ring settlement endpoint** — [api/x402/ring-settle.js](../api/x402/ring-settle.js).
+ Price-configurable (`X402_PRICE_RING_SETTLE`), internal (`discoverable:false`),
+ returns a real economic-tick receipt.
+- **Rebalancer** — [api/_lib/x402/pipelines/ring-rebalance.js](../api/_lib/x402/pipelines/ring-rebalance.js),
+ registered in the autonomous loop. Sweeps treasury→payer so the float never
+ drains. Recirculation, not spend — never consumes the daily spend cap.
+- **Net-position report** — [api/x402-ring.js](../api/x402-ring.js). `GET
+ /api/x402-ring?period=24h|7d|30d|all`. Gross volume, tx count, SOL burned (in
+ SOL + USD), sweep totals, live balances, and the honest bottom line: real cost
+ = fees only.
+- **Volume engine** — the existing autonomous loop
+ ([api/cron/x402-autonomous-loop.js](../api/cron/x402-autonomous-loop.js) →
+ [volume-bootstrap-loop.js](../api/_lib/x402/pipelines/volume-bootstrap-loop.js))
+ round-robins `VOLUME_ENDPOINTS`, which now includes `ring-settle`.
+- **Setup script** — [scripts/x402-ring-setup.mjs](../scripts/x402-ring-setup.mjs).
+ Generates the role wallets, writes secrets to a gitignored file, prints the env
+ block. Never funds anything.
+
+## Turning it on
+
+```bash
+# 1. Generate the wallets (no chain, no funding — just keys).
+node scripts/x402-ring-setup.mjs
+
+# 2. Apply the schema.
+psql "$DATABASE_URL" -f api/_lib/migrations/2026-07-01-x402-ring-economy.sql
+
+# 3. Set env (Vercel), from the printed block:
+# X402_SELF_FACILITATOR_ENABLED=true
+# X402_FACILITATOR_URL_SOLANA=https://three.ws/api/x402-facilitator
+# X402_EXTERNAL_ENABLED=false # only OUR endpoints get paid
+# X402_CHARITY_AUDIT_BPS=0 # no charity split leaves the ring
+# X402_PRICE_RING_SETTLE=1000000 # $1.00/call
+# X402_AUTONOMOUS_DAILY_CAP_ATOMIC=… # your daily volume target
+# X402_SPONSOR_SOL_FLOOR_LAMPORTS=20000000
+# + the payer / treasury / sponsor pub+secret pairs
+
+# 4. Fund (manual, real money):
+# payer → USDC float, e.g. $50 (recirculates)
+# sponsor → SOL for fees, e.g. 0.1 SOL (≈ thousands of settlements)
+# treasury→ nothing; it fills and gets swept back
+
+# 5. Watch it.
+curl https://three.ws/api/x402-ring?period=24h
+```
+
+Everything is **off by default**: without `X402_SELF_FACILITATOR_ENABLED=true` and
+the sponsor secret, the facilitator returns `503` and nothing settles.
+
+## Cost model
+
+For a monthly gross target `V` at per-call size `p`:
+
+- transactions ≈ `V / p`
+- SOL fee ≈ `V / p × ~0.00001 SOL` (base + tiny priority)
+- one-time ATA rent ≈ 0.002 SOL per new wallet pair (reclaimable by closing ATAs)
+- charity/facilitator leak = **$0** when `X402_CHARITY_AUDIT_BPS=0` and the
+ self-hosted facilitator is used
+- principal = recirculates; net USDC position stays ~flat (see `/api/x402-ring`)
+
+Example: $10k/mo at $1/call ≈ 10k txs ≈ 0.1 SOL ≈ ~$20 real cost.
+
+## Related
+
+- [STRUCTURE.md](../STRUCTURE.md) — surface map
+- [/api/x402-revenue](../api/x402-revenue.js) — the **public** organic-revenue
+ feed (self-cycled ring volume is excluded from the "organic" framing here)
+- [docs/x402-revenue.md](./x402-revenue.md) — revenue surface docs
diff --git a/scripts/x402-ring-setup.mjs b/scripts/x402-ring-setup.mjs
new file mode 100644
index 000000000..377bd0ad4
--- /dev/null
+++ b/scripts/x402-ring-setup.mjs
@@ -0,0 +1,121 @@
+#!/usr/bin/env node
+// scripts/x402-ring-setup.mjs
+//
+// Bootstrap the closed-loop agent-to-agent x402 ring: generate the platform-
+// controlled role wallets, write their secrets to a GITIGNORED local file, and
+// print a ready-to-paste env block. It NEVER funds anything and NEVER touches
+// mainnet — funding the wallets with real USDC/SOL is a deliberate manual step.
+//
+// Roles (all wallets are three.ws-controlled — nothing here is a user wallet):
+// sponsor → pays Solana fees for every settle. Env: X402_FEE_PAYER_SOLANA (pub)
+// + X402_FEE_PAYER_SECRET_BASE58 (secret). Fund with a little SOL.
+// treasury → receives every ring payment. Env: X402_PAY_TO_SOLANA (pub)
+// + X402_TREASURY_SECRET_BASE58 (secret, used by the rebalancer).
+// payer → the ring wallet that pays. Env: X402_SEED_SOLANA_SECRET_BASE58
+// (secret). Fund with the USDC float that will recirculate.
+//
+// Usage:
+// node scripts/x402-ring-setup.mjs # generate all three roles
+// node scripts/x402-ring-setup.mjs --roles=payer # just one role
+// node scripts/x402-ring-setup.mjs --out=./secrets.json
+// node scripts/x402-ring-setup.mjs --register # also record pubkeys in DB
+// node scripts/x402-ring-setup.mjs --print-secrets # echo secrets to stdout too
+
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+import { writeFileSync } from 'node:fs';
+
+const args = process.argv.slice(2);
+const flag = (name) => args.includes(`--${name}`);
+const opt = (name, def) => {
+ const p = args.find((a) => a.startsWith(`--${name}=`));
+ return p ? p.slice(name.length + 3) : def;
+};
+
+const ROLE_ENV = {
+ sponsor: { pub: 'X402_FEE_PAYER_SOLANA', secret: 'X402_FEE_PAYER_SECRET_BASE58' },
+ treasury: { pub: 'X402_PAY_TO_SOLANA', secret: 'X402_TREASURY_SECRET_BASE58' },
+ payer: { pub: null, secret: 'X402_SEED_SOLANA_SECRET_BASE58' },
+};
+
+const roles = String(opt('roles', 'sponsor,treasury,payer'))
+ .split(',')
+ .map((r) => r.trim())
+ .filter((r) => ROLE_ENV[r]);
+
+if (roles.length === 0) {
+ console.error('No valid roles. Choose from: sponsor, treasury, payer');
+ process.exit(1);
+}
+
+const outFile = opt('out', '.x402-ring-secrets.json');
+const printSecrets = flag('print-secrets');
+
+const generated = {};
+const envLines = [];
+for (const role of roles) {
+ const kp = Keypair.generate();
+ const pub = kp.publicKey.toBase58();
+ const secret = bs58.encode(kp.secretKey);
+ generated[role] = { pubkey: pub, secret };
+ const map = ROLE_ENV[role];
+ if (map.pub) envLines.push(`${map.pub}=${pub}`);
+ envLines.push(`${map.secret}=${secret}`);
+}
+
+// Persist secrets to a gitignored file so they are not lost and never echoed
+// into shell history / CI logs by default.
+writeFileSync(outFile, JSON.stringify(generated, null, 2) + '\n', { mode: 0o600 });
+
+console.log('\n=== three.ws x402 ring — wallets generated ===\n');
+for (const role of roles) {
+ console.log(` ${role.padEnd(9)} pubkey: ${generated[role].pubkey}`);
+}
+console.log(`\nSecrets written to ${outFile} (chmod 600, gitignored). KEEP THIS FILE SAFE.\n`);
+
+console.log('=== Env block — paste into Vercel (or .env) ===\n');
+console.log(envLines.map((l) => (printSecrets ? l : redact(l))).join('\n'));
+
+console.log('\n=== Turn the ring ON (review before setting) ===\n');
+console.log(
+ [
+ 'X402_SELF_FACILITATOR_ENABLED=true',
+ 'X402_FACILITATOR_URL_SOLANA=https://three.ws/api/x402-facilitator',
+ 'X402_EXTERNAL_ENABLED=false # only OUR endpoints get paid',
+ 'X402_CHARITY_AUDIT_BPS=0 # no charity split leaves the ring',
+ 'X402_PRICE_RING_SETTLE=1000000 # $1.00/call → fewer txs, less SOL burned',
+ 'X402_AUTONOMOUS_DAILY_CAP_ATOMIC=… # set to your daily volume target',
+ 'X402_VOLUME_PER_RUN_CAP_ATOMIC=… # per-tick ceiling',
+ 'X402_SPONSOR_SOL_FLOOR_LAMPORTS=20000000 # pause below 0.02 SOL',
+ ].join('\n'),
+);
+
+console.log('\n=== Funding (manual — real money, do this yourself) ===\n');
+console.log(' payer → USDC float that recirculates (e.g. $50). A little SOL not needed (sponsor pays fees).');
+console.log(' treasury → 0 to start; it fills from ring payments, rebalancer sweeps it back to payer.');
+console.log(' sponsor → SOL for fees only (e.g. 0.1 SOL ≈ thousands of settlements). Watch /api/x402-ring.');
+console.log('');
+
+if (flag('register')) {
+ try {
+ const { sql } = await import('../api/_lib/db.js');
+ for (const role of roles) {
+ await sql`
+ INSERT INTO x402_ring_wallets (pubkey, label, role, enabled)
+ VALUES (${generated[role].pubkey}, ${`ring-${role}`}, ${role}, true)
+ ON CONFLICT (pubkey) DO UPDATE SET role = EXCLUDED.role, enabled = true
+ `;
+ }
+ console.log(`Registered ${roles.length} wallet(s) in x402_ring_wallets.\n`);
+ } catch (err) {
+ console.error(`--register failed (need DATABASE_URL + migration applied): ${err.message}\n`);
+ }
+}
+
+function redact(line) {
+ const [k, v] = line.split('=');
+ if (/SECRET/.test(k) && v && v.length > 12) {
+ return `${k}=${v.slice(0, 4)}…${v.slice(-4)} (full value in ${outFile})`;
+ }
+ return line;
+}
diff --git a/vercel.json b/vercel.json
index da0718412..9bafd5ea0 100644
--- a/vercel.json
+++ b/vercel.json
@@ -46,6 +46,9 @@
"api/pay/execute.js": {
"maxDuration": 60
},
+ "api/x402-facilitator/[action].js": {
+ "maxDuration": 60
+ },
"api/widgets/[id]/knowledge-process.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300