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): report an empty ring payer as insufficient_payer_usdc, not as a cap to raise

nirholas9a0a13721bb0
diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.js
index f583fe7f0..d5fe49ce5 100644
--- a/api/_lib/x402/pay.js
+++ b/api/_lib/x402/pay.js
@@ -58,6 +58,31 @@ export function warnCapExceeded(url, priceAtomic, capAtomic) {
);
}
+/**
+ * Does a payment of `amountAtomic` exceed the payer's known USDC float? A null
+ * or unreadable float is unknown, never a shortfall.
+ */
+export function isFloatShortfall(amountAtomic, payerUsdcAtomic) {
+ if (payerUsdcAtomic === null || payerUsdcAtomic === undefined) return false;
+ const held = Number(payerUsdcAtomic);
+ return Number.isFinite(held) && Number(amountAtomic) > held;
+}
+
+/**
+ * The error token a skipped payment should be recorded under. A caller that
+ * folds the payer's float into `remainingCap` without passing it on gets
+ * `cap_would_exceed` back for what is really an empty wallet; this restores the
+ * funding signal so the ring dashboard and settle sensor stop filing it as a
+ * benign budget skip.
+ */
+export function skipReasonFor(outcome, payerUsdcAtomic) {
+ const reason = outcome?.errorMsg ?? null;
+ if (reason === 'cap_would_exceed' && isFloatShortfall(outcome?.amountAtomic, payerUsdcAtomic)) {
+ return 'insufficient_payer_usdc';
+ }
+ return reason;
+}
+
// ── Fee floor ─────────────────────────────────────────────────────────────────
// The ring's operating rule is "lowest fees always": 1-signature self-pay
// settlement (5,000 lamports base) with the priority fee pinned at the floor.
@@ -367,6 +392,11 @@ export async function payX402({
url, method = 'POST', body = null,
buyer, conn, blockhash, mintInfo,
remainingCap = Infinity,
+ // The buyer's USDC float in atomics, when the caller has read it. Callers
+ // that bound `remainingCap` by the float pass it too, so an empty payer is
+ // reported as `insufficient_payer_usdc` (a funding problem) rather than
+ // `cap_would_exceed` with advice to raise cap env vars that are not the limit.
+ payerUsdcAtomic = null,
userAgent = 'threews-x402-autonomous/1.0',
// Batch pipelines pass their own position; everyone else gets a distinct
// per-process nonce below so same-amount payments sharing a tick blockhash
@@ -454,6 +484,9 @@ export async function payX402({
}
const attemptAmount = Number(currentAccept.amount || 0);
+ if (isFloatShortfall(attemptAmount, payerUsdcAtomic)) {
+ return { skip: { success: false, paid: false, free: false, skipped: true, amountAtomic: attemptAmount, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'insufficient_payer_usdc' } };
+ }
if (attemptAmount > remainingCap) {
warnCapExceeded(url, attemptAmount, Number.isFinite(remainingCap) ? remainingCap : 0);
return { skip: { success: false, paid: false, free: false, skipped: true, amountAtomic: attemptAmount, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'cap_would_exceed' } };
diff --git a/api/_lib/x402/pipelines/sniper-intel-enrich.js b/api/_lib/x402/pipelines/sniper-intel-enrich.js
index 8a9c0cc49..7a56db14b 100644
--- a/api/_lib/x402/pipelines/sniper-intel-enrich.js
+++ b/api/_lib/x402/pipelines/sniper-intel-enrich.js
@@ -250,6 +250,9 @@ export async function run(ctx = {}) {
const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
const endpointUrl = `${origin}${ENDPOINT_PATH}`;
let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+ // The payer's float as the loop read it, so an empty wallet is reported as
+ // insufficient_payer_usdc rather than as a cap that needs raising.
+ let payerUsdc = ctx.payerUsdcAtomic == null ? null : Number(ctx.payerUsdcAtomic);
// ── Schema first: without the sentiment sink there's nothing to extract, so don't pay.
try {
@@ -313,6 +316,7 @@ export async function run(ctx = {}) {
body: { topic, mint },
buyer, conn, blockhash, mintInfo,
remainingCap,
+ payerUsdcAtomic: payerUsdc,
userAgent: 'threews-x402-sniper-intel/1.0',
});
} catch (err) {
@@ -329,6 +333,7 @@ export async function run(ctx = {}) {
if (result.paid) {
spentAtomic += result.amountAtomic;
remainingCap -= result.amountAtomic;
+ if (payerUsdc !== null) payerUsdc -= result.amountAtomic;
paid += 1;
if (result.txSig) lastTxSig = result.txSig;
}
diff --git a/api/_lib/x402/pipelines/token-intel-gate.js b/api/_lib/x402/pipelines/token-intel-gate.js
index d5dabbbfd..f2a8214fb 100644
--- a/api/_lib/x402/pipelines/token-intel-gate.js
+++ b/api/_lib/x402/pipelines/token-intel-gate.js
@@ -203,6 +203,9 @@ export async function run(ctx = {}) {
const runId = ctx.runId || randomUUID();
const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+ // The payer's float as the loop read it, so an empty wallet is reported as
+ // insufficient_payer_usdc rather than as a cap that needs raising.
+ let payerUsdc = ctx.payerUsdcAtomic == null ? null : Number(ctx.payerUsdcAtomic);
// ── Schema first: without the verdict sink there's nothing to extract, so don't pay.
try {
@@ -254,6 +257,7 @@ export async function run(ctx = {}) {
method: 'GET',
buyer, conn, blockhash, mintInfo,
remainingCap,
+ payerUsdcAtomic: payerUsdc,
userAgent: 'threews-x402-presnipe-gate/1.0',
});
} catch (err) {
@@ -269,6 +273,7 @@ export async function run(ctx = {}) {
if (result.paid) {
spentAtomic += result.amountAtomic;
remainingCap -= result.amountAtomic;
+ if (payerUsdc !== null) payerUsdc -= result.amountAtomic;
paid += 1;
if (result.txSig) lastTxSig = result.txSig;
}
diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.js
index 294a15b07..b3112c569 100644
--- a/api/cron/x402-autonomous-loop.js
+++ b/api/cron/x402-autonomous-loop.js
@@ -46,6 +46,7 @@ import {
expectedFeeLamports,
nextAutoNonce,
currentBlockhash,
+ skipReasonFor,
} from '../_lib/x402/pay.js';
import { assessFeeAdmission } from '../_lib/x402/wallet-fee-meter.js';
import {
@@ -463,7 +464,7 @@ export default wrapCron(async (req, res) => {
amountAtomic = Number(outcome.amountAtomic) || 0;
txSig = outcome.txSig || null;
success = outcome.success ?? false;
- errorMsg = outcome.errorMsg || errorMsg;
+ errorMsg = skipReasonFor(outcome, payerUsdcAtomic) || errorMsg;
responseBody = outcome.responseData ?? null;
signalData = outcome.signalData ?? null;
diff --git a/tests/x402-pay-float-shortfall.test.js b/tests/x402-pay-float-shortfall.test.js
new file mode 100644
index 000000000..38a8a6a51
--- /dev/null
+++ b/tests/x402-pay-float-shortfall.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
+import http from 'node:http';
+import { Keypair } from '@solana/web3.js';
+
+// The autonomous loop bounds every run() pipeline's remainingCap by the payer's
+// USDC float. With the payer down to 341 atomics on 2026-10-08, every $0.01 call
+// came back `cap_would_exceed` with a warning to raise cap env vars, and the ring
+// dashboard filed it as a benign amber skip: an empty wallet read as a budget
+// guard. A float shortfall must be named `insufficient_payer_usdc`.
+
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const { payX402, isFloatShortfall, skipReasonFor } = await import('../api/_lib/x402/pay.js');
+
+const payTo = Keypair.generate().publicKey.toBase58();
+const feePayer = Keypair.generate().publicKey.toBase58();
+const PRICE = 10_000;
+
+let server;
+let origin;
+let paidAttempts = 0;
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ if (req.headers['x-payment']) paidAttempts++;
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({
+ x402Version: 2,
+ accepts: [{
+ scheme: 'exact', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', asset: USDC, payTo,
+ amount: String(PRICE), extra: { name: 'USDC', decimals: 6, feePayer },
+ }],
+ }));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(() => server?.close());
+
+const ctx = () => ({
+ buyer: Keypair.generate(),
+ conn: {},
+ blockhash: '11111111111111111111111111111111',
+ mintInfo: { decimals: 6 },
+});
+
+describe('payX402 float shortfall', () => {
+ it('reports an empty payer as insufficient_payer_usdc and never warns about caps', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const out = await payX402({ url: `${origin}/intel-a`, method: 'GET', ...ctx(), remainingCap: 341, payerUsdcAtomic: 341 });
+ expect(out.skipped).toBe(true);
+ expect(out.errorMsg).toBe('insufficient_payer_usdc');
+ expect(out.amountAtomic).toBe(PRICE);
+ expect(warn.mock.calls.some((c) => String(c[0]).includes('price_exceeds_cap'))).toBe(false);
+ expect(paidAttempts).toBe(0);
+ warn.mockRestore();
+ });
+
+ it('still reports a real budget limit as cap_would_exceed when the float covers the call', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const out = await payX402({ url: `${origin}/intel-b`, method: 'GET', ...ctx(), remainingCap: 5_000, payerUsdcAtomic: 2_000_000 });
+ expect(out.errorMsg).toBe('cap_would_exceed');
+ expect(paidAttempts).toBe(0);
+ warn.mockRestore();
+ });
+
+ it('keeps the old behavior for callers that do not pass the float', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const out = await payX402({ url: `${origin}/intel-c`, method: 'GET', ...ctx(), remainingCap: 341 });
+ expect(out.errorMsg).toBe('cap_would_exceed');
+ warn.mockRestore();
+ });
+});
+
+describe('isFloatShortfall', () => {
+ it('treats an unknown float as no shortfall', () => {
+ expect(isFloatShortfall(PRICE, null)).toBe(false);
+ expect(isFloatShortfall(PRICE, undefined)).toBe(false);
+ expect(isFloatShortfall(PRICE, 'not-a-number')).toBe(false);
+ });
+
+ it('flags only an amount above the float', () => {
+ expect(isFloatShortfall(PRICE, 341)).toBe(true);
+ expect(isFloatShortfall(PRICE, PRICE)).toBe(false);
+ expect(isFloatShortfall(PRICE, 0)).toBe(true);
+ });
+});
+
+describe('skipReasonFor (the loop relabel for pipelines that do not pass the float)', () => {
+ it('relabels a cap skip the float explains', () => {
+ expect(skipReasonFor({ errorMsg: 'cap_would_exceed', amountAtomic: PRICE }, 341)).toBe('insufficient_payer_usdc');
+ });
+
+ it('leaves a cap skip the float does not explain', () => {
+ expect(skipReasonFor({ errorMsg: 'cap_would_exceed', amountAtomic: PRICE }, 5_000_000)).toBe('cap_would_exceed');
+ expect(skipReasonFor({ errorMsg: 'cap_would_exceed', amountAtomic: PRICE }, null)).toBe('cap_would_exceed');
+ });
+
+ it('passes every other reason through unchanged', () => {
+ expect(skipReasonFor({ errorMsg: 'missing_fee_payer', amountAtomic: PRICE }, 0)).toBe('missing_fee_payer');
+ expect(skipReasonFor({}, 0)).toBe(null);
+ expect(skipReasonFor(null, 0)).toBe(null);
+ });
+});
+
+describe('the autonomous loop records the relabelled reason', () => {
+ it('routes run() outcomes through skipReasonFor', async () => {
+ const { readFileSync } = await import('node:fs');
+ const src = readFileSync(new URL('../api/cron/x402-autonomous-loop.js', import.meta.url), 'utf8');
+ expect(src).toMatch(/errorMsg = skipReasonFor\(outcome, payerUsdcAtomic\)/);
+ });
+});