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): let buyers actually pay in $THREE, and stop quoting a door we cannot open

nirholasf32607388caa
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 275f40f4e..859947f21 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -1164,7 +1164,11 @@ export async function settlePayment(args) {
// (tens of thousands of 502 settle_failed rows during the July 2026 dry
// spells). 503 + the retryable code tells callers to back off and retry;
// genuinely unexplained settle failures stay 502.
- if (/^(fee_wallet_below_floor|sponsor_sol_floor|sol_floor)/.test(reason)) {
+ // `fee_wallet_cannot_cover_settle` is the same class: the wallet clears the
+ // floor but not by this settle's own cost (an ATA-create for a mint the
+ // recipient has never held carries ~0.00204 SOL of rent). Same cure, a
+ // top-up, so it must not read as a broken endpoint either.
+ if (/^(fee_wallet_below_floor|fee_wallet_cannot_cover_settle|sponsor_sol_floor|sol_floor)/.test(reason)) {
throw new X402Error(
'settlement_unavailable',
`settlement temporarily unavailable: ${reason} (sponsor wallet below its SOL floor; retry after it is refunded)`,
diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.js
index 2fa0ed0df..a73a5202b 100644
--- a/api/_lib/x402/self-facilitator.js
+++ b/api/_lib/x402/self-facilitator.js
@@ -399,6 +399,19 @@ function noteFloorState(lamports, now) {
_floorState = { below: lamports < SPONSOR_SOL_FLOOR_LAMPORTS, at: now };
}
+/**
+ * Record floor state only for the wallet the 402 challenge actually advertises.
+ *
+ * `_floorState` gates whether buildRequirements keeps offering the SPONSORED
+ * Solana accept, so it is only meaningful for X402_FEE_PAYER_SOLANA. Recording
+ * it from any fee wallet let a healthy self-pay buyer stamp `below:false` and
+ * re-advertise a starved sponsor for the full FLOOR_STATE_MS, which is how a
+ * dry sponsor kept handing out accepts that could not settle (2026-09).
+ */
+function noteFloorStateFor(pubkeyB58, lamports, now) {
+ if (pubkeyB58 === env.X402_FEE_PAYER_SOLANA) noteFloorState(lamports, now);
+}
+
/**
* Is this simulation error the chain saying the FEE PAYER cannot afford the fee
* without dropping below rent exemption?
@@ -491,7 +504,7 @@ export async function sponsorSolLamports(conn, feePayerPubkey, now = Date.now())
if (hit && hit.lamports != null && now - hit.at < SOL_CACHE_MS) return hit.lamports;
const lamports = await conn.getBalance(feePayerPubkey, 'confirmed');
_solCache.set(key, { lamports, at: now });
- noteFloorState(lamports, now);
+ noteFloorStateFor(key, lamports, now);
return lamports;
}
@@ -501,7 +514,7 @@ function bumpSolCache(pubkeyB58, deltaLamports) {
const hit = _solCache.get(pubkeyB58);
if (hit && hit.lamports != null) {
hit.lamports = Math.max(0, hit.lamports - deltaLamports);
- noteFloorState(hit.lamports, Date.now());
+ noteFloorStateFor(pubkeyB58, hit.lamports, Date.now());
}
}
@@ -577,6 +590,24 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee
};
}
+ // The floor is a reserve that must SURVIVE this settle, so the wallet has to
+ // clear it by the cost of the settle itself, not merely sit above it.
+ // estFeeLamports carries the ATA-create rent (~0.00204 SOL) when the recipient
+ // has no token account for this mint yet, which is the normal state the first
+ // time a resource is paid in a new token. Comparing the bare balance let such
+ // a settle pass the gate and then die on chain with InsufficientFundsForRent,
+ // a confusing failure at exactly the moment a new payment token goes live.
+ if (solLamports - estFeeLamports < SPONSOR_SOL_FLOOR_LAMPORTS) {
+ return {
+ success: false,
+ reason: `fee_wallet_cannot_cover_settle:${solLamports}-${estFeeLamports}<${SPONSOR_SOL_FLOOR_LAMPORTS}`,
+ sponsorSolLamports: solLamports,
+ estFeeLamports,
+ feePayer: decoded.feePayer,
+ selfPay,
+ };
+ }
+
// Wallet fee governor: admit this settle only if the fee-paying wallet still
// has daily fee budget. Governs every tenant of a shared wallet at the one
// choke point they all pass through, instead of throttling one pipeline while
diff --git a/api/x402/club-cover.js b/api/x402/club-cover.js
index 29d029a76..62ba18a81 100644
--- a/api/x402/club-cover.js
+++ b/api/x402/club-cover.js
@@ -31,9 +31,10 @@ import clubCoverListing from '../_lib/service-catalog/services/club-cover.js';
const ROUTE = '/api/x402/club-cover';
-// PASS_TTL_SEC + the bouncer (ban/tier/pass) live in ../_lib/club/cover-pass.js
-// so the USDC door here and the $THREE door (api/club/cover-three.js) issue an
-// identical pass.
+// PASS_TTL_SEC + the bouncer (ban/tier/pass) live in ../_lib/club/cover-pass.js.
+// There is one door, not two: this route's 402 advertises both the USDC and the
+// $THREE accept (see X402_ACCEPT_THREE_SOLANA in api/_lib/env.js), so whichever
+// token the buyer picks in the checkout issues the same pass.
// Single source of truth: api/_lib/service-catalog/services/club-cover.js is
// the storefront listing copy — importing it here keeps the live 402 challenge
@@ -103,8 +104,8 @@ const BAZAAR = {
};
// normalizeWallet / findBan / visitsFor / tierFor live in
-// ../_lib/club/cover-pass.js so the USDC door here and the $THREE door share
-// one bouncer (and one DB-backed ban/tier lookup). Imported above.
+// ../_lib/club/cover-pass.js, so the bouncer (and its DB-backed ban/tier
+// lookup) is one implementation regardless of which token paid. Imported above.
export const BAZAAR_SCHEMA = BAZAAR;
diff --git a/data/changelog.json b/data/changelog.json
index 49bd6bc92..cba5b0c5b 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-08",
+ "title": "The club now takes $THREE at the door and at the stage, not just USDC",
+ "summary": "The club has always advertised two ways to pay: USDC or $THREE, on Solana, for both the cover charge and every dance tip. Only one of them was reachable. The checkout window picked the first token a service offered and gave you no way to choose the other, so $THREE was quoted on every paid page and payable on none of them. Across every club tip ever settled, not one was paid in $THREE, which is what you would expect from a menu with a hidden second item. The checkout now shows a token picker whenever a service quotes more than one, with each token's real price on it, so you can compare 0.001 USDC against its $THREE equivalent before you approve anything, and the price at the top of the window follows what you pick. If you have agent wallets, they still pay in USDC only, and the window now says so instead of quietly hiding them when you switch tokens. Two settlement bugs behind the door were fixed at the same time. The first would have hit the very first person to pay in $THREE: sending a token to a wallet that has never held it requires opening an account for it on-chain, and the check that decides whether we can afford to sponsor a payment was ignoring that cost, so the payment would have been accepted and then failed on-chain for a reason that looked like something else entirely. The second was making the club look open when it was not: a healthy payer covering their own fees could reset a shared 'we can still sponsor payments' flag that belonged to a different wallet, so the door kept quoting prices it could not actually take. Finally, when payments are paused because the wallet that settles them needs topping up, the checkout now says that in a sentence and tells you nothing was charged, instead of showing you the raw error envelope it used to paste in, which read like a broken link.",
+ "tags": ["fix", "improvement"],
+ "link": "/club"
+ },
{
"date": "2026-09-08",
"title": "Forge tells you when uploads are down, instead of blaming your connection",
diff --git a/public/x402.js b/public/x402.js
index b17a9c6a9..49f4af043 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -123,6 +123,33 @@ function isEvmNetwork(net) {
return typeof net === 'string' && net.startsWith('eip155:');
}
+/** Display symbol for an accept's asset, normalizing the long USDC name. */
+function assetSymbol(accept) {
+ return String(accept?.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+}
+
+/**
+ * Every Solana accept the challenge offers, one per distinct asset mint and in
+ * advertised order (so the server's preferred token stays first / default).
+ *
+ * A resource may price itself in several tokens on the same network: three.ws
+ * advertises USDC and $THREE on every paid endpoint. The modal used to take the
+ * first Solana accept and offer no way to reach the rest, so a second token was
+ * advertised in the 402 but unpayable in the browser.
+ */
+function solanaAcceptsOf(challenge) {
+ const seen = new Set();
+ const out = [];
+ for (const accept of challenge?.accepts || []) {
+ if (!isSolanaNetwork(accept.network)) continue;
+ const key = accept.asset || assetSymbol(accept);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(accept);
+ }
+ return out;
+}
+
// Resolve the active injected Solana wallet provider. Priority mirrors
// src/onchain/adapters/solana.js so the drop-in modal recognizes the SAME
// wallets the rest of three.ws does — most importantly the platform's own
@@ -841,6 +868,33 @@ const STYLES = `
margin: 4px 0 0;
}
+/* Token chooser: shown only when one network advertises the same resource in
+ more than one asset (e.g. USDC and $THREE on Solana). Without it the modal
+ silently settled the first accept and a second advertised token was
+ unreachable no matter what the buyer held. */
+.x402-token-choice {
+ display: flex; gap: 6px; margin: 0 0 10px;
+}
+.x402-token-btn {
+ flex: 1 1 0; min-width: 0; padding: 8px 10px;
+ background: #ffffff; border: 1.5px solid #e2e5ec; border-radius: 10px;
+ font-family: inherit; cursor: pointer; text-align: center;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-token-btn:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-token-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-token-btn[aria-checked="true"] { border-color: #0a84ff; background: #f0f7ff; }
+.x402-token-btn:focus-visible { outline: 2px solid #0a84ff; outline-offset: 2px; }
+.x402-token-sym {
+ display: block; font-size: 13px; font-weight: 700; color: #0f0f0f;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.x402-token-amt {
+ display: block; font-size: 11px; font-weight: 500; color: #8a90a8;
+ margin-top: 1px; font-feature-settings: 'tnum' 1;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+
.x402-pay-btn {
width: 100%; padding: 14px 16px;
background: #0f0f0f; color: #fff; border: none;
@@ -1008,6 +1062,11 @@ const STYLES = `
.x402-wallet-meta { color: #6b7088; }
.x402-wallet-sub { color: #6b7088; }
.x402-wallet-group-label { color: #6b7088; }
+ .x402-token-btn { background: #1d1d1d; border-color: #2e2e2e; }
+ .x402-token-btn:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
+ .x402-token-btn[aria-checked="true"] { background: #10243a; border-color: #0a84ff; }
+ .x402-token-sym { color: #e6e8f0; }
+ .x402-token-amt { color: #6b7088; }
.x402-pay-btn { background: #ffffff; color: #0f0f0f; }
.x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
.x402-pay-btn:disabled { background: #2e2e2e; color: #5a6378; }
@@ -1225,18 +1284,60 @@ class CheckoutModal {
setPrice(accept) {
const decimals = accept.extra?.decimals ?? 6;
const amount = formatAmount(accept.amount, decimals);
- const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+ const sym = assetSymbol(accept);
this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
this.networkEl.textContent = networkLabel(accept.network, accept);
}
+ /**
+ * The Solana accept the buyer is currently paying with: their explicit token
+ * choice when they made one, otherwise the first token the server advertised.
+ */
+ pickedSolanaAccept() {
+ // Derive lazily too: renderConnect is reachable from retry paths that may
+ // not have gone through start() on this challenge object.
+ if (!this.solanaAccepts) this.solanaAccepts = solanaAcceptsOf(this.challenge);
+ const list = this.solanaAccepts;
+ if (!list.length) return undefined;
+ const picked = this.solanaAssetKey
+ ? list.find((a) => (a.asset || assetSymbol(a)) === this.solanaAssetKey)
+ : null;
+ return picked || list[0];
+ }
+
+ /**
+ * Token chooser for a resource priced in more than one Solana asset. Renders
+ * nothing for the single-token case, so the common checkout is unchanged.
+ */
+ renderTokenChoice() {
+ const list = this.solanaAccepts || [];
+ if (list.length < 2) return '';
+ const active = this.pickedSolanaAccept();
+ const options = list.map((accept) => {
+ const key = accept.asset || assetSymbol(accept);
+ const sym = assetSymbol(accept);
+ const amount = formatAmount(accept.amount, accept.extra?.decimals ?? 6);
+ const on = accept === active;
+ return `
+ <button class="x402-token-btn" role="radio" aria-checked="${on ? 'true' : 'false'}"
+ data-token="${escapeHtml(key)}" title="${escapeHtml(`Pay ${amount} ${sym}`)}">
+ <span class="x402-token-sym">${escapeHtml(sym)}</span>
+ <span class="x402-token-amt">${escapeHtml(amount)}</span>
+ </button>
+ `;
+ }).join('');
+ return `<div class="x402-token-choice" role="radiogroup" aria-label="Pay with">${options}</div>`;
+ }
+
renderConnect() {
this.currentView = 'connect';
const solanaProvider = detectSolanaProvider();
const phantomDetected = !!solanaProvider;
const evmDetected = typeof window !== 'undefined' && window.ethereum;
- const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
+ const solanaAccept = this.pickedSolanaAccept();
const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
+ // Keep the header price in step with the chosen token.
+ if (solanaAccept) { this.accept = solanaAccept; this.setPrice(solanaAccept); }
// Charity / round-up giving — only when the merchant configured it and the
// cause wallet is reachable on this Solana checkout. Default-included, but
@@ -1266,7 +1367,12 @@ class CheckoutModal {
// is actually detected. Zero wallets (must install) or two (must choose)
// still fall through to the picker, as does the SIWX "you haven't paid"
// fallback, which needs to explain itself. One-shot via autoConnectTried.
- if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice) {
+ // A multi-token resource always shows the picker at least once: skipping
+ // straight to the signature would silently commit the buyer to the first
+ // advertised token and hide the fact that the other one is payable at all.
+ // Once they pick, the choice is explicit and autoConnect is moot.
+ const mustChooseToken = (this.solanaAccepts?.length || 0) > 1 && !this.solanaAssetKey;
+ if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice && !mustChooseToken) {
this.autoConnectTried = true;
const solanaViable = !!(solanaAccept && phantomDetected);
const evmViable = !!(evmAccept && evmDetected);
@@ -1289,8 +1395,14 @@ class CheckoutModal {
// Solana accept charges USDC, matching the server-side mint pin in
// api/x402-pay (it refuses to sign any other SPL asset from an agent key).
const agentButtons = [];
- const agentSym = (solanaAccept?.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
- if (solanaAccept && agentSym === 'USDC' && Array.isArray(this.agentWallets) && this.agentWallets.length) {
+ const agentSym = solanaAccept ? assetSymbol(solanaAccept) : 'USDC';
+ const hasAgents = Array.isArray(this.agentWallets) && this.agentWallets.length > 0;
+ // Say WHY the agent wallets went away when the buyer switches to a token
+ // they cannot sign, instead of letting the list silently disappear.
+ const agentNote = hasAgents && solanaAccept && agentSym !== 'USDC'
+ ? `<div class="x402-trust">Your agent wallets pay in USDC only: switch to USDC to use them, or pay ${escapeHtml(agentSym)} from a browser wallet.</div>`
+ : '';
+ if (solanaAccept && agentSym === 'USDC' && hasAgents) {
const decimals = Number(solanaAccept.extra?.decimals ?? 6);
const priceUsdc = Number(solanaAccept.amount) / 10 ** decimals;
for (const agent of this.agentWallets.slice(0, 4)) {
@@ -1343,12 +1455,32 @@ class CheckoutModal {
${this.renderSteps('connect', { discover: 'done' })}
${payeeBox}
${fallbackBox}
+ ${this.renderTokenChoice()}
${givingBox}
<div class="x402-wallet-buttons">${walletList}</div>
+ ${agentNote}
<div class="x402-trust">${trustLine}</div>
`;
const giveEl = this.bodyEl.querySelector('[data-giving]');
if (giveEl) giveEl.addEventListener('change', (e) => { this.includeDonation = !!e.target.checked; });
+ // Token chooser: re-render so the price row, the giving box (its round-up
+ // is denominated in the paying asset) and the agent-wallet list all follow
+ // the newly chosen token.
+ this.bodyEl.querySelectorAll('[data-token]').forEach((b) => {
+ b.addEventListener('click', () => {
+ const key = b.dataset.token;
+ if (this.solanaAssetKey === key) return;
+ this.solanaAssetKey = key;
+ this.renderConnect();
+ // Keep focus on the token the buyer just chose. Matched by walking
+ // the fresh buttons rather than by selector: a mint is caller-shaped
+ // text, so building a selector out of it needs escaping the modal
+ // should not depend on.
+ const again = [...this.bodyEl.querySelectorAll('[data-token]')]
+ .find((el) => el.dataset.token === key);
+ try { again?.focus(); } catch { /* focus is best-effort */ }
+ });
+ });
const onClick = (e) => {
const btn = e.target.closest('[data-wallet]');
if (!btn || btn.disabled) return;
@@ -1381,7 +1513,7 @@ class CheckoutModal {
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
<button class="x402-pay-btn" data-action="siwx">${siwxLabel}</button>
- <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
+ <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} ${escapeHtml(assetSymbol(this.accept))} instead</button>
<div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
`;
const siwxBtn = this.bodyEl.querySelector('[data-action="siwx"]');
@@ -1551,7 +1683,12 @@ class CheckoutModal {
// first), so EVM users simply click the EVM option. Falls back to the
// first EIP-3009 EVM entry (skipping Permit2 siblings the modal can't
// sign for), then the first accept.
- const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));
+ // A resource can price itself in several Solana tokens (USDC and
+ // $THREE). Default to the first advertised one and let renderConnect
+ // offer the rest through the token chooser.
+ this.solanaAccepts = solanaAcceptsOf(challenge);
+ this.solanaAssetKey = null;
+ const solana = this.pickedSolanaAccept();
const evm = challenge.accepts.find(isEip3009Accept);
this.accept = solana || evm || challenge.accepts[0];
this.setPrice(this.accept);
@@ -2324,6 +2461,22 @@ async function discoverChallenge(opts) {
// case, surface a clear error — accidentally pointing the modal at a
// free endpoint should not silently succeed.
const txt = await res.text();
+ // A paid endpoint that cannot settle right now answers 503
+ // settlement_unavailable (the sponsor wallet is under its SOL floor, or
+ // the fee budget is spent). That is a temporary funding gap on our side,
+ // not a broken link or a buyer mistake, so say so in a sentence instead
+ // of pasting a JSON envelope at someone trying to walk through a door.
+ let parsed = null;
+ try { parsed = JSON.parse(txt); } catch { /* not JSON: fall through */ }
+ if (res.status === 503 || parsed?.error === 'settlement_unavailable') {
+ const err = new Error(
+ 'Payments are temporarily paused while we top up the wallet that settles them. ' +
+ 'Nothing was charged. Try again shortly.',
+ );
+ err.code = 'settlement_unavailable';
+ err.retryable = true;
+ throw err;
+ }
throw new Error(`Endpoint did not return 402 (got ${res.status}). Body: ${txt.slice(0, 120)}`);
}
diff --git a/tests/public/x402-token-chooser.test.js b/tests/public/x402-token-chooser.test.js
new file mode 100644
index 000000000..c7c9ce0f9
--- /dev/null
+++ b/tests/public/x402-token-chooser.test.js
@@ -0,0 +1,266 @@
+// @vitest-environment jsdom
+//
+// The drop-in payment modal's token chooser (public/x402.js).
+//
+// A three.ws 402 advertises the same resource in more than one Solana asset:
+// USDC first, then $THREE. The modal used to take the first Solana accept with
+// `.find()` and offer no way to reach the rest, so $THREE was advertised on
+// every paid endpoint and payable on none of them from a browser: 666,971
+// settled /club tips and not one in $THREE. These tests pin the chooser that
+// closes that gap, and the autoConnect interaction that would otherwise skip
+// straight past it and silently commit the buyer to USDC.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { pay } from '../../public/x402.js';
+
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const PAY_TO = THREE_MINT;
+const SOLANA_NET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+
+/** The USDC leg: first in `accepts`, matching what the server advertises. */
+const usdcAccept = {
+ scheme: 'exact',
+ network: SOLANA_NET,
+ amount: '1000', // $0.001: the /club dance-tip price
+ asset: USDC_MINT,
+ payTo: PAY_TO,
+ maxTimeoutSeconds: 60,
+ resource: 'https://three.ws/api/x402/dance-tip',
+ extra: { name: 'USDC', decimals: 6, feePayer: PAY_TO },
+};
+
+/** The $THREE leg: second, and unreachable before the chooser existed. */
+const threeAccept = {
+ ...usdcAccept,
+ amount: '10000000', // 10 THREE
+ asset: THREE_MINT,
+ extra: { name: 'THREE', decimals: 6, feePayer: PAY_TO },
+};
+
+function stub402(accepts) {
+ return {
+ status: 402,
+ headers: { get: () => null },
+ json: async () => ({ accepts }),
+ text: async () => '{"error":"payment required"}',
+ };
+}
+
+function flush() {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+function tokenButtons() {
+ return [...document.querySelectorAll('[data-token]')];
+}
+
+function closeModal(p) {
+ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));
+ return p.catch(() => {});
+}
+
+describe('x402 modal: multi-token chooser', () => {
+ beforeEach(() => {
+ document.body.innerHTML = '';
+ window.phantom = { solana: { isPhantom: true } };
+ global.fetch = vi.fn(async () => stub402([usdcAccept, threeAccept]));
+ global.requestAnimationFrame = (cb) => setTimeout(() => cb(Date.now()), 0);
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ });
+
+ afterEach(() => {
+ delete window.phantom;
+ vi.restoreAllMocks();
+ });
+
+ it('offers one button per advertised Solana asset, in advertised order', async () => {
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ const btns = tokenButtons();
+ expect(btns.map((b) => b.dataset.token)).toEqual([USDC_MINT, THREE_MINT]);
+ expect(btns.map((b) => b.querySelector('.x402-token-sym').textContent)).toEqual(['USDC', 'THREE']);
+ // Each button shows what that token actually costs, so the buyer compares
+ // prices before picking rather than after signing.
+ expect(btns[0].querySelector('.x402-token-amt').textContent).toBe('0.001');
+ expect(btns[1].querySelector('.x402-token-amt').textContent).toBe('10.00');
+
+ await closeModal(p);
+ });
+
+ it('defaults to the first advertised token and marks it checked', async () => {
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ const [usdcBtn, threeBtn] = tokenButtons();
+ expect(usdcBtn.getAttribute('aria-checked')).toBe('true');
+ expect(threeBtn.getAttribute('aria-checked')).toBe('false');
+ // Header price row reflects the default token.
+ expect(document.querySelector('.x402-currency')?.textContent.trim()).toBe('USDC');
+
+ await closeModal(p);
+ });
+
+ it('switches the header price and checked state when THREE is picked', async () => {
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ tokenButtons()[1].click();
+ await flush();
+
+ const [usdcBtn, threeBtn] = tokenButtons();
+ expect(threeBtn.getAttribute('aria-checked')).toBe('true');
+ expect(usdcBtn.getAttribute('aria-checked')).toBe('false');
+ expect(document.querySelector('.x402-currency')?.textContent.trim()).toBe('THREE');
+
+ await closeModal(p);
+ });
+
+ it('carries the THREE mint into the on-chain flow, not USDC', async () => {
+ // The strongest observable proof that the choice is real: the balance
+ // probe the modal fires before signing names a specific mint. If picking
+ // THREE only repainted the header, this would still read the USDC mint.
+ const probedMints = [];
+ window.phantom.solana.connect = async () => ({
+ publicKey: { toString: () => 'Payer1111111111111111111111111111111111111' },
+ });
+ global.fetch = vi.fn(async (url, init) => {
+ if (String(url).includes('solana-rpc')) {
+ const body = String(init?.body || '');
+ for (const mint of [USDC_MINT, THREE_MINT]) {
+ if (body.includes(mint)) probedMints.push(mint);
+ }
+ return {
+ ok: true,
+ json: async () => ({
+ result: {
+ value: [{
+ account: {
+ data: { parsed: { info: { tokenAmount: { amount: '999000000', decimals: 6 } } } },
+ },
+ }],
+ },
+ }),
+ };
+ }
+ return stub402([usdcAccept, threeAccept]);
+ });
+ // Stop the flow at signing: the mint has already been committed by then.
+ window.phantom.solana.signTransaction = async () => {
+ throw new Error('stop after asset selection');
+ };
+
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ tokenButtons()[1].click();
+ await flush();
+ expect(document.querySelector('.x402-currency')?.textContent.trim()).toBe('THREE');
+
+ document.querySelector('[data-wallet="phantom"]').click();
+ await vi.waitFor(() => expect(probedMints.length).toBeGreaterThan(0), { timeout: 15_000, interval: 20 });
+
+ expect(probedMints).toContain(THREE_MINT);
+ expect(probedMints).not.toContain(USDC_MINT);
+
+ await closeModal(p);
+ });
+
+ it('renders no chooser for a single-token resource', async () => {
+ global.fetch = vi.fn(async () => stub402([usdcAccept]));
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ expect(tokenButtons()).toHaveLength(0);
+ expect(document.querySelector('.x402-token-choice')).toBeNull();
+
+ await closeModal(p);
+ });
+
+ it('dedupes repeated accepts for the same mint', async () => {
+ // Permit2/auth-hint siblings can repeat a mint; the chooser shows it once.
+ global.fetch = vi.fn(async () => stub402([usdcAccept, { ...usdcAccept, amount: '2000' }, threeAccept]));
+ const p = pay({ endpoint: 'https://three.ws/api/x402/dance-tip', merchant: 'Club', action: 'Tip' });
+ p.catch(() => {});
+ await flush();
+
+ expect(tokenButtons().map((b) => b.dataset.token)).toEqual([USDC_MINT, THREE_MINT]);
+
+ await closeModal(p);
+ });
+
+ it('autoConnect still shows the chooser once instead of committing to USDC', async () => {
+ // /club passes autoConnect:true. Before the guard, a detected Phantom sent
+ // the buyer straight to a USDC signature and $THREE was never offered.
+ const p = pay({
+ endpoint: 'https://three.ws/api/x402/dance-tip',
+ merchant: 'Club',
+ action: 'Tip',
+ autoConnect: true,
+ });
+ p.catch(() => {});
+ await flush();
+
+ expect(tokenButtons()).toHaveLength(2);
+ expect(document.querySelector('[data-wallet="phantom"]')).toBeTruthy();
+
+ await closeModal(p);
+ });
+
+ it('explains a 503 settlement pause in a sentence, not a JSON envelope', async () => {
+ // What /club actually served on 2026-09-08 with the sponsor under its SOL
+ // floor. The buyer used to be shown the raw body, which reads as a broken
+ // link rather than "we are topping up, nothing was charged".
+ global.fetch = vi.fn(async () => ({
+ status: 503,
+ headers: { get: () => null },
+ json: async () => ({ error: 'settlement_unavailable' }),
+ text: async () => JSON.stringify({
+ error: 'settlement_unavailable',
+ error_description: 'paidEndpoint: settlement is temporarily unavailable, the sponsor wallet is below its SOL settle floor.',
+ }),
+ }));
+
+ const p = pay({ endpoint: 'https://three.ws/api/x402/club-cover', merchant: 'Club', action: 'Cover' });
+ p.catch(() => {});
+ await vi.waitFor(
+ () => expect(document.querySelector('.x402-error-detail, .x402-step.x402-error')).toBeTruthy(),
+ { timeout: 15_000, interval: 20 },
+ );
+
+ const shown = document.querySelector('[data-body]')?.textContent || '';
+ expect(shown).toMatch(/temporarily paused/i);
+ expect(shown).toMatch(/[Nn]othing was charged/);
+ // The raw envelope must not reach the buyer.
+ expect(shown).not.toMatch(/settlement_unavailable|paidEndpoint|error_description/);
+
+ await closeModal(p);
+ });
+
+ it('autoConnect skips the picker as before when only one token is offered', async () => {
+ global.fetch = vi.fn(async () => stub402([usdcAccept]));
+ window.phantom.solana.connect = async () => {
+ throw new Error('connect reached');
+ };
+ const p = pay({
+ endpoint: 'https://three.ws/api/x402/dance-tip',
+ merchant: 'Club',
+ action: 'Tip',
+ autoConnect: true,
+ });
+ p.catch(() => {});
+ await flush();
+ await flush();
+
+ // It left the wallet picker on its own: the single-token behavior is intact.
+ expect(document.querySelector('[data-wallet="phantom"]')).toBeNull();
+
+ await closeModal(p);
+ });
+});
diff --git a/tests/x402-floor-degradation.test.js b/tests/x402-floor-degradation.test.js
index 4a1b8d211..1d3f5d8de 100644
--- a/tests/x402-floor-degradation.test.js
+++ b/tests/x402-floor-degradation.test.js
@@ -51,6 +51,13 @@ describe('settlePayment floor classification', () => {
// the floor branch, so it kept answering 502 long after the floor stopped:
// 15,619 of the autonomous loop's 20,030 `http_502` rows in the 48h to
// 2026-08-06 were this one refusal wearing a server-fault status.
+ // A wallet that clears the floor but cannot afford this settle's ATA rent is
+ // the same transient funding gap, and must not read as a broken endpoint.
+ it('maps fee_wallet_cannot_cover_settle to 503 settlement_unavailable', async () => {
+ const err = await settleAgainst('fee_wallet_cannot_cover_settle:2100000-2049281<2000000');
+ expect(err).toMatchObject({ code: 'settlement_unavailable', status: 503 });
+ });
+
it('maps fee_runway_exhausted to 503 settlement_unavailable', async () => {
const err = await settleAgainst('fee_runway_exhausted:10132243+10000>10000000');
expect(err).toMatchObject({ code: 'settlement_unavailable', status: 503 });
@@ -65,20 +72,50 @@ describe('settlePayment floor classification', () => {
describe('sponsorKnownBelowFloor', () => {
beforeEach(() => vi.resetModules());
- it('reflects the last balance the settle path observed', async () => {
+ it('reflects the last balance the settle path observed for the sponsor', async () => {
+ // The state gates the SPONSORED accept, so only the advertised fee payer
+ // may write it. A read of any other wallet is somebody else's balance.
+ const SPONSOR = 'SponsorSponsorSponsorSponsorSponsorSponsor1';
+ process.env.X402_FEE_PAYER_SOLANA = SPONSOR;
const { sponsorSolLamports, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
- const pubkey = { toBase58: () => 'SponsorSponsorSponsorSponsorSponsorSponsor1' };
+ const pubkey = { toBase58: () => SPONSOR };
// Fresh module: no observation yet, must fail open (not paused).
expect(sponsorKnownBelowFloor()).toBe(false);
- await sponsorSolLamports({ getBalance: async () => 19_000_000 }, pubkey);
- expect(sponsorKnownBelowFloor()).toBe(true);
+ const t0 = Date.now();
+ await sponsorSolLamports({ getBalance: async () => 19_000_000 }, pubkey, t0);
+ expect(sponsorKnownBelowFloor(t0)).toBe(true);
- // A later healthy read clears it. Fresh pubkey defeats the balance cache.
- const pubkey2 = { toBase58: () => 'SponsorSponsorSponsorSponsorSponsorSponsor2' };
- await sponsorSolLamports({ getBalance: async () => 500_000_000 }, pubkey2);
- expect(sponsorKnownBelowFloor()).toBe(false);
+ // A later healthy read of the SAME wallet clears it. The read is dated
+ // past the balance cache TTL so it actually re-reads rather than
+ // replaying the dry observation.
+ const t1 = t0 + 10 * 60_000;
+ await sponsorSolLamports({ getBalance: async () => 500_000_000 }, pubkey, t1);
+ expect(sponsorKnownBelowFloor(t1)).toBe(false);
+ });
+
+ it('ignores a healthy balance read for a wallet that is not the sponsor', async () => {
+ // A self-pay buyer pays its own fee, so its balance says nothing about
+ // whether the sponsor can still settle. Letting it write the shared state
+ // re-advertised sponsored accepts that were guaranteed to fail.
+ process.env.X402_FEE_PAYER_SOLANA = 'SponsorSponsorSponsorSponsorSponsorSponsor1';
+ const { sponsorSolLamports, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
+
+ const t0 = Date.now();
+ await sponsorSolLamports(
+ { getBalance: async () => 19_000_000 },
+ { toBase58: () => 'SponsorSponsorSponsorSponsorSponsorSponsor1' },
+ t0,
+ );
+ expect(sponsorKnownBelowFloor(t0)).toBe(true);
+
+ await sponsorSolLamports(
+ { getBalance: async () => 500_000_000 },
+ { toBase58: () => 'BuyerBuyerBuyerBuyerBuyerBuyerBuyerBuyer22' },
+ t0,
+ );
+ expect(sponsorKnownBelowFloor(t0)).toBe(true);
});
it('warms itself on instances that never settle', async () => {
@@ -113,8 +150,10 @@ describe('sponsorKnownBelowFloor', () => {
});
it('expires: a stale observation stops pausing the challenge', async () => {
+ const SPONSOR = 'SponsorSponsorSponsorSponsorSponsorSponsor3';
+ process.env.X402_FEE_PAYER_SOLANA = SPONSOR;
const { sponsorSolLamports, sponsorKnownBelowFloor } = await import('../api/_lib/x402/self-facilitator.js');
- const pubkey = { toBase58: () => 'SponsorSponsorSponsorSponsorSponsorSponsor3' };
+ const pubkey = { toBase58: () => SPONSOR };
await sponsorSolLamports({ getBalance: async () => 19_000_000 }, pubkey);
expect(sponsorKnownBelowFloor(Date.now())).toBe(true);
diff --git a/tests/x402-self-facilitator-floor-accounting.test.js b/tests/x402-self-facilitator-floor-accounting.test.js
new file mode 100644
index 000000000..7af36d094
--- /dev/null
+++ b/tests/x402-self-facilitator-floor-accounting.test.js
@@ -0,0 +1,187 @@
+// Floor accounting in the self-hosted facilitator
+// (api/_lib/x402/self-facilitator.js).
+//
+// Two defects found while triaging why /club had not settled a payment since
+// 2026-09-04, both of which bite hardest the moment a NEW payment token goes
+// live (which is exactly what $THREE on /club is):
+//
+// 1. The hard SOL floor compared the bare sponsor balance against the floor and
+// ignored what the settle was about to spend. A settle that has to create the
+// recipient's associated token account carries ~0.00204 SOL of rent, so a
+// sponsor sitting just above the floor passed the gate and then died on chain
+// with InsufficientFundsForRent. The payTo has no $THREE token account, so the
+// first $THREE payment is precisely that case.
+// 2. Floor state (which decides whether the 402 keeps advertising the SPONSORED
+// Solana accept) was recorded from whichever wallet paid the fee. A healthy
+// self-pay buyer therefore stamped "not below floor" for a starved sponsor and
+// re-advertised accepts that could not settle.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ Keypair,
+ TransactionMessage,
+ VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+} from '@solana/spl-token';
+
+const { settleRingPayment, sponsorKnownBelowFloor, SPONSOR_SOL_FLOOR_LAMPORTS } =
+ await import('../api/_lib/x402/self-facilitator.js');
+
+const DECIMALS = 6;
+const ATA_RENT_LAMPORTS = 2_039_280;
+
+/**
+ * Build a buyer-signed transfer. `withAtaCreate` prepends the idempotent
+ * ATA-create the facilitator charges rent for, modelling a recipient that has
+ * never held this mint.
+ */
+function buildPayment({ amount = 10_000n, sponsor, withAtaCreate = false } = {}) {
+ const buyer = Keypair.generate();
+ const recipientOwner = Keypair.generate();
+ const mint = Keypair.generate().publicKey;
+ process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();
+ const feePayerKey = sponsor ? sponsor.publicKey : buyer.publicKey;
+
+ const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);
+ const destAta = getAssociatedTokenAddressSync(mint, recipientOwner.publicKey);
+ const instructions = [ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 })];
+ if (withAtaCreate) {
+ instructions.push(createAssociatedTokenAccountIdempotentInstruction(
+ feePayerKey, destAta, recipientOwner.publicKey, mint,
+ ));
+ }
+ instructions.push(createTransferCheckedInstruction(
+ sourceAta, mint, destAta, buyer.publicKey, amount, DECIMALS,
+ ));
+
+ const message = new TransactionMessage({
+ payerKey: feePayerKey,
+ recentBlockhash: '11111111111111111111111111111111',
+ instructions,
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(message);
+ tx.sign([buyer]);
+
+ return {
+ buyer,
+ payTo: recipientOwner.publicKey.toBase58(),
+ requirement: {
+ network: 'solana',
+ asset: mint.toBase58(),
+ amount: String(amount),
+ payTo: recipientOwner.publicKey.toBase58(),
+ },
+ paymentPayload: { transaction: Buffer.from(tx.serialize()).toString('base64') },
+ };
+}
+
+const ENV_KEYS = ['X402_PAY_TO_SOLANA', 'X402_ASSET_MINT_SOLANA', 'X402_FEE_PAYER_SOLANA'];
+let saved;
+beforeEach(() => {
+ saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+});
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+describe('settle affordability: the floor must survive the settle', () => {
+ it('refuses an ATA-creating settle the sponsor cannot cover, instead of dying on chain', async () => {
+ const sponsor = Keypair.generate();
+ const p = buildPayment({ sponsor, withAtaCreate: true });
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ // Comfortably over the bare floor, but not by the ATA rent this settle
+ // needs. The old gate passed this and the transaction failed on chain.
+ const balance = SPONSOR_SOL_FLOOR_LAMPORTS + 100_000;
+ const conn = { getBalance: async () => balance };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ feePayer: sponsor,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.reason).toMatch(/^fee_wallet_cannot_cover_settle:/);
+ // The reason carries the numbers an operator needs to size a top-up.
+ expect(res.estFeeLamports).toBeGreaterThanOrEqual(ATA_RENT_LAMPORTS);
+ expect(res.sponsorSolLamports).toBe(balance);
+ });
+
+ it('still reports the plain below-floor reason when the balance is under the floor', async () => {
+ const sponsor = Keypair.generate();
+ const p = buildPayment({ sponsor, withAtaCreate: true });
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const conn = { getBalance: async () => SPONSOR_SOL_FLOOR_LAMPORTS - 1 };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ feePayer: sponsor,
+ });
+
+ // The two conditions stay distinguishable: "top the wallet up at all" vs
+ // "this particular settle costs more than the headroom you have".
+ expect(res.success).toBe(false);
+ expect(res.reason).toMatch(/^fee_wallet_below_floor:/);
+ });
+
+ it('lets an ATA-creating settle through once the rent fits above the floor', async () => {
+ const sponsor = Keypair.generate();
+ const p = buildPayment({ sponsor, withAtaCreate: true });
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const conn = { getBalance: async () => SPONSOR_SOL_FLOOR_LAMPORTS + ATA_RENT_LAMPORTS + 1_000_000 };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ feePayer: sponsor,
+ });
+
+ // It gets past both SOL gates. It fails later for an unrelated reason (this
+ // stub connection cannot broadcast), which is exactly the point: neither
+ // floor check is what stopped it.
+ expect(res.reason || '').not.toMatch(/fee_wallet_below_floor|fee_wallet_cannot_cover_settle/);
+ });
+});
+
+describe('floor state is recorded only for the advertised sponsor wallet', () => {
+ it('does not clear a starved sponsor because an unrelated self-pay buyer is healthy', async () => {
+ const sponsor = Keypair.generate();
+ process.env.X402_FEE_PAYER_SOLANA = sponsor.publicKey.toBase58();
+
+ // A starved SPONSOR settle stamps the floor state below.
+ const sponsored = buildPayment({ sponsor });
+ process.env.X402_PAY_TO_SOLANA = sponsored.payTo;
+ await settleRingPayment({
+ paymentPayload: sponsored.paymentPayload,
+ requirement: sponsored.requirement,
+ conn: { getBalance: async () => 1 },
+ feePayer: sponsor,
+ });
+ expect(sponsorKnownBelowFloor()).toBe(true);
+
+ // Now a DIFFERENT wallet self-pays with a healthy balance. It must not
+ // speak for the sponsor: the 402 builder would otherwise resume
+ // advertising a sponsored accept that cannot settle.
+ const selfPaid = buildPayment({});
+ process.env.X402_PAY_TO_SOLANA = selfPaid.payTo;
+ await settleRingPayment({
+ paymentPayload: selfPaid.paymentPayload,
+ requirement: selfPaid.requirement,
+ conn: { getBalance: async () => SPONSOR_SOL_FLOOR_LAMPORTS * 100 },
+ });
+
+ expect(sponsorKnownBelowFloor()).toBe(true);
+ });
+});