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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(x402): gate the autonomous loop on the payer's real USDC float
fudjiad379bd18b1b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e2ee9ea5..dd9381440 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Crypto news is live: a real-time feed from 38 publishers, a rich article reader, and a 662,047-article archive back to 2017** — Markets grew a full news wing. /markets/news streams live headlines aggregated directly from 38 publisher feeds — filter by category (Bitcoin, DeFi, regulation, and more), search, and open any story in a reader that extracts the full text with a summary, key points, sentiment, and related coverage. Behind it sits the largest open crypto-news archive anywhere: 662,047 articles from September 2017 to today in English and Chinese, searchable by keyword, ticker, source, sentiment, date, and language at /markets/archive. A new /markets hub ties the whole suite together — live global stats, the top 100 coins, breaking news, and every market tool as its own card. (`/markets`) `[feature]`- **Friends now see you online — and can message you — while you're in /play** — Your account's friends list, presence, and DMs (already live on /walk) now work inside /play's coin worlds too: a Friends button on the HUD (or press J) opens a drawer showing who's online and where, with live direct messages that arrive instantly whether or not the drawer is open. Previously /play never told the server who you were signed in as, so friends saw you as offline no matter how long you played, and any message sent your way was silently lost. (`/play`) `[feature, fix]`- **News Digest: the day's crypto coverage, grouped into the stories that actually matter** — Reading 90 headlines to find the 8 things that happened is a chore. /markets/digest does it for you: it reads every story from all 38 publisher feeds over your chosen window (6 hours to 3 days) and groups them into distinct narratives — each with a plain-language summary, whether it reads bullish or bearish, the coins involved, and an expandable list of every outlet that covered it. When an AI provider is available it groups the stories semantically; otherwise it clusters them by keyword and ticker overlap. Either way, every story links back to the real articles behind it — nothing is invented. (`/markets/digest`) `[feature]`+- **The autonomous agent loop stops retrying payments it can't afford** — The platform runs an autonomous loop that pays its own paid endpoints in USDC, so the agent economy keeps moving on its own. It had two limits: a daily spending cap, and the actual balance in its wallet. Only the cap was being checked. When the wallet ran dry, the loop kept building and submitting payments it could never fund — roughly one failed attempt every minute, indefinitely. Nothing was ever lost (the payments failed before any money moved, and no network fees were burned), but the loop did no useful work and leaned on the Solana network for nothing. It now reads its own balance first and simply skips the paid calls when the float is empty, while its free and monitoring work carries on untouched. The moment the wallet is topped up, spending resumes on its own. We also made the platform's alerting status visible on the health endpoint, so a missing alert channel can no longer look identical to a healthy, quiet one. `[fix, infra]`- **The liquidations pulse on /coins is live** — The long/short liquidation strip on the markets page had been showing its offline state since launch — the collector that listens to Binance, Bybit, and OKX futures streams needs to run around the clock, which the old serverless setup couldn't do. It now runs as its own always-on service, so the dominant-side badge, the 1-hour long-vs-short bars, and the biggest recent liquidations fill in with real exchange data. (`/coins`) `[feature, infra]`- **The news archive now updates itself every hour — and the live feed has an RSS feed** — The 660,000-article news archive is no longer frozen in time: an hourly archiver now appends every new story from the live feed into the corpus, complete with the market snapshot at capture time (BTC/ETH/SOL price, market cap, Fear & Greed), so /markets/archive stays current forever. And if you'd rather read three.ws crypto news in your own reader, the feed is now available as standard RSS at /api/news/rss — subscribe to everything or just one category. (`/markets/archive`) `[feature, infra]`- **The Oracle can see the news again** — The Oracle's narrative pillar — one of the four signals behind every 0-100 conviction score — reads live headlines to tell whether a coin is riding a real story. It had been reading them from an outside news service that went offline, and because the code was built to fail quietly rather than break, it simply scored with no headlines at all. Conviction scores now draw on three.ws's own news engine, which reads 38 publisher feeds directly, so the narrative read is live again and no longer depends on anyone else staying up. The pump.fun news-meme detector and the sniper's coin classifier read from the same engine. (`/oracle`) `[fix, improvement]`diff --git a/api/_lib/alerts.js b/api/_lib/alerts.jsindex 0a66bcbb2..a2dab142f 100644--- a/api/_lib/alerts.js+++ b/api/_lib/alerts.js@@ -33,6 +33,17 @@ function config() {return token && chatId ? { token, chatId } : null;}+/**+ * Whether a real alert channel is wired. When false, every sendOpsAlert() is a+ * silent no-op — intended for dev/tests, but dangerous to leave unnoticed in+ * production, so /api/healthz reports this instead of letting the silence pass+ * for health.+ * @returns {boolean}+ */+export function alertsConfigured() {+ return config() !== null;+}+function signatureOf(text) {return createHash('sha256').update(text).digest('hex').slice(0, 16);}diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex ba9ffae0c..495545678 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -54,23 +54,37 @@ import { sendOpsAlert } from '../_lib/alerts.js';const log = logger('x402-autonomous-loop');-// Live USDC balance of the ring payer, in atomic units (6dp). A missing ATA —-// the wallet has never held USDC — is a legitimate zero, not an error, so it-// reads as 0 rather than throwing. An RPC failure is NOT treated as zero: a-// transient read error must not silently disable the whole spend path, so it-// returns null, which every caller reads as "unknown → don't gate on it".-async function readPayerUsdcAtomic(conn, payerPubkey) {+// Live USDC balance of the ring payer, in atomic units (6dp).+//+// Returns 0 when the wallet genuinely holds nothing (including the no-ATA case:+// a wallet that has never held USDC has no token account at all). Returns null+// when the balance could not be determined — a transient RPC failure must NOT+// read as "zero", because callers gate the spend path on this and an unknown+// balance should leave the path open rather than silently halt the ring.+//+// Existence is probed with getAccountInfo (returns null for a missing account,+// no throw) rather than by pattern-matching getTokenAccountBalance's error+// string, whose wording varies across RPC providers.+export async function readPayerUsdcAtomic(conn, payerPubkey) {if (!USDC_MINT) return 0;+ let ata;try {- const ata = getAssociatedTokenAddressSync(+ ata = getAssociatedTokenAddressSync(new PublicKey(USDC_MINT), payerPubkey,false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,);- const info = await conn.getTokenAccountBalance(ata);- return Number(info?.value?.amount ?? 0);} catch (err) {- // `could not find account` = no ATA = genuinely holds nothing.- if (/could not find account|Invalid param|account not found/i.test(String(err?.message || ''))) return 0;+ // Off-curve owner — a misconfigured payer key, not an empty wallet.+ log.warn('payer_usdc_ata_underivable', { message: err?.message });+ return null;+ }+ try {+ const info = await conn.getAccountInfo(ata);+ if (info === null) return 0; // no token account ⇒ holds no USDC+ const bal = await conn.getTokenAccountBalance(ata);+ const amount = Number(bal?.value?.amount);+ return Number.isFinite(amount) ? amount : null;+ } catch (err) {log.warn('payer_usdc_read_failed', { message: err?.message });return null;}diff --git a/api/healthz.js b/api/healthz.jsindex 18ea4bdd7..91a66a85e 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -11,6 +11,7 @@ import { cors, json, method, wrap } from './_lib/http.js';import { countRecentPayments } from './_lib/x402/audit-log.js';import { gatherSubsystemHealth } from './_lib/ops/subsystem-health.js';import { nvidiaTtsConfigured, nvidiaAsrConfigured } from './_lib/ai-speech.js';+import { alertsConfigured } from './_lib/alerts.js';const STARTED_AT = Date.now();const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_version || 'dev';@@ -360,5 +361,19 @@ export default wrap(async (req, res) => {requires: ['NVIDIA_API_KEY', 'NVIDIA_ASR_FUNCTION_ID'],},},+ // The real-time ops alert channel (api/_lib/alerts.js). It is a deliberate+ // silent no-op when unconfigured, so dev and tests need no secrets — but+ // that same silence in production means every 5xx report, browser-error+ // report, ring-leak CRITICAL, and low-balance warning goes nowhere with no+ // indication anything is wrong. Surface the gate here so a missing channel+ // is visible on the dashboard instead of only discoverable by reading code.+ alerts: {+ configured: alertsConfigured(),+ channel: 'telegram',+ requires: ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ALERTS_CHAT_ID'],+ ...(alertsConfigured() ? {} : {+ warning: 'ops alerts are a silent no-op — sendOpsAlert() calls (5xx faults, client errors, ring leaks, low-balance) are dropped',+ }),+ },}, { 'cache-control': 'public, max-age=2, s-maxage=2' });});diff --git a/data/changelog.json b/data/changelog.jsonindex f4678d59c..6665bcbba 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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-07-10",+ "title": "The autonomous agent loop stops retrying payments it can't afford",+ "summary": "The platform runs an autonomous loop that pays its own paid endpoints in USDC, so the agent economy keeps moving on its own. It had two limits: a daily spending cap, and the actual balance in its wallet. Only the cap was being checked. When the wallet ran dry, the loop kept building and submitting payments it could never fund — roughly one failed attempt every minute, indefinitely. Nothing was ever lost (the payments failed before any money moved, and no network fees were burned), but the loop did no useful work and leaned on the Solana network for nothing. It now reads its own balance first and simply skips the paid calls when the float is empty, while its free and monitoring work carries on untouched. The moment the wallet is topped up, spending resumes on its own. We also made the platform's alerting status visible on the health endpoint, so a missing alert channel can no longer look identical to a healthy, quiet one.",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-10","title": "Wallet balances and the leak scanner stay online when the RPC pool thins",diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex 9cd61aebc..662a59212 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -249,6 +249,43 @@ by CLI at all. Consequences and current state:| Collection authority | `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | Agent NFT collection ops can't sign | Intentionally excluded from `scripts/wire-master-wallet.mjs` (on-chain update authority must stay its original wallet). Owner holds the key. || R2/S3 storage creds | `S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_BUCKET`, `S3_PUBLIC_DOMAIN` | `/api/marketplace`, `/api/explore`, `/api/avatars/:id` — every route that resolves an asset URL — 503 `not_configured` | Real values already sit in the repo's `.env.local` (never committed). Apply with `scripts/gcp/apply-s3-env.sh` (needs a human-authed `gcloud auth login` first — the 89-var apply is still blocked on reauth per above). || CoinCommunities API key | `CC_API_KEY` | `/api/community/worlds` and `/api/clash/state` both 503 `cc_unconfigured` (`api/_lib/coin-communities.js`) | Third-party CoinCommunities account signup — not a platform-controlled secret, needs an owner decision to create the account and provision a key. |+| Ops alert channel | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_ALERTS_CHAT_ID` | **Every** `sendOpsAlert()` is silently dropped — 5xx faults, `api/client-errors.js` browser reports, ring-leak CRITICALs, low-balance warnings. `api/_lib/alerts.js` no-ops by design when either var is missing. Production currently has no real-time alerting. | Create a Telegram bot (`@BotFather`), add it to a **private** ops channel (never the public holders' channel — alerts carry stack traces, URLs, IPs), then set both vars on the Cloud Run service. `/api/healthz` → `alerts.configured` reports the gate. |+| x402 ring payer USDC float | — (not a var: an on-chain balance) | The autonomous loop's payer wallet holds $0 USDC, so every paid call is skipped. Since 2026-07-09 this manifested as ~1 failed settle/minute (`broadcast_failed:Simulation failed`); the loop now skips paid calls instead. Free + monitoring entries are unaffected. | Send USDC to the payer wallet (`X402_SEED_SOLANA_SECRET_BASE58`'s pubkey). Floor is `X402_RING_PAYER_USDC_FLOOR_ATOMIC` (default $5) — fund meaningfully above it or it re-drains. See **x402 ring payer float** below. |++### x402 ring payer float — why an empty wallet used to storm Solana++The autonomous loop (`api/cron/x402-autonomous-loop.js`, driven every minute by+`economy-tick`) spends real USDC against the platform's own paid endpoints. Two+independent limits apply, and for a long time only one was enforced:++- the **daily spend cap** (`remainingCap`) bounds what the loop is *allowed* to spend;+- the **payer's USDC balance** bounds what it is *able* to spend.++With a drained float and cap headroom remaining, each tick probed for a 402,+signed a payment transaction, and POSTed it — and the self-hosted facilitator+failed every one at settle with `broadcast_failed:Simulation failed`. Observed:+**1,665 failed settles against 3 successes** over 24h. Nothing was lost (the+transaction fails in simulation, before broadcast, so no fee is burned and no+funds move), but the ring did no useful work and hammered the RPC indefinitely.++`readPayerUsdcAtomic()` is now read once per tick and treated as a hard spend+ceiling. Its three-way contract is load-bearing, and `tests/x402-autonomous-payer-float.test.js`+pins it:++| Read result | Meaning | Loop behavior |+|---|---|---|+| a number > 0 | real float | pay up to `min(dailyCap, float)` |+| `0` | genuinely empty (**including a wallet with no ATA**) | skip every paid call; free + `run()` monitors still execute |+| `null` | balance **undeterminable** (RPC blip) | do *not* gate — leave the spend path open |++The `null`-vs-`0` distinction matters in both directions: if a transient RPC+failure read as `0`, one blip would silently halt the ring; if an empty wallet+read as `null`, the doomed-payment storm returns. Emptiness is detected+structurally (`getAccountInfo` → `null` ⇒ no token account ⇒ no USDC), not by+pattern-matching an RPC error string, whose wording varies by provider.++To resume autonomous spend, fund the payer's USDC float. The loop self-recovers+on the next tick — no redeploy, no flag flip.### Resolved: x402 sponsor co-signing key (2026-07-09)diff --git a/public/changelog.json b/public/changelog.jsonindex aeabaf5b3..ab801f88f 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-10T12:31:09.835Z",+ "generated_at": "2026-07-10T12:32:18.281Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -118,6 +118,17 @@"feature"]},+ {+ "date": "2026-07-10",+ "type": "update",+ "title": "The autonomous agent loop stops retrying payments it can't afford",+ "summary": "The platform runs an autonomous loop that pays its own paid endpoints in USDC, so the agent economy keeps moving on its own. It had two limits: a daily spending cap, and the actual balance in its wallet. Only the cap was being checked. When the wallet ran dry, the loop kept building and submitting payments it could never fund — roughly one failed attempt every minute, indefinitely. Nothing was ever lost (the payments failed before any money moved, and no network fees were burned), but the loop did no useful work and leaned on the Solana network for nothing. It now reads its own balance first and simply skips the paid calls when the float is empty, while its free and monitoring work carries on untouched. The moment the wallet is topped up, spending resumes on its own. We also made the platform's alerting status visible on the health endpoint, so a missing alert channel can no longer look identical to a healthy, quiet one.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-10","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 1141a4203..39af540f5 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -94,6 +94,14 @@<category>feature</category><description>Reading 90 headlines to find the 8 things that happened is a chore. /markets/digest does it for you: it reads every story from all 38 publisher feeds over your chosen window (6 hours to 3 days) and groups them into distinct narratives — each with a plain-language summary, whether it reads bullish or bearish, the coins involved, and an expandable list of every outlet that covered it. When an AI provider is available it groups the stories semantically; otherwise it clusters them by keyword and ticker overlap. Either way, every story links back to the real articles behind it — nothing is invented.</description></item>+ <item>+ <title>The autonomous agent loop stops retrying payments it can't afford</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-10:The autonomous agent loop stops retrying payments it can't afford</guid>+ <pubDate>Fri, 10 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The platform runs an autonomous loop that pays its own paid endpoints in USDC, so the agent economy keeps moving on its own. It had two limits: a daily spending cap, and the actual balance in its wallet. Only the cap was being checked. When the wallet ran dry, the loop kept building and submitting payments it could never fund — roughly one failed attempt every minute, indefinitely. Nothing was ever lost (the payments failed before any money moved, and no network fees were burned), but the loop did no useful work and leaned on the Solana network for nothing. It now reads its own balance first and simply skips the paid calls when the float is empty, while its free and monitoring work carries on untouched. The moment the wallet is topped up, spending resumes on its own. We also made the platform's alerting status visible on the health endpoint, so a missing alert channel can no longer look identical to a healthy, quiet one.</description>+ </item><item><title>The liquidations pulse on /coins is live</title><link>https://three.ws/coins</link>diff --git a/public/features.json b/public/features.jsonindex 040df13bd..d1e2f47a6 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-10T12:31:09.797Z",+ "generated_at": "2026-07-10T12:32:18.268Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api/healthz.test.js b/tests/api/healthz.test.jsindex 64135d07f..abb1258bc 100644--- a/tests/api/healthz.test.js+++ b/tests/api/healthz.test.js@@ -63,6 +63,44 @@ describe('GET /api/healthz', () => {expect(body.monitor.running).toBe(true);});+ // api/_lib/alerts.js is a deliberate silent no-op without both env vars. That+ // is right for dev/tests and wrong to leave unnoticed in production, where it+ // means every 5xx report, ring-leak CRITICAL, and low-balance warning is+ // dropped with nothing to show for it. healthz must report the gate honestly.+ describe('ops alert channel', () => {+ const SAVED = [process.env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_ALERTS_CHAT_ID];+ afterEach(() => {+ for (const [k, v] of [['TELEGRAM_BOT_TOKEN', SAVED[0]], ['TELEGRAM_ALERTS_CHAT_ID', SAVED[1]]]) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ });++ it('reports configured=false AND a warning when the channel is unwired', async () => {+ delete process.env.TELEGRAM_BOT_TOKEN;+ delete process.env.TELEGRAM_ALERTS_CHAT_ID;+ const { body } = await callHealthz();+ expect(body.alerts.configured).toBe(false);+ expect(body.alerts.warning).toMatch(/silent no-op/i);+ expect(body.alerts.requires).toEqual(['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ALERTS_CHAT_ID']);+ });++ it('reports configured=false when only one of the two vars is set', async () => {+ process.env.TELEGRAM_BOT_TOKEN = 'bot-token';+ delete process.env.TELEGRAM_ALERTS_CHAT_ID;+ const { body } = await callHealthz();+ expect(body.alerts.configured).toBe(false);+ });++ it('reports configured=true with no warning once both vars are set', async () => {+ process.env.TELEGRAM_BOT_TOKEN = 'bot-token';+ process.env.TELEGRAM_ALERTS_CHAT_ID = '-1001234567890';+ const { body } = await callHealthz();+ expect(body.alerts.configured).toBe(true);+ expect(body.alerts.warning).toBeUndefined();+ });+ });+it('rejects non-GET methods', async () => {const res = makeRes();await healthz(makeReq({ method: 'POST' }), res);diff --git a/tests/x402-autonomous-payer-float.test.js b/tests/x402-autonomous-payer-float.test.jsnew file mode 100644index 000000000..ffe9c31a5--- /dev/null+++ b/tests/x402-autonomous-payer-float.test.js@@ -0,0 +1,95 @@+// The autonomous loop must never attempt a payment the payer's USDC float+// cannot fund.+//+// Regression guard for a live production failure: the ring payer's USDC balance+// hit $0 while the daily spend cap still had headroom, so every tick probed,+// signed, and POSTed a payment for each ready entry — and the facilitator failed+// every one at settle with `broadcast_failed:Simulation failed`. 1,262 failures+// in 24h, roughly one per minute, indefinitely. The daily cap bounds what we're+// *allowed* to spend; only the token balance bounds what we're *able* to.+//+// readPayerUsdcAtomic() is the preflight read that closes the gap. Its contract:+// • a real balance → that balance, in atomic units (6dp)+// • a wallet with no ATA → 0 (never held USDC ⇒ holds no USDC)+// • an undeterminable balance → null ("unknown", callers must NOT gate on it)+//+// The null-vs-zero distinction is the load-bearing part: a transient RPC blip+// must not read as "empty wallet" and silently halt the whole ring.+//+// The Connection is a stub — these assert the branch logic, not Solana.++import { describe, it, expect, beforeAll } from 'vitest';+import { Keypair } from '@solana/web3.js';++let readPayerUsdcAtomic;+let PAYER;++beforeAll(async () => {+ // The module reads USDC_MINT from env at import time.+ process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+ process.env.CRON_SECRET = 'test-secret';+ PAYER = Keypair.generate().publicKey;+ ({ readPayerUsdcAtomic } = await import('../api/cron/x402-autonomous-loop.js'));+});++/** Stub Connection. `account` = what getAccountInfo yields; `balance` = getTokenAccountBalance. */+function stubConn({ account = {}, balance, accountThrows, balanceThrows } = {}) {+ return {+ async getAccountInfo() {+ if (accountThrows) throw accountThrows;+ return account;+ },+ async getTokenAccountBalance() {+ if (balanceThrows) throw balanceThrows;+ return balance;+ },+ };+}++describe('readPayerUsdcAtomic — the spend-path preflight', () => {+ it('returns the balance in atomic units when the payer holds USDC', async () => {+ const conn = stubConn({ balance: { value: { amount: '12500000', decimals: 6 } } });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBe(12_500_000);+ });++ it('returns 0 for a funded-but-drained ATA (the exact production condition)', async () => {+ const conn = stubConn({ balance: { value: { amount: '0', decimals: 6 } } });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBe(0);+ });++ it('returns 0 when the wallet has no token account at all', async () => {+ // getAccountInfo yields null for a missing account — it does not throw.+ // Detecting the no-ATA case structurally (rather than by pattern-matching+ // getTokenAccountBalance's error string, whose wording differs per RPC+ // provider) is what makes this branch reliable.+ const conn = stubConn({ account: null });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBe(0);+ });++ it('returns null (unknown, do not gate) when the RPC read fails', async () => {+ const conn = stubConn({ accountThrows: new Error('503 Service Unavailable') });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBeNull();+ });++ it('returns null when the balance call fails after the account resolves', async () => {+ const conn = stubConn({ balanceThrows: new Error('rpc timeout') });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBeNull();+ });++ it('returns null on an unparseable amount rather than treating it as empty', async () => {+ const conn = stubConn({ balance: { value: { amount: 'not-a-number' } } });+ await expect(readPayerUsdcAtomic(conn, PAYER)).resolves.toBeNull();+ });++ it('never confuses "unknown" with "empty"', async () => {+ // The whole point: 0 halts the spend path, null leaves it open. If a+ // transient failure ever returned 0, one RPC blip would silently stop the+ // ring; if a genuinely empty wallet ever returned null, the doomed-payment+ // storm this guard exists to prevent would come straight back.+ const empty = await readPayerUsdcAtomic(stubConn({ account: null }), PAYER);+ const unknown = await readPayerUsdcAtomic(stubConn({ accountThrows: new Error('boom') }), PAYER);+ expect(empty).toBe(0);+ expect(unknown).toBeNull();+ expect(empty).not.toBe(unknown);+ });+});