Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): add a prepaid ledger with chain settlement and MCP credit plans, with the /mcp-plans page and migrations
nirholasa37074e6770b
diff --git a/api/_lib/mcp-credits.js b/api/_lib/mcp-credits.jsnew file mode 100644index 000000000..86281c3c7--- /dev/null+++ b/api/_lib/mcp-credits.js@@ -0,0 +1,256 @@+// Credit plans and trials for paid MCP tools.+//+// A paid tool is billed per call over x402 (api/_lib/pump-pricing.js). An account+// that would rather prepay buys a plan (api/_lib/mcp-plans.js): a credit bundle+// or a time pass. This module is the meter the MCP dispatcher runs around every+// tool call that has a price:+//+// 1. begin - find what pays for the call, in this order:+// a time pass covering the tool (free while it lasts),+// a credit bundle with enough credits (debited atomically),+// a metered free trial (N calls per account per tool).+// 2. refund - a tool that throws or answers isError gives the charge back.+// 3. finish - settle a result-dependent cost, then report creditsUsed and+// creditsRemaining in the result's _meta.+//+// When nothing covers the call, an account that holds a plan (or every account,+// with MCP_METER_ALL=1) gets the same -32402 the per-call x402 path raises, so a+// drained balance degrades to pay-per-call instead of a dead end. Accounts that+// never bought a plan keep today's behaviour: an OAuth bearer bypasses payment.+//+// One credit is worth $0.001 of a tool's per-call price. Credits live in+// mcp_plan_balances; a balance debit is a single conditional UPDATE so a spend+// can never drive it negative under concurrent calls.++import { sql } from './db.js';+import { logger } from './usage.js';+import { priceFor } from './pump-pricing.js';++const log = logger('mcp-credits');++export const CREDIT_USD = 0.001;+const DEFAULT_TRIAL_CALLS = 3;++// Tools whose cost is not simply their list price. `base` is debited before the+// call; `settle(result, args)` returns the final cost once the result is known,+// and the difference is debited or refunded. Empty today: every metered tool+// costs its list price in credits.+export const CREDIT_COST_OVERRIDES = Object.freeze({});++export function trialCallsPerTool(env = process.env) {+ const n = Number(env.MCP_TRIAL_CALLS);+ return Number.isInteger(n) && n >= 0 ? n : DEFAULT_TRIAL_CALLS;+}++function meterAllAccounts(env = process.env) {+ return env.MCP_METER_ALL === '1' || env.MCP_METER_ALL === 'true';+}++/** Credits a tool call costs up front, or null when the tool is not metered. */+export function creditCostFor(toolName, args = {}) {+ const override = CREDIT_COST_OVERRIDES[toolName];+ if (override) {+ const base = typeof override.base === 'function' ? override.base(args) : override.base;+ return Math.max(1, Math.round(base));+ }+ const price = priceFor(toolName);+ if (!price || !(price.amount_usdc > 0)) return null;+ return Math.max(1, Math.round(price.amount_usdc / CREDIT_USD));+}++async function creditsRemaining(userId) {+ const [row] = await sql`+ select coalesce(sum(credits_remaining), 0)::int as remaining+ from mcp_plan_balances+ where user_id = ${userId} and kind = 'credits'+ and (expires_at is null or expires_at > now())+ `;+ return row?.remaining ?? 0;+}++async function activeTimePass(userId, tool) {+ const [row] = await sql`+ select id, expires_at from mcp_plan_balances+ where user_id = ${userId} and kind = 'time' and expires_at > now()+ and (cardinality(tools) = 0 or ${tool} = any(tools))+ order by expires_at desc+ limit 1+ `;+ return row || null;+}++async function debitBundle(userId, tool, cost) {+ const rows = await sql`+ with pick as (+ select id from mcp_plan_balances+ where user_id = ${userId} and kind = 'credits'+ and credits_remaining >= ${cost}+ and (expires_at is null or expires_at > now())+ and (cardinality(tools) = 0 or ${tool} = any(tools))+ order by created_at+ limit 1+ for update skip locked+ ), upd as (+ update mcp_plan_balances b+ set credits_remaining = b.credits_remaining - ${cost}+ from pick where b.id = pick.id+ returning b.id+ ), ev as (+ insert into mcp_credit_events (user_id, balance_id, tool, kind, credits)+ select ${userId}, id, ${tool}, 'debit', ${cost} from upd+ )+ select id from upd+ `;+ return rows[0]?.id ?? null;+}++async function takeTrialUse(userId, tool, limit) {+ if (limit <= 0) return null;+ const rows = await sql`+ with t as (+ insert into mcp_tool_trials (user_id, tool, used)+ values (${userId}, ${tool}, 1)+ on conflict (user_id, tool) do update+ set used = mcp_tool_trials.used + 1, updated_at = now()+ where mcp_tool_trials.used < ${limit}+ returning used+ ), ev as (+ insert into mcp_credit_events (user_id, tool, kind, credits)+ select ${userId}, ${tool}, 'trial', 0 from t+ )+ select used from t+ `;+ return rows[0] ? limit - rows[0].used : null;+}++async function holdsAnyPlan(userId) {+ const [row] = await sql`select 1 as held from mcp_plan_balances where user_id = ${userId} limit 1`;+ return Boolean(row);+}++function paymentRequired(rpcError, tool, cost, remaining, trialLimit) {+ const price = priceFor(tool);+ return rpcError(-32402, 'payment required for this tool', {+ scheme: 'x402',+ tool,+ amount_usdc: price?.amount_usdc,+ creditsRequired: cost,+ creditsRemaining: remaining,+ trialCalls: trialLimit,+ plans_url: '/mcp-plans',+ hint: 'Buy a credit plan at /mcp-plans, or call without a bearer token and pay this call over x402.',+ });+}++/**+ * Charge the account for a metered call. Returns a meter handle, or null when+ * the call is not metered (anonymous x402 principal, free tool, account without+ * a plan). Throws the rpcError built by `rpcError` when nothing covers the call.+ */+export async function beginMeter({ auth, tool, args, rpcError }) {+ const userId = auth?.userId;+ if (!userId || auth.x402Paid) return null;+ const cost = creditCostFor(tool, args);+ if (cost === null) return null;++ try {+ const pass = await activeTimePass(userId, tool);+ if (pass) {+ await sql`insert into mcp_credit_events (user_id, balance_id, tool, kind, credits) values (${userId}, ${pass.id}, ${tool}, 'time_pass', 0)`;+ return { userId, tool, cost, source: 'time_pass', balanceId: pass.id, paid: 0, expiresAt: pass.expires_at };+ }+ const balanceId = await debitBundle(userId, tool, cost);+ if (balanceId) return { userId, tool, cost, source: 'plan', balanceId, paid: cost };++ const trialLimit = trialCallsPerTool();+ const left = await takeTrialUse(userId, tool, trialLimit);+ if (left !== null) return { userId, tool, cost, source: 'trial', balanceId: null, paid: 0, trialRemaining: left };++ if (meterAllAccounts() || (await holdsAnyPlan(userId))) {+ throw paymentRequired(rpcError, tool, cost, await creditsRemaining(userId), trialLimit);+ }+ return null;+ } catch (err) {+ if (typeof err?.code === 'number') throw err;+ log.error('meter_begin_failed', { tool, message: err?.message });+ return null;+ }+}++/** Give back what beginMeter took. Safe to call once per meter. */+export async function refundMeter(meter) {+ if (!meter || meter.refunded) return;+ meter.refunded = true;+ try {+ if (meter.source === 'plan') {+ await sql`+ with upd as (+ update mcp_plan_balances set credits_remaining = credits_remaining + ${meter.paid}+ where id = ${meter.balanceId}+ returning id+ )+ insert into mcp_credit_events (user_id, balance_id, tool, kind, credits)+ select ${meter.userId}, id, ${meter.tool}, 'refund', ${meter.paid} from upd+ `;+ meter.paid = 0;+ } else if (meter.source === 'trial') {+ await sql`+ update mcp_tool_trials set used = greatest(used - 1, 0), updated_at = now()+ where user_id = ${meter.userId} and tool = ${meter.tool}+ `;+ meter.trialRemaining += 1;+ }+ } catch (err) {+ meter.refunded = false;+ log.error('meter_refund_failed', { tool: meter.tool, message: err?.message });+ }+}++async function settleCost(meter, result, args) {+ const override = CREDIT_COST_OVERRIDES[meter.tool];+ if (meter.refunded || meter.source !== 'plan' || typeof override?.settle !== 'function') return;+ const final = Math.max(0, Math.round(override.settle(result, args)));+ const delta = final - meter.paid;+ if (delta === 0) return;+ const [row] = await sql`+ with old as (select credits_remaining as before from mcp_plan_balances where id = ${meter.balanceId} for update),+ upd as (+ update mcp_plan_balances set credits_remaining = greatest(0, credits_remaining - ${delta})+ where id = ${meter.balanceId}+ returning credits_remaining as after+ ), ev as (+ insert into mcp_credit_events (user_id, balance_id, tool, kind, credits)+ select ${meter.userId}, ${meter.balanceId}, ${meter.tool},+ case when ${delta} > 0 then 'debit' else 'refund' end,+ abs((select before from old) - upd.after)+ from upd+ where (select before from old) <> upd.after+ )+ select (select before from old) as before, upd.after from upd+ `;+ if (row) meter.paid += row.before - row.after;+}++/** Settle a result-dependent cost and attach creditsUsed / creditsRemaining. */+export async function finishMeter(meter, result, args) {+ if (!meter || !result || typeof result !== 'object') return result;+ try {+ await settleCost(meter, result, args);+ } catch (err) {+ log.error('meter_settle_failed', { tool: meter.tool, message: err?.message });+ }+ let remaining = null;+ try {+ remaining = await creditsRemaining(meter.userId);+ } catch (err) {+ log.error('meter_balance_failed', { tool: meter.tool, message: err?.message });+ }+ const meta = {+ creditsUsed: meter.paid,+ creditsRemaining: remaining,+ creditSource: meter.source,+ ...(meter.source === 'trial' ? { trialRemaining: meter.trialRemaining } : {}),+ ...(meter.source === 'time_pass' ? { planExpiresAt: new Date(meter.expiresAt).toISOString() } : {}),+ };+ return { ...result, _meta: { ...(result._meta || {}), ...meta } };+}diff --git a/api/_lib/mcp-plans.js b/api/_lib/mcp-plans.jsnew file mode 100644index 000000000..7c5b876f6--- /dev/null+++ b/api/_lib/mcp-plans.js@@ -0,0 +1,122 @@+// MCP plan catalog, purchase and account summary. The meter that spends these+// balances is api/_lib/mcp-credits.js.+//+// A plan is bought with the account's prepaid USD credits (api/_lib/credits.js),+// the same checkout every other metered action uses: top up at /credits with+// SOL, USDC or $THREE, then buy. The USD debit and the plan grant are idempotent+// on one key, so a retried purchase charges once and grants once: if the grant+// insert fails after the debit, retrying the same request finishes the grant+// without a second charge.++import { sql } from './db.js';+import { debitCredits, getCreditAccount } from './credits.js';+import { trialCallsPerTool, CREDIT_USD } from './mcp-credits.js';+import { TOOL_PRICING } from './pump-pricing.js';++function failure(status, code, message) {+ return Object.assign(new Error(message), { status, code });+}++function planRow(r) {+ return {+ slug: r.slug,+ name: r.name,+ description: r.description,+ kind: r.kind,+ credits: r.credits,+ durationSeconds: r.duration_seconds,+ priceUsd: Number(r.price_usd),+ tools: r.tools,+ };+}++export async function listPlans() {+ const rows = await sql`+ select slug, name, description, kind, credits, duration_seconds, price_usd, tools+ from mcp_plans where active order by sort_order, price_usd+ `;+ return rows.map(planRow);+}++/** Per-tool credit cost table the account page shows next to the plans. */+export function toolCreditTable() {+ return Object.entries(TOOL_PRICING).map(([tool, p]) => ({+ tool,+ credits: Math.max(1, Math.round(p.amount_usdc / CREDIT_USD)),+ amountUsdc: p.amount_usdc,+ }));+}++export async function purchasePlan({ userId, slug, idempotencyKey }) {+ if (!idempotencyKey) throw failure(400, 'validation_error', 'idempotency_key is required');+ const [plan] = await sql`+ select id, slug, name, kind, credits, duration_seconds, price_usd, tools+ from mcp_plans where slug = ${slug} and active+ `;+ if (!plan) throw failure(404, 'not_found', 'unknown plan');++ const purchaseKey = `mcp-plan:${userId}:${idempotencyKey}`;+ const [existing] = await sql`select id from mcp_plan_balances where purchase_key = ${purchaseKey}`;+ if (existing) return { balanceId: existing.id, replay: true };++ await debitCredits({+ userId,+ amountUsd: Number(plan.price_usd),+ action: 'mcp_plan',+ refType: 'mcp_plan',+ refId: plan.id,+ idempotencyKey: purchaseKey,+ meta: { slug: plan.slug },+ });++ const expiresAt =+ plan.kind === 'time' ? new Date(Date.now() + plan.duration_seconds * 1000).toISOString() : null;+ const [row] = await sql`+ insert into mcp_plan_balances+ (user_id, plan_id, kind, credits_total, credits_remaining, tools, expires_at, purchase_key)+ values (${userId}, ${plan.id}, ${plan.kind}, ${plan.credits}, ${plan.credits}, ${plan.tools}, ${expiresAt}, ${purchaseKey})+ on conflict (purchase_key) do update set purchase_key = excluded.purchase_key+ returning id+ `;+ return { balanceId: row.id, replay: false };+}++export async function accountSummary(userId, { historyLimit = 50 } = {}) {+ const limit = Math.min(Math.max(Number(historyLimit) || 50, 1), 200);+ const [balances, trials, history, usd] = await Promise.all([+ sql`+ select b.id, p.slug, p.name, b.kind, b.credits_total, b.credits_remaining, b.tools,+ b.expires_at, b.created_at+ from mcp_plan_balances b join mcp_plans p on p.id = b.plan_id+ where b.user_id = ${userId}+ order by b.created_at desc+ `,+ sql`select tool, used from mcp_tool_trials where user_id = ${userId} order by tool`,+ sql`+ select id, tool, kind, credits, created_at from mcp_credit_events+ where user_id = ${userId} order by created_at desc, id desc limit ${limit}+ `,+ getCreditAccount(userId),+ ]);+ const now = Date.now();+ const live = balances.filter((b) => !b.expires_at || new Date(b.expires_at).getTime() > now);+ const trialLimit = trialCallsPerTool();+ return {+ creditsRemaining: live.filter((b) => b.kind === 'credits').reduce((n, b) => n + b.credits_remaining, 0),+ timePasses: live+ .filter((b) => b.kind === 'time')+ .map((b) => ({ id: b.id, plan: b.name, expiresAt: b.expires_at, tools: b.tools })),+ bundles: balances+ .filter((b) => b.kind === 'credits')+ .map((b) => ({+ id: b.id,+ plan: b.name,+ total: b.credits_total,+ remaining: b.credits_remaining,+ purchasedAt: b.created_at,+ })),+ trials: { callsPerTool: trialLimit, used: trials.map((t) => ({ tool: t.tool, used: t.used, remaining: Math.max(0, trialLimit - t.used) })) },+ history: history.map((h) => ({ id: h.id, tool: h.tool, kind: h.kind, credits: h.credits, at: h.created_at })),+ usdBalance: usd.balanceUsd,+ };+}diff --git a/api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql b/api/_lib/migrations/20261023160000_x402_prepaid_ledger.sqlnew file mode 100644index 000000000..3fb3afb64--- /dev/null+++ b/api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql@@ -0,0 +1,79 @@+begin;++-- x402 prepaid balances settled on-chain in batches.+--+-- x402_prepaid_accounts one row per (payer, network, asset). balance_atomic+-- is the spendable balance; the CHECK makes a negative+-- balance impossible even if a code path forgets the guard.+-- x402_prepaid_entries append-mostly journal. A deposit is one on-chain+-- payment (ref = tx signature). A debit is one paid+-- request (ref = request id): reserved while the handler+-- runs, committed on success, refunded on 5xx / cancel /+-- stale. Only committed debits are ever settled.+-- x402_prepaid_batches one row per payee per settlement window. A batch claims+-- its committed debits (entries.batch_id) in the same+-- statement that creates it, so a debit is in at most one+-- batch.++create table if not exists x402_prepaid_accounts (+ payer text not null,+ network text not null,+ asset text not null,+ balance_atomic bigint not null default 0 check (balance_atomic >= 0),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ primary key (payer, network, asset)+);++create table if not exists x402_prepaid_batches (+ id uuid primary key,+ payee text not null,+ network text not null,+ asset text not null,+ total_atomic bigint not null check (total_atomic > 0),+ debit_count integer not null check (debit_count > 0),+ status text not null default 'pending'+ check (status in ('pending', 'confirmed', 'failed', 'unconfirmed')),+ tx_signature text,+ error text,+ created_at timestamptz not null default now(),+ settled_at timestamptz+);++create index if not exists x402_prepaid_batches_open_idx+ on x402_prepaid_batches (status, created_at) where status in ('pending', 'unconfirmed');++create table if not exists x402_prepaid_entries (+ id bigserial primary key,+ kind text not null check (kind in ('deposit', 'debit')),+ payer text not null,+ network text not null,+ asset text not null,+ amount_atomic bigint not null check (amount_atomic > 0),+ ref text not null,+ state text not null+ check (state in ('credited', 'reserved', 'committed', 'refunded')),+ payee text,+ route text,+ batch_id uuid references x402_prepaid_batches (id),+ refund_reason text,+ created_at timestamptz not null default now(),+ resolved_at timestamptz,+ unique (kind, ref),+ check (+ (kind = 'deposit' and state = 'credited' and payee is null)+ or (kind = 'debit' and state <> 'credited' and payee is not null)+ )+);++create index if not exists x402_prepaid_entries_unsettled_idx+ on x402_prepaid_entries (payee, network, asset)+ where kind = 'debit' and state = 'committed' and batch_id is null;++create index if not exists x402_prepaid_entries_reserved_idx+ on x402_prepaid_entries (created_at) where state = 'reserved';++create index if not exists x402_prepaid_entries_payer_idx+ on x402_prepaid_entries (payer, network, asset, created_at desc);++commit;diff --git a/api/_lib/x402/prepaid-chain.js b/api/_lib/x402/prepaid-chain.jsnew file mode 100644index 000000000..dc269b7a2--- /dev/null+++ b/api/_lib/x402/prepaid-chain.js@@ -0,0 +1,203 @@+// api/_lib/x402/prepaid-chain.js+//+// The on-chain legs of the prepaid rail, kept apart from the ledger so the+// arithmetic can be tested against a bare database:+//+// · verifyPrepaidDeposit - confirm a finalized USDC transfer into the settler+// wallet and name who sent it. The credited account belongs to that sender.+// · sendBatchTransfers - ONE transaction paying every batch's seller, with a+// memo naming the batch ids.+//+// Solana only; USDC only. An EVM leg would be added alongside, never instead.++import {+ PublicKey,+ TransactionInstruction,+} from '@solana/web3.js';+import {+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferCheckedInstruction,+ getAssociatedTokenAddress,+} from '@solana/spl-token';+import { env } from '../env.js';+import { solanaConnection } from '../solana/connection.js';+import { ataExists } from '../solana/read-guards.js';+import { submitProtected } from '../execution-engine.js';+import { tokenProgramIdForMint } from '../token/token-program.js';+import { loadSignerKeypair, SOLANA_SIGNERS } from '../solana-signers.js';+import { NETWORK_SOLANA_MAINNET } from '../x402-spec.js';++export const PREPAID_NETWORK = NETWORK_SOLANA_MAINNET;+export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+export const USDC_DECIMALS = 6;+export const PREPAID_ASSET = USDC_MINT_SOLANA;++const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const SETTLER_SPEC = SOLANA_SIGNERS.find((s) => s.name === 'x402-prepaid-settler');++function chainError(message, status, code) {+ return Object.assign(new Error(message), { status, code });+}++/** The settler keypair, or null when X402_PREPAID_SETTLER_SECRET_BASE58 is unset or corrupt. */+export async function loadSettler() {+ const { keypair } = await loadSignerKeypair(SETTLER_SPEC);+ return keypair;+}++/**+ * Where buyers send a deposit: X402_PREPAID_DEPOSIT_WALLET if set, else the+ * settler's own address (the wallet that can pay sellers out of it).+ * @returns {Promise<string|null>}+ */+export async function prepaidDepositWallet() {+ const override = (env.X402_PREPAID_DEPOSIT_WALLET || '').trim();+ if (override) return override;+ const settler = await loadSettler();+ return settler ? settler.publicKey.toBase58() : null;+}++function keyStr(k) {+ return k?.pubkey?.toString?.() || String(k?.pubkey ?? '');+}++/**+ * Verify a deposit transaction and report the sender and the USDC credited.+ * Finalized commitment only: a reorged deposit must not stay credited.+ *+ * @param {string} signature+ * @returns {Promise<{ pending: true } | { pending: false, payer: string, amountAtomics: bigint }>}+ */+export async function verifyPrepaidDeposit(signature) {+ const sink = await prepaidDepositWallet();+ if (!sink) throw chainError('the prepaid deposit wallet is not configured', 503, 'deposit_unavailable');+ if (typeof signature !== 'string' || signature.length < 32 || signature.length > 128) {+ throw chainError('a valid tx_signature is required', 400, 'bad_request');+ }+ const connection = solanaConnection({ network: 'mainnet', commitment: 'finalized' });+ let tx = null;+ try {+ tx = await connection.getParsedTransaction(signature, {+ maxSupportedTransactionVersion: 1,+ commitment: 'finalized',+ });+ } catch {+ tx = null;+ }+ if (!tx) {+ const { value } = await connection+ .getSignatureStatuses([signature], { searchTransactionHistory: true })+ .catch(() => ({ value: [] }));+ const status = value?.[0];+ if (status?.err) throw chainError('transaction failed on-chain', 422, 'tx_failed');+ if (status) return { pending: true };+ throw chainError('transaction not found', 422, 'tx_not_found');+ }+ if (tx.meta?.err) throw chainError('transaction failed on-chain', 422, 'tx_failed');++ const pre = tx.meta?.preTokenBalances || [];+ const post = tx.meta?.postTokenBalances || [];+ let received = 0n;+ for (const p of post) {+ if (p.mint !== USDC_MINT_SOLANA || p.owner !== sink) continue;+ const before = pre.find((x) => x.accountIndex === p.accountIndex);+ received += BigInt(p.uiTokenAmount?.amount ?? '0') - BigInt(before?.uiTokenAmount?.amount ?? '0');+ }+ if (received <= 0n) {+ throw chainError('this transaction did not send USDC to the prepaid deposit wallet', 422, 'no_deposit_found');+ }++ // The sender is the owner whose USDC balance fell, and it must have signed.+ const signers = new Set(+ (tx.transaction?.message?.accountKeys || []).filter((k) => k.signer).map(keyStr),+ );+ const senders = [];+ for (const b of pre) {+ if (b.mint !== USDC_MINT_SOLANA || !b.owner || b.owner === sink) continue;+ const after = post.find((x) => x.accountIndex === b.accountIndex);+ const delta = BigInt(after?.uiTokenAmount?.amount ?? '0') - BigInt(b.uiTokenAmount?.amount ?? '0');+ if (delta < 0n && signers.has(b.owner)) senders.push(b.owner);+ }+ if (senders.length !== 1) {+ throw chainError(+ 'the deposit must come from exactly one signing wallet; send it from the wallet that will spend the balance',+ 422,+ 'deposit_sender_ambiguous',+ );+ }+ return { pending: false, payer: senders[0], amountAtomics: received };+}++/**+ * Pay every batch's seller in one transaction. Throws with `code: 'PRE_SEND'`+ * for anything that fails before a transaction could have been broadcast, so the+ * batcher can release the debits safely.+ *+ * @param {Array<{ id: string, payee: string, asset: string, totalAtomics: bigint }>} batches+ * @returns {Promise<string>} the confirmed transaction signature+ */+export async function sendBatchTransfers(batches) {+ const preSend = (err) => Object.assign(err, { code: err.code || 'PRE_SEND' });+ let settler;+ let built;+ const connection = solanaConnection({ network: 'mainnet', commitment: 'confirmed' });+ try {+ settler = await loadSettler();+ if (!settler) throw new Error('X402_PREPAID_SETTLER_SECRET_BASE58 is not configured');+ const mint = new PublicKey(USDC_MINT_SOLANA);+ const programId = await tokenProgramIdForMint(connection, mint);+ const sourceAta = await getAssociatedTokenAddress(mint, settler.publicKey, false, programId);+ const instructions = [];+ for (const b of batches) {+ if (b.asset !== USDC_MINT_SOLANA) throw new Error(`unsupported asset ${b.asset}`);+ const payee = new PublicKey(b.payee);+ const dest = await getAssociatedTokenAddress(mint, payee, true, programId);+ if (!(await ataExists(connection, dest))) {+ instructions.push(+ createAssociatedTokenAccountIdempotentInstruction(settler.publicKey, dest, payee, mint, programId),+ );+ }+ instructions.push(+ createTransferCheckedInstruction(sourceAta, mint, dest, settler.publicKey, b.totalAtomics, USDC_DECIMALS, [], programId),+ );+ }+ instructions.push(+ new TransactionInstruction({+ programId: MEMO_PROGRAM_ID,+ keys: [],+ data: Buffer.from(`three.ws x402 prepaid settle ${batches.map((b) => b.id).join(',')}`),+ }),+ );+ built = instructions;+ } catch (err) {+ throw preSend(err);+ }+ const { signature } = await submitProtected({+ network: 'mainnet',+ connection,+ payer: settler,+ instructions: built,+ });+ return signature;+}++/**+ * USDC atomics the deposit wallet actually holds, for the float check. Null when+ * no deposit wallet is configured or the chain could not be read, so a caller+ * reports "unknown" instead of a false shortfall.+ * @returns {Promise<bigint|null>}+ */+export async function depositWalletUsdcBalance() {+ const wallet = await prepaidDepositWallet();+ if (!wallet) return null;+ try {+ const connection = solanaConnection({ network: 'mainnet', commitment: 'confirmed' });+ const mint = new PublicKey(USDC_MINT_SOLANA);+ const programId = await tokenProgramIdForMint(connection, mint);+ const ata = await getAssociatedTokenAddress(mint, new PublicKey(wallet), true, programId);+ const bal = await connection.getTokenAccountBalance(ata, 'confirmed');+ return BigInt(bal.value.amount);+ } catch {+ return null;+ }+}diff --git a/api/_lib/x402/prepaid-ledger.js b/api/_lib/x402/prepaid-ledger.jsnew file mode 100644index 000000000..fd0b5f3f4--- /dev/null+++ b/api/_lib/x402/prepaid-ledger.js@@ -0,0 +1,293 @@+// api/_lib/x402/prepaid-ledger.js+//+// Per-payer prepaid balance for x402 routes that opt into `mode: 'prepaid'`.+//+// Why it exists: a $0.001 call settled on-chain on its own costs more in fees+// and fee-wallet float than it earns, and a burst of them is what starved the+// settle floor in past outages (docs/ops/x402-prepaid.md). Here the buyer makes+// ONE on-chain deposit; every request after that is a database debit, and the+// seller side is paid later in one batched transfer (prepaid-settle.js).+//+// Money rules, each enforced by a single atomic SQL statement so no ordering of+// concurrent requests can break them:+//+// · A debit never takes a balance below zero: the UPDATE's WHERE clause is the+// guard (re-evaluated after a row-lock wait under READ COMMITTED) and the+// column CHECK is the backstop.+// · A debit is RESERVED while the handler runs and only COMMITTED on success.+// A 4xx/5xx, a thrown handler, a cancelled request, or a reservation that+// outlives PREPAID_RESERVATION_TTL_SECONDS is refunded in full. Only+// committed debits are ever settled to the seller.+// · A deposit is idempotent on its transaction signature.+//+// All amounts are atomics (USDC has 6 decimals) carried as BigInt in JS and as+// text across the driver so nothing passes through a lossy Number.++import { sql } from '../db.js';++/** Reservations older than this are refunded by sweepStaleReservations. */+export const PREPAID_RESERVATION_TTL_SECONDS = 600;++/** Postgres `undefined_table`: the migration has not been applied here yet. */+const UNDEFINED_TABLE = '42P01';++/** True when a ledger failure is the table being absent (deploy ran ahead of its migration). */+export function isLedgerUnavailable(err) {+ const code = err?.code || err?.sourceError?.code;+ return code === UNDEFINED_TABLE;+}++/**+ * Normalise an amount to a positive BigInt, or throw a 400-shaped error.+ * @param {string|number|bigint} value+ */+export function toAtomics(value) {+ let n;+ try {+ n = BigInt(value);+ } catch {+ throw Object.assign(new Error('amount must be an integer count of atomics'), {+ status: 400,+ code: 'bad_amount',+ });+ }+ if (n <= 0n) {+ throw Object.assign(new Error('amount must be greater than zero'), {+ status: 400,+ code: 'bad_amount',+ });+ }+ return n;+}++function big(v) {+ return v == null ? 0n : BigInt(v);+}++/**+ * Credit a deposit. Idempotent on `ref` (the deposit transaction signature):+ * crediting the same signature twice returns `{ credited: false }` and leaves+ * the balance as it was.+ *+ * @param {{ payer: string, network: string, asset: string, amountAtomics: string|number|bigint, ref: string }} args+ * @returns {Promise<{ credited: boolean, balanceAtomics: bigint }>}+ */+export async function creditDeposit({ payer, network, asset, amountAtomics, ref }) {+ const amount = toAtomics(amountAtomics).toString();+ const [row] = await sql`+ with ins as (+ insert into x402_prepaid_entries (kind, payer, network, asset, amount_atomic, ref, state)+ values ('deposit', ${payer}::text, ${network}::text, ${asset}::text, ${amount}::bigint, ${ref}::text, 'credited')+ on conflict (kind, ref) do nothing+ returning payer, network, asset, amount_atomic+ ), acct as (+ insert into x402_prepaid_accounts (payer, network, asset, balance_atomic)+ select payer, network, asset, amount_atomic from ins+ on conflict (payer, network, asset) do update+ set balance_atomic = x402_prepaid_accounts.balance_atomic + excluded.balance_atomic,+ updated_at = now()+ returning balance_atomic+ )+ select (select count(*) from ins)::int as credited,+ (select balance_atomic::text from acct) as balance+ `;+ if (row.credited > 0) {+ return { credited: true, balanceAtomics: big(row.balance) };+ }+ return { credited: false, balanceAtomics: await getBalance({ payer, network, asset }) };+}++/**+ * Reserve a debit. Returns `{ ok: false, reason: 'insufficient' }` without+ * touching anything when the balance cannot cover it.+ *+ * @param {{ payer: string, network: string, asset: string, amountAtomics: string|number|bigint,+ * payee: string, route: string, ref: string }} args+ * @returns {Promise<{ ok: true, entryId: string, balanceAtomics: bigint } | { ok: false, reason: 'insufficient' }>}+ */+export async function reserveDebit({ payer, network, asset, amountAtomics, payee, route, ref }) {+ const amount = toAtomics(amountAtomics).toString();+ const [row] = await sql`+ with acct as (+ update x402_prepaid_accounts+ set balance_atomic = balance_atomic - ${amount}::bigint, updated_at = now()+ where payer = ${payer}::text and network = ${network}::text and asset = ${asset}::text+ and balance_atomic >= ${amount}::bigint+ returning balance_atomic+ ), ins as (+ insert into x402_prepaid_entries+ (kind, payer, network, asset, amount_atomic, ref, state, payee, route)+ select 'debit', ${payer}::text, ${network}::text, ${asset}::text, ${amount}::bigint,+ ${ref}::text, 'reserved', ${payee}::text, ${route}::text+ from acct+ returning id+ )+ select (select id::text from ins) as id, (select balance_atomic::text from acct) as balance+ `;+ if (!row?.id) return { ok: false, reason: 'insufficient' };+ return { ok: true, entryId: row.id, balanceAtomics: big(row.balance) };+}++/**+ * Commit a reserved debit after the handler succeeded. Returns false when the+ * reservation is no longer pending (already refunded by the stale sweep).+ * @param {string} entryId+ */+export async function commitDebit(entryId) {+ const rows = await sql`+ update x402_prepaid_entries+ set state = 'committed', resolved_at = now()+ where id = ${entryId}::bigint and kind = 'debit' and state = 'reserved'+ returning id+ `;+ return rows.length === 1;+}++/**+ * Refund a reserved debit: the entry flips to `refunded` and the amount returns+ * to the balance in one statement. A committed debit is never refunded here.+ * Returns the new balance, or null when the reservation was not pending.+ *+ * @param {string} entryId+ * @param {string} reason short machine tag: handler_error, client_cancelled, stale_reservation+ * @returns {Promise<bigint|null>}+ */+export async function refundDebit(entryId, reason) {+ const rows = await sql`+ with e as (+ update x402_prepaid_entries+ set state = 'refunded', resolved_at = now(), refund_reason = ${reason}::text+ where id = ${entryId}::bigint and kind = 'debit' and state = 'reserved'+ returning payer, network, asset, amount_atomic+ )+ update x402_prepaid_accounts a+ set balance_atomic = a.balance_atomic + e.amount_atomic, updated_at = now()+ from e+ where a.payer = e.payer and a.network = e.network and a.asset = e.asset+ returning a.balance_atomic::text as balance+ `;+ return rows.length === 1 ? big(rows[0].balance) : null;+}++/**+ * Refund every reservation older than the TTL (a process that died mid-request).+ * One statement, so a request that commits concurrently either wins or is refunded.+ * @param {{ olderThanSeconds?: number }} [opts]+ * @returns {Promise<number>} reservations refunded+ */+export async function sweepStaleReservations({ olderThanSeconds = PREPAID_RESERVATION_TTL_SECONDS } = {}) {+ const rows = await sql`+ with e as (+ update x402_prepaid_entries+ set state = 'refunded', resolved_at = now(), refund_reason = 'stale_reservation'+ where kind = 'debit' and state = 'reserved'+ and created_at < now() - make_interval(secs => ${Number(olderThanSeconds)}::double precision)+ returning payer, network, asset, amount_atomic+ ), per_acct as (+ select payer, network, asset, sum(amount_atomic) as amt from e group by 1, 2, 3+ ), upd as (+ update x402_prepaid_accounts a+ set balance_atomic = a.balance_atomic + p.amt, updated_at = now()+ from per_acct p+ where a.payer = p.payer and a.network = p.network and a.asset = p.asset+ returning 1+ )+ select count(*)::int as n from e+ `;+ return rows[0]?.n ?? 0;+}++/**+ * @param {{ payer: string, network: string, asset: string }} key+ * @returns {Promise<bigint>} 0n for a payer with no account+ */+export async function getBalance({ payer, network, asset }) {+ const rows = await sql`+ select balance_atomic::text as balance from x402_prepaid_accounts+ where payer = ${payer}::text and network = ${network}::text and asset = ${asset}::text+ `;+ return big(rows[0]?.balance);+}++/**+ * Reconciliation. Every figure is computed from the journal and compared with+ * the stored balances and batches, so a code path that edited one without the+ * other shows up as a non-zero delta.+ *+ * balanceDelta = deposits - (reserved + committed debits) - sum(balances)+ * batchDelta = committed debits with a batch - non-failed batch totals+ * settleDelta = confirmed batch totals - committed debits in confirmed batches+ *+ * `held` is what the platform still owes: payers' spendable balances plus+ * in-flight reservations plus committed debits not yet confirmed to the seller+ * (deposits - settled by construction, so balanceDelta covers it).+ *+ * @returns {Promise<{+ * depositsAtomics: bigint, debitsAtomics: bigint, refundedAtomics: bigint,+ * settledAtomics: bigint, balancesAtomics: bigint, heldAtomics: bigint,+ * balanceDelta: bigint, batchDelta: bigint, settleDelta: bigint,+ * delta: bigint, driftedAccounts: Array<{payer:string,network:string,asset:string,expected:bigint,actual:bigint}>,+ * staleReservations: number, stuckBatches: number, ok: boolean }>}+ */+export async function reconcile({ stuckBatchMinutes = 30 } = {}) {+ const [t] = await sql`+ select+ coalesce((select sum(amount_atomic) from x402_prepaid_entries where kind = 'deposit'), 0)::text as deposits,+ coalesce((select sum(amount_atomic) from x402_prepaid_entries where kind = 'debit' and state in ('reserved', 'committed')), 0)::text as debits,+ coalesce((select sum(amount_atomic) from x402_prepaid_entries where kind = 'debit' and state = 'refunded'), 0)::text as refunded,+ coalesce((select sum(balance_atomic) from x402_prepaid_accounts), 0)::text as balances,+ coalesce((select sum(amount_atomic) from x402_prepaid_entries where kind = 'debit' and state = 'committed' and batch_id is not null), 0)::text as batched,+ coalesce((select sum(total_atomic) from x402_prepaid_batches where status <> 'failed'), 0)::text as batch_totals,+ coalesce((select sum(total_atomic) from x402_prepaid_batches where status = 'confirmed'), 0)::text as settled,+ coalesce((select sum(e.amount_atomic) from x402_prepaid_entries e join x402_prepaid_batches b on b.id = e.batch_id+ where e.kind = 'debit' and e.state = 'committed' and b.status = 'confirmed'), 0)::text as settled_entries,+ (select count(*) from x402_prepaid_entries where state = 'reserved'+ and created_at < now() - make_interval(secs => ${PREPAID_RESERVATION_TTL_SECONDS}::double precision))::int as stale,+ (select count(*) from x402_prepaid_batches where status in ('pending', 'unconfirmed')+ and created_at < now() - make_interval(mins => ${Number(stuckBatchMinutes)}::double precision))::int as stuck+ `;+ const drifted = await sql`+ select a.payer, a.network, a.asset,+ (coalesce(d.dep, 0) - coalesce(x.deb, 0))::text as expected,+ a.balance_atomic::text as actual+ from x402_prepaid_accounts a+ left join (select payer, network, asset, sum(amount_atomic) dep from x402_prepaid_entries+ where kind = 'deposit' group by 1, 2, 3) d using (payer, network, asset)+ left join (select payer, network, asset, sum(amount_atomic) deb from x402_prepaid_entries+ where kind = 'debit' and state in ('reserved', 'committed') group by 1, 2, 3) x using (payer, network, asset)+ where a.balance_atomic <> coalesce(d.dep, 0) - coalesce(x.deb, 0)+ limit 20+ `;+ const deposits = big(t.deposits);+ const debits = big(t.debits);+ const balances = big(t.balances);+ const settled = big(t.settled);+ const held = balances + (debits - settled);+ const balanceDelta = deposits - debits - balances;+ const batchDelta = big(t.batched) - big(t.batch_totals);+ const settleDelta = settled - big(t.settled_entries);+ const abs = (n) => (n < 0n ? -n : n);+ const delta = abs(balanceDelta) + abs(batchDelta) + abs(settleDelta);+ return {+ depositsAtomics: deposits,+ debitsAtomics: debits,+ refundedAtomics: big(t.refunded),+ settledAtomics: settled,+ balancesAtomics: balances,+ heldAtomics: held,+ balanceDelta,+ batchDelta,+ settleDelta,+ delta,+ driftedAccounts: drifted.map((r) => ({+ payer: r.payer,+ network: r.network,+ asset: r.asset,+ expected: big(r.expected),+ actual: big(r.actual),+ })),+ staleReservations: t.stale,+ stuckBatches: t.stuck,+ ok: delta === 0n && drifted.length === 0 && t.stale === 0 && t.stuck === 0,+ };+}diff --git a/api/_lib/x402/prepaid-reconcile.js b/api/_lib/x402/prepaid-reconcile.jsnew file mode 100644index 000000000..8a1b4c270--- /dev/null+++ b/api/_lib/x402/prepaid-reconcile.js@@ -0,0 +1,67 @@+// api/_lib/x402/prepaid-reconcile.js+//+// Formats a prepaid ledger reconciliation (prepaid-ledger.js#reconcile) into the+// problem list, summary and printable lines shared by the nightly cron and+// scripts/x402-prepaid-reconcile.mjs.++import { reconcile } from './prepaid-ledger.js';+import { depositWalletUsdcBalance } from './prepaid-chain.js';++const usd = (a) => (Number(a) / 1e6).toFixed(6);++/**+ * @param {{ checkChain?: boolean }} [opts] also compare the deposit wallet's+ * real USDC balance with what the ledger says is held+ */+export async function reconcileReport({ checkChain = false } = {}) {+ const r = await reconcile();+ const problems = [];+ if (r.balanceDelta !== 0n) problems.push('balance_delta');+ if (r.batchDelta !== 0n) problems.push('batch_delta');+ if (r.settleDelta !== 0n) problems.push('settle_delta');+ if (r.driftedAccounts.length) problems.push('drifted_accounts');+ if (r.staleReservations) problems.push('stale_reservations');+ if (r.stuckBatches) problems.push('stuck_batches');++ let chainBalance = null;+ if (checkChain) {+ chainBalance = await depositWalletUsdcBalance();+ if (chainBalance !== null && chainBalance < r.heldAtomics) problems.push('wallet_short_of_held');+ }++ const lines = [+ `deposits ${usd(r.depositsAtomics)}`,+ `debits (kept) ${usd(r.debitsAtomics)}`,+ `refunded ${usd(r.refundedAtomics)}`,+ `settled ${usd(r.settledAtomics)}`,+ `payer balances ${usd(r.balancesAtomics)}`,+ `held (owed) ${usd(r.heldAtomics)}`,+ `balance delta ${usd(r.balanceDelta)} deposits - debits - balances`,+ `batch delta ${usd(r.batchDelta)} batched debits - batch totals`,+ `settle delta ${usd(r.settleDelta)} confirmed batches - their debits`,+ `drifted accounts ${r.driftedAccounts.length}`,+ `stale reservations ${r.staleReservations}`,+ `stuck batches ${r.stuckBatches}`,+ ...(checkChain+ ? [`wallet USDC ${chainBalance === null ? 'unknown' : usd(chainBalance)}`]+ : []),+ ...r.driftedAccounts.map(+ (d) => ` drift ${d.payer} expected ${usd(d.expected)} actual ${usd(d.actual)}`,+ ),+ `total delta ${usd(r.delta)}`,+ problems.length ? `PROBLEMS: ${problems.join(', ')}` : 'OK: ledger reconciles',+ ];+ return {+ ok: problems.length === 0,+ problems,+ lines,+ summary: {+ deposits_usd: usd(r.depositsAtomics),+ settled_usd: usd(r.settledAtomics),+ held_usd: usd(r.heldAtomics),+ delta_usd: usd(r.delta),+ wallet_usdc: chainBalance === null ? null : usd(chainBalance),+ },+ raw: r,+ };+}diff --git a/api/_lib/x402/prepaid-route.js b/api/_lib/x402/prepaid-route.jsnew file mode 100644index 000000000..3ba925866--- /dev/null+++ b/api/_lib/x402/prepaid-route.js@@ -0,0 +1,181 @@+// api/_lib/x402/prepaid-route.js+//+// The request path for `paidEndpoint({ mode: 'prepaid' })`. A buyer with a+// prepaid balance proves who they are with a SIGN-IN-WITH-X header (no X-PAYMENT)+// and the call is debited from their balance instead of settled on-chain.+//+// Charge only success. The debit is RESERVED before the handler runs and+// committed only if the handler returns normally and the client is still+// connected. A thrown handler (4xx or 5xx), a 5xx written by the handler itself,+// or a cancelled request is refunded in full, so a failed request is never billed.+//+// A route in this mode stays a normal x402 route: with no usable balance the+// buyer gets the usual 402 challenge and can still pay per call.++import { randomUUID } from 'node:crypto';+import { respondError } from '../http.js';+import { logPaymentEvent } from './audit-log.js';+import { clientIp } from '../rate-limit.js';+import { NETWORK_SOLANA_MAINNET, X402Error, send402 } from '../x402-spec.js';+import {+ commitDebit,+ isLedgerUnavailable,+ refundDebit,+ reserveDebit,+} from './prepaid-ledger.js';+import { USDC_MINT_SOLANA } from './prepaid-chain.js';++export const PREPAID_EXTENSION_KEY = 'prepaid';++/**+ * The accept entry a prepaid debit is priced from: Solana USDC.+ * @param {Array<Record<string, any>>} requirements+ */+export function prepaidRequirement(requirements) {+ return (+ requirements.find(+ (r) =>+ r.network === NETWORK_SOLANA_MAINNET &&+ r.asset === USDC_MINT_SOLANA &&+ r.payTo &&+ /^\d+$/.test(String(r.amount ?? '')),+ ) || null+ );+}++/**+ * The `prepaid` extension declared on the 402 body, so a buyer's client can+ * discover where to deposit and what a debit costs.+ * @param {{ requirement: Record<string, any>, origin: string }} args+ */+export function declarePrepaidExtension({ requirement, origin }) {+ return {+ [PREPAID_EXTENSION_KEY]: {+ info: {+ version: '1',+ network: requirement.network,+ asset: requirement.asset,+ amount: String(requirement.amount),+ depositUrl: `${origin}/api/x402-prepaid/deposit`,+ balanceUrl: `${origin}/api/x402-prepaid/balance`,+ auth: 'sign-in-with-x',+ },+ },+ };+}++/**+ * Serve one request from a prepaid balance.+ *+ * @returns {Promise<'served' | 'insufficient' | 'unavailable'>}+ * `served`: a response was written. `insufficient`: the balance cannot cover+ * it; the caller re-issues the 402. `unavailable`: the ledger could not be+ * reached; the caller falls back to the normal per-call challenge.+ */+export async function servePrepaid({+ req,+ res,+ payer,+ requirement,+ route,+ resourceUrl,+ handler,+ challenge,+ mimeType,+ startedAt,+}) {+ const key = { payer, network: requirement.network, asset: requirement.asset };+ let debit;+ try {+ debit = await reserveDebit({+ ...key,+ amountAtomics: requirement.amount,+ payee: requirement.payTo,+ route,+ ref: randomUUID(),+ });+ } catch (err) {+ console.error(+ `[x402-prepaid] reserve failed (${isLedgerUnavailable(err) ? 'table_missing' : 'db_unavailable'}):`,+ err?.message || err,+ );+ return 'unavailable';+ }+ if (!debit.ok) return 'insufficient';++ let aborted = false;+ const onClose = () => {+ if (!res.writableEnded) aborted = true;+ };+ req.on?.('close', onClose);++ const refund = async (reason) => {+ try {+ return await refundDebit(debit.entryId, reason);+ } catch (err) {+ // The stale sweep refunds an unresolved reservation, so a failed refund+ // here delays the money back rather than losing it.+ console.error('[x402-prepaid] refund failed, stale sweep will return it:', err?.message || err);+ return null;+ }+ };++ let result;+ try {+ result = await handler({+ req,+ res,+ requirement,+ payer,+ prepaid: { entryId: debit.entryId, balanceAtomics: debit.balanceAtomics },+ });+ } catch (err) {+ req.off?.('close', onClose);+ await refund('handler_error');+ if (err instanceof X402Error && err.status === 402) {+ await send402(res, { ...challenge, error: err.message });+ return 'served';+ }+ respondError(res, err.status || 500, err.code || 'internal_error', err);+ return 'served';+ }+ req.off?.('close', onClose);++ const handlerEnded = res.writableEnded;+ const failedStatus = handlerEnded && res.statusCode >= 400;+ if (aborted || res.destroyed || failedStatus) {+ await refund(aborted || res.destroyed ? 'client_cancelled' : 'handler_error');+ return 'served';+ }++ let committed = false;+ try {+ committed = await commitDebit(debit.entryId);+ } catch (err) {+ console.error('[x402-prepaid] commit failed:', err?.message || err);+ }+ if (!committed) {+ // The reservation was already refunded (stale sweep) or the commit could not+ // be recorded. The buyer is not billed and the call is delivered.+ res.setHeader?.('x-prepaid-charged', '0');+ } else if (!handlerEnded) {+ res.setHeader('x-prepaid-charged', String(requirement.amount));+ res.setHeader('x-prepaid-balance', debit.balanceAtomics.toString());+ }+ if (handlerEnded) return 'served';+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', `${mimeType}; charset=utf-8`);+ res.end(typeof result === 'string' ? result : JSON.stringify(result));+ logPaymentEvent({+ eventType: 'prepaid_debit',+ route,+ resourceUrl,+ payer,+ network: requirement.network,+ durationMs: Date.now() - startedAt,+ ipAddress: clientIp(req),+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,+ metadata: { amountAtomics: String(requirement.amount), committed },+ });+ return 'served';+}diff --git a/api/_lib/x402/prepaid-settle.js b/api/_lib/x402/prepaid-settle.jsnew file mode 100644index 000000000..75c7d40e6--- /dev/null+++ b/api/_lib/x402/prepaid-settle.js@@ -0,0 +1,175 @@+// api/_lib/x402/prepaid-settle.js+//+// The batcher: turns committed prepaid debits into ONE on-chain transaction per+// settlement window, paying every qualifying seller in it.+//+// 1. planSettlement - aggregate committed, unbatched debits per payee and+// keep the payees whose total clears the floor. A payee+// below the floor is not settled; its debits roll into a+// later window, so no transfer is smaller than what the+// network charges to make it.+// 2. claimBatch - per qualifying payee, one statement creates the batch+// row and stamps its debits with the batch id. A debit is+// therefore in at most one batch, however many crons race.+// 3. the sender - ONE transaction carrying a transfer per claimed batch+// plus a memo naming the batch ids (so a transaction that+// landed but was never recorded can be found on-chain).+// 4. finish - confirmed on success. A definitive failure (the chain+// rejected it, or it never left simulation) releases the+// debits for the next window. An ambiguous failure (it may+// have landed) parks the batches as `unconfirmed` and+// alerts, because re-sending could pay the seller twice.++import { randomUUID } from 'node:crypto';+import { sql } from '../db.js';++export const DEFAULT_MIN_SETTLE_ATOMICS = 1_000_000n; // 1 USDC+export const DEFAULT_MAX_PAYEES_PER_TX = 8;++/**+ * @param {Record<string, string|undefined>} [e]+ */+export function settleConfig(e = process.env) {+ const floor = e.X402_PREPAID_MIN_SETTLE_ATOMICS;+ const perTx = Number(e.X402_PREPAID_MAX_PAYEES_PER_TX);+ return {+ minSettleAtomics: floor && /^\d+$/.test(floor) ? BigInt(floor) : DEFAULT_MIN_SETTLE_ATOMICS,+ maxPayeesPerTx: Number.isInteger(perTx) && perTx > 0 && perTx <= 12 ? perTx : DEFAULT_MAX_PAYEES_PER_TX,+ live: e.X402_PREPAID_SETTLE_LIVE === '1',+ };+}++/**+ * What a window would settle, without claiming anything.+ * @param {{ minSettleAtomics?: bigint }} [opts]+ * @returns {Promise<{ settle: Array<{payee:string,network:string,asset:string,totalAtomics:bigint,count:number}>,+ * deferred: Array<{payee:string,network:string,asset:string,totalAtomics:bigint,count:number}> }>}+ */+export async function planSettlement({ minSettleAtomics = DEFAULT_MIN_SETTLE_ATOMICS } = {}) {+ const rows = await sql`+ select payee, network, asset, sum(amount_atomic)::text as total, count(*)::int as n+ from x402_prepaid_entries+ where kind = 'debit' and state = 'committed' and batch_id is null+ group by payee, network, asset+ order by sum(amount_atomic) desc+ `;+ const settle = [];+ const deferred = [];+ for (const r of rows) {+ const item = { payee: r.payee, network: r.network, asset: r.asset, totalAtomics: BigInt(r.total), count: r.n };+ (item.totalAtomics >= minSettleAtomics ? settle : deferred).push(item);+ }+ return { settle, deferred };+}++/**+ * Create the batch for one payee and claim its debits, atomically. Returns null+ * when nothing qualifies (another run claimed them, or the total is under the floor).+ *+ * @returns {Promise<{ id: string, payee: string, network: string, asset: string, totalAtomics: bigint, count: number } | null>}+ */+export async function claimBatch({ payee, network, asset, minSettleAtomics = DEFAULT_MIN_SETTLE_ATOMICS }) {+ const id = randomUUID();+ const rows = await sql`+ with picked as (+ update x402_prepaid_entries e+ set batch_id = ${id}::uuid+ where e.kind = 'debit' and e.state = 'committed' and e.batch_id is null+ and e.payee = ${payee}::text and e.network = ${network}::text and e.asset = ${asset}::text+ and (+ select coalesce(sum(amount_atomic), 0) from x402_prepaid_entries f+ where f.kind = 'debit' and f.state = 'committed' and f.batch_id is null+ and f.payee = ${payee}::text and f.network = ${network}::text and f.asset = ${asset}::text+ ) >= ${minSettleAtomics.toString()}::bigint+ returning e.amount_atomic+ ), tot as (+ select coalesce(sum(amount_atomic), 0) as total, count(*)::int as n from picked+ )+ insert into x402_prepaid_batches (id, payee, network, asset, total_atomic, debit_count, status)+ select ${id}::uuid, ${payee}::text, ${network}::text, ${asset}::text, total, n, 'pending'+ from tot where n > 0+ returning id, total_atomic::text as total, debit_count+ `;+ if (!rows.length) return null;+ return { id, payee, network, asset, totalAtomics: BigInt(rows[0].total), count: rows[0].debit_count };+}++async function markConfirmed(ids, signature) {+ await sql`+ update x402_prepaid_batches+ set status = 'confirmed', tx_signature = ${signature}::text, settled_at = now()+ where id = any(${ids}::uuid[]) and status = 'pending'+ `;+}++async function releaseBatches(ids, message) {+ await sql`+ with b as (+ update x402_prepaid_batches+ set status = 'failed', error = ${String(message).slice(0, 500)}::text+ where id = any(${ids}::uuid[]) and status = 'pending'+ returning id+ )+ update x402_prepaid_entries set batch_id = null where batch_id in (select id from b)+ `;+}++async function parkBatches(ids, message) {+ await sql`+ update x402_prepaid_batches+ set status = 'unconfirmed', error = ${String(message).slice(0, 500)}::text+ where id = any(${ids}::uuid[]) and status = 'pending'+ `;+}++/** Errors the chain layer raises when the transaction definitively did not land. */+export function isDefinitiveFailure(err) {+ return err?.code === 'TX_ERR' || err?.code === 'SIM_FAILED' || err?.code === 'PRE_SEND';+}++/**+ * Run one settlement window.+ *+ * `send` receives the claimed batches (<= maxPayeesPerTx) and must resolve to the+ * transaction signature once it is confirmed, or throw. Pass `dryRun: true` to+ * plan and return without claiming or sending anything.+ *+ * @param {{+ * send: (batches: Array<{id:string,payee:string,network:string,asset:string,totalAtomics:bigint}>) => Promise<string>,+ * minSettleAtomics?: bigint, maxPayeesPerTx?: number, dryRun?: boolean,+ * }} args+ */+export async function runSettlementWindow({+ send,+ minSettleAtomics = DEFAULT_MIN_SETTLE_ATOMICS,+ maxPayeesPerTx = DEFAULT_MAX_PAYEES_PER_TX,+ dryRun = false,+}) {+ const plan = await planSettlement({ minSettleAtomics });+ const out = { plan, transactions: [], unconfirmed: [], failed: [] };+ if (dryRun) return out;++ for (let i = 0; i < plan.settle.length; i += maxPayeesPerTx) {+ const claimed = [];+ for (const p of plan.settle.slice(i, i + maxPayeesPerTx)) {+ const batch = await claimBatch({ ...p, minSettleAtomics });+ if (batch) claimed.push(batch);+ }+ if (!claimed.length) continue;+ const ids = claimed.map((b) => b.id);+ try {+ const signature = await send(claimed);+ await markConfirmed(ids, signature);+ out.transactions.push({ signature, batches: claimed });+ } catch (err) {+ if (isDefinitiveFailure(err)) {+ await releaseBatches(ids, err.message);+ out.failed.push({ batches: claimed, error: err.message });+ } else {+ await parkBatches(ids, err?.message || String(err));+ out.unconfirmed.push({ batches: claimed, error: err?.message || String(err) });+ }+ }+ }+ return out;+}diff --git a/api/cron/x402-prepaid-reconcile.js b/api/cron/x402-prepaid-reconcile.jsnew file mode 100644index 000000000..fadac795a--- /dev/null+++ b/api/cron/x402-prepaid-reconcile.js@@ -0,0 +1,32 @@+// GET /api/cron/x402-prepaid-reconcile: nightly prepaid ledger integrity check.+//+// Deposits - debits - balances, batches vs the debits they claim, and settled vs+// confirmed batches must all be zero; no reservation may be stale and no batch+// stuck. Anything else alerts through the ops channel. Read-only.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { isLedgerUnavailable } from '../_lib/x402/prepaid-ledger.js';+import { reconcileReport } from '../_lib/x402/prepaid-reconcile.js';++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ let report;+ try {+ report = await reconcileReport({ checkChain: true });+ } catch (err) {+ if (isLedgerUnavailable(err)) {+ return json(res, 200, { ok: true, skipped: 'prepaid ledger migration not applied' });+ }+ throw err;+ }+ if (!report.ok) {+ await sendOpsAlert('x402 prepaid ledger out of balance', report.lines.join('\n'), {+ signature: `x402-prepaid-reconcile:${report.problems.join(',')}`,+ });+ }+ return json(res, 200, { ok: report.ok, problems: report.problems, ...report.summary });+});diff --git a/api/cron/x402-prepaid-settle.js b/api/cron/x402-prepaid-settle.jsnew file mode 100644index 000000000..93e889363--- /dev/null+++ b/api/cron/x402-prepaid-settle.js@@ -0,0 +1,66 @@+// GET /api/cron/x402-prepaid-settle: one prepaid settlement window.+//+// Refunds reservations left behind by dead requests, then pays every seller whose+// committed prepaid debits clear the floor in ONE on-chain transaction. Moving+// real USDC is gated on the owner: unless X402_PREPAID_SETTLE_LIVE=1 this only+// plans the window and reports what it WOULD settle.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { sweepStaleReservations } from '../_lib/x402/prepaid-ledger.js';+import { runSettlementWindow, settleConfig } from '../_lib/x402/prepaid-settle.js';+import { loadSettler, sendBatchTransfers } from '../_lib/x402/prepaid-chain.js';++const usd = (atomics) => (Number(atomics) / 1e6).toFixed(6);++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const cfg = settleConfig();+ const refundedStale = await sweepStaleReservations();++ const settlerReady = cfg.live ? Boolean(await loadSettler()) : false;+ const dryRun = !cfg.live || !settlerReady;+ const out = await runSettlementWindow({+ send: sendBatchTransfers,+ minSettleAtomics: cfg.minSettleAtomics,+ maxPayeesPerTx: cfg.maxPayeesPerTx,+ dryRun,+ });++ if (cfg.live && !settlerReady) {+ await sendOpsAlert(+ 'x402 prepaid settle blocked',+ 'X402_PREPAID_SETTLE_LIVE=1 but X402_PREPAID_SETTLER_SECRET_BASE58 is missing or unreadable; debits are accruing unsettled.',+ );+ }+ for (const group of out.unconfirmed) {+ await sendOpsAlert(+ 'x402 prepaid settle unconfirmed',+ `batches ${group.batches.map((b) => b.id).join(',')} may have landed (${group.error}). Look the batch ids up in the memo of recent settler transactions before any retry; re-sending could pay twice.`,+ );+ }+ for (const group of out.failed) {+ await sendOpsAlert(+ 'x402 prepaid settle failed',+ `transaction rejected (${group.error}); ${group.batches.length} payee batches released to the next window.`,+ );+ }++ return json(res, 200, {+ ok: true,+ mode: dryRun ? 'plan_only' : 'live',+ refunded_stale_reservations: refundedStale,+ floor_usd: usd(cfg.minSettleAtomics),+ would_settle: out.plan.settle.map((p) => ({ payee: p.payee, usd: usd(p.totalAtomics), debits: p.count })),+ deferred_below_floor: out.plan.deferred.map((p) => ({ payee: p.payee, usd: usd(p.totalAtomics), debits: p.count })),+ transactions: out.transactions.map((t) => ({+ signature: t.signature,+ payees: t.batches.map((b) => ({ payee: b.payee, usd: usd(b.totalAtomics) })),+ })),+ unconfirmed: out.unconfirmed.length,+ failed: out.failed.length,+ });+});diff --git a/api/mcp-plans.js b/api/mcp-plans.jsnew file mode 100644index 000000000..e58d73b5e--- /dev/null+++ b/api/mcp-plans.js@@ -0,0 +1,70 @@+/**+ * GET /api/mcp-plans : the plan catalog, per-tool credit costs, and (signed in)+ * the caller's balances, trials and call history.+ * POST /api/mcp-plans { plan, idempotency_key } : buy a plan with prepaid USD+ * credits (top up at /credits). Idempotent on the key.+ *+ * The meter that spends these balances is api/_lib/mcp-credits.js, wired into+ * the /api/mcp dispatcher.+ */++import { getRequestUser, hasScope } from './_lib/auth.js';+import { cors, json, wrap, error, readJson } from './_lib/http.js';+import { requireCsrf } from './_lib/csrf.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { listPlans, purchasePlan, accountSummary, toolCreditTable } from './_lib/mcp-plans.js';+import { trialCallsPerTool, CREDIT_USD } from './_lib/mcp-credits.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (req.method !== 'GET' && req.method !== 'POST') {+ return error(res, 405, 'method_not_allowed', 'method not allowed');+ }++ const user = await getRequestUser(req, res);++ if (req.method === 'GET') {+ const catalog = {+ creditUsd: CREDIT_USD,+ trialCallsPerTool: trialCallsPerTool(),+ plans: await listPlans(),+ tools: toolCreditTable(),+ };+ if (!user) return json(res, 200, { data: catalog }, { 'cache-control': 'no-store' });+ const account = await accountSummary(user.id);+ return json(res, 200, { data: { ...catalog, account } }, { 'cache-control': 'no-store' });+ }++ if (!user) return error(res, 401, 'unauthorized', 'sign in to buy a plan');+ if (user.source === 'bearer' && !hasScope(user.scope, 'wallet:write')) {+ return error(res, 403, 'insufficient_scope', 'this token needs wallet:write');+ }+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests, try again shortly');+ if (!(await requireCsrf(req, res, user.id))) return;++ const body = await readJson(req);+ const slug = typeof body?.plan === 'string' ? body.plan.trim() : '';+ const key = typeof body?.idempotency_key === 'string' ? body.idempotency_key.trim() : '';+ if (!slug) return error(res, 400, 'validation_error', 'plan is required');+ if (key.length < 8 || key.length > 128) {+ return error(res, 400, 'validation_error', 'idempotency_key must be 8 to 128 characters');+ }++ try {+ const out = await purchasePlan({ userId: user.id, slug, idempotencyKey: key });+ return json(res, out.replay ? 200 : 201, { data: { ...out, account: await accountSummary(user.id) } });+ } catch (err) {+ if (err.code === 'insufficient_credits') {+ return json(res, 402, {+ error: 'insufficient_credits',+ error_description: 'not enough prepaid balance, top up at /credits',+ available_usd: err.available_usd,+ required_usd: err.required_usd,+ topup_url: '/credits',+ });+ }+ if (err.status && err.status < 500) return error(res, err.status, err.code || 'error', err.message);+ throw err;+ }+});diff --git a/api/x402-prepaid/balance.js b/api/x402-prepaid/balance.jsnew file mode 100644index 000000000..a1033b40e--- /dev/null+++ b/api/x402-prepaid/balance.js@@ -0,0 +1,37 @@+// GET /api/x402-prepaid/balance?payer=<solana address>+//+// A payer's prepaid x402 balance (USDC atomics). Balances are not secret: the+// ledger is keyed by a public wallet address and the deposit that funded it is on-chain.++import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { rateLimited } from '../_lib/http.js';+import { getBalance, isLedgerUnavailable } from '../_lib/x402/prepaid-ledger.js';+import { PREPAID_ASSET, PREPAID_NETWORK } from '../_lib/x402/prepaid-chain.js';++const SOL_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.x402ProbeIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const payer = String(req.query?.payer || new URL(req.url, 'http://x').searchParams.get('payer') || '');+ if (!SOL_ADDRESS.test(payer)) return error(res, 400, 'bad_request', 'payer must be a Solana address');+ try {+ const balance = await getBalance({ payer, network: PREPAID_NETWORK, asset: PREPAID_ASSET });+ return json(res, 200, {+ payer,+ network: PREPAID_NETWORK,+ asset: PREPAID_ASSET,+ balance_atomics: balance.toString(),+ balance_usd: Number(balance) / 1e6,+ });+ } catch (err) {+ if (isLedgerUnavailable(err)) {+ return error(res, 503, 'prepaid_unavailable', 'prepaid balances are not enabled on this deployment yet');+ }+ throw err;+ }+});diff --git a/api/x402-prepaid/deposit.js b/api/x402-prepaid/deposit.jsnew file mode 100644index 000000000..2671c99a7--- /dev/null+++ b/api/x402-prepaid/deposit.js@@ -0,0 +1,69 @@+// POST /api/x402-prepaid/deposit { tx_signature }+//+// Credit a prepaid x402 balance from ONE on-chain USDC transfer into the+// prepaid deposit wallet. The balance belongs to the wallet that sent and signed+// the transfer and is spent by signing in with that same wallet (SIGN-IN-WITH-X).+//+// The signature alone proves nothing, so the server reads the finalized+// transaction itself. Crediting is idempotent on the signature: retrying a+// deposit (or two clients submitting the same one) credits it once.++import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { creditDeposit, isLedgerUnavailable } from '../_lib/x402/prepaid-ledger.js';+import {+ PREPAID_ASSET,+ PREPAID_NETWORK,+ prepaidDepositWallet,+ verifyPrepaidDeposit,+} from '../_lib/x402/prepaid-chain.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ if (req.method === 'GET') {+ const wallet = await prepaidDepositWallet();+ if (!wallet) return error(res, 503, 'deposit_unavailable', 'prepaid deposits are not configured on this deployment yet');+ return json(res, 200, { deposit_wallet: wallet, network: PREPAID_NETWORK, asset: PREPAID_ASSET, decimals: 6 });+ }++ const body = await readJson(req).catch(() => null);+ const signature = typeof body?.tx_signature === 'string' ? body.tx_signature.trim() : '';+ if (!signature) return error(res, 400, 'bad_request', 'tx_signature is required');++ try {+ const verified = await verifyPrepaidDeposit(signature);+ if (verified.pending) {+ return json(res, 202, {+ ok: false,+ pending: true,+ status: 'awaiting_finalization',+ tx_signature: signature,+ message: 'Confirmed on-chain, still finalizing. Retry in a few seconds; the credit lands once.',+ });+ }+ const credit = await creditDeposit({+ payer: verified.payer,+ network: PREPAID_NETWORK,+ asset: PREPAID_ASSET,+ amountAtomics: verified.amountAtomics,+ ref: signature,+ });+ return json(res, 200, {+ ok: true,+ credited: credit.credited,+ payer: verified.payer,+ deposited_atomics: verified.amountAtomics.toString(),+ balance_atomics: credit.balanceAtomics.toString(),+ tx_signature: signature,+ });+ } catch (err) {+ if (isLedgerUnavailable(err)) {+ return error(res, 503, 'prepaid_unavailable', 'prepaid balances are not enabled on this deployment yet');+ }+ return respondError(res, err.status || 500, err.code || 'deposit_failed', err);+ }+});diff --git a/pages/mcp-plans.html b/pages/mcp-plans.htmlnew file mode 100644index 000000000..d2d463c2d--- /dev/null+++ b/pages/mcp-plans.html@@ -0,0 +1,84 @@+<!doctype html>+<html lang="en">+ <head>+ <script>+ (function () {+ document.documentElement.classList.add('js');+ try {+ var m = localStorage.getItem('twx_theme');+ var l = m === 'auto' ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>MCP Plans · three.ws</title>+ <meta name="description" content="Prepay for paid three.ws MCP tools with credit bundles or time passes, try each tool free, and see every credit spent." />+ <meta property="og:title" content="MCP Plans · three.ws" />+ <meta property="og:url" content="https://three.ws/mcp-plans" />+ <link rel="canonical" href="https://three.ws/mcp-plans" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ .mp-wrap { max-width: 1040px; width: 100%; min-width: 0; margin: 0 auto; padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem; }+ .mp-wrap h1 { font-size: clamp(1.7rem, 4vw, 2.5rem); margin: 0 0 0.35rem; letter-spacing: -0.02em; }+ .mp-lede { margin: 0 0 1.75rem; color: var(--ink-dim, #9aa3b2); max-width: 60ch; line-height: 1.5; }+ .mp-card { background: var(--surface-1, #14161c); border: 1px solid var(--stroke, #262a33); border-radius: 16px; padding: 1.25rem 1.35rem; min-width: 0; }+ .mp-card h2 { font-size: 0.82rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-dim, #9aa3b2); margin: 0 0 0.9rem; font-weight: 600; }+ .mp-section { margin-top: 1.1rem; }+ .mp-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 1rem; }+ .mp-balance { font-size: clamp(2.4rem, 7vw, 3.4rem); font-weight: 700; letter-spacing: -0.03em; line-height: 1; font-variant-numeric: tabular-nums; }+ .mp-sub { margin-top: 0.6rem; color: var(--ink-dim, #9aa3b2); font-size: 0.9rem; overflow-wrap: anywhere; }+ .mp-plan h3 { margin: 0 0 0.25rem; font-size: 1.1rem; overflow-wrap: anywhere; }+ .mp-price { font-size: 1.6rem; font-weight: 700; font-variant-numeric: tabular-nums; margin: 0.4rem 0; }+ .mp-plan p { margin: 0 0 1rem; color: var(--ink-dim, #9aa3b2); font-size: 0.9rem; line-height: 1.45; }+ .mp-btn { font: inherit; font-weight: 600; padding: 0.6rem 1rem; border-radius: 10px; border: 1px solid var(--stroke, #262a33); background: var(--accent, #6d5efc); color: #fff; cursor: pointer; width: 100%; transition: filter 0.15s, transform 0.05s; }+ .mp-btn:hover:not(:disabled) { filter: brightness(1.12); }+ .mp-btn:active:not(:disabled) { transform: translateY(1px); }+ .mp-btn:focus-visible, .mp-link:focus-visible { outline: 2px solid var(--accent, #6d5efc); outline-offset: 2px; }+ .mp-btn:disabled { opacity: 0.55; cursor: not-allowed; }+ .mp-link { color: var(--accent, #6d5efc); }+ .mp-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }+ .mp-table th, .mp-table td { text-align: left; padding: 0.5rem 0.6rem 0.5rem 0; border-bottom: 1px solid var(--stroke, #262a33); overflow-wrap: anywhere; }+ .mp-table th { color: var(--ink-dim, #9aa3b2); font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.06em; }+ .mp-table td.num, .mp-table th.num { text-align: right; font-variant-numeric: tabular-nums; }+ .mp-scroll { overflow-x: auto; }+ .mp-empty, .mp-error { padding: 1rem; border-radius: 12px; border: 1px dashed var(--stroke, #262a33); color: var(--ink-dim, #9aa3b2); }+ .mp-error { border-style: solid; border-color: #d9534f; color: inherit; }+ .mp-skel { height: 110px; border-radius: 12px; background: linear-gradient(90deg, var(--surface-1, #14161c), var(--stroke, #262a33), var(--surface-1, #14161c)); background-size: 200% 100%; animation: mp-shimmer 1.4s linear infinite; }+ @keyframes mp-shimmer { to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .mp-skel { animation: none; } }+ </style>+ </head>+ <body>+ <a href="#main-content" class="h-skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="mp-wrap">+ <h1>MCP plans</h1>+ <p class="mp-lede">+ Prepay for paid three.ws MCP tools. A credit is worth $0.001 of a tool's per-call price. Time passes cover every+ paid tool without counting calls. Every account also gets free trial calls on each tool. When a plan runs out, calls fall back to+ pay-per-call over x402.+ </p>+ <div id="mp-root" aria-live="polite">+ <div class="mp-skel"></div>+ </div>+ </main>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/src/mcp-plans.js"></script>+ </body>+</html>diff --git a/src/mcp-plans.js b/src/mcp-plans.jsnew file mode 100644index 000000000..3d9736e04--- /dev/null+++ b/src/mcp-plans.js@@ -0,0 +1,129 @@+// /mcp-plans: credit bundles and time passes for paid MCP tools.+// Data and purchase come from /api/mcp-plans; plans are paid from the prepaid+// USD balance shown on /credits.++const root = document.getElementById('mp-root');++const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const usd = (n) => `$${Number(n).toFixed(2)}`;+const when = (iso) => new Date(iso).toLocaleString();++function duration(seconds) {+ const days = seconds / 86400;+ return days >= 1 ? `${days} day${days === 1 ? '' : 's'}` : `${seconds / 3600} hours`;+}++let csrf = null;+async function csrfToken() {+ if (csrf && csrf.expiresAt > Date.now() + 5000) return csrf.token;+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!r.ok) throw new Error('Could not get a security token. Sign in again.');+ const j = await r.json();+ csrf = { token: j.data.token, expiresAt: Date.now() + (j.data.expires_in - 30) * 1000 };+ return csrf.token;+}++async function load() {+ const r = await fetch('/api/mcp-plans', { credentials: 'include' });+ if (!r.ok) throw new Error(`Could not load plans (${r.status}).`);+ return (await r.json()).data;+}++function planCard(p, signedIn) {+ const what = p.kind === 'credits' ? `${p.credits.toLocaleString()} credits` : `${duration(p.durationSeconds)} unlimited`;+ return `<div class="mp-card mp-plan">+ <h3>${esc(p.name)}</h3>+ <div class="mp-price">${usd(p.priceUsd)}</div>+ <p>${esc(what)}. ${esc(p.description)}</p>+ <button class="mp-btn" data-plan="${esc(p.slug)}" ${signedIn ? '' : 'disabled'}>${signedIn ? 'Buy with balance' : 'Sign in to buy'}</button>+ </div>`;+}++function render(data, notice) {+ const acct = data.account;+ const signedIn = Boolean(acct);+ const balance = signedIn+ ? `<section class="mp-card mp-section"><h2>Your balance</h2>+ <div class="mp-balance">${acct.creditsRemaining.toLocaleString()} <span style="font-size:1rem;font-weight:500">credits</span></div>+ <div class="mp-sub">${+ acct.timePasses.length+ ? acct.timePasses.map((t) => `${esc(t.plan)} active until ${esc(when(t.expiresAt))}`).join('. ')+ : 'No active time pass.'+ }</div>+ <div class="mp-sub">Prepaid balance ${usd(acct.usdBalance)}. <a class="mp-link" href="/credits">Top up</a></div>+ </section>`+ : `<section class="mp-card mp-section"><div class="mp-empty"><a class="mp-link" href="/login?next=/mcp-plans">Sign in</a> to buy a plan, see your balance and spend history.</div></section>`;++ const trials = signedIn+ ? `<section class="mp-card mp-section"><h2>Free trial calls (${data.trialCallsPerTool} per tool)</h2>${+ acct.trials.used.length+ ? `<div class="mp-scroll"><table class="mp-table"><thead><tr><th>Tool</th><th class="num">Used</th><th class="num">Left</th></tr></thead><tbody>${acct.trials.used+ .map((t) => `<tr><td>${esc(t.tool)}</td><td class="num">${t.used}</td><td class="num">${t.remaining}</td></tr>`)+ .join('')}</tbody></table></div>`+ : `<div class="mp-empty">No trial calls used yet. Your first ${data.trialCallsPerTool} calls to each paid tool are free.</div>`+ }</section>`+ : '';++ const tools = `<section class="mp-card mp-section"><h2>Credits per call</h2><div class="mp-scroll"><table class="mp-table"><thead><tr><th>Tool</th><th class="num">Credits</th><th class="num">Pay-per-call</th></tr></thead><tbody>${data.tools+ .map((t) => `<tr><td>${esc(t.tool)}</td><td class="num">${t.credits}</td><td class="num">$${t.amountUsdc}</td></tr>`)+ .join('')}</tbody></table></div></section>`;++ const history = signedIn+ ? `<section class="mp-card mp-section"><h2>History</h2>${+ acct.history.length+ ? `<div class="mp-scroll"><table class="mp-table"><thead><tr><th>When</th><th>Tool</th><th>Event</th><th class="num">Credits</th></tr></thead><tbody>${acct.history+ .map((h) => `<tr><td>${esc(when(h.at))}</td><td>${esc(h.tool)}</td><td>${esc(h.kind.replace('_', ' '))}</td><td class="num">${h.kind === 'refund' ? '+' : h.kind === 'debit' ? '-' : ''}${h.credits}</td></tr>`)+ .join('')}</tbody></table></div>`+ : '<div class="mp-empty">No metered calls yet. Buy a plan above, then call a paid tool through <code>/api/mcp</code> with your bearer token.</div>'+ }</section>`+ : '';++ root.innerHTML = `${notice ? `<div class="${notice.error ? 'mp-error' : 'mp-empty'}" role="status">${notice.html}</div>` : ''}+ ${balance}+ <div class="mp-grid mp-section">${data.plans.map((p) => planCard(p, signedIn)).join('')}</div>+ ${trials}${tools}${history}`;+}++async function buy(slug, button) {+ button.disabled = true;+ button.textContent = 'Buying...';+ try {+ const key = crypto.randomUUID();+ const r = await fetch('/api/mcp-plans', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': await csrfToken() },+ body: JSON.stringify({ plan: slug, idempotency_key: key }),+ });+ const body = await r.json().catch(() => ({}));+ if (r.status === 402) {+ render(await load(), {+ error: true,+ html: `Your prepaid balance is ${usd(body.available_usd ?? 0)}, this plan costs ${usd(body.required_usd ?? 0)}. <a class="mp-link" href="/credits">Top up</a> and try again.`,+ });+ return;+ }+ if (!r.ok) throw new Error(body.error_description || `Purchase failed (${r.status}).`);+ render(await load(), { html: 'Plan purchased. Your credits are ready to use.' });+ } catch (err) {+ try {+ render(await load(), { error: true, html: esc(err.message) });+ } catch {+ root.innerHTML = `<div class="mp-error" role="alert">${esc(err.message)}</div>`;+ }+ }+}++root.addEventListener('click', (e) => {+ const b = e.target.closest('button[data-plan]');+ if (b) buy(b.dataset.plan, b);+});++load().then(+ (data) => render(data),+ (err) => {+ root.innerHTML = `<div class="mp-error" role="alert">${esc(err.message)} <button class="mp-btn" style="width:auto" id="mp-retry">Retry</button></div>`;+ document.getElementById('mp-retry').addEventListener('click', () => location.reload());+ },+);diff --git a/tests/x402-prepaid-ledger.test.js b/tests/x402-prepaid-ledger.test.jsnew file mode 100644index 000000000..c4bf41181--- /dev/null+++ b/tests/x402-prepaid-ledger.test.js@@ -0,0 +1,287 @@+// The prepaid x402 ledger against a REAL Postgres engine (PGlite) built from the+// shipped migration. Mocked SQL could not see a lost update or a negative+// balance; these run the actual statements.++import { readFileSync } from 'node:fs';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { PGlite } from '@electric-sql/pglite';++const dbState = { pg: null };++vi.mock('../api/_lib/db.js', () => {+ const sql = async (strings, ...values) => {+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');+ const out = await dbState.pg.query(text, values);+ return out.rows;+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++const ledger = await import('../api/_lib/x402/prepaid-ledger.js');+const settle = await import('../api/_lib/x402/prepaid-settle.js');+const { reconcileReport } = await import('../api/_lib/x402/prepaid-reconcile.js');+const { servePrepaid } = await import('../api/_lib/x402/prepaid-route.js');+const { PREPAID_ASSET, PREPAID_NETWORK } = await import('../api/_lib/x402/prepaid-chain.js');++const MIGRATION = new URL(+ '../api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql',+ import.meta.url,+);++const PAYER = 'THREEsynthPayer1111111111111111111111111111';+const PAYEE_A = 'THREEsynthPayeeA111111111111111111111111111';+const PAYEE_B = 'THREEsynthPayeeB111111111111111111111111111';+const key = { payer: PAYER, network: PREPAID_NETWORK, asset: PREPAID_ASSET };++async function fund(amount, ref = `dep-${Math.random()}`) {+ return ledger.creditDeposit({ ...key, amountAtomics: amount, ref });+}+async function debit(amount, payee = PAYEE_A, ref = `req-${Math.random()}`) {+ return ledger.reserveDebit({ ...key, amountAtomics: amount, payee, route: '/api/x402/test', ref });+}++beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(readFileSync(MIGRATION, 'utf8'));+});++describe('deposits', () => {+ it('credits once per transaction signature', async () => {+ const first = await ledger.creditDeposit({ ...key, amountAtomics: 5_000_000n, ref: 'sig-1' });+ const again = await ledger.creditDeposit({ ...key, amountAtomics: 5_000_000n, ref: 'sig-1' });+ expect(first).toEqual({ credited: true, balanceAtomics: 5_000_000n });+ expect(again).toEqual({ credited: false, balanceAtomics: 5_000_000n });+ });++ it('rejects a zero or non-integer amount', async () => {+ await expect(fund(0n)).rejects.toMatchObject({ code: 'bad_amount' });+ await expect(fund('1.5')).rejects.toMatchObject({ code: 'bad_amount' });+ });+});++describe('debits', () => {+ it('never takes the balance below zero', async () => {+ await fund(1000n);+ expect((await debit(1001n)).ok).toBe(false);+ expect((await debit(1000n)).ok).toBe(true);+ expect((await debit(1n)).ok).toBe(false);+ expect(await ledger.getBalance(key)).toBe(0n);+ });++ it('refuses a payer with no account', async () => {+ expect(await debit(1n)).toEqual({ ok: false, reason: 'insufficient' });+ });++ it('100 parallel debits against a small balance leave an exact balance', async () => {+ await fund(500n);+ const results = await Promise.all(Array.from({ length: 100 }, () => debit(7n)));+ const won = results.filter((r) => r.ok).length;+ const balance = await ledger.getBalance(key);+ console.log(`parallel debits: balance 500, 100 x 7 -> ${won} succeeded, balance ${balance}`);+ expect(won).toBe(71);+ expect(balance).toBe(500n - 71n * 7n);+ expect(balance).toBeGreaterThanOrEqual(0n);+ const report = await reconcileReport();+ expect(report.ok).toBe(true);+ });+});++describe('charge only success', () => {+ it('refunds a reserved debit and restores the balance', async () => {+ await fund(1000n);+ const d = await debit(400n);+ expect(await ledger.getBalance(key)).toBe(600n);+ expect(await ledger.refundDebit(d.entryId, 'handler_error')).toBe(1000n);+ expect(await ledger.refundDebit(d.entryId, 'handler_error')).toBeNull();+ expect(await ledger.getBalance(key)).toBe(1000n);+ });++ it('does not refund a committed debit, and a refunded one cannot commit', async () => {+ await fund(1000n);+ const a = await debit(100n);+ expect(await ledger.commitDebit(a.entryId)).toBe(true);+ expect(await ledger.refundDebit(a.entryId, 'late')).toBeNull();+ const b = await debit(100n);+ await ledger.refundDebit(b.entryId, 'handler_error');+ expect(await ledger.commitDebit(b.entryId)).toBe(false);+ expect(await ledger.getBalance(key)).toBe(900n);+ });++ it('sweeps reservations a dead request left behind', async () => {+ await fund(1000n);+ await debit(300n);+ await dbState.pg.query("update x402_prepaid_entries set created_at = now() - interval '1 hour'");+ expect(await ledger.sweepStaleReservations()).toBe(1);+ expect(await ledger.getBalance(key)).toBe(1000n);+ expect(await ledger.sweepStaleReservations()).toBe(0);+ });+});++describe('servePrepaid', () => {+ const requirement = { network: PREPAID_NETWORK, asset: PREPAID_ASSET, amount: '1000', payTo: PAYEE_A };++ function makeRes() {+ const res = {+ statusCode: 200,+ headers: {},+ body: null,+ writableEnded: false,+ destroyed: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+ return res;+ }+ const makeReq = () => ({ headers: {}, on() {}, off() {} });+ async function serve(handler, res = makeRes(), req = makeReq()) {+ const outcome = await servePrepaid({+ req, res, payer: PAYER, requirement, route: '/api/x402/test',+ resourceUrl: 'https://three.ws/api/x402/test', handler, challenge: { accepts: [] },+ mimeType: 'application/json', startedAt: Date.now(),+ });+ return { outcome, res };+ }++ it('debits and commits a successful call', async () => {+ await fund(5000n);+ const { outcome, res } = await serve(async () => ({ ok: true }));+ expect(outcome).toBe('served');+ expect(res.body).toBe('{"ok":true}');+ expect(res.headers['x-prepaid-charged']).toBe('1000');+ expect(await ledger.getBalance(key)).toBe(4000n);+ });++ it('does not charge a handler that throws a 5xx', async () => {+ await fund(5000n);+ const { res } = await serve(async () => {+ throw Object.assign(new Error('upstream down'), { status: 502, code: 'upstream_error' });+ });+ expect(res.statusCode).toBe(502);+ expect(await ledger.getBalance(key)).toBe(5000n);+ });++ it('does not charge a handler that throws a 4xx', async () => {+ await fund(5000n);+ await serve(async () => {+ throw Object.assign(new Error('bad input'), { status: 400, code: 'bad_request' });+ });+ expect(await ledger.getBalance(key)).toBe(5000n);+ });++ it('does not charge a cancelled request', async () => {+ await fund(5000n);+ const res = makeRes();+ const { res: out } = await serve(async () => {+ res.destroyed = true;+ return { ok: true };+ }, res);+ expect(out.body).toBeNull();+ expect(await ledger.getBalance(key)).toBe(5000n);+ });++ it('reports insufficient without touching the balance', async () => {+ await fund(500n);+ const { outcome } = await serve(async () => ({ ok: true }));+ expect(outcome).toBe('insufficient');+ expect(await ledger.getBalance(key)).toBe(500n);+ });+});++describe('batch settlement', () => {+ async function spend(count, amount, payee) {+ for (let i = 0; i < count; i++) {+ const d = await debit(amount, payee);+ await ledger.commitDebit(d.entryId);+ }+ }++ it('settles per payee in one transaction and skips payees under the floor', async () => {+ await fund(10_000_000n);+ await spend(1500, 1000n, PAYEE_A); // 1.5 USDC, over the 1 USDC floor+ await spend(100, 1000n, PAYEE_B); // 0.1 USDC, under it+ const sent = [];+ const out = await settle.runSettlementWindow({+ send: async (batches) => { sent.push(batches); return 'sigOK'; },+ });+ expect(sent).toHaveLength(1);+ expect(sent[0]).toHaveLength(1);+ expect(sent[0][0]).toMatchObject({ payee: PAYEE_A, totalAtomics: 1_500_000n, count: 1500 });+ expect(out.plan.deferred.map((d) => d.payee)).toEqual([PAYEE_B]);++ const again = await settle.runSettlementWindow({ send: async () => { throw new Error('must not send'); } });+ expect(again.transactions).toHaveLength(0);++ const report = await reconcileReport();+ expect(report.raw.settledAtomics).toBe(1_500_000n);+ expect(report.ok).toBe(true);+ });++ it('two racing windows pay a debit once', async () => {+ await fund(10_000_000n);+ await spend(2000, 1000n, PAYEE_A);+ let total = 0n;+ const send = async (batches) => { for (const b of batches) total += b.totalAtomics; return 'sigRace'; };+ await Promise.all([settle.runSettlementWindow({ send }), settle.runSettlementWindow({ send })]);+ expect(total).toBe(2_000_000n);+ });++ it('releases the debits when the chain definitively rejects, and retries them', async () => {+ await fund(10_000_000n);+ await spend(1200, 1000n, PAYEE_A);+ const failed = await settle.runSettlementWindow({+ send: async () => { throw Object.assign(new Error('tx failed on-chain'), { code: 'TX_ERR' }); },+ });+ expect(failed.failed).toHaveLength(1);+ const retried = await settle.runSettlementWindow({ send: async () => 'sigRetry' });+ expect(retried.transactions[0].batches[0].totalAtomics).toBe(1_200_000n);+ expect((await reconcileReport()).ok).toBe(true);+ });++ it('parks an ambiguous failure instead of risking a double payment', async () => {+ await fund(10_000_000n);+ await spend(1200, 1000n, PAYEE_A);+ const parked = await settle.runSettlementWindow({ send: async () => { throw new Error('confirmation timeout'); } });+ expect(parked.unconfirmed).toHaveLength(1);+ const next = await settle.runSettlementWindow({ send: async () => { throw new Error('must not send'); } });+ expect(next.plan.settle).toHaveLength(0);+ await dbState.pg.query("update x402_prepaid_batches set created_at = now() - interval '2 hours'");+ const report = await reconcileReport();+ expect(report.problems).toEqual(['stuck_batches']);+ });++ it('splits a window across transactions at the payee cap', async () => {+ await fund(50_000_000n);+ for (let i = 0; i < 5; i++) {+ await dbState.pg.query(+ `insert into x402_prepaid_entries (kind, payer, network, asset, amount_atomic, ref, state, payee, route)+ values ('debit', $1, $2, $3, 2000000, $4, 'committed', $5, '/r')`,+ [PAYER, PREPAID_NETWORK, PREPAID_ASSET, `seed-${i}`, `THREEsynthPayee${i}`],+ );+ }+ await dbState.pg.query("update x402_prepaid_accounts set balance_atomic = balance_atomic");+ const sizes = [];+ await settle.runSettlementWindow({+ maxPayeesPerTx: 2,+ send: async (batches) => { sizes.push(batches.length); return `sig${sizes.length}`; },+ });+ expect(sizes).toEqual([2, 2, 1]);+ });+});++describe('reconciliation', () => {+ it('reads zero on a clean ledger and flags a tampered balance', async () => {+ await fund(9_000_000n);+ const a = await debit(1_000_000n);+ await ledger.commitDebit(a.entryId);+ const b = await debit(500_000n);+ await ledger.refundDebit(b.entryId, 'handler_error');+ const clean = await reconcileReport();+ expect(clean.ok).toBe(true);+ expect(clean.raw.delta).toBe(0n);++ await dbState.pg.query('update x402_prepaid_accounts set balance_atomic = balance_atomic + 5');+ const dirty = await reconcileReport();+ expect(dirty.ok).toBe(false);+ expect(dirty.problems).toEqual(['balance_delta', 'drifted_accounts']);+ });+});