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.

fix(api): harden subsystem health, x402 spec, forge and pipeline paywalls and vanity drops, and update walk-room and selfpay tests

nirholas280ce6bfd81c
diff --git a/api/_lib/ops/subsystem-health.js b/api/_lib/ops/subsystem-health.js
index 1d706b4c8..23cfc7daf 100644
--- a/api/_lib/ops/subsystem-health.js
+++ b/api/_lib/ops/subsystem-health.js
@@ -30,6 +30,7 @@
// Only `degraded` and `down` count against the overall roll-up; `paused` and
// `unknown` are surfaced but neutral.
+import { createHash } from 'node:crypto';
import { cacheHealth, cacheGet } from '../cache.js';
import { heliusHealth } from '../balances.js';
import { rpcLaneHealth } from '../solana/connection.js';
@@ -50,6 +51,38 @@ const WORLD_HEALTH_CACHE_KEY = 'world:health';
// A parked world-health outcome older than this is treated as stale/unknown
// rather than trusted — the 15-min cron should refresh it well within the window.
const WORLD_STALE_MS = 90 * 60 * 1000;
+// The world-health cron's cache write is best-effort and per-instance when Redis
+// is failing, so /healthz can miss a real outage. Its sendOpsAlert calls land in
+// the durable ops_alerts table keyed by sha256(signature).slice(0,16) (see
+// signatureOf in ../alerts.js). A row refreshed within two 15-min cron ticks
+// plus slack means the world is down right now.
+const WORLD_DOWN_SIGNATURES = ['world-health:status-http', 'world-health:status-unreachable'].map(
+ (t) => createHash('sha256').update(t).digest('hex').slice(0, 16),
+);
+const WORLD_ALERT_FRESH_MS = 40 * 60 * 1000;
+
+/**
+ * Durable fallback for checkWorld(): the freshest world-down alert detail, or
+ * null when none is recent or the database cannot be read.
+ * @returns {Promise<string|null>}
+ */
+async function recentWorldDownAlert() {
+ try {
+ const { sql } = await import('../db.js');
+ const rows = await sql`
+ select detail, last_seen from ops_alerts
+ where signature in (${WORLD_DOWN_SIGNATURES[0]}, ${WORLD_DOWN_SIGNATURES[1]})
+ order by last_seen desc limit 1
+ `;
+ const row = rows?.[0];
+ if (!row?.last_seen) return null;
+ const age = Date.now() - new Date(row.last_seen).getTime();
+ if (!(age <= WORLD_ALERT_FRESH_MS)) return null;
+ return row.detail || 'world unreachable';
+ } catch {
+ return null;
+ }
+}
// Sniper worker heartbeat (bot_heartbeat, worker='agent-sniper'). It beats every
// ~30s; /api/sniper/status calls it dead past 90s. For paging we use a wider
// window so a deploy blip doesn't page, but a real death pages within two ticks.
@@ -337,10 +370,14 @@ async function checkWorld() {
try {
const parked = await cacheGet(WORLD_HEALTH_CACHE_KEY);
if (!parked || typeof parked !== 'object') {
+ const alert = await recentWorldDownAlert();
+ if (alert) return { ...base, status: 'down', detail: alert };
return { ...base, status: 'unknown', detail: 'no world-health report yet' };
}
const age = parked.checkedAt ? Date.now() - parked.checkedAt : Infinity;
if (age > WORLD_STALE_MS) {
+ const alert = await recentWorldDownAlert();
+ if (alert) return { ...base, status: 'down', detail: alert };
return { ...base, status: 'unknown', detail: 'world-health report is stale' };
}
if (parked.status === 'down') {
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 12a48492a..d3792136f 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -209,10 +209,8 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
// broadcasts. Mirrors the same fallback in x402-paid-endpoint.js, so the 17
// hand-rolled paid endpoints on this builder keep receiving on an empty
// sponsor wallet instead of going dark with it.
- const solanaSelfPayOnly =
- resolveSolanaFacilitator().self &&
- (!env.X402_FEE_PAYER_SOLANA || !solanaSettleable() || sponsorKnownBelowFloor());
- if (env.X402_PAY_TO_SOLANA && (solanaSettleable() || solanaSelfPayOnly)) {
+ const selfPayOnly = solanaSelfPayOnly();
+ if (env.X402_PAY_TO_SOLANA && (solanaSettleable() || selfPayOnly)) {
out.push({
...common,
network: NETWORK_SOLANA_MAINNET,
@@ -225,7 +223,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
extra: {
name: 'USDC',
decimals: 6,
- ...(solanaSelfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
+ ...(selfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
},
});
// $THREE alongside USDC on the same Solana rail (opt-in via
@@ -233,7 +231,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
// clients that pick the first Solana accept keep settling USDC; the modal
// surfaces both as a token chooser. Same fee-payer co-sign path, the
// checkout server transfers any SPL mint, so no extra wiring is needed.
- if (env.X402_ACCEPT_THREE_SOLANA && (env.X402_FEE_PAYER_SOLANA || solanaSelfPayOnly)) {
+ if (env.X402_ACCEPT_THREE_SOLANA && (env.X402_FEE_PAYER_SOLANA || selfPayOnly)) {
out.push({
...common,
...(env.X402_THREE_AMOUNT_SOLANA ? { amount: String(env.X402_THREE_AMOUNT_SOLANA) } : {}),
@@ -243,7 +241,7 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {
extra: {
name: 'THREE',
decimals: env.THREE_TOKEN_DECIMALS,
- ...(solanaSelfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
+ ...(selfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
},
});
}
@@ -405,6 +403,19 @@ export function solanaSettleable() {
return !!String(process.env.X402_FEE_PAYER_SECRET_BASE58 || '').trim();
}
+// True when Solana must be advertised WITHOUT extra.feePayer: we settle in-house
+// and the sponsor cannot co-sign (none configured, no key loaded, or the wallet
+// is under its SOL floor). The buyer then signs as its own fee payer and the
+// facilitator only broadcasts. Every Solana accept builder must consult this;
+// advertising a sponsor the facilitator refuses at the floor gate makes buyers
+// sign payments that can never settle.
+export function solanaSelfPayOnly() {
+ return (
+ resolveSolanaFacilitator().self &&
+ (!env.X402_FEE_PAYER_SOLANA || !solanaSettleable() || sponsorKnownBelowFloor())
+ );
+}
+
// Shared exact-scheme requirements builder for the hand-rolled x402 endpoints that
// call send402()/verifyPayment() directly instead of going through paidEndpoint().
// Emits the platform-standard accept set for a USDC price:
@@ -423,11 +434,12 @@ export function solanaSettleable() {
export function buildExactRequirements(resourceUrl, amount = env.X402_MAX_AMOUNT_REQUIRED) {
const amt = String(amount);
const out = [];
+ const selfPayOnly = solanaSelfPayOnly();
if (
env.X402_PAY_TO_SOLANA &&
env.X402_ASSET_MINT_SOLANA &&
- env.X402_FEE_PAYER_SOLANA &&
- solanaSettleable()
+ (solanaSettleable() || selfPayOnly) &&
+ (env.X402_FEE_PAYER_SOLANA || selfPayOnly)
) {
out.push({
scheme: 'exact',
@@ -437,7 +449,11 @@ export function buildExactRequirements(resourceUrl, amount = env.X402_MAX_AMOUNT
asset: env.X402_ASSET_MINT_SOLANA,
maxTimeoutSeconds: 60,
resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ extra: {
+ name: 'USDC',
+ decimals: 6,
+ ...(selfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
+ },
});
}
if (baseSettleable() && env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) {
diff --git a/api/vanity/drops.js b/api/vanity/drops.js
index 21c0828e0..f1d9fc044 100644
--- a/api/vanity/drops.js
+++ b/api/vanity/drops.js
@@ -48,6 +48,7 @@ import {
settlePayment,
encodePaymentResponseHeader,
permit2VariantOf,
+ solanaSelfPayOnly,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -132,7 +133,7 @@ const CREATE_FEE_ATOMICS = 50_000; // $0.05
// ── x402 challenge ────────────────────────────────────────────────────────────
-function buildRequirements(resourceUrl, priceAtomics) {
+export function buildRequirements(resourceUrl, priceAtomics) {
const amount = String(priceAtomics);
const out = [];
if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) {
@@ -150,7 +151,7 @@ function buildRequirements(resourceUrl, priceAtomics) {
const permit2 = permit2VariantOf(eip3009);
if (permit2) out.push(permit2);
}
- if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_SOLANA) {
+ if (env.X402_PAY_TO_SOLANA && env.X402_ASSET_MINT_SOLANA && (env.X402_FEE_PAYER_SOLANA || solanaSelfPayOnly())) {
out.push({
scheme: 'exact',
network: NETWORK_SOLANA_MAINNET,
@@ -159,7 +160,7 @@ function buildRequirements(resourceUrl, priceAtomics) {
asset: env.X402_ASSET_MINT_SOLANA,
maxTimeoutSeconds: 60,
resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ extra: { name: 'USDC', decimals: 6, ...(solanaSelfPayOnly() ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }) },
});
}
return out;
@@ -251,7 +252,7 @@ function bad(message, code) {
function activeNetworks() {
const nets = [];
if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) nets.push('base');
- if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_SOLANA) nets.push('solana');
+ if (env.X402_PAY_TO_SOLANA && env.X402_ASSET_MINT_SOLANA && (env.X402_FEE_PAYER_SOLANA || solanaSelfPayOnly())) nets.push('solana');
return nets;
}
diff --git a/api/x402/forge.js b/api/x402/forge.js
index 908e11b78..0c4c8459b 100644
--- a/api/x402/forge.js
+++ b/api/x402/forge.js
@@ -39,6 +39,7 @@ import {
settlePayment,
encodePaymentResponseHeader,
permit2VariantOf,
+ solanaSelfPayOnly,
resolveResourceUrl,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
@@ -129,7 +130,7 @@ const ROUTE_DESCRIPTION = FORGE_ROUTE_DESCRIPTION;
const INPUT_SCHEMA = FORGE_INPUT_SCHEMA;
const ROUTE_BAZAAR = FORGE_BAZAAR;
-function buildRequirements(resourceUrl, priceAtomics) {
+export function buildRequirements(resourceUrl, priceAtomics) {
const amount = String(priceAtomics);
// The paid Forge settles in USDC on Solana mainnet ONLY. Base/EVM is
// intentionally not offered — every quote on this route is a Solana 402.
@@ -143,7 +144,7 @@ function buildRequirements(resourceUrl, priceAtomics) {
asset: env.X402_ASSET_MINT_SOLANA,
maxTimeoutSeconds: 60,
resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ extra: { name: 'USDC', decimals: 6, ...(solanaSelfPayOnly() ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }) },
},
];
}
diff --git a/api/x402/pipeline.js b/api/x402/pipeline.js
index 5ab55104d..851badafc 100644
--- a/api/x402/pipeline.js
+++ b/api/x402/pipeline.js
@@ -34,6 +34,7 @@ import {
settlePayment,
encodePaymentResponseHeader,
permit2VariantOf,
+ solanaSelfPayOnly,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -158,7 +159,7 @@ const OUTPUT_SCHEMA = {
},
};
-function buildRequirements(resourceUrl, priceAtomics) {
+export function buildRequirements(resourceUrl, priceAtomics) {
const amount = String(priceAtomics);
// Solana mainnet USDC only in production. Base is a dev/preview failsafe when
// X402_PAY_TO_SOLANA is unset so the route never dead-ends with an empty 402.
@@ -172,7 +173,7 @@ function buildRequirements(resourceUrl, priceAtomics) {
asset: env.X402_ASSET_MINT_SOLANA,
maxTimeoutSeconds: 60,
resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ extra: { name: 'USDC', decimals: 6, ...(solanaSelfPayOnly() ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }) },
},
];
}
diff --git a/package.json b/package.json
index b3036fe99..eaab47f92 100644
--- a/package.json
+++ b/package.json
@@ -57,6 +57,7 @@
"yaml@^1": "^1.10.3",
"zod": "^4.6.7",
"nanoid@^2": "^3.3.20",
+ "@colyseus/core": { "nanoid": "2.1.11" },
"uuid@^10": "^11.1.1",
"fast-xml-parser": "^5.11.2",
"decode-uri-component": "^0.5.1"
diff --git a/tests/studio-room.test.js b/tests/studio-room.test.js
index 8c2d417ff..1afeebb48 100644
--- a/tests/studio-room.test.js
+++ b/tests/studio-room.test.js
@@ -18,7 +18,7 @@ function makeRoom() {
room._opLedger = new Map();
const models = new Map();
const viewers = new Map();
- room.state = { models, viewers, roomKey: room.roomKey };
+ Object.defineProperty(room, 'state', { value: { models, viewers, roomKey: room.roomKey }, writable: true, configurable: true });
// The reject channel: record what the server tells a client.
room._rejects = [];
return room;
diff --git a/tests/subsystem-health.test.js b/tests/subsystem-health.test.js
index 2ff9e237b..15707c7f7 100644
--- a/tests/subsystem-health.test.js
+++ b/tests/subsystem-health.test.js
@@ -11,10 +11,21 @@
* DB ping has its own behavior (down when unreachable) that isn't the point here.
*/
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { gatherSubsystemHealth, classifySniperBeat } from '../api/_lib/ops/subsystem-health.js';
import { cacheSet, cacheDel } from '../api/_lib/cache.js';
+// Durable ops_alerts rows the world fallback reads. Default empty so every other
+// case behaves as before; the world-fallback cases set it per test.
+const dbState = vi.hoisted(() => ({ rows: [], throws: false, lastValues: null }));
+vi.mock('../api/_lib/db.js', () => ({
+ sql: async (strings, ...values) => {
+ if (dbState.throws) throw new Error('db down');
+ dbState.lastValues = values;
+ return dbState.rows;
+ },
+}));
+
// Env the ring + x402-config checks read. Save/restore so cases don't leak.
const ENV_KEYS = [
'X402_AUTONOMOUS_ENABLED',
@@ -171,6 +182,72 @@ describe('gatherSubsystemHealth', () => {
expect(world.hint).toMatch(/ADMIN_CODE/);
});
+ describe('world durable fallback (order 453)', () => {
+ afterEach(() => {
+ dbState.rows = [];
+ dbState.throws = false;
+ dbState.lastValues = null;
+ });
+
+ it('reports DOWN from a fresh ops_alerts row when the cache entry is missing', async () => {
+ await cacheDel('world:health');
+ dbState.rows = [
+ {
+ detail: 'https://world.three.ws/status returned HTTP 404',
+ last_seen: new Date(Date.now() - 4 * 60 * 1000).toISOString(),
+ },
+ ];
+ const health = await gatherSubsystemHealth({ probeDb: false });
+ const world = sub(health, 'world');
+ expect(world.status).toBe('down');
+ expect(world.detail).toMatch(/HTTP 404/);
+ expect(health.degraded).toContain('world');
+ });
+
+ it('reports DOWN from a fresh alert when the cache entry is stale', async () => {
+ await cacheSet(
+ 'world:health',
+ { status: 'ok', protected: true, problems: [], checkedAt: Date.now() - 3 * 60 * 60 * 1000 },
+ 3600,
+ );
+ dbState.rows = [{ detail: 'unreachable - timeout', last_seen: new Date().toISOString() }];
+ const health = await gatherSubsystemHealth({ probeDb: false });
+ expect(sub(health, 'world').status).toBe('down');
+ await cacheDel('world:health');
+ });
+
+ it('stays UNKNOWN when the only alert row is older than the cron window', async () => {
+ await cacheDel('world:health');
+ dbState.rows = [
+ { detail: 'old', last_seen: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString() },
+ ];
+ const health = await gatherSubsystemHealth({ probeDb: false });
+ expect(sub(health, 'world').status).toBe('unknown');
+ });
+
+ it('stays UNKNOWN when there is no alert row at all', async () => {
+ await cacheDel('world:health');
+ dbState.rows = [];
+ const health = await gatherSubsystemHealth({ probeDb: false });
+ expect(sub(health, 'world').status).toBe('unknown');
+ });
+
+ it('degrades to cache-only UNKNOWN when the database read fails', async () => {
+ await cacheDel('world:health');
+ dbState.throws = true;
+ const health = await gatherSubsystemHealth({ probeDb: false });
+ expect(sub(health, 'world').status).toBe('unknown');
+ });
+
+ it('queries only the two down signatures the cron writes (sha256 prefix of the literal)', async () => {
+ await cacheDel('world:health');
+ await gatherSubsystemHealth({ probeDb: false });
+ const { createHash } = await import('node:crypto');
+ const h = (t) => createHash('sha256').update(t).digest('hex').slice(0, 16);
+ expect(dbState.lastValues).toEqual([h('world-health:status-http'), h('world-health:status-unreachable')]);
+ });
+ });
+
it('reports world as DOWN from a parked world-health outcome', async () => {
await cacheSet(
'world:health',
diff --git a/tests/walk-room.test.js b/tests/walk-room.test.js
index e1aa514b2..05935af62 100644
--- a/tests/walk-room.test.js
+++ b/tests/walk-room.test.js
@@ -10,7 +10,7 @@ function makeRoom() {
Object.defineProperty(room, 'roomId', { value: 'room-1' });
Object.defineProperty(room, 'clients', { value: [] });
room.coinCreator = '';
- room.state = { coin: MINT, coinName: '', coinSymbol: '', coinImage: '' };
+ Object.defineProperty(room, 'state', { value: { coin: MINT, coinName: '', coinSymbol: '', coinImage: '' }, writable: true, configurable: true });
return room;
}
diff --git a/tests/walkroom-avatar-swap.test.js b/tests/walkroom-avatar-swap.test.js
index f9277a7dc..fce2076d5 100644
--- a/tests/walkroom-avatar-swap.test.js
+++ b/tests/walkroom-avatar-swap.test.js
@@ -13,7 +13,7 @@ import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';
function makeRoom() {
const room = Object.create(WalkRoom.prototype);
- room.state = { players: new Map() };
+ Object.defineProperty(room, 'state', { value: { players: new Map() }, writable: true, configurable: true });
room._actionCounters = new Map();
return room;
}
diff --git a/tests/walkroom-build-perms.test.js b/tests/walkroom-build-perms.test.js
index c61b59331..513c8b958 100644
--- a/tests/walkroom-build-perms.test.js
+++ b/tests/walkroom-build-perms.test.js
@@ -17,7 +17,7 @@ function makeRoom({ creator = '' } = {}) {
room.columnCounts = new Map();
room.coinCreator = creator;
room.econ = new Map();
- room.state = { players: new Map() };
+ Object.defineProperty(room, 'state', { value: { players: new Map() }, writable: true, configurable: true });
return room;
}
diff --git a/tests/walkroom-king.test.js b/tests/walkroom-king.test.js
index 01c818ad0..fb10ccfeb 100644
--- a/tests/walkroom-king.test.js
+++ b/tests/walkroom-king.test.js
@@ -22,7 +22,7 @@ function player(name, x, z, dead = false) {
// outgoing room messages so tests can assert what every client receives.
function makeRoom() {
const room = Object.create(WalkRoom.prototype);
- room.state = { players: new Map() };
+ Object.defineProperty(room, 'state', { value: { players: new Map() }, writable: true, configurable: true });
room.clients = [];
room.broadcasts = [];
room.sent = [];
diff --git a/tests/walkroom-prop-assets.test.js b/tests/walkroom-prop-assets.test.js
index 9afa7ecb8..0cdbef244 100644
--- a/tests/walkroom-prop-assets.test.js
+++ b/tests/walkroom-prop-assets.test.js
@@ -20,7 +20,7 @@ const GOOD_URL = 'https://pub-test.r2.dev/u/anon/avatar/8f14e45f.glb';
function makeRoom({ tier = '', creator = '' } = {}) {
const room = Object.create(WalkRoom.prototype);
- room.state = { objects: new Map(), players: new Map(), tier, coin: 'THREEsynthetic1111111111111111111111111111' };
+ Object.defineProperty(room, 'state', { value: { objects: new Map(), players: new Map(), tier, coin: 'THREEsynthetic1111111111111111111111111111' }, writable: true, configurable: true });
room.econ = new Map();
room._objCounters = new Map();
room._objSeq = 0;
diff --git a/tests/walkroom-tag.test.js b/tests/walkroom-tag.test.js
index 7a7bde657..ecf7e6a23 100644
--- a/tests/walkroom-tag.test.js
+++ b/tests/walkroom-tag.test.js
@@ -19,7 +19,7 @@ function player(name, x, z) {
// client's own send), so tests can assert what peers and individuals receive.
function makeRoom() {
const room = Object.create(WalkRoom.prototype);
- room.state = { players: new Map() };
+ Object.defineProperty(room, 'state', { value: { players: new Map() }, writable: true, configurable: true });
room._tagImmunity = new Map();
room._tagTime = new Map();
room.clients = [];
diff --git a/tests/walkroom-worldobjects.test.js b/tests/walkroom-worldobjects.test.js
index b499424c7..36c83a937 100644
--- a/tests/walkroom-worldobjects.test.js
+++ b/tests/walkroom-worldobjects.test.js
@@ -14,7 +14,7 @@ import { WorldObject } from '../multiplayer/src/schemas.js';
function makeRoom() {
const room = Object.create(WalkRoom.prototype);
- room.state = { objects: new Map() };
+ Object.defineProperty(room, 'state', { value: { objects: new Map() }, writable: true, configurable: true });
room.econ = new Map();
room._objCounters = new Map();
return room;
diff --git a/tests/x402-selfpay-fallback.test.js b/tests/x402-selfpay-fallback.test.js
index 5d799293a..55cb78469 100644
--- a/tests/x402-selfpay-fallback.test.js
+++ b/tests/x402-selfpay-fallback.test.js
@@ -166,3 +166,59 @@ describe('paymentRequirements shares the self-pay fallback', () => {
}
});
});
+
+// The four sibling builders that never got the guard: they advertised the
+// sponsor as fee payer unconditionally, so a sponsor under its floor kept being
+// offered and every payment buyers signed against it was refused at settle.
+describe.each([
+ [
+ 'buildExactRequirements',
+ async () => (await import('../api/_lib/x402-spec.js')).buildExactRequirements,
+ ],
+ [
+ 'pipeline.js buildRequirements',
+ async () => (await import('../api/x402/pipeline.js')).buildRequirements,
+ ],
+ [
+ 'forge.js buildRequirements',
+ async () => (await import('../api/x402/forge.js')).buildRequirements,
+ ],
+ [
+ 'drops.js buildRequirements',
+ async () => (await import('../api/vanity/drops.js')).buildRequirements,
+ ],
+])('%s shares the self-pay fallback', (_name, load) => {
+ async function requirements({ belowFloor }) {
+ vi.doMock('../api/_lib/x402/self-facilitator.js', () => ({
+ sponsorKnownBelowFloor: () => belowFloor,
+ refreshSponsorFloorState: () => {},
+ }));
+ const build = await load();
+ return build('https://three.ws/api/x402/example', '1000');
+ }
+
+ it('keeps the Solana accept but drops feePayer when the sponsor is below its floor', async () => {
+ const accepts = solanaAccepts(await requirements({ belowFloor: true }));
+ expect(accepts.length).toBeGreaterThan(0);
+ for (const accept of accepts) {
+ expect(accept.extra.feePayer).toBeUndefined();
+ }
+ });
+
+ it('keeps sponsoring gas while the sponsor is healthy', async () => {
+ const accepts = solanaAccepts(await requirements({ belowFloor: false }));
+ expect(accepts.length).toBeGreaterThan(0);
+ for (const accept of accepts) {
+ expect(accept.extra.feePayer).toBe(SPONSOR);
+ }
+ });
+
+ it('advertises Solana via self-pay when no sponsor is configured', async () => {
+ delete process.env.X402_FEE_PAYER_SOLANA;
+ const accepts = solanaAccepts(await requirements({ belowFloor: false }));
+ expect(accepts.length).toBeGreaterThan(0);
+ for (const accept of accepts) {
+ expect(accept.extra.feePayer).toBeUndefined();
+ }
+ });
+});