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(x402): warm the sponsor floor state on challenge-only instances

nirholas05b796f9e6e7
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 6d90ddc0f..b608adb4f 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -50,7 +50,7 @@ import {
verifyPayment,
} from './x402-spec.js';
import { declareBuilderCodeExtension } from './x402-builder-code.js';
-import { sponsorKnownBelowFloor } from './x402/self-facilitator.js';
+import { sponsorKnownBelowFloor, refreshSponsorFloorState } from './x402/self-facilitator.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
@@ -435,6 +435,11 @@ export function paidEndpoint(spec) {
typeof resourceUrlBuilder === 'function'
? resourceUrlBuilder(req)
: resolveResourceUrl(req, route);
+ // Keep this instance's sponsor floor state warm so the challenge below
+ // reflects reality. Deliberately not awaited: at most one balance read per
+ // 20s per instance, and a slow or failed RPC must never delay a 402.
+ refreshSponsorFloorState();
+
let requirements;
try {
requirements = buildRequirements({
diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.js
index 4cd003795..6c49483ef 100644
--- a/api/_lib/x402/self-facilitator.js
+++ b/api/_lib/x402/self-facilitator.js
@@ -383,6 +383,39 @@ function noteFloorState(lamports, now) {
_floorState = { below: lamports < SPONSOR_SOL_FLOOR_LAMPORTS, at: now };
}
+// Keep the floor state warm on instances that never settle.
+//
+// The state above is per-process and was only written by the settle path, so a
+// Cloud Run instance serving nothing but 402 challenges never learned the
+// sponsor was dry and kept advertising a Solana accept that could not settle.
+// Callers on the challenge path invoke this WITHOUT awaiting: it refreshes at
+// most once per SOL_CACHE_MS per instance, swallows every error (an RPC blip
+// must never affect a challenge), and leaves the state untouched on failure so
+// the fail-open default stands. First request after a cold start still
+// advertises Solana; every request after it is accurate.
+let _floorRefreshInFlight = null;
+
+export function refreshSponsorFloorState(now = Date.now()) {
+ const pubkey = env.X402_FEE_PAYER_SOLANA;
+ if (!pubkey) return;
+ if (_floorRefreshInFlight) return;
+ const hit = _solCache.get(pubkey);
+ if (hit && hit.lamports != null && now - hit.at < SOL_CACHE_MS) return;
+
+ _floorRefreshInFlight = (async () => {
+ try {
+ const conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const lamports = await conn.getBalance(new PublicKey(pubkey), 'confirmed');
+ _solCache.set(pubkey, { lamports, at: Date.now() });
+ noteFloorState(lamports, Date.now());
+ } catch {
+ /* RPC unreachable: keep the last known state, fail open */
+ } finally {
+ _floorRefreshInFlight = null;
+ }
+ })();
+}
+
export async function sponsorSolLamports(conn, feePayerPubkey, now = Date.now()) {
const key = feePayerPubkey.toBase58();
const hit = _solCache.get(key);
diff --git a/tests/x402-floor-degradation.test.js b/tests/x402-floor-degradation.test.js
index 66e92828e..9305e127f 100644
--- a/tests/x402-floor-degradation.test.js
+++ b/tests/x402-floor-degradation.test.js
@@ -72,6 +72,37 @@ describe('sponsorKnownBelowFloor', () => {
expect(sponsorKnownBelowFloor()).toBe(false);
});
+ it('warms itself on instances that never settle', async () => {
+ // The gap this closes: the floor state used to be written only by the
+ // settle path, so an instance serving nothing but 402 challenges kept
+ // advertising a Solana accept while the sponsor was dry.
+ process.env.X402_FEE_PAYER_SOLANA = 'SponsorSponsorSponsorSponsorSponsorSponsor9';
+ vi.doMock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: () => ({ getBalance: async () => 19_000_000 }),
+ }));
+ const { refreshSponsorFloorState, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
+
+ expect(sponsorKnownBelowFloor()).toBe(false); // nothing observed yet
+ refreshSponsorFloorState();
+ await new Promise((r) => setTimeout(r, 20)); // fire-and-forget settles
+ expect(sponsorKnownBelowFloor()).toBe(true);
+ vi.doUnmock('../api/_lib/solana/connection.js');
+ });
+
+ it('leaves the state untouched when the balance read fails', async () => {
+ process.env.X402_FEE_PAYER_SOLANA = 'SponsorSponsorSponsorSponsorSponsorSponsorA';
+ vi.doMock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: () => ({ getBalance: async () => { throw new Error('rpc down'); } }),
+ }));
+ const { refreshSponsorFloorState, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
+
+ refreshSponsorFloorState();
+ await new Promise((r) => setTimeout(r, 20));
+ // Fail open: an RPC outage must not pause payments.
+ expect(sponsorKnownBelowFloor()).toBe(false);
+ vi.doUnmock('../api/_lib/solana/connection.js');
+ });
+
it('expires: a stale observation stops pausing the challenge', async () => {
const { sponsorSolLamports, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
const pubkey = { toBase58: () => 'SponsorSponsorSponsorSponsorSponsorSponsor3' };