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.

13.4 KB
Raw Blame
// 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:'settlement_pending', transaction }
//            |  { success:false, errorReason }
//
// The middle shape is the non-terminal outcome every x402 SDK now understands:
// the transaction is broadcast but its confirmation is not yet known, so the
// caller retries instead of reporting a failed payment. The retry reconciles
// against the recorded signature rather than broadcasting a second transaction
// (api/_lib/x402/pending-settlements.js), and /api/cron/x402-settlement-reconcile
// closes the row once the chain answers.

import { cors, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.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,
} from '../_lib/x402/self-facilitator.js';
import {
	PENDING_SCOPE_FACILITATOR,
	SETTLEMENT_PENDING_REASON,
	SqlPendingSettlementStore,
} from '../_lib/x402/pending-settlements.js';
import { facilitatorFeeMeter, recordSettledFee } from '../_lib/x402/wallet-fee-meter.js';
import { claimSettleCredit } from '../_lib/x402/settle-credit.js';
import { listDiscoveryResources } from '../_lib/x402/discovery-resources.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();
}

// 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. Returns the write promise
// (never rejects — a DB error resolves after being logged) so the caller can
// AWAIT it before responding: on Vercel the function is frozen the instant the
// response is sent, so a truly fire-and-forget INSERT is dropped before it
// flushes (observed: every external /verify + /settle left this table empty
// despite 200 responses). Awaiting keeps the instance alive for the ~1 RPC the
// write costs, which is negligible against the on-chain settle it records.
function logOp(row) {
	return sql`
		INSERT INTO x402_self_facilitator_log
			(action, network, payer, pay_to, mint, amount_atomic, tx_sig,
			 fee_lamports, ok, reject_reason, idempotency_key, fee_payer)
		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}, ${row.feePayer || 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);

	// GET /api/x402-facilitator (root) — self-describing discovery document. The
	// bare path used to 404 (the route table only matched /:action), which reads as
	// "broken" when someone opens the facilitator URL in a browser. This index names
	// the service, its endpoints, the networks/schemes it settles, and the public
	// receiver — no secret, no payment. It is descriptive only; verify/settle stay POST.
	if (action === 'index' || action === '' || action === 'x402-facilitator') {
		if (!method(req, res, ['GET'])) return;
		const base = '/api/x402-facilitator';
		return json(res, 200, {
			service: 'three.ws self-hosted x402 facilitator',
			description:
				'Verifies and settles x402 USDC payments on Solana over our own RPC. ' +
				'No third party touches settlement.',
			x402Version: X402_VERSION,
			enabled: SELF_FACILITATOR_ENABLED,
			kinds: [
				{ x402Version: X402_VERSION, scheme: 'exact', network: NETWORK_SOLANA_MAINNET },
			],
			// Non-terminal settle outcomes this facilitator can answer with. Named
			// here so a client can tell, before paying, that a pending settlement
			// will be reconciled rather than reported as a failure.
			settleStatuses: ['success', SETTLEMENT_PENDING_REASON, 'failure'],
			payTo: env.X402_PAY_TO_SOLANA || null,
			feePayer: env.X402_FEE_PAYER_SOLANA || null,
			asset: env.X402_ASSET_MINT_SOLANA || null,
			endpoints: {
				supported: { method: 'GET', path: `${base}/supported` },
				verify: { method: 'POST', path: `${base}/verify` },
				settle: { method: 'POST', path: `${base}/settle` },
				discovery: { method: 'GET', path: `${base}/discovery/resources` },
			},
			docs: 'https://three.ws/docs/x402-ring-economy',
		});
	}

	// GET /discovery/resources — the facilitator-standard catalog list that
	// x402scan's crawler (useFacilitator().list()) pages through when this
	// facilitator's registry entry carries a discoveryConfig. Serves the same
	// canonical catalog as /.well-known/x402.json, projected to the legacy v1
	// wire format the crawler validates. Public read, no payment. The route
	// table maps the two-segment path to action=discovery-resources; the bare
	// last-segment fallback in actionFrom() yields 'resources'.
	if (action === 'discovery-resources' || action === 'resources') {
		if (!method(req, res, ['GET'])) return;
		const list = await listDiscoveryResources({
			type: req.query?.type,
			limit: req.query?.limit,
			offset: req.query?.offset,
		});
		return json(res, 200, list, { 'cache-control': 'public, max-age=300' });
	}

	// /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',
		});
	}

	// Flood guard on the money-moving path. /supported (public probe) and the
	// disabled-503 above are exempt — only real verify/settle work reaches here,
	// and each settle burns sponsor SOL, so cap per-IP and globally. Both CRITICAL
	// (fail closed): a throttled settle just leaves the buyer to retry.
	const ip = clientIp(req);
	const ipRl = await limits.x402FacilitatorIp(ip);
	if (!ipRl.success) return rateLimited(res, ipRl);
	const globalRl = await limits.x402FacilitatorGlobal();
	if (!globalRl.success) return rateLimited(res, globalRl);

	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 = await verifyRingPayment({ paymentPayload, requirement });
		await 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') {
		// No eager sponsor-key load: self-pay settles need no sponsor at all, and
		// sponsor-mode settles load the key lazily inside settleRingPayment.
		// The fee meter governs the fee-paying wallet's daily SOL burn across
		// every pipeline that settles here (wallet-fee-meter.js).
		const result = await settleRingPayment({
			paymentPayload,
			requirement,
			feeMeter: facilitatorFeeMeter(),
			idempotencyKey: req.headers?.['idempotency-key'] || null,
			// Shared across replicas on purpose: a settle retry has no session
			// affinity, so the in-memory default store the x402 SDK ships would miss
			// every retry that lands on another Cloud Run instance and re-broadcast
			// instead of reconciling.
			pendingStore: new SqlPendingSettlementStore({ scope: PENDING_SCOPE_FACILITATOR }),
		});

		const idempotencyKey = req.headers?.['idempotency-key'] || null;

		// `settlement_pending`: broadcast, outcome not yet known. NOT a failure.
		// the credit is deliberately NOT claimed and the fee is deliberately NOT
		// metered, because neither is decided until the chain answers. The caller
		// retries (and reconciles against the recorded signature), and
		// /api/cron/x402-settlement-reconcile closes the row either way.
		if (!result.success && result.pending) {
			await logOp({
				action: 'settle',
				network: requirement.network,
				payer: result.payer,
				payTo: requirement.payTo,
				mint: requirement.asset,
				amountAtomic: Number(requirement.amount) || null,
				txSig: result.transaction,
				ok: false,
				reason: result.pendingDetail
					? `${SETTLEMENT_PENDING_REASON}:${result.pendingDetail}`
					: SETTLEMENT_PENDING_REASON,
				idempotencyKey,
				feePayer: result.feePayer,
			});
			return json(res, 200, {
				success: false,
				errorReason: SETTLEMENT_PENDING_REASON,
				transaction: result.transaction,
				network: result.network || requirement.network,
				payer: result.payer || null,
			});
		}

		if (!result.success) {
			await 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: false,
				reason: result.reason,
				idempotencyKey,
				feePayer: result.feePayer,
			});
			// 200 + success:false → settlePayment throws a clean settle_failed without
			// the transient-5xx retry path.
			return json(res, 200, { success: false, errorReason: result.reason });
		}

		// A broadcast success is NOT yet a settled payment. settleRingPayment's
		// already-processed recovery cannot distinguish a retry of THIS payment from
		// a different payment whose transaction compiled to the same signature, so
		// the credit is claimed here, atomically, one payment per signature. The
		// claim writes its own audit row (ok=true on grant, ok=false with the refusal
		// reason otherwise), which is why logOp is not called on this path.
		const credit = await claimSettleCredit({
			sql,
			row: {
				network: requirement.network,
				payer: result.payer,
				payTo: requirement.payTo,
				mint: requirement.asset,
				amountAtomic: Number(requirement.amount) || null,
				txSig: result.transaction,
				feeLamports: result.feeLamports,
				idempotencyKey,
				feePayer: result.feePayer,
			},
		});

		if (!credit.granted && !credit.idempotentReplay) {
			// Someone else's payment owns this signature (or the DB is unavailable and
			// we cannot prove otherwise). Refusing is what stops a service being
			// delivered against a transfer that settled a different payment.
			return json(res, 200, { success: false, errorReason: credit.reason });
		}

		// Meter the SOL burn once per actual settlement. An idempotent replay already
		// had its fee counted when the credit was first granted; counting it again
		// would drain the wallet's daily runway on retries alone.
		if (credit.granted) recordSettledFee(result.feePayer, result.feeLamports);

		return json(res, 200, {
			success: true,
			transaction: result.transaction,
			network: result.network,
			payer: result.payer,
		});
	}

	return json(res, 404, { error: `unknown_action:${action}` });
});