Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402): payment policy engine, spend simulator, and runway lab

nirholasdfb4a067647c
diff --git a/api/_lib/pay/payment-session.js b/api/_lib/pay/payment-session.js
index 78465ab9a..e3587168f 100644
--- a/api/_lib/pay/payment-session.js
+++ b/api/_lib/pay/payment-session.js
@@ -25,13 +25,16 @@ import {
atomicsToUsd,
normalizeHost,
} from './spend-governor.js';
+import { SESSION_LIMITS } from './policy.js';
-const MAX_LABEL_LEN = 120;
-const MAX_ALLOWED_HOSTS = 50;
-const MIN_BUDGET_USD = 0.001; // $0.001 minimum
-const MAX_BUDGET_USD = 1000; // $1000 maximum per session
-const MIN_TTL_SECONDS = 60;
-const MAX_TTL_SECONDS = 90 * 24 * 3600; // 90 days
+const {
+ MAX_LABEL_LEN,
+ MAX_ALLOWED_HOSTS,
+ MIN_BUDGET_USD,
+ MAX_BUDGET_USD,
+ MIN_TTL_SECONDS,
+ MAX_TTL_SECONDS,
+} = SESSION_LIMITS;
function bad(message, code = 'bad_request') {
return Object.assign(new Error(message), { status: 400, code });
diff --git a/api/_lib/pay/policy.js b/api/_lib/pay/policy.js
new file mode 100644
index 000000000..071d72cd6
--- /dev/null
+++ b/api/_lib/pay/policy.js
@@ -0,0 +1,245 @@
+// Payment session policy predicates — the single source of truth for every
+// "may this agent spend?" decision on the platform.
+//
+// Two callers depend on this module and they must never disagree:
+//
+// api/_lib/pay/spend-governor.js enforces policy on a real payment
+// api/pay/simulate.js predicts policy on a hypothetical one
+//
+// Before this module existed, the simulator would have had to reimplement the
+// allowlist and ceiling rules, and any later fix to one copy would silently
+// leave the other lying. A dry run that says "this call is allowed" and an
+// enforcer that then rejects it is worse than having no dry run at all, because
+// the user authorizes a budget against a promise the platform does not keep.
+// So the rules live here, as pure functions over plain values: no DB, no clock
+// reads except the one passed in, no network. Both callers import them.
+//
+// One thing deliberately does NOT live here: the atomic budget reservation.
+// Checking `remaining >= amount` in JavaScript is advisory only, because two
+// concurrent requests can both read the same remaining balance and both pass.
+// The authoritative check is the SQL `UPDATE ... WHERE (budget - spent) >= amt`
+// in the governor. This module exposes `budgetVerdict()` for prediction and for
+// building the error message, and the governor calls it only to describe a
+// failure the database already decided.
+
+/**
+ * The limits session creation enforces (api/_lib/pay/payment-session.js).
+ *
+ * They live here, next to the rules, so the dry-run simulator can clamp a
+ * proposed policy to exactly what the create endpoint will accept. A simulator
+ * that blessed a $2000 budget would be recommending a session the API refuses.
+ */
+export const SESSION_LIMITS = Object.freeze({
+ MAX_LABEL_LEN: 120,
+ MAX_ALLOWED_HOSTS: 50,
+ MIN_BUDGET_USD: 0.001,
+ MAX_BUDGET_USD: 1000,
+ MIN_TTL_SECONDS: 60,
+ MAX_TTL_SECONDS: 90 * 24 * 3600, // 90 days
+});
+
+// USDC has 6 decimals everywhere we settle (Solana mainnet and Base mainnet).
+export const USDC_DECIMALS = 6;
+const USDC_SCALE = 10 ** USDC_DECIMALS;
+
+export function usdToAtomics(usd) {
+ return BigInt(Math.round(Number(usd) * USDC_SCALE));
+}
+
+export function atomicsToUsd(atomics) {
+ return Number(atomics) / USDC_SCALE;
+}
+
+/** Bare lowercase hostname from a URL or an already-bare host. Never throws. */
+export function normalizeHost(raw) {
+ const s = String(raw || '').trim().toLowerCase();
+ if (!s) return '';
+ try {
+ const u = new URL(s.includes('://') ? s : `https://${s}`);
+ return u.hostname;
+ } catch {
+ return s.split('/')[0].split(':')[0] || '';
+ }
+}
+
+/**
+ * Canonicalize a session's allowlist for comparison.
+ * Entries may be written as bare hosts, full URLs, or hosts with a port.
+ */
+export function canonicalizeAllowlist(allowedHosts) {
+ if (!Array.isArray(allowedHosts)) return [];
+ return allowedHosts.map(normalizeHost).filter(Boolean);
+}
+
+/**
+ * Does `targetHost` match `entry`, treating the entry as a domain suffix?
+ *
+ * `api.example.com` matches the entry `example.com` because it is a true
+ * subdomain. `evil-example.com` does NOT, which is the whole reason this is a
+ * named function with a test rather than an inline `endsWith`: `endsWith` alone
+ * would hand an attacker every domain that merely ends in the allowed string.
+ */
+export function hostMatches(targetHost, entry) {
+ if (!targetHost || !entry) return false;
+ return targetHost === entry || targetHost.endsWith(`.${entry}`);
+}
+
+// ── Individual verdicts ─────────────────────────────────────────────────────
+// Each returns either null (this rule permits the call) or a rejection object
+// { code, message, detail }. `code` is the machine-readable governance error the
+// API layer maps to an HTTP status; the strings are user-facing.
+
+const INACTIVE_MESSAGES = {
+ exhausted: 'Session budget is exhausted',
+ expired: 'Session has expired',
+ cancelled: 'Session has been cancelled',
+};
+
+/** Rule 1: the session must be in the `active` state. */
+export function statusVerdict(status) {
+ if (status === 'active') return null;
+ return {
+ code: 'session_inactive',
+ message: INACTIVE_MESSAGES[status] ?? `Session is ${status}`,
+ detail: { status },
+ };
+}
+
+/** Rule 2: the session's TTL must not have elapsed. */
+export function expiryVerdict(expiresAt, now = new Date()) {
+ if (expiresAt == null) return null;
+ const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt);
+ if (Number.isNaN(expiry.getTime())) return null;
+ if (expiry >= now) return null;
+ return { code: 'session_expired', message: 'Session has expired', detail: {} };
+}
+
+/** Rule 3: the target host must be on the allowlist, when one is set. */
+export function allowlistVerdict(url, allowedHosts) {
+ const canonical = canonicalizeAllowlist(allowedHosts);
+ if (canonical.length === 0) return null; // empty allowlist means "any host"
+
+ let targetHost;
+ try {
+ targetHost = new URL(url).hostname.toLowerCase();
+ } catch {
+ return {
+ code: 'allowlist_blocked',
+ message: `Invalid target URL: ${url}`,
+ detail: {},
+ };
+ }
+
+ if (canonical.some((entry) => hostMatches(targetHost, entry))) return null;
+
+ return {
+ code: 'allowlist_blocked',
+ message: `Host ${targetHost} is not in this session's allowlist`,
+ detail: { host: targetHost, allowlist: canonical },
+ };
+}
+
+/** Rule 4: a single payment must not exceed the per-transaction ceiling. */
+export function perTxVerdict(amountAtomics, maxPerTxAtomics) {
+ if (maxPerTxAtomics == null) return null;
+ const cap = BigInt(maxPerTxAtomics);
+ const amount = BigInt(amountAtomics);
+ if (amount <= cap) return null;
+ return {
+ code: 'per_tx_exceeded',
+ message: `Payment $${atomicsToUsd(amount)} exceeds the per-transaction limit $${atomicsToUsd(cap)}`,
+ detail: { amount_usd: atomicsToUsd(amount), cap_usd: atomicsToUsd(cap) },
+ };
+}
+
+/**
+ * Rule 5: the remaining budget must cover the payment.
+ *
+ * Advisory in the enforcer (the SQL predicate is authoritative), authoritative
+ * in the simulator, where the spend curve is replayed in memory and nothing is
+ * concurrent. Callers pass `remainingAtomics` so this stays a pure function.
+ */
+export function budgetVerdict(amountAtomics, remainingAtomics) {
+ const amount = BigInt(amountAtomics);
+ const remaining = BigInt(remainingAtomics);
+ if (remaining >= amount) return null;
+ return {
+ code: 'insufficient_budget',
+ message: `Insufficient session budget. Need $${atomicsToUsd(amount)}, remaining $${atomicsToUsd(remaining)}`,
+ detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },
+ };
+}
+
+/**
+ * Run every rule in enforcement order and return the first rejection, or null.
+ *
+ * Order matters and mirrors the governor exactly: state, then expiry, then
+ * allowlist, then ceiling, then budget. A caller that reordered these would
+ * report "insufficient budget" for a call that is actually blocked by the
+ * allowlist, which sends the user off to fund a session that still would not
+ * work.
+ *
+ * @param {object} call
+ * @param {string} call.url target endpoint
+ * @param {bigint|string|number} call.amountAtomics price in USDC atomics
+ * @param {object} call.policy { status, expiresAt, allowedHosts, maxPerTxAtomics }
+ * @param {bigint|string|number} call.remainingAtomics budget left before this call
+ * @param {Date} [call.now]
+ * @returns {{code: string, message: string, detail: object} | null}
+ */
+export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, now = new Date() }) {
+ return (
+ statusVerdict(policy.status ?? 'active') ??
+ expiryVerdict(policy.expiresAt ?? null, now) ??
+ allowlistVerdict(url, policy.allowedHosts) ??
+ perTxVerdict(amountAtomics, policy.maxPerTxAtomics ?? null) ??
+ budgetVerdict(amountAtomics, remainingAtomics)
+ );
+}
+
+/**
+ * Replay a sequence of priced calls against a policy, in order.
+ *
+ * This is what makes a dry run more useful than checking each call in
+ * isolation: a call can be individually affordable and still fail because the
+ * eleven calls before it drained the budget. The returned steps carry the
+ * running balance so a UI can draw the exact point of exhaustion.
+ *
+ * A denied call consumes nothing, which matches the enforcer: the atomic
+ * reservation only increments `spent_usdc` on the success path, and every
+ * failure path either never reserved or rolled back.
+ *
+ * @param {Array<{url: string, amountAtomics: bigint|string|number, [k: string]: any}>} calls
+ * @param {object} policy { budgetAtomics, maxPerTxAtomics, allowedHosts, status, expiresAt }
+ * @param {Date} [now]
+ */
+export function replay(calls, policy, now = new Date()) {
+ const budget = BigInt(policy.budgetAtomics ?? 0);
+ let spent = 0n;
+ const steps = [];
+
+ for (const call of calls) {
+ const amount = BigInt(call.amountAtomics ?? 0);
+ const remainingBefore = budget - spent;
+ const rejection = evaluateCall({
+ url: call.url,
+ amountAtomics: amount,
+ policy,
+ remainingAtomics: remainingBefore,
+ now,
+ });
+
+ if (!rejection) spent += amount;
+
+ steps.push({
+ call,
+ allowed: rejection === null,
+ rejection,
+ amountAtomics: amount,
+ remainingBeforeAtomics: remainingBefore,
+ remainingAfterAtomics: budget - spent,
+ });
+ }
+
+ return { steps, spentAtomics: spent, remainingAtomics: budget - spent };
+}
diff --git a/api/_lib/pay/probe.js b/api/_lib/pay/probe.js
new file mode 100644
index 000000000..55b29cd81
--- /dev/null
+++ b/api/_lib/pay/probe.js
@@ -0,0 +1,151 @@
+// x402 challenge probing, shared by the payment executor and the dry-run simulator.
+//
+// Both need the identical network behaviour: an SSRF-guarded request that never
+// follows a redirect, pins the resolved address against DNS rebinding, and reads
+// the 402 challenge from either the JSON body or the `payment-required` header.
+// They differ only in what they do with the answer. The executor selects one
+// Solana USDC accept and signs it; the simulator reports every rail and signs
+// nothing. Keeping the transport in one place means a hardening fix to one path
+// cannot leave the other exposed.
+
+import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from '../ssrf.js';
+
+/** Canonical USDC mint on Solana mainnet. */
+export const USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+export const DEFAULT_TIMEOUT_MS = 20_000;
+
+export function safeJson(text) {
+ try { return JSON.parse(text); } catch { return null; }
+}
+
+export function b64decodeJson(s) {
+ if (!s) return null;
+ try { return JSON.parse(Buffer.from(String(s), 'base64').toString('utf8')); } catch { return null; }
+}
+
+/**
+ * Fetch a third-party URL with the full SSRF guard chain.
+ *
+ * `redirect: 'manual'` matters as much as the address pin: a 302 to
+ * 169.254.169.254 would otherwise bypass the check that just passed.
+ */
+export async function guardedFetch(rawUrl, {
+ method = 'GET',
+ headers = {},
+ body,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ userAgent = 'three.ws-payment-session/1.0 (+https://three.ws/)',
+} = {}) {
+ const url = validatePublicUrl(rawUrl);
+ const addrs = await resolvePublicHost(url.hostname);
+ const agent = pinnedAgent(url.hostname, addrs);
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetch(url, {
+ method,
+ redirect: 'manual',
+ signal: controller.signal,
+ dispatcher: agent,
+ headers: {
+ 'user-agent': userAgent,
+ accept: 'application/json, text/plain;q=0.8, */*;q=0.5',
+ ...(body != null ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ },
+ ...(body != null ? { body: typeof body === 'string' ? body : JSON.stringify(body) } : {}),
+ });
+ const text = await res.text();
+ return { status: res.status, ok: res.ok, headers: res.headers, text };
+ } finally {
+ clearTimeout(timer);
+ await agent.close().catch(() => {});
+ }
+}
+
+/** Read the challenge out of a 402 response, wherever the service put it. */
+export function readChallenge(res) {
+ return safeJson(res.text) || b64decodeJson(res.headers.get('payment-required'));
+}
+
+/**
+ * Summarize one `accepts` entry into the shape both the simulator UI and the
+ * MCP tool render. `amount` is a decimal string of atomic units in the x402
+ * spec, so it is parsed as BigInt and never as a float.
+ */
+export function describeRail(accept) {
+ let atomics = null;
+ try { atomics = BigInt(accept?.amount); } catch { atomics = null; }
+ return {
+ network: typeof accept?.network === 'string' ? accept.network : null,
+ asset: accept?.asset ?? null,
+ pay_to: accept?.payTo ?? null,
+ amount_atomics: atomics === null ? null : atomics.toString(),
+ // Every asset we transact in uses 6 decimals; a rail that does not is
+ // reported with a null price rather than a wrong one.
+ amount_usd: atomics === null ? null : Number(atomics) / 1_000_000,
+ usdc: accept?.asset === USDC_SOLANA_MINT || /usdc/i.test(String(accept?.extra?.name ?? '')),
+ };
+}
+
+/**
+ * Probe an endpoint and report what it charges, without paying anything.
+ *
+ * Never throws for an ordinary remote failure: an unreachable host, a blocked
+ * URL, or an unreadable challenge are all legitimate outcomes of a dry run and
+ * each is returned as a typed result so the caller can show the row instead of
+ * failing the whole batch.
+ *
+ * @returns {Promise<{kind: 'priced'|'free'|'error', ...}>}
+ */
+export async function probePrice(rawUrl, { method = 'GET', body = null, timeoutMs } = {}) {
+ let res;
+ try {
+ res = await guardedFetch(rawUrl, { method, body, timeoutMs });
+ } catch (err) {
+ if (err instanceof SsrfError) {
+ return {
+ kind: 'error',
+ code: 'blocked_url',
+ message: 'Target URL is not a reachable public endpoint',
+ };
+ }
+ return {
+ kind: 'error',
+ code: 'endpoint_unreachable',
+ message: `Could not reach endpoint: ${err?.message ?? 'network error'}`,
+ };
+ }
+
+ if (res.status !== 402) {
+ return { kind: 'free', status: res.status };
+ }
+
+ const challenge = readChallenge(res);
+ if (!challenge || !Array.isArray(challenge.accepts) || challenge.accepts.length === 0) {
+ return {
+ kind: 'error',
+ code: 'invalid_challenge',
+ message: 'Service returned an unreadable payment challenge',
+ };
+ }
+
+ const rails = challenge.accepts.map(describeRail);
+ return { kind: 'priced', status: 402, rails, description: challenge.description ?? null };
+}
+
+/**
+ * Pick the rail a payment session would actually settle on.
+ *
+ * Sessions settle Solana-first (the platform's home chain), so a Solana USDC
+ * accept always wins. `base` sessions select the EVM rail. When the requested
+ * network is absent the caller is told which networks the service does offer,
+ * because "no Solana option" is a useful dry-run finding, not an error to hide.
+ */
+export function selectRail(rails, network = 'solana') {
+ const want = String(network || 'solana').toLowerCase();
+ const onNetwork = rails.filter((r) => typeof r.network === 'string' && r.network.toLowerCase().startsWith(want));
+ if (onNetwork.length === 0) return null;
+ return onNetwork.find((r) => r.usdc) ?? onNetwork[0];
+}
diff --git a/api/_lib/pay/spend-governor.js b/api/_lib/pay/spend-governor.js
index 6f03f85f9..29ad34ade 100644
--- a/api/_lib/pay/spend-governor.js
+++ b/api/_lib/pay/spend-governor.js
@@ -25,14 +25,22 @@
import { createHmac, randomBytes } from 'node:crypto';
import { sql } from '../db.js';
import { env } from '../env.js';
+import {
+ usdToAtomics,
+ atomicsToUsd,
+ normalizeHost,
+ statusVerdict,
+ expiryVerdict,
+ allowlistVerdict,
+ perTxVerdict,
+ budgetVerdict,
+} from './policy.js';
-// USDC has 6 decimals. Convert human USD to atomic units.
-export function usdToAtomics(usd) {
- return BigInt(Math.round(Number(usd) * 1_000_000));
-}
-export function atomicsToUsd(atomics) {
- return Number(atomics) / 1_000_000;
-}
+// The policy predicates below are shared with the dry-run simulator
+// (api/pay/simulate.js) so a simulated verdict and an enforced one can never
+// disagree. Re-exported here because this module was the original home of these
+// helpers and several callers already import them from this path.
+export { usdToAtomics, atomicsToUsd, normalizeHost };
export class SpendGovernorError extends Error {
constructor(code, message, detail = {}) {
@@ -87,17 +95,9 @@ export function extractSessionId(token) {
return rest.slice(0, 36);
}
-// Normalize any URL/host to a bare lowercase hostname for allowlist comparison.
-export function normalizeHost(raw) {
- const s = String(raw || '').trim().toLowerCase();
- if (!s) return '';
- try {
- const u = new URL(s.includes('://') ? s : `https://${s}`);
- return u.hostname;
- } catch {
- // Might already be a bare hostname
- return s.split('/')[0].split(':')[0] || '';
- }
+/** Turn a policy rejection from policy.js into the thrown governance error. */
+function throwVerdict(verdict) {
+ if (verdict) throw new SpendGovernorError(verdict.code, verdict.message, verdict.detail);
}
/**
@@ -137,61 +137,25 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {
const session = await verifySessionToken(token);
// Phase 2: status check
- if (session.status !== 'active') {
- const messages = {
- exhausted: 'Session budget is exhausted',
- expired: 'Session has expired',
- cancelled: 'Session has been cancelled',
- };
- throw new SpendGovernorError(
- 'session_inactive',
- messages[session.status] ?? `Session is ${session.status}`,
- { status: session.status },
- );
- }
+ throwVerdict(statusVerdict(session.status));
// Phase 3: time expiry (belt-and-suspenders; DB sweep also marks expired rows)
const now = new Date();
- if (new Date(session.expires_at) < now) {
+ const expired = expiryVerdict(session.expires_at, now);
+ if (expired) {
// Mark it expired so future checks skip the DB read
await sql`
UPDATE payment_sessions SET status = 'expired', updated_at = now()
WHERE id = ${session.id} AND status = 'active'
`.catch(() => {});
- throw new SpendGovernorError('session_expired', 'Session has expired');
+ throwVerdict(expired);
}
// Phase 4: URL allowlist enforcement
- const allowedHosts = Array.isArray(session.allowed_hosts) ? session.allowed_hosts : [];
- if (allowedHosts.length > 0) {
- let targetHost;
- try {
- targetHost = new URL(url).hostname.toLowerCase();
- } catch {
- throw new SpendGovernorError('allowlist_blocked', `Invalid target URL: ${url}`);
- }
- const canonicalAllowlist = allowedHosts.map(normalizeHost).filter(Boolean);
- const allowed = canonicalAllowlist.some(
- (h) => targetHost === h || targetHost.endsWith(`.${h}`),
- );
- if (!allowed) {
- throw new SpendGovernorError(
- 'allowlist_blocked',
- `Host ${targetHost} is not in this session's allowlist`,
- { host: targetHost, allowlist: canonicalAllowlist },
- );
- }
- }
+ throwVerdict(allowlistVerdict(url, session.allowed_hosts));
// Phase 5: per-transaction ceiling
- const perTxCap = session.max_per_tx_usdc != null ? BigInt(session.max_per_tx_usdc) : null;
- if (perTxCap !== null && amountAtomics > perTxCap) {
- throw new SpendGovernorError(
- 'per_tx_exceeded',
- `Payment $${atomicsToUsd(amountAtomics)} exceeds the per-transaction limit $${atomicsToUsd(perTxCap)}`,
- { amount_usd: atomicsToUsd(amountAtomics), cap_usd: atomicsToUsd(perTxCap) },
- );
- }
+ throwVerdict(perTxVerdict(amountAtomics, session.max_per_tx_usdc));
// Phase 6: atomic budget reservation
// The WHERE clause ensures (budget_usdc - spent_usdc) >= amountAtomics before
@@ -214,10 +178,14 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {
SELECT budget_usdc, spent_usdc FROM payment_sessions WHERE id = ${session.id}
`;
const remaining = fresh ? BigInt(fresh.budget_usdc) - BigInt(fresh.spent_usdc) : 0n;
- throw new SpendGovernorError(
- 'insufficient_budget',
- `Insufficient session budget. Need $${atomicsToUsd(amount)}, remaining $${atomicsToUsd(remaining)}`,
- { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },
+ // The SQL predicate already decided; budgetVerdict only phrases the failure,
+ // using the same wording the simulator shows for a predicted shortfall.
+ throwVerdict(
+ budgetVerdict(amount, remaining) ?? {
+ code: 'insufficient_budget',
+ message: 'Session was not active when the payment was reserved',
+ detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },
+ },
);
}
diff --git a/api/_lib/x402/runway-sim.js b/api/_lib/x402/runway-sim.js
new file mode 100644
index 000000000..8ff7d8896
--- /dev/null
+++ b/api/_lib/x402/runway-sim.js
@@ -0,0 +1,364 @@
+// api/_lib/x402/runway-sim.js
+//
+// A forward simulation of the x402 settle path's admission control — the
+// "digital twin" behind /economy-lab.
+//
+// Why this exists
+// ---------------
+// When settlement stops, the outward symptom is always the same ("payments are
+// failing") and the causes are not: the fee wallet can be under its hard SOL
+// floor, or above the floor but out of daily fee budget, or simply out of
+// demand. Those three have completely different fixes (fund the wallet / widen
+// the governor / nothing is wrong), and telling them apart historically meant
+// hand-writing SQL against x402_self_facilitator_log and reading lamport math
+// off alert strings. On 2026-07-31 that hand work attributed 5,483 of 8,657
+// settle failures to fee_runway_exhausted — a config problem that looked
+// exactly like an empty wallet.
+//
+// The simulation is faithful because it does NOT reimplement the decision. It
+// imports walletDailyFeeBudgetLamports() and assessWalletFeeBudget() from
+// wallet-fee-governor.js — the very functions api/x402-facilitator/[action].js
+// calls through wallet-fee-meter.js — and applies them in the same ORDER the
+// settle path does (self-facilitator.js settleRingPayment):
+//
+// 1. hard SOL floor → reason `fee_wallet_below_floor:<bal><<floor>`
+// 2. wallet fee governor → reason `fee_runway_exhausted:<spent>+<fee>><budget>`
+// 3. admit, burn the fee
+//
+// so a projection can never drift from production the way a parallel model
+// would. Change the governor and this simulation changes with it.
+//
+// Zero I/O and zero imports beyond the governor, which is itself dependency-
+// free. That is deliberate: the browser at /economy-lab imports this module
+// directly (see scripts/check-browser-graph.mjs — no node: built-in may become
+// reachable from here), so the page runs the real admission logic client-side
+// against a live seed from GET /api/x402/runway-lab.
+
+import {
+ walletDailyFeeBudgetLamports,
+ assessWalletFeeBudget,
+} from './wallet-fee-governor.js';
+
+export const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// The 1-signature Solana base fee: the cheapest a settle can possibly cost, and
+// the floor we clamp a caller-supplied fee estimate to. Mirrors
+// ring-dashboard-model.js FEE_FLOOR_LAMPORTS.
+export const MIN_FEE_LAMPORTS = 5_000;
+
+// Guard rail for the attempt loop. A 30-day horizon at 500 settles/hour is
+// 360k attempts, which runs in a few milliseconds; beyond this we stop
+// simulating and say so rather than freezing a browser tab.
+export const MAX_ATTEMPTS = 600_000;
+
+const int = (v, d = 0) => {
+ const n = Math.floor(Number(v));
+ return Number.isFinite(n) ? n : d;
+};
+
+/**
+ * Project the fee wallet forward, settle attempt by settle attempt.
+ *
+ * @param {object} input
+ * @param {number} input.startLamports fee wallet SOL balance at t=0
+ * @param {number} input.floorLamports X402_SPONSOR_SOL_FLOOR_LAMPORTS
+ * @param {number} input.runwayDays X402_WALLET_FEE_RUNWAY_DAYS
+ * @param {number} input.minBudgetLamports X402_WALLET_FEE_MIN_BUDGET_LAMPORTS
+ * @param {number} input.feeLamports SOL burned per admitted settle
+ * @param {number} input.demandPerHour settles ATTEMPTED per hour
+ * @param {number} input.hours horizon
+ * @param {number} [input.spentTodayLamports] fee already burned in the current UTC day
+ * @param {number} [input.startHourOfDay] UTC hour at t=0, so day resets land correctly
+ * @param {{hour:number, lamports:number}[]} [input.funding] deposits applied at the top of an hour
+ * @param {boolean} [input.governorEnabled] X402_WALLET_FEE_GOVERNOR_ENABLED
+ */
+export function simulateRunway(input = {}) {
+ const floorLamports = Math.max(0, int(input.floorLamports));
+ const runwayDays = Math.max(0.5, Number(input.runwayDays) || 3);
+ const minBudgetLamports = Math.max(0, int(input.minBudgetLamports));
+ const feeLamports = Math.max(MIN_FEE_LAMPORTS, int(input.feeLamports, MIN_FEE_LAMPORTS));
+ const demandPerHour = Math.max(0, int(input.demandPerHour));
+ const hours = Math.min(24 * 90, Math.max(1, int(input.hours, 24 * 7)));
+ const governorEnabled = input.governorEnabled !== false;
+ const startHourOfDay = ((int(input.startHourOfDay) % 24) + 24) % 24;
+
+ const fundingByHour = new Map();
+ for (const f of input.funding || []) {
+ const h = int(f?.hour, -1);
+ const lam = int(f?.lamports);
+ if (h < 0 || h >= hours || lam === 0) continue;
+ fundingByHour.set(h, (fundingByHour.get(h) || 0) + lam);
+ }
+
+ let lamports = Math.max(0, int(input.startLamports));
+ let spentToday = Math.max(0, int(input.spentTodayLamports));
+
+ const series = [];
+ let admitted = 0;
+ let refusedFloor = 0;
+ let refusedGovernor = 0;
+ let attempts = 0;
+ let truncated = false;
+ let firstRefusalHour = null;
+ let floorBreachHour = null;
+ let fundedLamports = 0;
+ const perDayAdmitted = [];
+
+ for (let h = 0; h < hours; h++) {
+ // A UTC midnight crossing resets the governor's daily meter. `h === 0` is
+ // the seed hour, which carries the real spent-today read from the ledger.
+ if (h > 0 && (startHourOfDay + h) % 24 === 0) spentToday = 0;
+
+ const deposit = fundingByHour.get(h);
+ if (deposit) {
+ lamports = Math.max(0, lamports + deposit);
+ fundedLamports += deposit;
+ }
+
+ let hourAdmitted = 0;
+ let hourRefusedFloor = 0;
+ let hourRefusedGovernor = 0;
+ let lastReason = null;
+ let hourBudget = walletDailyFeeBudgetLamports({
+ solLamports: lamports, floorLamports, runwayDays, minBudgetLamports,
+ });
+
+ for (let i = 0; i < demandPerHour; i++) {
+ if (attempts >= MAX_ATTEMPTS) { truncated = true; break; }
+ attempts++;
+
+ // (1) Hard SOL floor — self-facilitator.js checks this first, on the
+ // live balance, before the meter is ever consulted. Note the strict
+ // `<`: a wallet sitting exactly ON its floor still admits one more
+ // settle and lands just under it. That is production's comparison,
+ // reproduced rather than rounded away.
+ if (lamports < floorLamports) {
+ hourRefusedFloor++;
+ lastReason = `fee_wallet_below_floor:${lamports}<${floorLamports}`;
+ if (floorBreachHour === null) floorBreachHour = h;
+ if (firstRefusalHour === null) firstRefusalHour = h;
+ continue;
+ }
+
+ // (1b) With a floor at or near zero the floor check stops binding and
+ // the chain becomes the constraint: a transaction cannot pay a fee the
+ // account does not hold. Same bucket as the floor (both are "the wallet
+ // is out of SOL"), distinct reason so the cause stays legible.
+ if (lamports < feeLamports) {
+ hourRefusedFloor++;
+ lastReason = `insufficient_lamports_for_fee:${lamports}<${feeLamports}`;
+ if (floorBreachHour === null) floorBreachHour = h;
+ if (firstRefusalHour === null) firstRefusalHour = h;
+ continue;
+ }
+
+ // (2) Wallet fee governor, recomputed per settle from the live balance
+ // exactly as wallet-fee-meter.js does.
+ const budgetLamports = walletDailyFeeBudgetLamports({
+ solLamports: lamports, floorLamports, runwayDays, minBudgetLamports,
+ });
+ hourBudget = budgetLamports;
+ if (governorEnabled) {
+ const verdict = assessWalletFeeBudget({
+ spentTodayLamports: spentToday, budgetLamports, nextFeeLamports: feeLamports,
+ });
+ if (!verdict.ok) {
+ hourRefusedGovernor++;
+ lastReason = verdict.reason;
+ if (firstRefusalHour === null) firstRefusalHour = h;
+ continue;
+ }
+ }
+
+ // (3) Admitted: the fee is burned and metered.
+ lamports -= feeLamports;
+ spentToday += feeLamports;
+ hourAdmitted++;
+ }
+
+ admitted += hourAdmitted;
+ refusedFloor += hourRefusedFloor;
+ refusedGovernor += hourRefusedGovernor;
+
+ series.push({
+ hour: h,
+ lamports,
+ budgetLamports: hourBudget,
+ spentTodayLamports: spentToday,
+ admitted: hourAdmitted,
+ refusedFloor: hourRefusedFloor,
+ refusedGovernor: hourRefusedGovernor,
+ fundedLamports: deposit || 0,
+ reason: lastReason,
+ });
+
+ const day = Math.floor((startHourOfDay + h) / 24);
+ perDayAdmitted[day] = (perDayAdmitted[day] || 0) + hourAdmitted;
+ if (truncated) break;
+ }
+
+ const refused = refusedFloor + refusedGovernor;
+ const demanded = admitted + refused;
+ const settledDays = perDayAdmitted.filter((n) => n !== undefined);
+
+ return {
+ series,
+ summary: {
+ admitted,
+ refused,
+ refusedFloor,
+ refusedGovernor,
+ demanded,
+ admissionRate: demanded > 0 ? admitted / demanded : 1,
+ firstRefusalHour,
+ floorBreachHour,
+ startLamports: Math.max(0, int(input.startLamports)),
+ endLamports: lamports,
+ feesBurnedLamports: admitted * feeLamports,
+ fundedLamports,
+ settlesPerDay: settledDays,
+ steadySettlesPerDay: steadyStateSettlesPerDay(settledDays),
+ limiter: limiterOf({ refusedFloor, refusedGovernor, admitted, demandPerHour, hours }),
+ verdict: verdictOf({ admitted, refused, refusedFloor }),
+ truncated,
+ hoursSimulated: series.length,
+ },
+ };
+}
+
+// The last FULL day in the projection is the honest steady-state read: day 0 is
+// partial (the seed hour lands mid-day) and the final day may be truncated by
+// the horizon. With fewer than three days on record, fall back to the max.
+function steadyStateSettlesPerDay(perDay) {
+ if (!perDay.length) return 0;
+ if (perDay.length < 3) return Math.max(...perDay);
+ return perDay[perDay.length - 2];
+}
+
+// What is actually holding throughput back — the question an operator is really
+// asking when they say "why did settlement stop".
+function limiterOf({ refusedFloor, refusedGovernor, admitted, demandPerHour, hours }) {
+ if (refusedFloor > refusedGovernor && refusedFloor > 0) return 'floor';
+ if (refusedGovernor > 0) return 'governor';
+ if (admitted >= demandPerHour * hours && demandPerHour > 0) return 'demand';
+ return 'none';
+}
+
+function verdictOf({ admitted, refused, refusedFloor }) {
+ if (admitted === 0 && refused > 0) return 'starved';
+ if (refusedFloor > 0) return 'starved';
+ if (refused > 0) return 'throttled';
+ return 'healthy';
+}
+
+/**
+ * Closed-form daily throughput, for the UI to explain a projection without
+ * re-running it.
+ *
+ * The governor recomputes its budget from the LIVE balance on every settle, so
+ * spending shrinks the budget that authorises the next spend. That feedback
+ * settles at a fixed point well below the naive `budget / fee`:
+ *
+ * n·fee = (spendable − n·fee) / runwayDays
+ * ⇒ n = spendable / (fee · (runwayDays + 1))
+ *
+ * With the stock 3-day runway that is spendable/4 per day, not spendable/3 —
+ * a 25% gap between the configured intent and the delivered throughput, and
+ * the reason "the wallet has 3 days of runway" and "settlement stopped today"
+ * are not contradictory statements. The heartbeat floor raises the result, and
+ * the wallet's own distance to its hard floor caps it.
+ */
+export function equilibriumSettlesPerDay({
+ spendableLamports, feeLamports, runwayDays, minBudgetLamports = 0,
+}) {
+ const fee = Math.max(MIN_FEE_LAMPORTS, int(feeLamports, MIN_FEE_LAMPORTS));
+ const spendable = Math.max(0, int(spendableLamports));
+ const days = Math.max(0.5, Number(runwayDays) || 3);
+ const damped = spendable / (fee * (days + 1));
+ const heartbeat = Math.max(0, int(minBudgetLamports)) / fee;
+ const hardCap = spendable / fee;
+ return Math.floor(Math.min(hardCap, Math.max(damped, heartbeat)));
+}
+
+/**
+ * Given a throughput target, solve each of the three independent levers for the
+ * exact value that reaches it. This is the "what fixes it" half of the lab: the
+ * governor's budget is one equation with three tunable terms, so an operator
+ * should never have to guess which knob to turn or by how much.
+ *
+ * budget = max(minBudgetLamports, floor((balance - floor) / runwayDays))
+ * throughput_per_day = budget / feeLamports
+ *
+ * @returns {{ targetSettlesPerDay:number, requiredDailyBudgetLamports:number,
+ * currentDailyBudgetLamports:number, alreadyMet:boolean,
+ * fund:{lamports:number, sol:number}|null,
+ * runwayDays:{value:number}|null,
+ * minBudget:{lamports:number, sol:number} }}
+ */
+export function solveForThroughput({
+ targetSettlesPerDay, startLamports, floorLamports, runwayDays, minBudgetLamports, feeLamports,
+}) {
+ const fee = Math.max(MIN_FEE_LAMPORTS, int(feeLamports, MIN_FEE_LAMPORTS));
+ const target = Math.max(0, int(targetSettlesPerDay));
+ const floor = Math.max(0, int(floorLamports));
+ const days = Math.max(0.5, Number(runwayDays) || 3);
+ const balance = Math.max(0, int(startLamports));
+ const required = target * fee;
+ const current = walletDailyFeeBudgetLamports({
+ solLamports: balance, floorLamports: floor, runwayDays: days, minBudgetLamports,
+ });
+
+ // Lever 1 — fund the wallet, keeping the governor as configured.
+ const neededBalance = floor + Math.ceil(required * days);
+ const fundLamports = Math.max(0, neededBalance - balance);
+
+ // Lever 2 — shorten the runway target, keeping the balance as-is. Only
+ // solvable while the wallet is above its floor; below it there is nothing to
+ // spread and the hard floor refuses every settle regardless.
+ const spendable = balance - floor;
+ const solvedRunwayDays = spendable > 0 && required > 0
+ ? Math.max(0.5, Math.floor((spendable / required) * 100) / 100)
+ : null;
+
+ // Lever 3 — raise the heartbeat floor. Always solvable, and the only lever
+ // that does not depend on the balance, which is precisely why it is the one
+ // that keeps a nearly-empty wallet transacting.
+ return {
+ targetSettlesPerDay: target,
+ requiredDailyBudgetLamports: required,
+ currentDailyBudgetLamports: current,
+ alreadyMet: current >= required,
+ fund: fundLamports > 0 ? { lamports: fundLamports, sol: fundLamports / LAMPORTS_PER_SOL } : null,
+ runwayDays: solvedRunwayDays !== null && solvedRunwayDays < days ? { value: solvedRunwayDays } : null,
+ minBudget: { lamports: required, sol: required / LAMPORTS_PER_SOL },
+ };
+}
+
+/**
+ * The env changes that turn a simulated config into a real one. Emitted so the
+ * lab hands over an exact, runnable `gcloud run services update` instead of a
+ * description of one — the step where hand-transcribed lamport values have gone
+ * wrong before. Only keys that actually differ from live are returned, and
+ * --update-env-vars is used because --set-env-vars REPLACES the whole set.
+ */
+export function envDiff(live = {}, proposed = {}) {
+ const keys = [
+ ['runwayDays', 'X402_WALLET_FEE_RUNWAY_DAYS'],
+ ['minBudgetLamports', 'X402_WALLET_FEE_MIN_BUDGET_LAMPORTS'],
+ ['floorLamports', 'X402_SPONSOR_SOL_FLOOR_LAMPORTS'],
+ ['governorEnabled', 'X402_WALLET_FEE_GOVERNOR_ENABLED'],
+ ];
+ const changes = [];
+ for (const [field, envName] of keys) {
+ if (proposed[field] === undefined || live[field] === undefined) continue;
+ if (String(proposed[field]) === String(live[field])) continue;
+ changes.push({ env: envName, from: String(live[field]), to: String(proposed[field]) });
+ }
+ return changes;
+}
+
+export function formatSol(lamports, digits = 4) {
+ const n = Number(lamports) / LAMPORTS_PER_SOL;
+ if (!Number.isFinite(n)) return '0';
+ return n.toFixed(digits).replace(/\.?0+$/, '') || '0';
+}
diff --git a/api/pay/execute.js b/api/pay/execute.js
index 27a26da21..cee2391c3 100644
--- a/api/pay/execute.js
+++ b/api/pay/execute.js
@@ -36,7 +36,14 @@ import { loadSeedKeypair } from '../_lib/x402/pay.js';
import { cors, error, json, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
-import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from '../_lib/ssrf.js';
+import { validatePublicUrl, SsrfError } from '../_lib/ssrf.js';
+import {
+ guardedFetch,
+ safeJson,
+ b64decodeJson,
+ readChallenge,
+ USDC_SOLANA_MINT,
+} from '../_lib/pay/probe.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import {
usdToAtomics,
@@ -47,11 +54,8 @@ import {
recordExecution,
SpendGovernorError,
} from '../_lib/pay/spend-governor.js';
-// Known USDC mint address on Solana
-const USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const SOLANA_RPC = env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-const FETCH_TIMEOUT_MS = 20_000;
// ── Platform payer: Solana ───────────────────────────────────────────────────
let _solanaKeypair = null;
@@ -74,44 +78,6 @@ function loadSolanaKeypair() {
}
}
-// ── SSRF-guarded fetch ──────────────────────────────────────────────────────
-async function guardedFetch(rawUrl, { method = 'GET', headers = {}, body } = {}) {
- const url = validatePublicUrl(rawUrl);
- const addrs = await resolvePublicHost(url.hostname);
- const agent = pinnedAgent(url.hostname, addrs);
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
- try {
- const res = await fetch(url, {
- method,
- redirect: 'manual',
- signal: controller.signal,
- dispatcher: agent,
- headers: {
- 'user-agent': 'three.ws-payment-session/1.0 (+https://three.ws/)',
- accept: 'application/json, text/plain;q=0.8, */*;q=0.5',
- ...(body != null ? { 'content-type': 'application/json' } : {}),
- ...headers,
- },
- ...(body != null ? { body: typeof body === 'string' ? body : JSON.stringify(body) } : {}),
- });
- const text = await res.text();
- return { status: res.status, ok: res.ok, headers: res.headers, text };
- } finally {
- clearTimeout(timer);
- await agent.close().catch(() => {});
- }
-}
-
-function safeJson(text) {
- try { return JSON.parse(text); } catch { return null; }
-}
-
-function b64decodeJson(s) {
- if (!s) return null;
- try { return JSON.parse(Buffer.from(String(s), 'base64').toString('utf8')); } catch { return null; }
-}
-
// ── Probe a 402 endpoint and select a Solana USDC accept ────────────────────
async function probe402(rawUrl, { method, body }) {
let res;
@@ -132,7 +98,7 @@ async function probe402(rawUrl, { method, body }) {
return { free: true, status: res.status, result: safeJson(res.text) ?? res.text };
}
- const challenge = safeJson(res.text) || b64decodeJson(res.headers.get('payment-required'));
+ const challenge = readChallenge(res);
if (!challenge || !Array.isArray(challenge.accepts)) {
throw Object.assign(new Error('Service returned an unreadable payment challenge'), {
status: 502, code: 'invalid_challenge',
diff --git a/api/pay/simulate.js b/api/pay/simulate.js
new file mode 100644
index 000000000..b7fc125c4
--- /dev/null
+++ b/api/pay/simulate.js
@@ -0,0 +1,472 @@
+// POST /api/pay/simulate — dry-run a payment session policy against real prices.
+//
+// The problem this solves: authorizing an agent budget is a guess. You pick
+// $10 and a $0.50 per-transaction cap because those are round numbers, hand the
+// token to an agent, and find out which of your assumptions was wrong only when
+// the agent is already running and something has already been spent. If the cap
+// was too low the agent stalls on its third call. If the allowlist missed a
+// host the agent stalls on its first. If the budget was too small it dies
+// halfway through the job with money already gone.
+//
+// So: run the policy first, with no money and no session.
+//
+// This endpoint takes a proposed policy and the list of endpoints an agent
+// intends to call, probes each endpoint for its real x402 price (a live 402
+// challenge, not an estimate), and replays the whole sequence through the exact
+// predicates the enforcer uses (api/_lib/pay/policy.js). It reports which calls
+// would settle, which would be refused and by which rule, where the budget
+// runs dry, and the smallest policy that would let every call through.
+//
+// Nothing is signed. No session is created. No credits are debited. No row is
+// written. The only side effect is one unpaid HTTP request per unique endpoint,
+// which is exactly what any x402 client does before it decides to pay.
+
+import { cors, error, json, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { validatePublicUrl, isPrivateAddress } from '../_lib/ssrf.js';
+import { isIP } from 'node:net';
+import { probePrice, selectRail } from '../_lib/pay/probe.js';
+import {
+ SESSION_LIMITS,
+ replay,
+ usdToAtomics,
+ atomicsToUsd,
+ canonicalizeAllowlist,
+ normalizeHost,
+ hostMatches,
+} from '../_lib/pay/policy.js';
+
+// A simulation fans out one request per unique endpoint. These bounds keep a
+// single call from turning the platform into an amplifier.
+const MAX_CALLS = 40;
+const MAX_UNIQUE_URLS = 20;
+const MAX_REPEAT = 500;
+const PROBE_CONCURRENCY = 6;
+const PROBE_TIMEOUT_MS = 10_000;
+
+function bad(res, code, message, detail) {
+ return error(res, 400, code, message, detail);
+}
+
+/**
+ * Normalize the `calls` input.
+ *
+ * Accepts a bare string, `{url}`, or `{url, method, body, times, price_usd}`.
+ * `times` models the realistic case the naive version of this tool misses: an
+ * agent that polls one endpoint sixty times has a completely different budget
+ * profile from one that calls sixty endpoints once.
+ */
+export function parseCalls(raw) {
+ if (!Array.isArray(raw) || raw.length === 0) {
+ throw Object.assign(new Error('calls must be a non-empty array of endpoint URLs'), {
+ code: 'invalid_calls',
+ });
+ }
+ if (raw.length > MAX_CALLS) {
+ throw Object.assign(
+ new Error(`calls may contain at most ${MAX_CALLS} entries (received ${raw.length})`),
+ { code: 'too_many_calls' },
+ );
+ }
+
+ const calls = raw.map((entry, i) => {
+ const spec = typeof entry === 'string' ? { url: entry } : (entry ?? {});
+ const url = String(spec.url ?? '').trim();
+ if (!url) {
+ throw Object.assign(new Error(`calls[${i}] has no url`), { code: 'invalid_calls' });
+ }
+ // `allowHttp: false` is passed explicitly rather than relying on the
+ // default, which relaxes to http outside production. This endpoint is
+ // unauthenticated and fetches caller-chosen URLs, so it holds the
+ // production rule everywhere instead of being laxer on a dev box.
+ let parsed;
+ try {
+ parsed = validatePublicUrl(url, { allowHttp: false });
+ } catch {
+ throw Object.assign(
+ new Error(`calls[${i}] must be a public https URL: ${url}`),
+ { code: 'invalid_url' },
+ );
+ }
+ // A literal private address is refused here, before any DNS work. The
+ // probe path re-checks resolved addresses and pins them (api/_lib/ssrf.js),
+ // which is what catches a public hostname that resolves inward; this is the
+ // cheap first gate for the obvious `https://169.254.169.254/` case.
+ const literal = parsed.hostname.replace(/^\[|\]$/g, '');
+ const family = isIP(literal);
+ if (family && isPrivateAddress(literal, family)) {
+ throw Object.assign(
+ new Error(`calls[${i}] points at a private address: ${parsed.hostname}`),
+ { code: 'invalid_url' },
+ );
+ }
+
+ const times = Math.max(1, Math.min(MAX_REPEAT, Math.round(Number(spec.times ?? 1)) || 1));
+ // price_usd lets a caller simulate an endpoint that is not live yet, or
+ // model a price change, without any network access at all.
+ const priceUsd =
+ spec.price_usd == null || spec.price_usd === ''
+ ? null
+ : Number(spec.price_usd);
+ if (priceUsd !== null && (!Number.isFinite(priceUsd) || priceUsd < 0)) {
+ throw Object.assign(new Error(`calls[${i}].price_usd must be a non-negative number`), {
+ code: 'invalid_price',
+ });
+ }
+
+ return {
+ url,
+ method: String(spec.method ?? 'GET').toUpperCase() === 'POST' ? 'POST' : 'GET',
+ body: spec.body ?? null,
+ times,
+ label: spec.label ? String(spec.label).slice(0, 120) : null,
+ priceUsd,
+ };
+ });
+
+ const unique = new Set(calls.filter((c) => c.priceUsd === null).map((c) => `${c.method} ${c.url}`));
+ if (unique.size > MAX_UNIQUE_URLS) {
+ throw Object.assign(
+ new Error(`calls may reference at most ${MAX_UNIQUE_URLS} distinct endpoints to probe`),
+ { code: 'too_many_endpoints' },
+ );
+ }
+
+ return calls;
+}
+
+/** Normalize the proposed policy, clamping to the real session-creation limits. */
+export function parsePolicy(raw = {}) {
+ const notes = [];
+ const { MIN_BUDGET_USD, MAX_BUDGET_USD, MIN_TTL_SECONDS, MAX_TTL_SECONDS, MAX_ALLOWED_HOSTS } =
+ SESSION_LIMITS;
+
+ let budgetUsd = Number(raw.budget_usd);
+ if (!Number.isFinite(budgetUsd) || budgetUsd <= 0) budgetUsd = 1;
+ if (budgetUsd < MIN_BUDGET_USD) {
+ notes.push(`budget_usd raised to the $${MIN_BUDGET_USD} minimum a session accepts`);
+ budgetUsd = MIN_BUDGET_USD;
+ }
+ if (budgetUsd > MAX_BUDGET_USD) {
+ notes.push(`budget_usd lowered to the $${MAX_BUDGET_USD} maximum a session accepts`);
+ budgetUsd = MAX_BUDGET_USD;
+ }
+
+ let maxPerTxUsd =
+ raw.max_per_tx_usd == null || raw.max_per_tx_usd === '' ? null : Number(raw.max_per_tx_usd);
+ if (maxPerTxUsd !== null && (!Number.isFinite(maxPerTxUsd) || maxPerTxUsd <= 0)) {
+ maxPerTxUsd = null;
+ notes.push('max_per_tx_usd ignored: not a positive number');
+ }
+ if (maxPerTxUsd !== null && maxPerTxUsd > budgetUsd) {
+ notes.push('max_per_tx_usd exceeds the budget, so it can never bind');
+ }
+
+ const rawHosts = Array.isArray(raw.allowed_hosts)
+ ? raw.allowed_hosts
+ : String(raw.allowed_hosts ?? '').split(/[\s,]+/);
+ let allowedHosts = [...new Set(canonicalizeAllowlist(rawHosts))];
+ if (allowedHosts.length > MAX_ALLOWED_HOSTS) {
+ notes.push(`allowed_hosts truncated to the ${MAX_ALLOWED_HOSTS}-entry maximum`);
+ allowedHosts = allowedHosts.slice(0, MAX_ALLOWED_HOSTS);
+ }
+
+ let expirySeconds = Number(raw.expiry_seconds ?? 3600);
+ if (!Number.isFinite(expirySeconds)) expirySeconds = 3600;
+ expirySeconds = Math.min(MAX_TTL_SECONDS, Math.max(MIN_TTL_SECONDS, Math.round(expirySeconds)));
+
+ const network = String(raw.network ?? 'solana').toLowerCase() === 'base' ? 'base' : 'solana';
+
+ return {
+ budgetUsd,
+ maxPerTxUsd,
+ allowedHosts,
+ expirySeconds,
+ network,
+ notes,
+ };
+}
+
+/** Probe the distinct endpoints, at bounded concurrency. */
+async function priceEndpoints(calls, network) {
+ const keys = [...new Set(calls.filter((c) => c.priceUsd === null).map((c) => `${c.method} ${c.url}`))];
+ const byKey = new Map();
+ const queue = [...keys];
+
+ async function worker() {
+ for (;;) {
+ const key = queue.shift();
+ if (!key) return;
+ const call = calls.find((c) => `${c.method} ${c.url}` === key);
+ const probe = await probePrice(call.url, {
+ method: call.method,
+ body: call.body,
+ timeoutMs: PROBE_TIMEOUT_MS,
+ });
+ byKey.set(key, { probe, rail: probe.kind === 'priced' ? selectRail(probe.rails, network) : null });
+ }
+ }
+
+ await Promise.all(Array.from({ length: Math.min(PROBE_CONCURRENCY, keys.length) }, worker));
+ return byKey;
+}
+
+/**
+ * Expand each call spec into one priced step per repetition.
+ *
+ * A repeated call is expanded rather than multiplied because the budget check
+ * is per payment: 60 calls at $0.02 against a $1 budget is 50 settlements and
+ * 10 refusals, not one $1.20 refusal.
+ */
+export function buildSteps(calls, priced, network) {
+ const steps = [];
+ const problems = [];
+
+ for (const call of calls) {
+ const key = `${call.method} ${call.url}`;
+ let amountAtomics = null;
+ let pricing;
+
+ if (call.priceUsd !== null) {
+ amountAtomics = usdToAtomics(call.priceUsd);
+ pricing = { source: 'supplied', amount_usd: call.priceUsd, network: null };
+ } else {
+ const entry = priced.get(key);
+ const probe = entry?.probe;
+ if (!probe || probe.kind === 'error') {
+ problems.push({
+ url: call.url,
+ code: probe?.code ?? 'probe_failed',
+ message: probe?.message ?? 'Endpoint could not be priced',
+ });
+ pricing = {
+ source: 'unpriced',
+ amount_usd: null,
+ network: null,
+ error: probe?.code ?? 'probe_failed',
+ error_message: probe?.message ?? 'Endpoint could not be priced',
+ };
+ } else if (probe.kind === 'free') {
+ // api/pay/execute.js returns the response before touching the session
+ // when an endpoint answers without a 402. So a free call is never
+ // allowlist-checked, never capped, and never charged. Treating it as a
+ // $0 payment here would let the simulator report an allowlist refusal
+ // the real enforcer would never raise.
+ pricing = { source: 'free', amount_usd: 0, network: null, http_status: probe.status };
+ } else if (!entry.rail) {
+ const offered = [...new Set(probe.rails.map((r) => r.network).filter(Boolean))];
+ problems.push({
+ url: call.url,
+ code: 'no_rail_for_network',
+ message: `Endpoint charges on ${offered.join(', ') || 'an unknown network'} but this session settles on ${network}`,
+ });
+ pricing = {
+ source: 'unpriced',
+ amount_usd: null,
+ network: null,
+ error: 'no_rail_for_network',
+ error_message: `No ${network} payment option (offered: ${offered.join(', ') || 'none'})`,
+ networks_offered: offered,
+ };
+ } else {
+ amountAtomics = BigInt(entry.rail.amount_atomics ?? 0);
+ pricing = {
+ source: 'probed',
+ amount_usd: entry.rail.amount_usd,
+ network: entry.rail.network,
+ pay_to: entry.rail.pay_to,
+ asset: entry.rail.asset,
+ rails_offered: probe.rails.length,
+ description: probe.description,
+ };
+ }
+ }
+
+ for (let i = 0; i < call.times; i++) {
+ steps.push({
+ url: call.url,
+ method: call.method,
+ label: call.label,
+ repetition: call.times > 1 ? i + 1 : null,
+ of: call.times > 1 ? call.times : null,
+ pricing,
+ // Only priced calls enter the replay. An unpriced call is excluded
+ // rather than treated as free, because charging it $0 would quietly
+ // inflate how far the budget goes; a free call is excluded because the
+ // enforcer never runs governance on it.
+ priceable: amountAtomics !== null,
+ free: pricing.source === 'free',
+ amountAtomics: amountAtomics ?? 0n,
+ });
+ }
+ }
+
+ return { steps, problems };
+}
+
+/**
+ * Work out the smallest policy that would have let every priceable call settle.
+ *
+ * This is the part a user cannot compute in their head: it needs the summed
+ * cost of the whole sequence, the largest single payment in it, and the exact
+ * set of hosts touched.
+ */
+export function recommend(steps, policy) {
+ const priceable = steps.filter((s) => s.priceable);
+ const totalAtomics = priceable.reduce((acc, s) => acc + s.amountAtomics, 0n);
+ const maxAtomics = priceable.reduce((acc, s) => (s.amountAtomics > acc ? s.amountAtomics : acc), 0n);
+
+ const hosts = [...new Set(priceable.map((s) => normalizeHost(s.url)).filter(Boolean))];
+ const covered = (host) =>
+ policy.allowedHosts.length === 0 || policy.allowedHosts.some((entry) => hostMatches(host, entry));
+ const missingHosts = hosts.filter((h) => !covered(h));
+
+ const { MIN_BUDGET_USD, MAX_BUDGET_USD } = SESSION_LIMITS;
+ // Round the recommended budget up to a whole cent: a budget of exactly the
+ // summed cost leaves no room for a price that moves between now and the run.
+ const exactUsd = atomicsToUsd(totalAtomics);
+ const roundedUsd = Math.min(MAX_BUDGET_USD, Math.max(MIN_BUDGET_USD, Math.ceil(exactUsd * 100) / 100));
+
+ return {
+ budget_usd: roundedUsd,
+ exact_cost_usd: exactUsd,
+ max_per_tx_usd: maxAtomics > 0n ? atomicsToUsd(maxAtomics) : null,
+ allowed_hosts: hosts,
+ missing_hosts: missingHosts,
+ network: policy.network,
+ expiry_seconds: policy.expirySeconds,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (req.method?.toUpperCase() !== 'POST') {
+ return error(res, 405, 'method_not_allowed', 'POST required');
+ }
+
+ // Unauthenticated on purpose: evaluating the governance model should not
+ // require an account, and the simulation cannot move money. It does make
+ // outbound requests, so it is rate limited like any other fan-out endpoint.
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req, res);
+ if (!body) return;
+
+ let calls;
+ try {
+ calls = parseCalls(body.calls);
+ } catch (err) {
+ return bad(res, err.code ?? 'invalid_calls', err.message);
+ }
+
+ const policy = parsePolicy(body.policy ?? body);
+ const t0 = Date.now();
+
+ const priced = await priceEndpoints(calls, policy.network);
+ const { steps, problems } = buildSteps(calls, priced, policy.network);
+
+ // Replay only the calls that have a real price. The unpriced ones are
+ // reported separately so a probe failure never masquerades as a policy pass.
+ const replayInput = steps.filter((s) => s.priceable);
+ const expiresAt = new Date(Date.now() + policy.expirySeconds * 1000);
+ const { steps: verdicts, spentAtomics, remainingAtomics } = replay(
+ replayInput.map((s) => ({ url: s.url, amountAtomics: s.amountAtomics, ref: s })),
+ {
+ budgetAtomics: usdToAtomics(policy.budgetUsd),
+ maxPerTxAtomics: policy.maxPerTxUsd == null ? null : usdToAtomics(policy.maxPerTxUsd),
+ allowedHosts: policy.allowedHosts,
+ status: 'active',
+ expiresAt,
+ },
+ );
+
+ const verdictByStep = new Map(verdicts.map((v) => [v.call.ref, v]));
+ let firstDenialIndex = null;
+
+ const timeline = steps.map((step, index) => {
+ const verdict = verdictByStep.get(step);
+ const outcome = step.free
+ ? 'free'
+ : !step.priceable
+ ? 'unpriced'
+ : verdict.allowed
+ ? 'settles'
+ : 'refused';
+ if (outcome === 'refused' && firstDenialIndex === null) firstDenialIndex = index;
+ return {
+ index,
+ url: step.url,
+ host: normalizeHost(step.url),
+ method: step.method,
+ label: step.label,
+ repetition: step.repetition,
+ of: step.of,
+ outcome,
+ amount_usd: step.free ? 0 : step.priceable ? atomicsToUsd(step.amountAtomics) : null,
+ pricing: step.pricing,
+ rejected_by: verdict?.rejection?.code ?? null,
+ reason: verdict?.rejection?.message ?? null,
+ detail: verdict?.rejection?.detail ?? null,
+ remaining_after_usd: verdict ? atomicsToUsd(verdict.remainingAfterAtomics) : null,
+ };
+ });
+
+ const settled = timeline.filter((s) => s.outcome === 'settles');
+ const refused = timeline.filter((s) => s.outcome === 'refused');
+ const free = timeline.filter((s) => s.outcome === 'free');
+ const unpriced = timeline.filter((s) => s.outcome === 'unpriced');
+
+ // Group refusals by rule so the caller sees "the allowlist blocked 6 calls",
+ // not six near-identical rows they have to read one at a time.
+ const byRule = {};
+ for (const s of refused) byRule[s.rejected_by] = (byRule[s.rejected_by] ?? 0) + 1;
+
+ const suggestion = recommend(steps, policy);
+ const feasible = refused.length === 0 && problems.length === 0;
+
+ return json(res, 200, {
+ ok: true,
+ simulated: true,
+ note: 'Dry run only. Nothing was signed, no session was created, and no credits were spent.',
+ policy: {
+ budget_usd: policy.budgetUsd,
+ max_per_tx_usd: policy.maxPerTxUsd,
+ allowed_hosts: policy.allowedHosts,
+ expiry_seconds: policy.expirySeconds,
+ network: policy.network,
+ notes: policy.notes,
+ },
+ verdict: {
+ feasible,
+ calls_total: timeline.length,
+ calls_settled: settled.length,
+ calls_refused: refused.length,
+ calls_free: free.length,
+ calls_unpriced: unpriced.length,
+ refusals_by_rule: byRule,
+ first_refusal_index: firstDenialIndex,
+ spend_usd: atomicsToUsd(spentAtomics),
+ remaining_usd: atomicsToUsd(remainingAtomics),
+ budget_used_pct:
+ policy.budgetUsd > 0
+ ? Math.round((atomicsToUsd(spentAtomics) / policy.budgetUsd) * 1000) / 10
+ : 0,
+ },
+ timeline,
+ problems,
+ recommended_policy: suggestion,
+ // Ready to paste: the exact create call that would run this workload.
+ create_request: {
+ endpoint: 'POST /api/pay/session',
+ body: {
+ budget_usd: suggestion.budget_usd,
+ max_per_tx_usd: suggestion.max_per_tx_usd,
+ allowed_hosts: suggestion.allowed_hosts,
+ expiry_seconds: suggestion.expiry_seconds,
+ network: suggestion.network,
+ },
+ },
+ duration_ms: Date.now() - t0,
+ });
+});
diff --git a/api/pulse.js b/api/pulse.js
index 144e1057f..f13d78c6b 100644
--- a/api/pulse.js
+++ b/api/pulse.js
@@ -26,6 +26,7 @@
// GET /api/pulse?view=stats — aggregate money intelligence
// GET /api/pulse?view=marketplace — marketplace commerce viability metrics
// GET /api/pulse?view=trading — trading viability: activity, cost, realized P&L
+// GET /api/pulse?view=graph&window=… — money-flow topology: who paid whom, for what
// GET /api/pulse?view=agent-summary&agent_id=<id> — one wallet's lifetime summary
//
// Filters: type=all|tips|launches|trades|payments, network=mainnet|devnet.
@@ -39,6 +40,7 @@ import { explorerTxUrl, explorerAccountUrl } from './_lib/avatar-wallet.js';
import { cacheGet, cacheSet } from './_lib/cache.js';
import { marketplaceFeeBps } from './_lib/marketplace-platform-fee.js';
import { shapeTradingWindow, shapeTradingPnl, shapeTradingSeries, solFromLamports } from './_lib/pulse-trading.js';
+import { MARKET_PAID_KINDS } from './_lib/marketplace-kinds.js';
// The custody categories that are safe to surface publicly. Everything else
// (withdraw, vanity_swap, limit_change, key_recover) is owner-private and is
@@ -56,7 +58,6 @@ const FEED_SPEND_CATEGORIES = [...PUBLIC_SPEND_CATEGORIES, 'marketplace'];
// "paid" only when status='confirmed' and it's not a free trial.
const THREE_MINT = process.env.THREE_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const THREE_DECIMALS = 6;
-const MARKET_PAID_KINDS = ['purchase', 'time_pass'];
// atomic $THREE → whole-token float (keeps the fractional part Number-division gives).
const threeFromAtomic = (atomic) => Number(atomic || 0) / 10 ** THREE_DECIMALS;
@@ -342,6 +343,231 @@ async function handleFeed(req, res, { network, type, agentId, mint, cursor, sinc
};
}
+// ── money-flow graph view ─────────────────────────────────────────────────────
+// The TOPOLOGY of the agent economy: who paid whom, for what, and how much.
+//
+// Every other economy surface here is a leaderboard: totals per agent, ranked.
+// A ranking cannot show the shape of the flow, and the shape is what diagnoses
+// the platform's real failure mode. Capital dispersion looks perfectly healthy
+// on a leaderboard (busy agents, real volume) while the money is in fact
+// draining one-way into wallets that receive and never spend again. On a graph
+// that is a glance: a node with inbound edges and no outbound ones.
+//
+// Two edge sources, both already-public on-chain movements with an
+// explorer-verifiable signature. There is no third "estimated" or "inferred"
+// edge type; if the platform is quiet the graph is honestly empty.
+//
+// · agent-to-agent x402 payments — the row's agent SPENT, meta.to is the payee
+// wallet and meta.service names the skill that was bought.
+// · tips — the row's agent RECEIVED, meta.from is the payer wallet.
+//
+// Marketplace purchases are deliberately excluded: they settle in $THREE from a
+// human buyer, so they are not an agent-to-agent edge and would silently mix a
+// second denomination into the USD flow totals.
+//
+// Privacy: identical gate to the live feed on the side we own (no deleted, no
+// private, no pulse_opt_out). A counterparty wallet is named ONLY when it
+// resolves to a public agent; anything else stays an address-only node, which is
+// exactly what the feed already exposes as `counterparty`.
+const GRAPH_WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days', '90d': '90 days' };
+const GRAPH_TTL_S = 60;
+// Aggregated edges are ranked by value, so the cap keeps the biggest flows. When
+// it bites we say so in the payload rather than presenting a truncated graph as
+// the whole economy.
+const GRAPH_MAX_EDGES = 400;
+
+const shortAddr = (a) => (a && a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
+
+async function handleGraph(network, windowKey) {
+ const interval = GRAPH_WINDOWS[windowKey] || GRAPH_WINDOWS['30d'];
+ const pubAgent = sql`deleted_at IS NULL AND is_public = true
+ AND COALESCE((meta->>'pulse_opt_out')::boolean, false) = false`;
+
+ // One directed-transfer CTE, then aggregate to edges. Counterparty resolution
+ // runs through a LATERAL with LIMIT 1 so two identities sharing a wallet can
+ // never fan a single payment into two edges.
+ const rows = await sql`
+ WITH transfers AS (
+ SELECT
+ ce.created_at AS ts,
+ 'payment'::text AS kind,
+ payer.id::text AS from_agent,
+ NULL::text AS from_addr,
+ payee.id AS to_agent,
+ ce.meta->>'to' AS to_addr,
+ ce.amount_lamports AS lamports,
+ ce.usd AS usd,
+ ce.signature AS signature,
+ NULLIF(ce.meta->>'service', '') AS service
+ FROM agent_custody_events ce
+ JOIN agent_identities payer
+ ON payer.id = ce.agent_id
+ AND payer.deleted_at IS NULL AND payer.is_public = true
+ AND COALESCE((payer.meta->>'pulse_opt_out')::boolean, false) = false
+ LEFT JOIN LATERAL (
+ SELECT ai.id::text AS id FROM agent_identities ai
+ WHERE ai.meta->>'solana_address' = ce.meta->>'to' AND ${pubAgent}
+ LIMIT 1
+ ) payee ON true
+ WHERE ce.network = ${network}
+ AND ce.event_type = 'spend' AND ce.category = 'x402'
+ AND ce.status IN ('ok', 'confirmed')
+ AND NULLIF(ce.meta->>'to', '') IS NOT NULL
+ AND ce.created_at > now() - ${interval}::interval
+
+ UNION ALL
+
+ SELECT
+ ce.created_at, 'tip'::text,
+ tipper.id, ce.meta->>'from',
+ recv.id::text, NULL::text,
+ ce.amount_lamports, ce.usd, ce.signature, NULL::text
+ FROM agent_custody_events ce
+ JOIN agent_identities recv
+ ON recv.id = ce.agent_id
+ AND recv.deleted_at IS NULL AND recv.is_public = true
+ AND COALESCE((recv.meta->>'pulse_opt_out')::boolean, false) = false
+ LEFT JOIN LATERAL (
+ SELECT ai.id::text AS id FROM agent_identities ai
+ WHERE ai.meta->>'solana_address' = ce.meta->>'from' AND ${pubAgent}
+ LIMIT 1
+ ) tipper ON true
+ WHERE ce.network = ${network}
+ AND ce.event_type = 'tip'
+ AND ce.status IN ('ok', 'confirmed')
+ AND NULLIF(ce.meta->>'from', '') IS NOT NULL
+ AND ce.created_at > now() - ${interval}::interval
+ )
+ SELECT
+ COALESCE('a:' || from_agent, 'w:' || from_addr) AS from_key,
+ COALESCE('a:' || to_agent, 'w:' || to_addr) AS to_key,
+ from_agent, to_agent, from_addr, to_addr,
+ COUNT(*)::int AS count,
+ COALESCE(SUM(lamports), 0)::text AS lamports,
+ COALESCE(SUM(usd), 0)::float8 AS usd,
+ MAX(ts) AS last_ts,
+ (ARRAY_AGG(signature ORDER BY ts DESC))[1] AS last_signature,
+ ARRAY_REMOVE(ARRAY_AGG(DISTINCT kind), NULL) AS kinds,
+ ARRAY_REMOVE(ARRAY_AGG(DISTINCT service), NULL) AS services
+ FROM transfers
+ WHERE COALESCE(from_agent, from_addr) IS NOT NULL
+ AND COALESCE(to_agent, to_addr) IS NOT NULL
+ GROUP BY 1, 2, from_agent, to_agent, from_addr, to_addr
+ ORDER BY usd DESC, count DESC
+ LIMIT ${GRAPH_MAX_EDGES + 1}
+ `;
+
+ const truncated = rows.length > GRAPH_MAX_EDGES;
+ const edgeRows = truncated ? rows.slice(0, GRAPH_MAX_EDGES) : rows;
+
+ // Name the agent nodes in one round trip. Only ids that survived the public
+ // gate above reach here, so this join adds no new disclosure.
+ const agentIds = [
+ ...new Set(edgeRows.flatMap((r) => [r.from_agent, r.to_agent]).filter(Boolean)),
+ ];
+ const agentRows = agentIds.length
+ ? await sql`
+ SELECT ai.id::text AS id, ai.name, ai.meta->>'solana_address' AS addr,
+ av.thumbnail_key AS thumb_key, av.visibility AS avatar_vis
+ FROM agent_identities ai
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ai.id::text = ANY(${agentIds})
+ `
+ : [];
+ const agentById = new Map(agentRows.map((a) => [a.id, a]));
+
+ // Assemble nodes from the edges so the two collections can never disagree.
+ const nodes = new Map();
+ const nodeFor = (key, agentId, addr) => {
+ const existing = nodes.get(key);
+ if (existing) return existing;
+ const agent = agentId ? agentById.get(agentId) : null;
+ const address = agent?.addr || addr || null;
+ const node = {
+ id: key,
+ kind: agent ? 'agent' : 'wallet',
+ agent_id: agent?.id || null,
+ name: agent?.name || shortAddr(addr),
+ url: agent ? `/agent/${agent.id}` : null,
+ avatar_thumbnail_url: agent
+ ? r2Url(agent.thumb_key, agent.avatar_vis === 'public' || agent.avatar_vis === 'unlisted')
+ : null,
+ address,
+ address_short: shortAddr(address),
+ explorer: address ? explorerAccountUrl(address, network) : null,
+ in_usd: 0, out_usd: 0, in_sol: 0, out_sol: 0, in_count: 0, out_count: 0,
+ partners_in: 0, partners_out: 0,
+ };
+ nodes.set(key, node);
+ return node;
+ };
+
+ // Service totals come from their own aggregation, never from the edges: one
+ // edge can cover several skills, so folding its USD into each of them would
+ // report more revenue per service than actually settled.
+ const serviceRows = await sql`
+ SELECT NULLIF(ce.meta->>'service', '') AS name,
+ COUNT(*)::int AS count,
+ COALESCE(SUM(ce.usd), 0)::float8 AS usd
+ FROM agent_custody_events ce
+ JOIN agent_identities payer
+ ON payer.id = ce.agent_id
+ AND payer.deleted_at IS NULL AND payer.is_public = true
+ AND COALESCE((payer.meta->>'pulse_opt_out')::boolean, false) = false
+ WHERE ce.network = ${network}
+ AND ce.event_type = 'spend' AND ce.category = 'x402'
+ AND ce.status IN ('ok', 'confirmed')
+ AND NULLIF(ce.meta->>'service', '') IS NOT NULL
+ AND ce.created_at > now() - ${interval}::interval
+ GROUP BY 1
+ ORDER BY usd DESC
+ `;
+
+ const edges = edgeRows.map((r) => {
+ const sol = Number(r.lamports || 0) / 1e9;
+ const usd = Number(r.usd || 0);
+ const from = nodeFor(r.from_key, r.from_agent, r.from_addr);
+ const to = nodeFor(r.to_key, r.to_agent, r.to_addr);
+ from.out_usd += usd; from.out_sol += sol; from.out_count += r.count; from.partners_out += 1;
+ to.in_usd += usd; to.in_sol += sol; to.in_count += r.count; to.partners_in += 1;
+ return {
+ from: r.from_key,
+ to: r.to_key,
+ count: r.count,
+ sol,
+ usd,
+ kinds: r.kinds || [],
+ services: r.services || [],
+ last_ts: r.last_ts,
+ last_signature: r.last_signature || null,
+ explorer: r.last_signature ? explorerTxUrl(r.last_signature, network) : null,
+ };
+ });
+
+ const nodeList = [...nodes.values()];
+ return {
+ network,
+ window: GRAPH_WINDOWS[windowKey] ? windowKey : '30d',
+ generated_at: new Date().toISOString(),
+ nodes: nodeList,
+ edges,
+ services: serviceRows.map((s) => ({ name: s.name, count: s.count, usd: Number(s.usd || 0) })),
+ totals: {
+ nodes: nodeList.length,
+ edges: edges.length,
+ transfers: edges.reduce((n, e) => n + e.count, 0),
+ usd: edges.reduce((n, e) => n + e.usd, 0),
+ sol: edges.reduce((n, e) => n + e.sol, 0),
+ payments: edges.filter((e) => e.kinds.includes('payment')).reduce((n, e) => n + e.count, 0),
+ tips: edges.filter((e) => e.kinds.includes('tip')).reduce((n, e) => n + e.count, 0),
+ named_agents: nodeList.filter((n) => n.kind === 'agent').length,
+ },
+ // Honest about its own limits: a capped graph must never read as the whole economy.
+ truncated,
+ max_edges: GRAPH_MAX_EDGES,
+ };
+}
+
// ── aggregate stats view ──────────────────────────────────────────────────────
async function handleStats(network) {
// Public-agent gate, reused across every aggregate below so each counter honours
@@ -994,6 +1220,20 @@ export default async function handler(req, res) {
return json(res, 200, { data: body });
}
+ if (view === 'graph') {
+ const windowKey = GRAPH_WINDOWS[url.searchParams.get('window')]
+ ? url.searchParams.get('window')
+ : '30d';
+ const cacheKey = `pulse:graph:${network}:${windowKey}`;
+ let body = await cacheGet(cacheKey);
+ if (body === null) {
+ body = await handleGraph(network, windowKey);
+ await cacheSet(cacheKey, body, GRAPH_TTL_S);
+ }
+ res.setHeader('cache-control', 'public, max-age=30');
+ return json(res, 200, { data: body });
+ }
+
if (view === 'agent-summary') {
if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required for agent-summary');
const body = await handleAgentSummary(network, agentId);
diff --git a/api/x402/runway-lab.js b/api/x402/runway-lab.js
new file mode 100644
index 000000000..e7987de72
--- /dev/null
+++ b/api/x402/runway-lab.js
@@ -0,0 +1,226 @@
+// GET /api/x402/runway-lab
+//
+// The live seed for /economy-lab: everything the settle path's admission
+// control depends on, read from the systems that actually enforce it.
+//
+// Nothing here is modelled or estimated where a real reading exists:
+//
+// • fee wallet + hard floor → ring-allowlist.js ringRoleWallets() and
+// self-facilitator.js SPONSOR_SOL_FLOOR_LAMPORTS,
+// the same constants the settle path enforces.
+// • live SOL balance → Solana RPC through the platform's lane-failover
+// connection, not a cached number.
+// • governor config → wallet-fee-governor.js walletFeeGovernorConfig()
+// over the running process env, so the lab shows
+// what THIS deploy is configured with.
+// • spent today → x402_self_facilitator_log, the exact SUM the
+// meter itself runs (wallet-fee-meter.js).
+// • fee per settle + demand → observed from the same log over 24h, so the
+// projection starts from measured behaviour
+// rather than a guessed arrival rate.
+// • refusal mix → reject_reason histogram, bucketed by cause, so
+// the page can show what the rail is ACTUALLY
+// refusing next to what the model predicts.
+//
+// Read-only and unauthenticated by design: every field is already public
+// through /api/x402-ring and /api/x402-status (balances of platform wallets,
+// config thresholds, aggregate settle counts). No secret, no key material, and
+// no per-user data is reachable from here.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { sql, isDbUnavailableError } from '../_lib/db.js';
+import { PublicKey } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
+import { ringRoleWallets } from '../_lib/x402/ring-allowlist.js';
+import { SPONSOR_SOL_FLOOR_LAMPORTS, SELF_FACILITATOR_ENABLED } from '../_lib/x402/self-facilitator.js';
+import { walletFeeGovernorConfig } from '../_lib/x402/wallet-fee-governor.js';
+import {
+ MIN_FEE_LAMPORTS,
+ LAMPORTS_PER_SOL,
+ equilibriumSettlesPerDay,
+} from '../_lib/x402/runway-sim.js';
+
+const WINDOW_HOURS = 24;
+
+// Map a raw reject_reason to the cause an operator can act on. The reasons are
+// prefixed strings with lamport detail appended (`fee_runway_exhausted:12+5>10`),
+// so bucket on the prefix and keep one verbatim example per bucket.
+function bucketReason(reason) {
+ const r = String(reason || '');
+ if (r.startsWith('fee_runway_exhausted')) return 'governor';
+ if (r.startsWith('fee_wallet_below_floor')) return 'floor';
+ if (r.startsWith('insufficient_lamports_for_fee')) return 'floor';
+ if (r.startsWith('amount_below_min_settle')) return 'dust_guard';
+ // Idempotency, not scarcity: the payment already landed and a retry hit the
+ // unique-signature guard (migration 20260729000000). Counted separately
+ // because folding it into the refusal total makes a healthy rail read as a
+ // starved one — on 2026-07-31 it was 3,470 of 9,504 "refusals".
+ if (r.startsWith('signature_already_settled')) return 'duplicate';
+ if (!r) return 'unspecified';
+ return 'other';
+}
+
+// Which buckets mean "the rail could not afford this settle". Duplicates and the
+// dust guard are working-as-intended rejections, so the capacity view must not
+// count them against admission.
+const CAPACITY_CAUSES = new Set(['governor', 'floor']);
+
+// Live SOL for one pubkey. A null result means "not read", never "zero" — the
+// page must not draw a starvation conclusion from an RPC failure.
+async function solLamportsOf(address) {
+ if (!address) return null;
+ try {
+ const connection = solanaConnection('mainnet');
+ return await connection.getBalance(new PublicKey(address), 'confirmed');
+ } catch {
+ return null;
+ }
+}
+
+// The meter's own query, verbatim in intent: today's summed fee burn for the
+// fee wallet over successful settles.
+async function spentTodayLamports(feeWallet) {
+ if (!feeWallet) return null;
+ const rows = await sql`
+ SELECT COALESCE(SUM(fee_lamports), 0)::bigint AS spent
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ok = true
+ AND fee_payer = ${feeWallet}
+ AND ts >= date_trunc('day', now() at time zone 'utc')
+ `;
+ return Number(rows?.[0]?.spent ?? 0);
+}
+
+// Observed behaviour over the window: how often settles are attempted, how many
+// land, what a landed settle costs, and why the rest were refused.
+async function observeWindow() {
+ const since = new Date(Date.now() - WINDOW_HOURS * 3600_000).toISOString();
+
+ const [totals] = await sql`
+ SELECT
+ COUNT(*)::int AS attempts,
+ COUNT(*) FILTER (WHERE ok)::int AS settled,
+ COALESCE(SUM(fee_lamports) FILTER (WHERE ok), 0)::bigint AS fee_total,
+ COALESCE(
+ PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY fee_lamports)
+ FILTER (WHERE ok AND fee_lamports > 0), 0)::bigint AS fee_median
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ts >= ${since}
+ `;
+
+ const reasons = await sql`
+ SELECT reject_reason, COUNT(*)::int AS n
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ok = false AND ts >= ${since}
+ GROUP BY reject_reason
+ ORDER BY n DESC
+ LIMIT 40
+ `;
+
+ const buckets = new Map();
+ for (const row of reasons) {
+ const key = bucketReason(row.reject_reason);
+ const hit = buckets.get(key) || { cause: key, count: 0, example: null };
+ hit.count += Number(row.n) || 0;
+ if (!hit.example) hit.example = row.reject_reason || null;
+ buckets.set(key, hit);
+ }
+
+ const attempts = Number(totals?.attempts ?? 0);
+ const settled = Number(totals?.settled ?? 0);
+ const feeMedian = Number(totals?.fee_median ?? 0);
+
+ return {
+ window_hours: WINDOW_HOURS,
+ attempts,
+ settled,
+ refused: attempts - settled,
+ admission_rate: attempts > 0 ? settled / attempts : null,
+ fee_total_lamports: Number(totals?.fee_total ?? 0),
+ // Median over landed settles is the honest per-settle cost: the mean is
+ // dragged by the occasional multi-signature transaction.
+ fee_lamports_observed: feeMedian > 0 ? feeMedian : MIN_FEE_LAMPORTS,
+ fee_source: feeMedian > 0 ? 'observed_median_24h' : 'base_fee_default',
+ demand_per_hour: Math.round(attempts / WINDOW_HOURS),
+ refusals: [...buckets.values()].sort((a, b) => b.count - a.count),
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const roles = await ringRoleWallets();
+ // The wallet the governor actually meters is whichever one pays the fee. In
+ // sponsor mode that is the sponsor; the payer only pays its own fee when
+ // X402_RING_SELF_PAY is on, and the sponsor is still the shared-tenant wallet
+ // the starvation math is about.
+ const feeWallet = roles.sponsor || roles.payer || null;
+ const cfg = walletFeeGovernorConfig();
+
+ const [sponsorLamports, payerLamports] = await Promise.all([
+ solLamportsOf(feeWallet),
+ roles.payer && roles.payer !== feeWallet ? solLamportsOf(roles.payer) : Promise.resolve(null),
+ ]);
+
+ let spent_today_lamports = null;
+ let observed = null;
+ let db_error = null;
+ try {
+ [spent_today_lamports, observed] = await Promise.all([
+ spentTodayLamports(feeWallet),
+ observeWindow(),
+ ]);
+ } catch (err) {
+ // A DB outage must not blank the page: the config and the live balance are
+ // still enough to seed a projection, and the page says what is missing.
+ db_error = isDbUnavailableError(err) ? 'database_unavailable' : 'ledger_read_failed';
+ }
+
+ const spendable =
+ sponsorLamports != null ? Math.max(0, sponsorLamports - SPONSOR_SOL_FLOOR_LAMPORTS) : null;
+
+ json(res, 200, {
+ ok: true,
+ generated_at: new Date().toISOString(),
+ self_facilitator_enabled: SELF_FACILITATOR_ENABLED,
+ fee_wallet: {
+ role: roles.sponsor ? 'sponsor' : roles.payer ? 'payer' : null,
+ address: feeWallet,
+ sol_lamports: sponsorLamports,
+ sol: sponsorLamports != null ? sponsorLamports / LAMPORTS_PER_SOL : null,
+ spendable_lamports: spendable,
+ balance_read: sponsorLamports != null,
+ },
+ payer_wallet: roles.payer && roles.payer !== feeWallet
+ ? { address: roles.payer, sol_lamports: payerLamports }
+ : null,
+ treasury: roles.treasury || null,
+ config: {
+ // The exact env names the lab emits a change command for.
+ floor_lamports: SPONSOR_SOL_FLOOR_LAMPORTS, // X402_SPONSOR_SOL_FLOOR_LAMPORTS
+ runway_days: cfg.runwayDays, // X402_WALLET_FEE_RUNWAY_DAYS
+ min_budget_lamports: cfg.minBudgetLamports, // X402_WALLET_FEE_MIN_BUDGET_LAMPORTS
+ governor_enabled: cfg.enabled, // X402_WALLET_FEE_GOVERNOR_ENABLED
+ spent_cache_ms: cfg.spentCacheMs,
+ },
+ meter: {
+ spent_today_lamports,
+ utc_hour: new Date().getUTCHours(),
+ },
+ // The closed-form throughput this configuration delivers at the live
+ // balance, so the headline number is available even before the browser
+ // runs a projection.
+ projected_settles_per_day:
+ spendable != null
+ ? equilibriumSettlesPerDay({
+ spendableLamports: spendable,
+ feeLamports: observed?.fee_lamports_observed ?? MIN_FEE_LAMPORTS,
+ runwayDays: cfg.runwayDays,
+ minBudgetLamports: cfg.enabled ? cfg.minBudgetLamports : Number.MAX_SAFE_INTEGER,
+ })
+ : null,
+ observed,
+ db_error,
+ }, { 'Cache-Control': 'public, max-age=20, s-maxage=20' });
+});
diff --git a/pages/admin/economy.html b/pages/admin/economy.html
index 3ad5b6168..c6b636596 100644
--- a/pages/admin/economy.html
+++ b/pages/admin/economy.html
@@ -20,11 +20,11 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex, nofollow" />
- <title>Economy Health · Control · three.ws</title>
+ <title data-i18n="admin_economy.meta_title">Economy Health · Control · three.ws</title>
<meta
name="description"
content="Operator dashboard for the autonomous economy: one-line verdict on why the Money Pulse is quiet, the funding chain from master to agents, per-lane settle rates, and the USDC refuel lane."
- />
+ data-i18n-attr="content:admin_economy.meta_description"/>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/src/admin-economy.css" />
</head>
@@ -36,8 +36,8 @@
<!-- Auth gate -->
<section class="ec-gate" id="ec-gate" hidden>
<div class="ec-gate-mark" aria-hidden="true">◈</div>
- <h1>Economy Health</h1>
- <p>Operator control. Enter the secret to read the funding chain.</p>
+ <h1 data-i18n="admin_economy.economy_health">Economy Health</h1>
+ <p data-i18n="admin_economy.operator_control_enter_the_secret_to_read">Operator control. Enter the secret to read the funding chain.</p>
<form id="ec-gate-form" autocomplete="off">
<input
type="password"
@@ -47,7 +47,7 @@
aria-label="Operator secret"
autocomplete="current-password"
/>
- <button type="submit" class="ec-btn ec-btn-primary">Unlock</button>
+ <button type="submit" class="ec-btn ec-btn-primary" data-i18n="admin_economy.unlock">Unlock</button>
<p class="ec-gate-err" id="ec-gate-err" role="alert" aria-live="assertive"></p>
</form>
</section>
@@ -56,30 +56,30 @@
<div id="ec-panel" hidden>
<div class="ec-head">
<div>
- <h1>Economy Health</h1>
- <p>
+ <h1 data-i18n="admin_economy.economy_health_2">Economy Health</h1>
+ <p data-i18n="admin_economy.why_the_money_pulse_is_loud_or">
Why the Money Pulse is loud or quiet, read from the same endpoints the
crons use. Every number is a live read; nothing here can move funds.
</p>
</div>
<div class="ec-head-actions">
<span class="ec-stamp" id="ec-stamp" aria-live="polite"></span>
- <button type="button" class="ec-btn" id="ec-refresh">Refresh</button>
- <button type="button" class="ec-btn" id="ec-pause" aria-pressed="false">Pause</button>
+ <button type="button" class="ec-btn" id="ec-refresh" data-i18n="admin_economy.refresh">Refresh</button>
+ <button type="button" class="ec-btn" id="ec-pause" aria-pressed="false" data-i18n="admin_economy.pause">Pause</button>
</div>
</div>
<section class="ec-verdict" id="ec-verdict" data-level="warn" role="status" aria-live="polite" hidden>
<span class="ec-verdict-dot" aria-hidden="true"></span>
<div>
- <h2 id="ec-verdict-title">Reading the economy…</h2>
+ <h2 id="ec-verdict-title" data-i18n="admin_economy.reading_the_economy">Reading the economy…</h2>
<p id="ec-verdict-detail"></p>
</div>
</section>
<section class="ec-section">
- <h2>Money Pulse · last 24h</h2>
- <p class="ec-sub">
+ <h2 data-i18n="admin_economy.money_pulse_last_24h">Money Pulse · last 24h</h2>
+ <p class="ec-sub" data-i18n-html="admin_economy.real_settled_movement_from_free_actions_such">
Real settled movement from <code>/api/pulse</code>. Free actions such as
reviews and trials are deliberately excluded: they stay healthy through
exactly the outage this page exists to catch.
@@ -88,14 +88,14 @@
</section>
<section class="ec-section">
- <h2>Funding chain</h2>
+ <h2 data-i18n="admin_economy.funding_chain">Funding chain</h2>
<p class="ec-sub" id="ec-chain-summary"></p>
<div class="ec-chain" id="ec-chain"></div>
</section>
<section class="ec-section">
- <h2>Circulation engine</h2>
- <p class="ec-sub">
+ <h2 data-i18n="admin_economy.circulation_engine">Circulation engine</h2>
+ <p class="ec-sub" data-i18n="admin_economy.the_agent_pool_and_its_tick_cadence">
The agent pool and its tick cadence. A healthy action count with zero paid
lanes below is the signature of a treasury under its reserve.
</p>
@@ -103,8 +103,8 @@
</section>
<section class="ec-section">
- <h2>Action lanes · last 24h</h2>
- <p class="ec-sub">
+ <h2 data-i18n="admin_economy.action_lanes_last_24h">Action lanes · last 24h</h2>
+ <p class="ec-sub" data-i18n-html="admin_economy.per_kind_settle_rate_never_ran_means">
Per-kind settle rate. <b>Never ran</b> means the budget governor never
planned it, which is a funding problem. <b>All failing</b> means it was
planned and rejected, which is not.
@@ -113,8 +113,8 @@
</section>
<section class="ec-section">
- <h2>USDC refuel lane</h2>
- <p class="ec-sub">
+ <h2 data-i18n="admin_economy.usdc_refuel_lane">USDC refuel lane</h2>
+ <p class="ec-sub" data-i18n="admin_economy.when_the_chain_runs_short_the_master">
When the chain runs short the master converts a bounded slice of its own
USDC revenue into SOL, so recovery does not wait on a human.
</p>
@@ -123,32 +123,32 @@
</section>
<section class="ec-section">
- <h2>If the pulse is quiet</h2>
- <p class="ec-sub">
+ <h2 data-i18n="admin_economy.if_the_pulse_is_quiet">If the pulse is quiet</h2>
+ <p class="ec-sub" data-i18n="admin_economy.the_order_matters_each_step_rules_out">
The order matters. Each step rules out a cause that would make every later
reading meaningless.
</p>
<ol class="ec-runbook">
- <li>
+ <li data-i18n-html="admin_economy.check_the_verdict_above_first_it_already">
<b>Check the verdict above first.</b> It already applies these rules to
live data and names the single most actionable cause.
</li>
- <li>
+ <li data-i18n-html="admin_economy.is_money_moving_at_all_volume_and">
<b>Is money moving at all?</b> Volume and trades near zero while the
activity feed looks busy means the free lanes are carrying the feed and
the paid lanes are dead.
</li>
- <li>
+ <li data-i18n-html="admin_economy.did_the_paid_lanes_ever_run_zero">
<b>Did the paid lanes ever run?</b> Zero <i>attempts</i> (not zero
successes) means the governor cut the paid budget because the
circulation treasury sat under its reserve.
</li>
- <li>
+ <li data-i18n-html="admin_economy.read_the_funding_chain_several_roles_can">
<b>Read the funding chain.</b> Several roles can share one wallet, so a
link can be starved while another role's lower floor reports it healthy.
Always compare against the strictest floor.
</li>
- <li>
+ <li data-i18n-html="admin_economy.separate_dry_from_unreadable_genuinely_needs">
<b>Separate "dry" from "unreadable".</b>
<code>no_spare_usdc</code> genuinely needs funding.
<code>usdc_read_failed</code> means an RPC lane broke and the balance is
@@ -158,9 +158,9 @@
</section>
<div class="ec-foot">
- <span>Reads: <code>/api/pulse</code>, <code>/api/admin/circulation-health</code>, <code>/api/cron/treasury-topup?dry=1</code></span>
- <a href="/admin/ring">Ring dashboard →</a>
- <a href="/pulse">Public Money Pulse →</a>
+ <span data-i18n-html="admin_economy.reads">Reads: <code>/api/pulse</code>, <code>/api/admin/circulation-health</code>, <code>/api/cron/treasury-topup?dry=1</code></span>
+ <a href="/admin/ring" data-i18n="admin_economy.ring_dashboard">Ring dashboard →</a>
+ <a href="/pulse" data-i18n="admin_economy.public_money_pulse">Public Money Pulse →</a>
</div>
</div>
</main>
@@ -170,5 +170,7 @@
</div>
<script type="module" src="/src/admin-economy.js"></script>
- </body>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+</body>
</html>
diff --git a/tests/payment-policy-simulator.test.js b/tests/payment-policy-simulator.test.js
new file mode 100644
index 000000000..6f047548e
--- /dev/null
+++ b/tests/payment-policy-simulator.test.js
@@ -0,0 +1,592 @@
+// Tests for the shared payment-policy core and the dry-run simulator.
+//
+// The whole value of /api/pay/simulate is that its answer is binding: if the
+// dry run says a call settles, the enforcer must settle it. That guarantee
+// rests on both surfaces importing api/_lib/pay/policy.js rather than each
+// implementing the rules. So this file tests the predicates directly, and then
+// adds a structural test asserting the governor still delegates to them, which
+// is the assertion that fails if a future change reintroduces a second copy.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import {
+ SESSION_LIMITS,
+ usdToAtomics,
+ atomicsToUsd,
+ normalizeHost,
+ canonicalizeAllowlist,
+ hostMatches,
+ statusVerdict,
+ expiryVerdict,
+ allowlistVerdict,
+ perTxVerdict,
+ budgetVerdict,
+ evaluateCall,
+ replay,
+} from '../api/_lib/pay/policy.js';
+
+import { describeRail, selectRail } from '../api/_lib/pay/probe.js';
+import { parseCalls, parsePolicy, buildSteps, recommend } from '../api/pay/simulate.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = resolve(here, '..');
+const read = (rel) => readFileSync(resolve(root, rel), 'utf8');
+
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const SOLANA_NET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+
+describe('USDC atomics', () => {
+ it('converts dollars to 6-decimal atomics', () => {
+ expect(usdToAtomics(1)).toBe(1_000_000n);
+ expect(usdToAtomics(0.001)).toBe(1000n);
+ expect(usdToAtomics(0.000001)).toBe(1n);
+ });
+
+ it('rounds sub-atomic amounts rather than truncating to zero', () => {
+ // $0.0000004 is below one atomic unit. Truncation would make it free.
+ expect(usdToAtomics(0.0000004)).toBe(0n);
+ expect(usdToAtomics(0.0000006)).toBe(1n);
+ });
+
+ it('round-trips through atomicsToUsd', () => {
+ for (const usd of [0.001, 0.25, 1, 12.5, 1000]) {
+ expect(atomicsToUsd(usdToAtomics(usd))).toBeCloseTo(usd, 9);
+ }
+ });
+});
+
+describe('host normalization', () => {
+ it('reduces URLs, ports, and casing to a bare hostname', () => {
+ expect(normalizeHost('https://API.Example.com/v1/data?x=1')).toBe('api.example.com');
+ expect(normalizeHost('example.com:8443')).toBe('example.com');
+ expect(normalizeHost(' Example.COM ')).toBe('example.com');
+ });
+
+ it('returns empty for junk instead of throwing', () => {
+ expect(normalizeHost('')).toBe('');
+ expect(normalizeHost(null)).toBe('');
+ expect(normalizeHost(undefined)).toBe('');
+ });
+
+ it('deduplicates and drops empties when canonicalizing an allowlist', () => {
+ expect(canonicalizeAllowlist(['https://a.com/x', 'A.com', '', null, 'b.com'])).toEqual([
+ 'a.com',
+ 'a.com',
+ 'b.com',
+ ]);
+ });
+});
+
+describe('hostMatches', () => {
+ it('accepts the exact host and true subdomains', () => {
+ expect(hostMatches('example.com', 'example.com')).toBe(true);
+ expect(hostMatches('api.example.com', 'example.com')).toBe(true);
+ expect(hostMatches('a.b.example.com', 'example.com')).toBe(true);
+ });
+
+ it('refuses a lookalike domain that merely ends in the allowed string', () => {
+ // The bug a bare endsWith() would ship: an attacker registers
+ // evil-example.com and inherits every allowlist naming example.com.
+ expect(hostMatches('evil-example.com', 'example.com')).toBe(false);
+ expect(hostMatches('notexample.com', 'example.com')).toBe(false);
+ });
+
+ it('refuses empty operands', () => {
+ expect(hostMatches('', 'example.com')).toBe(false);
+ expect(hostMatches('example.com', '')).toBe(false);
+ });
+});
+
+describe('individual policy verdicts', () => {
+ it('permits an active session and names the state otherwise', () => {
+ expect(statusVerdict('active')).toBeNull();
+ expect(statusVerdict('exhausted').code).toBe('session_inactive');
+ expect(statusVerdict('exhausted').message).toBe('Session budget is exhausted');
+ expect(statusVerdict('cancelled').message).toBe('Session has been cancelled');
+ expect(statusVerdict('expired').message).toBe('Session has expired');
+ expect(statusVerdict('weird').message).toBe('Session is weird');
+ });
+
+ it('rejects only a past expiry', () => {
+ const now = new Date('2026-07-31T00:00:00Z');
+ expect(expiryVerdict('2026-07-31T00:00:01Z', now)).toBeNull();
+ expect(expiryVerdict('2026-07-30T23:59:59Z', now).code).toBe('session_expired');
+ });
+
+ it('treats a null or unparseable expiry as no expiry rather than expired', () => {
+ // Failing open here is deliberate and safe: the budget still bounds spend,
+ // whereas failing closed would brick every session whose row lacks a TTL.
+ expect(expiryVerdict(null)).toBeNull();
+ expect(expiryVerdict('not a date')).toBeNull();
+ });
+
+ it('treats an empty allowlist as "any host"', () => {
+ expect(allowlistVerdict('https://anything.example/x', [])).toBeNull();
+ expect(allowlistVerdict('https://anything.example/x', null)).toBeNull();
+ });
+
+ it('blocks a host that is not on a non-empty allowlist', () => {
+ const v = allowlistVerdict('https://evil.test/x', ['example.com']);
+ expect(v.code).toBe('allowlist_blocked');
+ expect(v.detail).toEqual({ host: 'evil.test', allowlist: ['example.com'] });
+ });
+
+ it('allows a subdomain of an allowlisted domain', () => {
+ expect(allowlistVerdict('https://api.example.com/x', ['example.com'])).toBeNull();
+ });
+
+ it('reports an unparseable target URL as a block, never as a pass', () => {
+ const v = allowlistVerdict('not-a-url', ['example.com']);
+ expect(v.code).toBe('allowlist_blocked');
+ expect(v.message).toContain('Invalid target URL');
+ });
+
+ it('enforces the per-transaction ceiling at the boundary', () => {
+ expect(perTxVerdict(500_000n, 500_000n)).toBeNull(); // exactly at the cap passes
+ const v = perTxVerdict(500_001n, 500_000n);
+ expect(v.code).toBe('per_tx_exceeded');
+ expect(v.detail).toEqual({ amount_usd: 0.500001, cap_usd: 0.5 });
+ });
+
+ it('treats a null ceiling as uncapped', () => {
+ expect(perTxVerdict(999_000_000n, null)).toBeNull();
+ });
+
+ it('enforces the budget at the boundary', () => {
+ expect(budgetVerdict(1000n, 1000n)).toBeNull();
+ const v = budgetVerdict(1001n, 1000n);
+ expect(v.code).toBe('insufficient_budget');
+ expect(v.detail).toEqual({ need_usd: 0.001001, remaining_usd: 0.001 });
+ });
+});
+
+describe('evaluateCall rule ordering', () => {
+ const base = {
+ url: 'https://blocked.test/x',
+ amountAtomics: 10_000_000n,
+ policy: {
+ status: 'active',
+ expiresAt: new Date(Date.now() + 60_000),
+ allowedHosts: ['example.com'],
+ maxPerTxAtomics: 1n,
+ },
+ remainingAtomics: 0n,
+ };
+
+ it('reports the allowlist before the ceiling and the budget', () => {
+ // All three rules would reject this call. Reporting the budget first would
+ // send the user to fund a session that still could not reach the host.
+ expect(evaluateCall(base).code).toBe('allowlist_blocked');
+ });
+
+ it('reports the ceiling before the budget', () => {
+ const v = evaluateCall({ ...base, url: 'https://example.com/x' });
+ expect(v.code).toBe('per_tx_exceeded');
+ });
+
+ it('reports state before everything else', () => {
+ const v = evaluateCall({ ...base, policy: { ...base.policy, status: 'cancelled' } });
+ expect(v.code).toBe('session_inactive');
+ });
+
+ it('reports expiry before the allowlist', () => {
+ const v = evaluateCall({
+ ...base,
+ policy: { ...base.policy, expiresAt: new Date(Date.now() - 1000) },
+ });
+ expect(v.code).toBe('session_expired');
+ });
+
+ it('returns null when every rule permits the call', () => {
+ expect(
+ evaluateCall({
+ url: 'https://api.example.com/x',
+ amountAtomics: 1000n,
+ policy: {
+ status: 'active',
+ expiresAt: new Date(Date.now() + 60_000),
+ allowedHosts: ['example.com'],
+ maxPerTxAtomics: 5000n,
+ },
+ remainingAtomics: 5000n,
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('replay', () => {
+ const policy = {
+ budgetAtomics: 10_000n, // $0.01
+ maxPerTxAtomics: null,
+ allowedHosts: [],
+ status: 'active',
+ expiresAt: null,
+ };
+ const call = (n) => ({ url: `https://example.com/${n}`, amountAtomics: 3000n });
+
+ it('spends down the budget across the sequence', () => {
+ const out = replay([call(1), call(2), call(3)], policy);
+ expect(out.steps.every((s) => s.allowed)).toBe(true);
+ expect(out.spentAtomics).toBe(9000n);
+ expect(out.remainingAtomics).toBe(1000n);
+ });
+
+ it('refuses exactly the call that no longer fits, and every one after it', () => {
+ const out = replay([call(1), call(2), call(3), call(4), call(5)], policy);
+ expect(out.steps.map((s) => s.allowed)).toEqual([true, true, true, false, false]);
+ expect(out.steps[3].rejection.code).toBe('insufficient_budget');
+ expect(out.spentAtomics).toBe(9000n);
+ });
+
+ it('lets a cheaper later call through after an expensive one is refused', () => {
+ // The budget is not "closed" by a refusal: the enforcer only reserves on
+ // success, so a $0.001 call still settles after a $1 call was turned away.
+ const out = replay(
+ [
+ { url: 'https://example.com/big', amountAtomics: 50_000n },
+ { url: 'https://example.com/small', amountAtomics: 1000n },
+ ],
+ policy,
+ );
+ expect(out.steps.map((s) => s.allowed)).toEqual([false, true]);
+ expect(out.spentAtomics).toBe(1000n);
+ });
+
+ it('charges nothing for a refused call', () => {
+ const out = replay([{ url: 'https://blocked.test/x', amountAtomics: 1000n }], {
+ ...policy,
+ allowedHosts: ['example.com'],
+ });
+ expect(out.steps[0].allowed).toBe(false);
+ expect(out.spentAtomics).toBe(0n);
+ expect(out.remainingAtomics).toBe(10_000n);
+ });
+
+ it('exposes the running balance around each step', () => {
+ const out = replay([call(1), call(2)], policy);
+ expect(out.steps[0].remainingBeforeAtomics).toBe(10_000n);
+ expect(out.steps[0].remainingAfterAtomics).toBe(7000n);
+ expect(out.steps[1].remainingBeforeAtomics).toBe(7000n);
+ expect(out.steps[1].remainingAfterAtomics).toBe(4000n);
+ });
+
+ it('handles an empty call list', () => {
+ const out = replay([], policy);
+ expect(out.steps).toEqual([]);
+ expect(out.spentAtomics).toBe(0n);
+ });
+});
+
+describe('402 rail description', () => {
+ it('parses an amount as BigInt, never as a float', () => {
+ // 9007199254740993 is beyond Number's exact integer range. Parsing it as a
+ // float would silently change the price.
+ const rail = describeRail({ network: SOLANA_NET, asset: USDC, amount: '9007199254740993' });
+ expect(rail.amount_atomics).toBe('9007199254740993');
+ });
+
+ it('reports a null price for an unparseable amount instead of guessing zero', () => {
+ const rail = describeRail({ network: SOLANA_NET, asset: USDC, amount: 'free!' });
+ expect(rail.amount_atomics).toBeNull();
+ expect(rail.amount_usd).toBeNull();
+ });
+
+ it('converts atomics to dollars', () => {
+ const rail = describeRail({ network: SOLANA_NET, asset: USDC, amount: '1000', payTo: 'abc' });
+ expect(rail.amount_usd).toBe(0.001);
+ expect(rail.pay_to).toBe('abc');
+ expect(rail.usdc).toBe(true);
+ });
+});
+
+describe('rail selection', () => {
+ const rails = [
+ describeRail({ network: 'base', asset: '0x833589', amount: '2000' }),
+ describeRail({ network: SOLANA_NET, asset: 'SomeOtherMint', amount: '3000' }),
+ describeRail({ network: SOLANA_NET, asset: USDC, amount: '1000' }),
+ ];
+
+ it('prefers the Solana USDC rail, which is what a session settles on', () => {
+ expect(selectRail(rails, 'solana').asset).toBe(USDC);
+ });
+
+ it('selects the requested EVM rail when the session is a base session', () => {
+ expect(selectRail(rails, 'base').network).toBe('base');
+ });
+
+ it('returns null when the endpoint offers nothing on the session network', () => {
+ expect(selectRail([describeRail({ network: 'base', amount: '1' })], 'solana')).toBeNull();
+ });
+});
+
+describe('simulator input parsing', () => {
+ it('accepts a bare URL string', () => {
+ const [call] = parseCalls(['https://example.com/a']);
+ expect(call).toMatchObject({ url: 'https://example.com/a', method: 'GET', times: 1 });
+ });
+
+ it('rejects an empty or non-array calls list', () => {
+ expect(() => parseCalls([])).toThrow(/non-empty/);
+ expect(() => parseCalls(null)).toThrow(/non-empty/);
+ });
+
+ it('requires https even on a dev box, where validatePublicUrl would allow http', () => {
+ // The endpoint is unauthenticated and fetches caller-chosen URLs, so it must
+ // not be laxer locally than in production.
+ expect(() => parseCalls(['http://example.com/a'])).toThrow(/public https/);
+ expect(() => parseCalls(['file:///etc/passwd'])).toThrow(/public https/);
+ expect(() => parseCalls(['gopher://example.com/a'])).toThrow(/public https/);
+ });
+
+ it('refuses a literal private address before any DNS work', () => {
+ // Without this the simulator would be an SSRF probe with a friendly UI.
+ // A public hostname that resolves inward is caught later, at probe time,
+ // by resolvePublicHost and the connect-time address pin.
+ expect(() => parseCalls(['https://169.254.169.254/latest/meta-data/'])).toThrow(/private address/);
+ expect(() => parseCalls(['https://127.0.0.1/admin'])).toThrow(/private address/);
+ expect(() => parseCalls(['https://10.0.0.5/internal'])).toThrow(/private address/);
+ expect(() => parseCalls(['https://[::1]/admin'])).toThrow(/private address/);
+ });
+
+ it('clamps repetition to a sane range', () => {
+ expect(parseCalls([{ url: 'https://example.com/a', times: 0 }])[0].times).toBe(1);
+ expect(parseCalls([{ url: 'https://example.com/a', times: 1e9 }])[0].times).toBe(500);
+ });
+
+ it('rejects a negative supplied price', () => {
+ expect(() => parseCalls([{ url: 'https://example.com/a', price_usd: -1 }])).toThrow(
+ /non-negative/,
+ );
+ });
+
+ it('caps the number of endpoints a single simulation may probe', () => {
+ const many = Array.from({ length: 25 }, (_, i) => `https://example.com/${i}`);
+ expect(() => parseCalls(many)).toThrow(/distinct endpoints/);
+ });
+
+ it('does not count supplied-price calls against the probe cap', () => {
+ // They cost no outbound request, so bounding them would be arbitrary.
+ const many = Array.from({ length: 30 }, (_, i) => ({
+ url: `https://example.com/${i}`,
+ price_usd: 0.01,
+ }));
+ expect(parseCalls(many)).toHaveLength(30);
+ });
+});
+
+describe('simulator policy parsing', () => {
+ it('clamps a budget to the range session creation accepts', () => {
+ expect(parsePolicy({ budget_usd: 99_999 }).budgetUsd).toBe(SESSION_LIMITS.MAX_BUDGET_USD);
+ expect(parsePolicy({ budget_usd: 0.0000001 }).budgetUsd).toBe(SESSION_LIMITS.MIN_BUDGET_USD);
+ });
+
+ it('says so when it clamped, rather than silently changing the answer', () => {
+ expect(parsePolicy({ budget_usd: 99_999 }).notes.join(' ')).toMatch(/lowered/);
+ expect(parsePolicy({ budget_usd: 0.0000001 }).notes.join(' ')).toMatch(/raised/);
+ });
+
+ it('clamps the TTL to the creatable range', () => {
+ expect(parsePolicy({ expiry_seconds: 1 }).expirySeconds).toBe(SESSION_LIMITS.MIN_TTL_SECONDS);
+ expect(parsePolicy({ expiry_seconds: 1e12 }).expirySeconds).toBe(SESSION_LIMITS.MAX_TTL_SECONDS);
+ });
+
+ it('flags a per-tx ceiling that can never bind', () => {
+ const p = parsePolicy({ budget_usd: 1, max_per_tx_usd: 5 });
+ expect(p.notes.join(' ')).toMatch(/never bind/);
+ });
+
+ it('drops a nonsense ceiling instead of enforcing it', () => {
+ const p = parsePolicy({ budget_usd: 1, max_per_tx_usd: -3 });
+ expect(p.maxPerTxUsd).toBeNull();
+ expect(p.notes.join(' ')).toMatch(/ignored/);
+ });
+
+ it('accepts an allowlist as an array or a delimited string, deduplicated', () => {
+ expect(parsePolicy({ allowed_hosts: ['A.com', 'https://a.com/x', 'b.com'] }).allowedHosts)
+ .toEqual(['a.com', 'b.com']);
+ expect(parsePolicy({ allowed_hosts: 'a.com, b.com c.com' }).allowedHosts)
+ .toEqual(['a.com', 'b.com', 'c.com']);
+ });
+
+ it('defaults to Solana and only accepts base as an alternative', () => {
+ expect(parsePolicy({}).network).toBe('solana');
+ expect(parsePolicy({ network: 'base' }).network).toBe('base');
+ expect(parsePolicy({ network: 'ethereum' }).network).toBe('solana');
+ });
+});
+
+describe('simulator step construction', () => {
+ const priced = (amount) =>
+ new Map([
+ [
+ 'GET https://api.example.com/data',
+ {
+ probe: { kind: 'priced', rails: [], description: null },
+ rail: describeRail({ network: SOLANA_NET, asset: USDC, amount, payTo: 'x' }),
+ },
+ ],
+ ]);
+
+ it('expands a repeated call into one step per repetition', () => {
+ const calls = parseCalls([{ url: 'https://api.example.com/data', times: 3 }]);
+ const { steps } = buildSteps(calls, priced('1000'), 'solana');
+ expect(steps).toHaveLength(3);
+ expect(steps.map((s) => s.repetition)).toEqual([1, 2, 3]);
+ expect(steps.every((s) => s.amountAtomics === 1000n)).toBe(true);
+ });
+
+ it('marks a free endpoint as free rather than as a zero-dollar payment', () => {
+ // The executor returns before governance when there is no 402, so a free
+ // call can never be allowlist-blocked. Modelling it as a $0 payment would
+ // make the simulator predict a refusal the enforcer would never raise.
+ const calls = parseCalls(['https://api.example.com/data']);
+ const map = new Map([
+ ['GET https://api.example.com/data', { probe: { kind: 'free', status: 200 }, rail: null }],
+ ]);
+ const { steps } = buildSteps(calls, map, 'solana');
+ expect(steps[0].free).toBe(true);
+ expect(steps[0].priceable).toBe(false);
+ });
+
+ it('reports an unreachable endpoint as a problem and never as free', () => {
+ const calls = parseCalls(['https://api.example.com/data']);
+ const map = new Map([
+ [
+ 'GET https://api.example.com/data',
+ { probe: { kind: 'error', code: 'endpoint_unreachable', message: 'nope' }, rail: null },
+ ],
+ ]);
+ const { steps, problems } = buildSteps(calls, map, 'solana');
+ expect(steps[0].priceable).toBe(false);
+ expect(steps[0].free).toBe(false);
+ expect(problems[0].code).toBe('endpoint_unreachable');
+ });
+
+ it('reports which networks an endpoint does offer when the session network is absent', () => {
+ const calls = parseCalls(['https://api.example.com/data']);
+ const map = new Map([
+ [
+ 'GET https://api.example.com/data',
+ {
+ probe: { kind: 'priced', rails: [describeRail({ network: 'base', amount: '10' })] },
+ rail: null,
+ },
+ ],
+ ]);
+ const { steps, problems } = buildSteps(calls, map, 'solana');
+ expect(problems[0].code).toBe('no_rail_for_network');
+ expect(steps[0].pricing.networks_offered).toEqual(['base']);
+ });
+
+ it('uses a supplied price without probing', () => {
+ const calls = parseCalls([{ url: 'https://api.example.com/data', price_usd: 0.25 }]);
+ const { steps } = buildSteps(calls, new Map(), 'solana');
+ expect(steps[0].amountAtomics).toBe(250_000n);
+ expect(steps[0].pricing.source).toBe('supplied');
+ });
+});
+
+describe('policy recommendation', () => {
+ const step = (url, usd) => ({
+ url,
+ priceable: true,
+ free: false,
+ amountAtomics: usdToAtomics(usd),
+ });
+
+ it('recommends a budget covering the whole sequence, rounded up to the cent', () => {
+ const rec = recommend([step('https://a.com/x', 0.004), step('https://a.com/y', 0.008)], {
+ allowedHosts: [],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.exact_cost_usd).toBeCloseTo(0.012, 9);
+ expect(rec.budget_usd).toBe(0.02);
+ });
+
+ it('sets the ceiling to the largest single payment in the run', () => {
+ const rec = recommend([step('https://a.com/x', 0.01), step('https://a.com/y', 0.5)], {
+ allowedHosts: [],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.max_per_tx_usd).toBe(0.5);
+ });
+
+ it('lists every host the run touches', () => {
+ const rec = recommend([step('https://a.com/x', 0.01), step('https://b.com/y', 0.01)], {
+ allowedHosts: [],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.allowed_hosts).toEqual(['a.com', 'b.com']);
+ });
+
+ it('names the hosts the proposed allowlist is missing', () => {
+ const rec = recommend([step('https://a.com/x', 0.01), step('https://b.com/y', 0.01)], {
+ allowedHosts: ['a.com'],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.missing_hosts).toEqual(['b.com']);
+ });
+
+ it('counts a subdomain as covered by its parent domain entry', () => {
+ const rec = recommend([step('https://api.a.com/x', 0.01)], {
+ allowedHosts: ['a.com'],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.missing_hosts).toEqual([]);
+ });
+
+ it('never recommends a budget below the creatable minimum', () => {
+ const rec = recommend([], { allowedHosts: [], network: 'solana', expirySeconds: 3600 });
+ expect(rec.budget_usd).toBe(SESSION_LIMITS.MIN_BUDGET_USD);
+ expect(rec.max_per_tx_usd).toBeNull();
+ });
+
+ it('caps the recommendation at the creatable maximum', () => {
+ const rec = recommend([step('https://a.com/x', 5000)], {
+ allowedHosts: [],
+ network: 'solana',
+ expirySeconds: 3600,
+ });
+ expect(rec.budget_usd).toBe(SESSION_LIMITS.MAX_BUDGET_USD);
+ });
+});
+
+describe('the enforcer and the simulator share one rule set', () => {
+ const governor = read('api/_lib/pay/spend-governor.js');
+ const flat = governor.replace(/\s+/g, ' ');
+
+ it('imports its predicates from policy.js', () => {
+ expect(governor).toMatch(/from '\.\/policy\.js'/);
+ for (const fn of ['statusVerdict', 'expiryVerdict', 'allowlistVerdict', 'perTxVerdict']) {
+ expect(governor, `the governor no longer uses ${fn}`).toContain(fn);
+ }
+ });
+
+ it('does not reimplement the allowlist suffix rule inline', () => {
+ // This is the exact line that used to live in the governor. If it comes
+ // back, the simulator and the enforcer can drift apart again.
+ expect(flat).not.toMatch(/targetHost\.endsWith/);
+ });
+
+ it('still decides the budget in SQL, not in JavaScript', () => {
+ // The pure budgetVerdict is advisory. Only a predicated UPDATE is race-safe,
+ // so the atomic reservation must remain a single statement.
+ expect(flat).toContain('UPDATE payment_sessions SET spent_usdc = spent_usdc +');
+ expect(flat).toContain('AND (budget_usdc - spent_usdc) >=');
+ });
+
+ it('keeps the simulator free of any signing or database path', () => {
+ const sim = read('api/pay/simulate.js');
+ for (const forbidden of ['@solana/web3.js', 'loadSeedKeypair', 'X-PAYMENT', '../_lib/db.js']) {
+ expect(sim, `simulate.js must not reach for ${forbidden}`).not.toContain(forbidden);
+ }
+ });
+});
diff --git a/tests/x402-runway-sim.test.js b/tests/x402-runway-sim.test.js
new file mode 100644
index 000000000..570b0c14c
--- /dev/null
+++ b/tests/x402-runway-sim.test.js
@@ -0,0 +1,274 @@
+// Tests for the settle-path forward simulation (api/_lib/x402/runway-sim.js),
+// the model behind /economy-lab.
+//
+// The simulation's whole value claim is fidelity: it applies the REAL governor
+// functions in the REAL order the settle path uses (hard SOL floor first, then
+// the wallet fee governor). These tests pin that ordering, the per-settle
+// budget recomputation, the UTC day reset, and the three-lever solver, using
+// the exact production shape that starved settlement on 2026-07-31: a fee
+// wallet sitting on its floor with a governor budget of one heartbeat.
+
+import { describe, it, expect } from 'vitest';
+import {
+ simulateRunway,
+ equilibriumSettlesPerDay,
+ solveForThroughput,
+ envDiff,
+ formatSol,
+ LAMPORTS_PER_SOL,
+ MIN_FEE_LAMPORTS,
+ MAX_ATTEMPTS,
+} from '../api/_lib/x402/runway-sim.js';
+
+// A comfortable wallet: 1 SOL, 0.02 SOL floor, stock 3-day/0.01-SOL governor.
+const HEALTHY = {
+ startLamports: LAMPORTS_PER_SOL,
+ floorLamports: 20_000_000,
+ runwayDays: 3,
+ minBudgetLamports: 10_000_000,
+ feeLamports: 5_000,
+};
+
+describe('simulateRunway — admission ordering', () => {
+ it('refuses on the hard SOL floor before the governor is consulted', () => {
+ // Below the floor the settle path returns fee_wallet_below_floor and never
+ // reaches the meter, so every refusal must be attributed to the floor.
+ const { summary, series } = simulateRunway({
+ ...HEALTHY,
+ startLamports: 19_000_000, // under the 0.02 SOL floor
+ demandPerHour: 10,
+ hours: 2,
+ });
+ expect(summary.admitted).toBe(0);
+ expect(summary.refusedFloor).toBe(20);
+ expect(summary.refusedGovernor).toBe(0);
+ expect(summary.limiter).toBe('floor');
+ expect(summary.verdict).toBe('starved');
+ expect(series[0].reason).toBe('fee_wallet_below_floor:19000000<20000000');
+ });
+
+ it('admits every attempt when budget and balance both allow it', () => {
+ const { summary } = simulateRunway({ ...HEALTHY, demandPerHour: 5, hours: 4 });
+ expect(summary.admitted).toBe(20);
+ expect(summary.refused).toBe(0);
+ expect(summary.verdict).toBe('healthy');
+ expect(summary.limiter).toBe('demand');
+ expect(summary.feesBurnedLamports).toBe(20 * 5_000);
+ });
+
+ it('stops at the governor budget, not at the balance, when the wallet is rich', () => {
+ // 1 SOL, floor 0.02 → spendable 0.98 SOL. The naive read is 0.98/3 days =
+ // 0.3266 SOL/day = 65,333 settles. The real answer is 49,000, because the
+ // governor recomputes its budget from the LIVE balance on every settle, so
+ // spending shrinks the budget authorising the next spend. The fixed point
+ // is spendable/(fee·(runwayDays+1)) = 0.98 SOL / (5,000 × 4).
+ const { summary } = simulateRunway({
+ ...HEALTHY, demandPerHour: 10_000, hours: 24, startHourOfDay: 0,
+ });
+ expect(summary.refusedGovernor).toBeGreaterThan(0);
+ expect(summary.refusedFloor).toBe(0);
+ expect(summary.limiter).toBe('governor');
+ expect(summary.admitted).toBe(49_000);
+ });
+
+ it('the closed form agrees with the simulation it explains', () => {
+ const { summary } = simulateRunway({
+ ...HEALTHY, demandPerHour: 10_000, hours: 24, startHourOfDay: 0,
+ });
+ expect(equilibriumSettlesPerDay({
+ spendableLamports: HEALTHY.startLamports - HEALTHY.floorLamports,
+ feeLamports: HEALTHY.feeLamports,
+ runwayDays: HEALTHY.runwayDays,
+ minBudgetLamports: HEALTHY.minBudgetLamports,
+ })).toBe(summary.admitted);
+ });
+});
+
+describe('simulateRunway — the 2026-07-31 starvation shape', () => {
+ // The production failure: the fee wallet sits essentially ON its floor, so
+ // spendable SOL is ~0 and the runway term contributes nothing. Only the
+ // heartbeat floor keeps any settlement alive at all, and it caps the day.
+ const STARVED = {
+ startLamports: 28_700_000, // 0.0287 SOL
+ floorLamports: 20_000_000, // 0.02 SOL
+ runwayDays: 3,
+ minBudgetLamports: 10_000_000, // 0.01 SOL heartbeat
+ feeLamports: 5_000,
+ };
+
+ it('the heartbeat promises more throughput than the wallet can fund', () => {
+ const { summary } = simulateRunway({ ...STARVED, demandPerHour: 500, hours: 24 });
+ // The heartbeat budget (0.01 SOL / 5,000 = 2,000 settles) is not the
+ // binding constraint here: only 0.0087 SOL sits above the hard floor, so
+ // the wallet runs out of spendable SOL at 1,741 and the FLOOR refuses the
+ // rest. Reading the config alone would have predicted 2,000 and blamed the
+ // governor. This is the distinction the lab exists to make visible.
+ expect(summary.admitted).toBe(1_741);
+ expect(summary.limiter).toBe('floor');
+ expect(summary.verdict).toBe('starved');
+ expect(summary.refusedFloor).toBeGreaterThan(0);
+ });
+
+ it('reports the exact hour throughput first breaks, so the alert has a clock', () => {
+ const { summary } = simulateRunway({ ...STARVED, demandPerHour: 500, hours: 24 });
+ // 1,741 admitted at 500/hour → the 4th hour (index 3) is the first refusal.
+ expect(summary.firstRefusalHour).toBe(3);
+ });
+
+ it('a heartbeat raise cannot rescue a wallet that has no spendable SOL', () => {
+ const wider = simulateRunway({ ...STARVED, minBudgetLamports: 50_000_000, demandPerHour: 500, hours: 24 });
+ // Same 1,741: widening the governor changes nothing once the hard floor is
+ // what binds. Only funding moves this number, which is exactly the
+ // misdiagnosis the three-lever solver prevents.
+ expect(wider.summary.admitted).toBe(1_741);
+ expect(wider.summary.endLamports).toBeGreaterThanOrEqual(STARVED.floorLamports - STARVED.feeLamports);
+ });
+
+ it('funding, not config, is what restores throughput here', () => {
+ const funded = simulateRunway({
+ ...STARVED, funding: [{ hour: 0, lamports: 500_000_000 }], demandPerHour: 500, hours: 24,
+ });
+ // 0.5 SOL clears every constraint at this demand: all 12,000 attempts land
+ // and the limiter becomes demand, i.e. nothing in the rail is holding back.
+ expect(funded.summary.admitted).toBe(12_000);
+ expect(funded.summary.refused).toBe(0);
+ expect(funded.summary.limiter).toBe('demand');
+ expect(funded.summary.verdict).toBe('healthy');
+ });
+
+ it('disabling the governor exposes the hard floor as the only remaining stop', () => {
+ const { summary } = simulateRunway({
+ ...STARVED, governorEnabled: false, demandPerHour: 5_000, hours: 24,
+ });
+ expect(summary.refusedGovernor).toBe(0);
+ expect(summary.refusedFloor).toBeGreaterThan(0);
+ expect(summary.limiter).toBe('floor');
+ // (28.7M − 20M)/5k = 1,740 settles land the balance exactly ON the floor;
+ // production's strict `<` admits one more before refusing.
+ expect(summary.admitted).toBe(1_741);
+ });
+});
+
+describe('simulateRunway — time', () => {
+ it('resets the daily meter at UTC midnight, not at hour 0 of the sim', () => {
+ // Seeded at 23:00 UTC with the day's budget already spent: hour 0 refuses,
+ // hour 1 crosses midnight and admits again.
+ const { series } = simulateRunway({
+ ...HEALTHY,
+ spentTodayLamports: 400_000_000, // well past the 0.3266 SOL budget
+ startHourOfDay: 23,
+ demandPerHour: 2,
+ hours: 3,
+ });
+ expect(series[0].admitted).toBe(0);
+ expect(series[1].admitted).toBe(2);
+ expect(series[1].spentTodayLamports).toBe(2 * 5_000);
+ });
+
+ it('applies funding at the top of its hour and records it', () => {
+ const { summary, series } = simulateRunway({
+ startLamports: 19_000_000,
+ floorLamports: 20_000_000,
+ runwayDays: 3,
+ minBudgetLamports: 10_000_000,
+ feeLamports: 5_000,
+ demandPerHour: 4,
+ hours: 4,
+ funding: [{ hour: 2, lamports: 500_000_000 }],
+ });
+ expect(series[0].admitted).toBe(0); // under the floor
+ expect(series[2].fundedLamports).toBe(500_000_000);
+ expect(series[2].admitted).toBe(4); // funded, so it clears the floor
+ expect(summary.fundedLamports).toBe(500_000_000);
+ });
+
+ it('bounds the attempt loop instead of hanging on an absurd horizon', () => {
+ const { summary } = simulateRunway({ ...HEALTHY, demandPerHour: 100_000, hours: 24 * 30 });
+ expect(summary.truncated).toBe(true);
+ expect(summary.admitted + summary.refused).toBeLessThanOrEqual(MAX_ATTEMPTS);
+ });
+});
+
+describe('simulateRunway — input hardening', () => {
+ it('clamps a sub-base-fee estimate to the 1-signature floor', () => {
+ const { summary } = simulateRunway({ ...HEALTHY, feeLamports: 1, demandPerHour: 3, hours: 1 });
+ expect(summary.feesBurnedLamports).toBe(3 * MIN_FEE_LAMPORTS);
+ });
+
+ it('survives a fully empty input without throwing', () => {
+ const { summary } = simulateRunway({});
+ expect(summary.admitted).toBe(0);
+ expect(summary.verdict).toBe('healthy');
+ });
+
+ it('never lets the balance go negative', () => {
+ const { summary } = simulateRunway({
+ startLamports: 12_000, floorLamports: 0, runwayDays: 0.5,
+ minBudgetLamports: 10_000_000, feeLamports: 5_000, demandPerHour: 100, hours: 2,
+ });
+ expect(summary.endLamports).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe('solveForThroughput', () => {
+ const STARVED = {
+ startLamports: 28_700_000,
+ floorLamports: 20_000_000,
+ runwayDays: 3,
+ minBudgetLamports: 10_000_000,
+ feeLamports: 5_000,
+ };
+
+ it('quotes the exact deposit that reaches the target at the current runway', () => {
+ const s = solveForThroughput({ ...STARVED, targetSettlesPerDay: 10_000 });
+ // 10,000 × 5,000 = 0.05 SOL/day × 3 days + 0.02 floor = 0.17 SOL needed.
+ expect(s.requiredDailyBudgetLamports).toBe(50_000_000);
+ expect(s.fund.lamports).toBe(170_000_000 - 28_700_000);
+ expect(s.alreadyMet).toBe(false);
+ });
+
+ it('offers the heartbeat lever at exactly the required daily budget', () => {
+ const s = solveForThroughput({ ...STARVED, targetSettlesPerDay: 10_000 });
+ expect(s.minBudget.lamports).toBe(50_000_000);
+ });
+
+ it('withholds the runway lever when there is nothing spendable to spread', () => {
+ const s = solveForThroughput({
+ ...STARVED, startLamports: 20_000_000, targetSettlesPerDay: 10_000,
+ });
+ expect(s.runwayDays).toBeNull();
+ expect(s.fund).not.toBeNull();
+ });
+
+ it('reports a target already met rather than inventing work', () => {
+ const s = solveForThroughput({
+ startLamports: LAMPORTS_PER_SOL, floorLamports: 20_000_000, runwayDays: 3,
+ minBudgetLamports: 10_000_000, feeLamports: 5_000, targetSettlesPerDay: 100,
+ });
+ expect(s.alreadyMet).toBe(true);
+ expect(s.fund).toBeNull();
+ });
+});
+
+describe('envDiff', () => {
+ it('emits only the keys that actually changed', () => {
+ const live = { runwayDays: 3, minBudgetLamports: 10_000_000, floorLamports: 20_000_000, governorEnabled: true };
+ const changes = envDiff(live, { ...live, minBudgetLamports: 50_000_000 });
+ expect(changes).toEqual([
+ { env: 'X402_WALLET_FEE_MIN_BUDGET_LAMPORTS', from: '10000000', to: '50000000' },
+ ]);
+ });
+
+ it('returns nothing when the proposal matches live', () => {
+ const live = { runwayDays: 3, minBudgetLamports: 10_000_000 };
+ expect(envDiff(live, { ...live })).toEqual([]);
+ });
+});
+
+describe('formatSol', () => {
+ it('trims trailing zeros without losing precision', () => {
+ expect(formatSol(LAMPORTS_PER_SOL)).toBe('1');
+ expect(formatSol(28_700_000)).toBe('0.0287');
+ expect(formatSol(0)).toBe('0');
+ });
+});