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): keep Solana payable in self-pay mode when the sponsor wallet is dry

nirholase7f03bcd8996
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index a2bfde094..510631562 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -100,7 +100,7 @@ function atomicsToUsd(atomics) {
return Number.isFinite(n) ? n / 1e6 : undefined;
}
-function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {
+function buildAccept(network, priceAtomics, resourceUrl, payToOverride, selfPayOnly = false) {
const common = {
scheme: 'exact',
amount: String(priceAtomics),
@@ -125,7 +125,14 @@ function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {
payTo: payToOverride?.solana || env.X402_PAY_TO_SOLANA,
asset: env.X402_ASSET_MINT_SOLANA,
// PayAI requires this account as fee payer; without it /verify rejects.
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ // Omitted deliberately in self-pay mode: absence of feePayer is the
+ // wire signal that the buyer covers their own gas, which is what keeps
+ // the endpoint payable while the sponsor wallet is empty.
+ extra: {
+ name: 'USDC',
+ decimals: 6,
+ ...(selfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
+ },
};
}
if (network === NETWORK_BSC_MAINNET) {
@@ -150,7 +157,10 @@ function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {
throw new X402Error('unsupported_network', `paidEndpoint: unsupported network ${network}`, 500);
}
-function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride, acceptThree = true }) {
+// Exported for tests: the self-pay fallback below decides whether a paid
+// endpoint stays payable while the sponsor wallet is empty, which is the
+// difference between taking money and answering 503.
+export function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride, acceptThree = true }) {
const out = [];
for (const name of networks) {
const net = resolveNetwork(name);
@@ -183,20 +193,22 @@ function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride,
// secret is set. See solanaSettleable() in x402-spec.js.
if (
net === NETWORK_SOLANA_MAINNET &&
- (!solTo ||
- !env.X402_FEE_PAYER_SOLANA ||
- !env.X402_ASSET_MINT_SOLANA ||
- !solanaSettleable() ||
- // Sponsor recently observed under its SOL settle floor (sync,
- // cache-backed, fail-open): every sponsor-mode settle is refused at
- // that level, so advertising the accept just makes the buyer sign a
- // payment that dies with settlement_unavailable. Drop Solana until
- // the wallet is refunded; other networks keep the endpoint payable.
- sponsorKnownBelowFloor())
+ (!solTo || !env.X402_ASSET_MINT_SOLANA)
)
continue;
+ // Sponsoring the buyer's gas is a convenience, not a precondition for
+ // taking money. When the sponsor cannot co-sign (no key loaded, or the
+ // wallet is under its SOL settle floor) we used to drop Solana entirely
+ // and answer 503 on a paid endpoint whose whole job is RECEIVING crypto.
+ // Advertise the accept without a feePayer instead: that is the self-pay
+ // contract, where the buyer signs as their own fee payer and the
+ // facilitator only broadcasts, spending none of our SOL. Sponsored mode
+ // resumes on its own the moment the wallet is topped up.
+ const solanaSelfPayOnly =
+ net === NETWORK_SOLANA_MAINNET &&
+ (!env.X402_FEE_PAYER_SOLANA || !solanaSettleable() || sponsorKnownBelowFloor());
if (net === NETWORK_BSC_MAINNET && (!bscTo || !env.X402_ASSET_ADDRESS_BSC)) continue;
- const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride);
+ const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride, solanaSelfPayOnly);
out.push(accept);
// $THREE alongside USDC on Solana (opt-in via X402_ACCEPT_THREE_SOLANA).
// Pushed right after the USDC Solana accept — and after the network guard
@@ -218,7 +230,11 @@ function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride,
resource: resourceUrl,
payTo: solTo,
asset: env.THREE_TOKEN_MINT,
- extra: { name: 'THREE', decimals: env.THREE_TOKEN_DECIMALS, feePayer: env.X402_FEE_PAYER_SOLANA },
+ extra: {
+ name: 'THREE',
+ decimals: env.THREE_TOKEN_DECIMALS,
+ ...(solanaSelfPayOnly ? {} : { feePayer: env.X402_FEE_PAYER_SOLANA }),
+ },
});
}
// For EVM `exact` networks, advertise a Permit2 sibling so @x402/* SDK
diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.js
index a73a5202b..ce0d2e494 100644
--- a/api/_lib/x402/self-facilitator.js
+++ b/api/_lib/x402/self-facilitator.js
@@ -580,10 +580,16 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee
// Self-pay → the payer pays its own fee; sponsor mode → the sponsor pays.
const feeWallet = new PublicKey(decoded.feePayer);
const solLamports = await sponsorSolLamports(connection, feeWallet);
- if (solLamports < SPONSOR_SOL_FLOOR_LAMPORTS) {
+ // The floor is a reserve protecting OUR sponsor wallet from being drained by
+ // the paying loop. In self-pay the fee wallet is the buyer's own, so holding
+ // their balance to our reserve would refuse a perfectly good payment for the
+ // crime of not keeping 0.02 SOL spare. They only have to afford the fee they
+ // are about to pay, which the affordability check below enforces.
+ const floorFor = selfPay ? 0 : SPONSOR_SOL_FLOOR_LAMPORTS;
+ if (solLamports < floorFor) {
return {
success: false,
- reason: `fee_wallet_below_floor:${solLamports}<${SPONSOR_SOL_FLOOR_LAMPORTS}`,
+ reason: `fee_wallet_below_floor:${solLamports}<${floorFor}`,
sponsorSolLamports: solLamports,
feePayer: decoded.feePayer,
selfPay,
@@ -597,10 +603,10 @@ export async function settleRingPayment({ paymentPayload, requirement, conn, fee
// 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) {
+ if (solLamports - estFeeLamports < floorFor) {
return {
success: false,
- reason: `fee_wallet_cannot_cover_settle:${solLamports}-${estFeeLamports}<${SPONSOR_SOL_FLOOR_LAMPORTS}`,
+ reason: `fee_wallet_cannot_cover_settle:${solLamports}-${estFeeLamports}<${floorFor}`,
sponsorSolLamports: solLamports,
estFeeLamports,
feePayer: decoded.feePayer,
diff --git a/api/x402-checkout.js b/api/x402-checkout.js
index 6d371a4b8..13f5615a7 100644
--- a/api/x402-checkout.js
+++ b/api/x402-checkout.js
@@ -227,8 +227,17 @@ async function handlePrepare(req, res) {
const conn = solanaConnection({ url: rpc, commitment: 'confirmed' });
const mint = toPubkey(accept.asset, 'asset');
const payTo = toPubkey(accept.payTo, 'payTo');
- const feePayer = toPubkey(accept.extra.feePayer, 'feePayer');
const buyerPubkey = toPubkey(buyer, 'buyer');
+ // Who pays the Solana fee. Sponsor mode (the default) is a convenience we
+ // offer so a buyer holding only USDC can pay without owning any SOL, and it
+ // costs the platform a fee per settle. It is NOT a requirement for receiving
+ // money: an accept advertised without `extra.feePayer` means "you pay your
+ // own gas", the buyer signs as fee payer, and the facilitator broadcasts a
+ // fully-signed transaction without touching a sponsor key or a lamport of
+ // ours. That is the mode a paid endpoint falls back to when the sponsor
+ // wallet is dry, so the door stays open instead of answering 503.
+ const selfPay = !accept.extra?.feePayer;
+ const feePayer = selfPay ? buyerPubkey : toPubkey(accept.extra.feePayer, 'feePayer');
const amount = BigInt(accept.amount);
const senderAta = getAssociatedTokenAddressSync(
@@ -314,6 +323,11 @@ async function handlePrepare(req, res) {
network: accept.network,
tx_base64: txBase64,
recent_blockhash: blockhash,
+ // Lets the checkout tell the buyer they are covering the network fee on
+ // this one, rather than silently handing them a transaction that debits
+ // their SOL when every previous payment did not.
+ self_pay: selfPay,
+ fee_payer: feePayer.toBase58(),
});
}
diff --git a/tests/x402-self-facilitator-floor-accounting.test.js b/tests/x402-self-facilitator-floor-accounting.test.js
index 7af36d094..c3eb0efdb 100644
--- a/tests/x402-self-facilitator-floor-accounting.test.js
+++ b/tests/x402-self-facilitator-floor-accounting.test.js
@@ -185,3 +185,57 @@ describe('floor state is recorded only for the advertised sponsor wallet', () =>
expect(sponsorKnownBelowFloor()).toBe(true);
});
});
+
+describe('self-pay: a dry sponsor must not close a receiving endpoint', () => {
+ it('holds a self-pay buyer to the fee only, not to the sponsor reserve', async () => {
+ // The buyer is their own fee payer. Our 0.02 SOL reserve is there to stop
+ // the paying loop draining the PLATFORM wallet, so applying it to a
+ // stranger's wallet would refuse a payment we can settle for free.
+ const p = buildPayment({});
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ // Far under the sponsor floor, but comfortably able to pay its own fee.
+ const conn = { getBalance: async () => 30_000 };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ });
+
+ expect(res.reason || '').not.toMatch(/fee_wallet_below_floor|fee_wallet_cannot_cover_settle/);
+ });
+
+ it('still refuses a self-pay buyer who cannot cover the fee', async () => {
+ const p = buildPayment({});
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const conn = { getBalance: async () => 1 };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.reason).toMatch(/^fee_wallet_cannot_cover_settle:/);
+ });
+
+ it('leaves the sponsor reserve fully in force for sponsored settles', async () => {
+ // The relaxation above must not leak into sponsor mode, which is the only
+ // thing standing between the paying loop and an empty platform wallet.
+ const sponsor = Keypair.generate();
+ const p = buildPayment({ sponsor });
+ process.env.X402_PAY_TO_SOLANA = p.payTo;
+ const conn = { getBalance: async () => 30_000 };
+
+ const res = await settleRingPayment({
+ paymentPayload: p.paymentPayload,
+ requirement: p.requirement,
+ conn,
+ feePayer: sponsor,
+ });
+
+ expect(res.success).toBe(false);
+ expect(res.reason).toMatch(/^fee_wallet_below_floor:30000</);
+ });
+});
diff --git a/tests/x402-self-facilitator-min-settle.test.js b/tests/x402-self-facilitator-min-settle.test.js
index 237e86589..7b0f024ca 100644
--- a/tests/x402-self-facilitator-min-settle.test.js
+++ b/tests/x402-self-facilitator-min-settle.test.js
@@ -96,8 +96,8 @@ describe('settleRingPayment minimum-settle guard', () => {
it('does NOT apply the minimum to a self-pay dust settle (buyer pays its own fee)', async () => {
const p = buildPayment({ amount: 1n });
process.env.X402_PAY_TO_SOLANA = p.payTo;
- // Self-pay is exempt from the min guard, so it proceeds to the SOL floor
- // check — which fails here (balance 0), proving the guard did not fire.
+ // Self-pay is exempt from the min guard, so it proceeds to the SOL check,
+ // which fails here (balance 0), proving the guard did not fire.
const conn = {
getBalance: async () => 0,
};
@@ -107,6 +107,10 @@ describe('settleRingPayment minimum-settle guard', () => {
conn,
});
expect(res.success).toBe(false);
- expect(res.reason).toMatch(/^fee_wallet_below_floor:/);
+ // A self-pay buyer is not held to the sponsor's reserve (that floor exists
+ // to stop OUR wallet draining), only to affording the fee they are about
+ // to pay. So the refusal is the affordability one against a zero floor.
+ expect(res.reason).toMatch(/^fee_wallet_cannot_cover_settle:0-\d+<0$/);
+ expect(res.selfPay).toBe(true);
});
});
diff --git a/tests/x402-selfpay-fallback.test.js b/tests/x402-selfpay-fallback.test.js
new file mode 100644
index 000000000..4d460f9f7
--- /dev/null
+++ b/tests/x402-selfpay-fallback.test.js
@@ -0,0 +1,116 @@
+// A paid endpoint's job is RECEIVING crypto. It must not stop doing that
+// because the wallet we use to sponsor buyers' gas ran dry.
+//
+// Sponsoring is a convenience: three.ws pays the Solana fee so a buyer holding
+// only USDC can pay without owning SOL. It is not a precondition for taking
+// money. The x402 rail already supports self-pay end to end (settleRingPayment
+// broadcasts a fully-signed buyer-paid transaction without touching a sponsor
+// key), but buildRequirements used to DROP the Solana accept entirely when the
+// sponsor was under its SOL floor, so /club answered 503 on both the cover
+// charge and every dance tip for four days while the payTo wallet sat there
+// perfectly able to receive.
+//
+// The contract these tests pin: no sponsor means the accept is advertised
+// WITHOUT `extra.feePayer`, which is the wire signal that the buyer signs as
+// their own fee payer.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const SPONSOR = 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';
+const PAY_TO = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const ENV = {
+ X402_PAY_TO_SOLANA: PAY_TO,
+ X402_ASSET_MINT_SOLANA: USDC,
+ X402_FEE_PAYER_SOLANA: SPONSOR,
+ THREE_TOKEN_MINT: THREE,
+ X402_ACCEPT_THREE_SOLANA: 'true',
+ X402_SELF_FACILITATOR_ENABLED: 'true',
+ // Non-empty means the sponsor co-signing key is loaded, so solanaSettleable()
+ // reports sponsor mode available. Never parsed by buildRequirements.
+ X402_FEE_PAYER_SECRET_BASE58: 'test-cosigning-key-present',
+};
+
+let saved;
+beforeEach(() => {
+ saved = {};
+ for (const [k, v] of Object.entries(ENV)) {
+ saved[k] = process.env[k];
+ process.env[k] = v;
+ }
+ vi.resetModules();
+});
+afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ vi.restoreAllMocks();
+ vi.resetModules();
+});
+
+/** Load buildRequirements with the sponsor's floor state stubbed. */
+async function requirementsWith({ belowFloor }) {
+ vi.doMock('../api/_lib/x402/self-facilitator.js', () => ({
+ sponsorKnownBelowFloor: () => belowFloor,
+ refreshSponsorFloorState: () => {},
+ }));
+ const { buildRequirements } = await import('../api/_lib/x402-paid-endpoint.js');
+ return buildRequirements({
+ priceAtomics: '1000',
+ networks: ['solana'],
+ resourceUrl: 'https://three.ws/api/x402/dance-tip',
+ });
+}
+
+const solanaAccepts = (list) => list.filter((a) => String(a.network).startsWith('solana'));
+
+describe('a dry sponsor keeps the endpoint payable via self-pay', () => {
+ it('still advertises Solana when the sponsor is below its floor', async () => {
+ const accepts = await requirementsWith({ belowFloor: true });
+ // The regression: this list used to come back empty and the endpoint 503'd.
+ expect(solanaAccepts(accepts).length).toBeGreaterThan(0);
+ });
+
+ it('omits feePayer on every Solana accept when the sponsor is dry', async () => {
+ const accepts = solanaAccepts(await requirementsWith({ belowFloor: true }));
+ for (const accept of accepts) {
+ expect(accept.extra).toBeDefined();
+ expect(accept.extra.feePayer).toBeUndefined();
+ }
+ // Both tokens stay on the menu, so $THREE does not quietly disappear the
+ // moment the sponsor runs out.
+ expect(accepts.map((a) => a.asset)).toEqual([USDC, THREE]);
+ });
+
+ it('keeps sponsoring gas while the sponsor is healthy', async () => {
+ const accepts = solanaAccepts(await requirementsWith({ belowFloor: false }));
+ expect(accepts.length).toBeGreaterThan(0);
+ for (const accept of accepts) {
+ expect(accept.extra.feePayer).toBe(SPONSOR);
+ }
+ });
+
+ it('falls back to self-pay when no sponsor is configured at all', async () => {
+ delete process.env.X402_FEE_PAYER_SOLANA;
+ const accepts = solanaAccepts(await requirementsWith({ belowFloor: false }));
+ // Previously this dropped Solana too, so a deployment that never set a
+ // sponsor could not take Solana payments at all.
+ expect(accepts.length).toBeGreaterThan(0);
+ for (const accept of accepts) {
+ expect(accept.extra.feePayer).toBeUndefined();
+ }
+ });
+
+ it('still refuses to advertise Solana when the receiving address is missing', async () => {
+ // Self-pay fixes who pays gas. It cannot conjure somewhere to send the
+ // money, so a genuinely unconfigured lane must stay unadvertised, and with
+ // Solana the only requested network that leaves nothing payable at all.
+ delete process.env.X402_PAY_TO_SOLANA;
+ await expect(requirementsWith({ belowFloor: false })).rejects.toMatchObject({
+ code: 'no_payto_configured',
+ });
+ });
+});