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): spend each fee admission out of its snapshot so paced wallets stop starting doomed settles

overstepping22f1e08df94c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 602e17b77..77174144d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-24
- **Paying the Club cover in USDC works in wallets that refused to show the request**: Some visitors paying the Club cover in USDC saw their wallet refuse to open the approval window, and the payment stopped with "Your wallet could not display this payment request". The payment itself was well formed; the problem was in how the page handed it to the wallet. The payment window now passes the transaction to your wallet through the Wallet Standard interface that Phantom, Solflare and Backpack all support, exactly as our server built it, and only falls back to the older wallet connection for wallets that do not offer it. Nothing was ever charged on a refused attempt. (`/club`) `[fix]`
+- **The x402 payment rail stops starting payments it cannot afford to finish**: The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget. (`/economy-lab`) `[fix, infra]`
## 2026-09-22
diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.js
index f5c397adf..97d421dbb 100644
--- a/api/_lib/economy-sweepback.js
+++ b/api/_lib/economy-sweepback.js
@@ -374,15 +374,32 @@ export function reclaimKeepLineSol(minSol) {
* @param {number} minSol
* @returns {{name:string, reason:string, heldSol:number, keepSol:number, floorSol:number}}
*/
-export function floorBlockedSkip(name, currentSol, minSol) {
+export function floorBlockedSkip(name, currentSol, minSol, minSweep = MIN_SWEEP_SOL) {
const heldSol = round(Math.max(0, currentSol));
const keepSol = reclaimKeepLineSol(minSol);
+ const floorSol = round(Math.max(0, minSol));
+ // A wallet ABOVE its keep line whose excess is under the minimum sweep is not at
+ // its floor; it holds dust the sweep declines to move. Printing it as
+ // `at_or_below_floor:0.0193<0.01` contradicted itself in one token, and on
+ // 2026-09-24 31 agent wallets read that way while holding 0.161 SOL of excess
+ // between them. The lever for that SOL is ECONOMY_SWEEPBACK_MIN_SOL, not a floor.
+ const excessSol = round(heldSol - keepSol);
+ if (excessSol > 0) {
+ return {
+ name,
+ reason: `below_min_sweep:${excessSol}<${round(minSweep)}`,
+ heldSol,
+ keepSol,
+ floorSol,
+ excessSol,
+ };
+ }
return {
name,
reason: `at_or_below_floor:${heldSol}<${keepSol}`,
heldSol,
keepSol,
- floorSol: round(Math.max(0, minSol)),
+ floorSol,
};
}
@@ -605,7 +622,7 @@ export function planAgentReclaim(candidates, opts = {}) {
const floorSol = agentReclaimFloorSol(c.strategy);
const reclaimable = reclaimableSol(c.sol, floorSol, minSweep);
if (reclaimable <= 0) {
- skipped.push(floorBlockedSkip(c.name, c.sol, floorSol));
+ skipped.push(floorBlockedSkip(c.name, c.sol, floorSol, minSweep));
continue;
}
if (plan.length >= maxWallets) {
diff --git a/api/_lib/ops/x402-settle-health.js b/api/_lib/ops/x402-settle-health.js
index 7fc3aeda9..9a5b3a152 100644
--- a/api/_lib/ops/x402-settle-health.js
+++ b/api/_lib/ops/x402-settle-health.js
@@ -206,7 +206,9 @@ export function diagnoseSettleDrop({ noSolanaAccept, floorSignals, governorSkips
'at_or_below_floor or secret_undecryptable AND that plan reports ' +
'skipped_floor_held_sol 0. A floor skip carries its numbers ' +
'(at_or_below_floor:<held><<keep>), so a non-zero held total means the SOL exists on a ' +
- 'platform wallet and a floor is fencing it, not that the fleet is empty. ' +
+ 'platform wallet and a floor is fencing it, not that the fleet is empty. A ' +
+ 'below_min_sweep:<excess><<min> skip is a wallet ABOVE its keep line whose excess is under ' +
+ 'ECONOMY_SWEEPBACK_MIN_SOL: that SOL is released by the sweep minimum, not by a floor. ' +
'See docs/ops/production-log-triage.md.',
};
}
diff --git a/api/_lib/x402/sponsor-runway.js b/api/_lib/x402/sponsor-runway.js
index 40c8cfcef..5806a38ad 100644
--- a/api/_lib/x402/sponsor-runway.js
+++ b/api/_lib/x402/sponsor-runway.js
@@ -232,7 +232,8 @@ export function formatSponsorRunwayAlert(r) {
: 'Below the floor the Solana accept is withdrawn from every 402 challenge and settles stop while rail ' +
'faults stay flat, so this will not look like a rail outage when it lands.',
'Free self-heal first: POST /api/cron/treasury-topup?dry=1 (Bearer CRON_SECRET) to see the reclaim plan, ' +
- 'then without ?dry=1 to apply. Owner SOL is needed only when every source reports at_or_below_floor.',
+ 'then without ?dry=1 to apply. Owner SOL is needed only when every source reports at_or_below_floor; ' +
+ 'a below_min_sweep skip is excess above the keep line that ECONOMY_SWEEPBACK_MIN_SOL declines to move.',
topUp != null && topUp > 0
? `A top-up of about ${topUp.toFixed(3)} SOL buys 14 days at the measured burn. Send it to the SPONSOR or ` +
'the economy master, NEVER to per-agent wallets (that strands SOL and kills the rail).'
diff --git a/api/_lib/x402/wallet-fee-meter.js b/api/_lib/x402/wallet-fee-meter.js
index 6309ab2f9..bed371247 100644
--- a/api/_lib/x402/wallet-fee-meter.js
+++ b/api/_lib/x402/wallet-fee-meter.js
@@ -98,6 +98,7 @@ export function resetWalletFeeMeterCaches() {
_allowCache = { set: null, at: 0 };
_spentCache.clear();
_admissionCache.clear();
+ _admissionInflight.clear();
}
// ── Caller-side admission ───────────────────────────────────────────────────────
@@ -131,10 +132,66 @@ export function resetWalletFeeMeterCaches() {
// the budget down). One minute collapses a storm while still letting a top-up
// reopen the rail promptly.
const ADMISSION_REFUSED_TTL_MS = 60_000;
-const _admissionCache = new Map(); // pubkeyB58 → { ok, reason, at, day, ttl }
+// pubkeyB58 → { ok, reason, at, day, ttl, spent, budget, admitted }
+const _admissionCache = new Map();
+// pubkeyB58 → in-flight snapshot promise, so a burst of concurrent calls shares
+// one balance read and one ledger read instead of each racing its own.
+const _admissionInflight = new Map();
const ADMIT = { ok: true, reason: null };
+// Why an admitted snapshot carries its headroom instead of a bare "yes".
+//
+// A cached admission used to mean "admit everything for the next spentCacheMs".
+// Under intraday pacing the unlocked budget sits right at the spent line all day
+// (the wallet earns one settle's worth of budget roughly every half minute), so
+// every fresh read found room for exactly one settle and then admitted every call
+// for twenty seconds. Measured on production 2026-09-24: about 230 settles an hour
+// landed and about 1,700 an hour were refused by the settle-path meter with
+// `fee_runway_exhausted`, one wallet, every hour of the day. Each refusal had
+// already paid for an ATA read, a signature and a simulated verify, which is the
+// exact waste this gate exists to remove.
+//
+// Each admission now spends its estimated fee out of the snapshot's headroom, with
+// the same pure arithmetic the settle path runs, so one cache window admits only
+// what the budget can actually fund. The first call past the headroom turns the
+// snapshot into a refusal. It changes no money and no budget: the settles it holds
+// back were going to be refused at the end of the handshake anyway.
+function snapshotVerdict(entry, estFeeLamports, now) {
+ if (!entry.ok) return { ok: false, reason: entry.reason };
+ const verdict = assessWalletFeeBudget({
+ spentTodayLamports: entry.spent + entry.admitted,
+ budgetLamports: entry.budget,
+ nextFeeLamports: estFeeLamports,
+ });
+ if (verdict.ok) {
+ entry.admitted += Math.max(0, Number(estFeeLamports) || 0);
+ return verdict;
+ }
+ entry.ok = false;
+ entry.reason = verdict.reason;
+ entry.at = now;
+ entry.ttl = ADMISSION_REFUSED_TTL_MS;
+ return verdict;
+}
+
+async function readAdmissionSnapshot({ feeWalletB58, connection, cfg, now, day }) {
+ let solLamports;
+ try {
+ const conn = connection || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ // Shares self-facilitator.js's balance cache, so this adds no RPC traffic of
+ // its own beyond what the settle path already reads for the same wallet.
+ solLamports = await sponsorSolLamports(conn, new PublicKey(feeWalletB58), now);
+ } catch {
+ return null;
+ }
+ const spent = await spentTodayLamports(feeWalletB58, cfg.spentCacheMs, now);
+ const budget = effectiveBudgetLamports(solLamports, cfg, now);
+ const entry = { ok: true, reason: null, at: now, day, ttl: cfg.spentCacheMs, spent, budget, admitted: 0 };
+ _admissionCache.set(feeWalletB58, entry);
+ return entry;
+}
+
export async function assessFeeAdmission({
feeWalletB58, estFeeLamports = 0, connection = null, config, now = Date.now(),
} = {}) {
@@ -146,7 +203,8 @@ export async function assessFeeAdmission({
const day = utcDay(now);
const hit = _admissionCache.get(feeWalletB58);
if (hit && hit.day === day && now - hit.at < hit.ttl) {
- return { ok: hit.ok, reason: hit.reason, cached: true };
+ const verdict = snapshotVerdict(hit, estFeeLamports, now);
+ return { ok: verdict.ok, reason: verdict.reason, cached: true };
}
// Only platform-controlled wallets are governed. An external buyer self-paying
@@ -159,37 +217,24 @@ export async function assessFeeAdmission({
}
if (!allowed || !allowed.has(feeWalletB58)) return ADMIT;
- let solLamports;
- try {
- const conn = connection || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
- // Shares self-facilitator.js's balance cache, so this adds no RPC traffic of
- // its own beyond what the settle path already reads for the same wallet.
- solLamports = await sponsorSolLamports(conn, new PublicKey(feeWalletB58), now);
- } catch {
- return ADMIT;
+ let pending = _admissionInflight.get(feeWalletB58);
+ const leader = !pending;
+ if (leader) {
+ pending = readAdmissionSnapshot({ feeWalletB58, connection, cfg, now, day })
+ .finally(() => _admissionInflight.delete(feeWalletB58));
+ _admissionInflight.set(feeWalletB58, pending);
}
+ const entry = await pending;
+ // Unreadable balance: fail open, exactly like the settle-path meter.
+ if (!entry) return ADMIT;
- const spent = await spentTodayLamports(feeWalletB58, cfg.spentCacheMs, now);
- const budget = effectiveBudgetLamports(solLamports, cfg, now);
- const verdict = assessWalletFeeBudget({
- spentTodayLamports: spent,
- budgetLamports: budget,
- nextFeeLamports: estFeeLamports,
- });
-
- _admissionCache.set(feeWalletB58, {
- ok: verdict.ok,
- reason: verdict.reason,
- at: now,
- day,
- ttl: verdict.ok ? cfg.spentCacheMs : ADMISSION_REFUSED_TTL_MS,
- });
+ const verdict = snapshotVerdict(entry, estFeeLamports, now);
return {
ok: verdict.ok,
reason: verdict.reason,
- budgetLamports: budget,
- spentTodayLamports: spent,
- cached: false,
+ budgetLamports: entry.budget,
+ spentTodayLamports: entry.spent,
+ cached: !leader,
};
}
diff --git a/api/x402/runway-lab.js b/api/x402/runway-lab.js
index f689f6cbb..3a1f8d7ab 100644
--- a/api/x402/runway-lab.js
+++ b/api/x402/runway-lab.js
@@ -108,21 +108,28 @@ async function observeWindow() {
WHERE action = 'settle' AND ts >= ${since}
`;
+ // Group on the reason CLASS (the text before the first colon), not the whole
+ // string. Governor refusals carry their lamport arithmetic
+ // (`fee_runway_exhausted:8600843+10000>7509606`), so nearly every one is a
+ // distinct string; grouping on the full text under a row limit counted 391 of
+ // the 40,987 governor refusals on 2026-09-24 and reported a 92% capacity
+ // admission rate for a rail that was admitting 10%.
const reasons = await sql`
- SELECT reject_reason, COUNT(*)::int AS n
+ SELECT split_part(COALESCE(reject_reason, ''), ':', 1) AS reason_class,
+ COUNT(*)::int AS n,
+ (ARRAY_AGG(reject_reason ORDER BY ts DESC))[1] AS example
FROM x402_self_facilitator_log
WHERE action = 'settle' AND ok = false AND ts >= ${since}
- GROUP BY reject_reason
+ GROUP BY 1
ORDER BY n DESC
- LIMIT 40
`;
const buckets = new Map();
for (const row of reasons) {
- const key = bucketReason(row.reject_reason);
+ const key = bucketReason(row.reason_class);
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;
+ if (!hit.example) hit.example = row.example || null;
buckets.set(key, hit);
}
diff --git a/data/changelog.json b/data/changelog.json
index 4166b5830..83ebd77f8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -28707,6 +28707,16 @@
"fix"
],
"link": "/club"
+ },
+ {
+ "date": "2026-09-24",
+ "title": "The x402 payment rail stops starting payments it cannot afford to finish",
+ "summary": "The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget.",
+ "tags": [
+ "fix",
+ "infra"
+ ],
+ "link": "/economy-lab"
}
]
}
diff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.md
index f00a96fcf..80b9961b6 100644
--- a/docs/ops/production-log-triage.md
+++ b/docs/ops/production-log-triage.md
@@ -271,7 +271,10 @@ HTTP 502/503 GET|POST /api/x402/*, /api/mcp ua: threews-x402-autonomous/1.0 or
`skipped_floor_held_sol` 0**. A floor skip carries its numbers
(`at_or_below_floor:<held><<keep>`), so a non-zero held total means the SOL is
sitting on a platform wallet behind a configured floor, not that the fleet is
- empty; review that wallet's `minSol` before asking for capital. See
+ empty; review that wallet's `minSol` before asking for capital. A
+ `below_min_sweep:<excess><<min>` skip is a wallet above its keep line whose
+ excess is under `ECONOMY_SWEEPBACK_MIN_SOL` (default 0.01 SOL): dust the
+ sweep declines to move, released by that minimum rather than by a floor. See
[economy-master.md](../economy-master.md) "A floor skip says whether the
wallet is empty or fenced".
2. `--grep "data_unavailable"` hits = paid endpoints refunding honestly (no
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
index 07577a382..e6f46a09e 100644
--- a/docs/x402-ring-economy.md
+++ b/docs/x402-ring-economy.md
@@ -122,6 +122,14 @@ decision logic in
`api/cron/x402-autonomous-loop.js` (the autonomous buyer) gate on it; the loop
records each skip to `x402_autonomous_log` so a paced rail reads as paced rather
than as a rail nobody used.
+- **An admission spends its own headroom.** A fresh read caches the wallet's
+ budget and spent-today for `X402_WALLET_FEE_SPENT_CACHE_MS`, and every call
+ admitted from that snapshot deducts its estimated fee from it. The first call
+ past the headroom turns the snapshot into a refusal for a minute. Concurrent
+ callers share one in-flight read. Before 2026-09-24 a cached "yes" admitted
+ every call in the window, and under intraday pacing (where the unlocked budget
+ sits at the spent line all day) that let about 1,700 doomed handshakes an hour
+ reach the settle path to be refused there, beside about 230 that settled.
- **Platform wallets only.** The meter governs only wallets in
`ringAllowedAddresses()`. An external organic buyer self-paying through this
facilitator spends its own SOL and is always admitted.
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 51d924ebc..47eb9fa7d 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-09-24T06:31:21.519Z",
+ "generated_at": "2026-09-24T06:37:24.403Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3752,
+ "total": 3753,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -19,6 +19,17 @@
"fix"
]
},
+ {
+ "date": "2026-09-24",
+ "type": "update",
+ "title": "The x402 payment rail stops starting payments it cannot afford to finish",
+ "summary": "The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget.",
+ "link": "/economy-lab",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-09-22",
"type": "launch",
@@ -1598,17 +1609,6 @@
"infra",
"improvement"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The OpenAI partner page now proves the free ChatGPT connector is up instead of just claiming it",
- "summary": "The /openai page told readers that a free, keyless 3D connector answers at three.ws/api/mcp-studio and then listed the eleven tools it exposes. Both were claims on a static page. Now the page calls the connector from the reader's own browser on load and reports what came back: live with the tool count and the response time, or a plain explanation and a Check again button if the call was blocked. The printed tool table is reconciled against the same response, so every tool the server really answers with is ticked, one the server has dropped is flagged, and one the server has added since the page was written is appended with its own description. The connector URL and the curl command both got copy buttons, and hover plates on the page no longer turn near-white when the site theme is switched to light.",
- "link": "/openai",
- "tags": [
- "improvement",
- "fix"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 0f1328a83..082bcbdb6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-24T06:31:21.495Z",
+ "generated_at": "2026-09-24T06:37:24.362Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,17 @@
"fix"
]
},
+ {
+ "date": "2026-09-24",
+ "type": "update",
+ "title": "The x402 payment rail stops starting payments it cannot afford to finish",
+ "summary": "The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget.",
+ "link": "/economy-lab",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-09-22",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index c7170afda..dbc084f8b 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>Some visitors paying the Club cover in USDC saw their wallet refuse to open the approval window, and the payment stopped with &quot;Your wallet could not display this payment request&quot;. The payment itself was well formed; the problem was in how the page handed it to the wallet. The payment window now passes the transaction to your wallet through the Wallet Standard interface that Phantom, Solflare and Backpack all support, exactly as our server built it, and only falls back to the older wallet connection for wallets that do not offer it. Nothing was ever charged on a refused attempt.</description>
</item>
+ <item>
+ <title>The x402 payment rail stops starting payments it cannot afford to finish</title>
+ <link>https://three.ws/economy-lab</link>
+ <guid isPermaLink="false">2026-09-24:The x402 payment rail stops starting payments it cannot afford to finish</guid>
+ <pubDate>Thu, 24 Sep 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The platform's own agents pay each other for services over x402, and a daily budget caps how much SOL the shared fee wallet spends on network fees. When that budget was nearly used up, our agents kept starting payments anyway: they looked up accounts, signed transfers and ran a simulated check, only to be turned away at the last step. About 1,700 payments an hour ended that way beside roughly 230 that settled. Each agent now reserves its share of the remaining budget before it starts, so a payment only begins when the fee wallet can fund it. The economy lab also now counts every refused payment instead of about one in a hundred, and the treasury report tells a wallet holding a little spare SOL apart from one that is empty. Payments from customer wallets are never held back by this budget.</description>
+ </item>
<item>
<title>Authorize the three-ws CLI</title>
<link>https://three.ws/cli/authorize</link>
diff --git a/tests/economy-sweepback.test.js b/tests/economy-sweepback.test.js
index 30fe62784..2c9e84ed2 100644
--- a/tests/economy-sweepback.test.js
+++ b/tests/economy-sweepback.test.js
@@ -571,6 +571,29 @@ test('the reported keep line is the one that made the sweep return nothing', ()
}
});
+// The other half of the same defect: a wallet ABOVE its keep line whose excess is
+// merely under the minimum sweep. Production 2026-09-24 printed
+// `at_or_below_floor:0.019334483<0.01` for 31 agent wallets, a reason whose own two
+// numbers disprove it, while those wallets held 0.161 SOL of excess between them.
+test('a wallet above its keep line reports sweep dust, never a floor it is not at', () => {
+ const dust = floorBlockedSkip('Sable #25', 0.019334483, 0.005);
+ assert.equal(dust.keepSol, 0.01);
+ assert.equal(dust.excessSol, 0.009334483);
+ assert.equal(dust.reason, `below_min_sweep:0.009334483<${MIN_SWEEP_SOL}`);
+ assert.doesNotMatch(dust.reason, /at_or_below_floor/);
+ // The sizing agrees: this is exactly the case reclaimableSol returns 0 for.
+ assert.equal(reclaimableSol(0.019334483, 0.005), 0);
+
+ // The planner passes its own minimum through, so the reason names the threshold used.
+ const planned = planAgentReclaim([
+ { agentId: 'a', name: 'Sable #25', address: 'S25', owner: BOT, sol: 0.0193, strategy: { enabled: false } },
+ ], { minSweepSol: 0.02 });
+ assert.match(planned.skipped[0].reason, /^below_min_sweep:[0-9.]+<0\.02$/);
+
+ // A wallet genuinely under its keep line still reads as a floor skip.
+ assert.match(floorBlockedSkip('Swarm 1', 0.02499497, 0.05).reason, /^at_or_below_floor:/);
+});
+
test('floorHeldSol totals only the SOL a floor is fencing', () => {
const skipped = [
floorBlockedSkip('treasury', 0.054995, 0.1),
diff --git a/tests/x402-fee-admission.test.js b/tests/x402-fee-admission.test.js
index 9224e8bc4..7006c3f4d 100644
--- a/tests/x402-fee-admission.test.js
+++ b/tests/x402-fee-admission.test.js
@@ -222,6 +222,58 @@ describe('verdict cache', () => {
});
});
+describe('headroom: a cached admission funds only what the budget can pay', () => {
+ // Production 2026-09-24, paced wallet: every fresh read found room for about one
+ // settle, then the cached "yes" admitted every call for 20 seconds. ~230 settles
+ // an hour landed and ~1,700 an hour were refused at the END of the handshake by
+ // the settle-path meter. The snapshot now spends each admission's fee out of its
+ // own headroom, so the calls past it are held back before any work is done.
+ it('admits exactly the settles that fit, then refuses from the same snapshot', async () => {
+ // 1_000_000 budget, 985_000 spent: room for three 5_000-lamport settles.
+ h.sql.mockResolvedValue([{ spent: '985000' }]);
+ const verdicts = [];
+ for (let i = 0; i < 6; i++) verdicts.push(await admit({ estFeeLamports: 5_000 }));
+ expect(verdicts.map((v) => v.ok)).toEqual([true, true, true, false, false, false]);
+ // The refusal names the arithmetic, including what this window already admitted.
+ expect(verdicts[3].reason).toBe('fee_runway_exhausted:1000000+5000>1000000');
+ // One ledger read and one balance read served the whole burst.
+ expect(h.sql).toHaveBeenCalledTimes(1);
+ expect(h.sponsorSolLamports).toHaveBeenCalledTimes(1);
+ });
+
+ it('a headroom refusal holds for the refusal window, then a fresh read reopens the rail', async () => {
+ h.sql.mockResolvedValue([{ spent: '995000' }]);
+ expect((await admit()).ok).toBe(true);
+ expect((await admit()).ok).toBe(false);
+
+ // Still inside the 20s admission window, but the snapshot is now a refusal:
+ // it must not flip back to "yes" while nothing has changed.
+ vi.setSystemTime(T0 + 15_000);
+ expect((await admit()).ok).toBe(false);
+
+ vi.setSystemTime(T0 + 15_000 + 60_001);
+ h.sponsorSolLamports.mockResolvedValue(SOL_FOR_1M_BUDGET + 10_000_000);
+ const v = await admit();
+ expect(v.ok).toBe(true);
+ expect(v.cached).toBe(false);
+ });
+
+ it('concurrent callers share one snapshot and still admit no more than it funds', async () => {
+ // A ring tick fires its calls in parallel. Before single-flight, every one of
+ // them missed the cache together, read the same headroom, and all said yes.
+ h.sql.mockResolvedValue([{ spent: '990000' }]);
+ const verdicts = await Promise.all(Array.from({ length: 8 }, () => admit({ estFeeLamports: 5_000 })));
+ expect(verdicts.filter((v) => v.ok)).toHaveLength(2);
+ expect(h.sql).toHaveBeenCalledTimes(1);
+ expect(h.sponsorSolLamports).toHaveBeenCalledTimes(1);
+ });
+
+ it('an unreadable ledger still fails open for every caller in the window', async () => {
+ h.sql.mockRejectedValue(new Error('db down'));
+ for (let i = 0; i < 4; i++) expect((await admit()).ok).toBe(true);
+ });
+});
+
describe('parity with the settle-path meter', () => {
// The gate's whole value is that it predicts the settle path's answer. A laxer
// admission re-creates the wasted handshakes it exists to remove; a stricter