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.

Add detailed documentation for USDC agent vaults and implement MCP tool source discovery

nirholas12a3117f7820
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5999e6900..936abb320 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Payment Sessions, the developer platform, and the media APIs are now documented** — Three new developer guides: Payment Sessions (fund a capped spend envelope from prepaid credits and let an agent pay x402 services with a bearer token, no private key involved), the developer platform (API keys, usage metrics, signed webhooks, the one-call MCP connection test, and the public tool and skills catalogs), and the media and render API (avatar image renders, posed clip renders, the runtime GLB optimizer, the open model proxy, and the free vision and speech-to-text endpoints). Every endpoint ships with a runnable example. (`/docs/payment-sessions`) `[docs]`
- **Runnable examples for the x402 fetch wrapper, the MCP server, and the avatar SDK** — Three example sets you can run as-is against live three.ws services: a zero-spend x402 discovery probe plus a key-gated real paid call, curl and plain Node walkthroughs of the full MCP session lifecycle including a free tool call, and a build-free HTML page that renders a live 3D avatar straight from the CDN. `[docs, sdk]`
- **Solana reads keep working when every paid RPC plan runs dry at once** — Everything on the platform that reads the Solana chain (wallet balances, coin prices, launch history, agent payments) goes through a chain of RPC providers, tried in order. All four of our paid providers hit their limits on the same day, so every read started by failing over to a free node before it could succeed. The primary now points at a healthy node directly. The health monitor was also counting whichever node we point at as paid capacity, which meant switching to a free node during an outage would have made the monitor report the paid tier as healthy at the exact moment all of it was down. It now judges a lane by the provider it belongs to, so an exhausted paid tier is always visible on the status page. `[infra, fix]`
+- **The economy's self-refuel can no longer mistake an unreadable balance for an empty wallet** — When the autonomous economy runs short of SOL it converts a small, capped slice of its own USDC revenue to keep paying agents. That check treated a failed balance lookup exactly like a zero balance, so whenever a Solana data provider was rate-limited the platform concluded its revenue was spent and stopped refuelling, with the funds it needed sitting in its own wallet. The balance read now has a second, cheaper path, and a lookup that genuinely fails is reported as unknown rather than empty, so recovery no longer waits on a human. `[fix, infra]`
- **The pages that shipped without docs now have them** — Thirteen surfaces that launched with no guide are now fully documented: the Agent-Forged Gallery, Generation Watch, the KOL Tracker, the Character and Object Libraries, the Minted gallery, the Reasoning Ledger, the 3D history timeline, Daily Match, Agent Symphony, the notifications center, the creator portfolio, and the Token Screener. Each guide explains what the page shows, where every number comes from, and the public API behind it, and all of them are linked from the Start Here page. (`/docs/start-here`) `[docs]`
- **The README is reorganized around what you came to do** — Our README had grown to cover almost a hundred topics, but in an order that made it hard to use: anyone who came to build had to scroll past the long-term vision, the roadmap, and our marketplace and partner listings before reaching install instructions. It now follows the order a reader actually needs. What three.ws is, what it looks like, then how to run it, then the architecture, the individual systems, the developer platform, and the on-chain and payment rails, with the vision and roadmap sitting together further down next to the phased projects they describe. Nothing was removed or reworded, only moved. The table of contents also had an entry for the in-game economy that pointed nowhere, because the section had been dropped from the file a while back; that documentation is written again and now covers the cash purse, the general store, the bank, the $THREE cosmetics boutique, and the wheel of fortune. `[docs]`
- **The treasury self-repair now reports when it cannot repair** — The platform keeps its automated payments funded by pulling idle funds back from its own agent wallets. When that repair could not run, it said nothing at all: no log line, no alert. A recent stall lasted about eleven hours for exactly that reason, with funds available the whole time and no way to see the repair was blocked. It now raises an alert, and distinguishes the two cases that look identical but need opposite responses: the network providers were unreachable (free to fix, nothing to fund), or every source really is empty (the only case that needs a top-up). `[infra, improvement]`
diff --git a/ISSUES.md b/ISSUES.md
index 055e91cfc..8916a2faf 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -29,30 +29,36 @@ this repo:
OpenRouter as $0). Traffic survives on the free lanes (Groq/NIM plus the
vertex-gemini credits anchor). Action: reactivate OpenAI billing and/or
fund the OpenRouter key, or accept free-lane-only service.
-2. **Neon storage pressure — RESOLVED, re-verified 2026-07-29.** The branch
- measures 2538MB against a 3072MB high-water (`isStoragePressured()` reports
- `pressured: false`), so no write cron is gated. The two code defects behind
- the original report are also closed: `wrapCron`'s `requireWriteCapacity`
- preflight logs a named warn and heartbeats a healthy skip instead of failing
- silently, and `db-retention` now VACUUM FULLs the worst offenders under
- pressure (section D), which does return space to the OS. Re-open only if the
- size crosses the high-water again.
-3. **Helius quota exhaustion, still live** (observed 2026-07-22: mainnet and
- devnet RPC 429 "max usage reached"; balances and solana-rpc fail over to
- public RPC with the designed 10min/360min cooldowns). Action: bump the
- Helius plan if the 429s persist at this volume.
+2. **Every paid Solana RPC lane is over quota at once** (owner action: money).
+ Re-probed 2026-07-30 with a metered `getBalance` (never `getHealth`, which is
+ unmetered and returns ok on an exhausted endpoint): Helius `-32429 max usage
+ reached`, QuickNode `-32003 daily request limit reached`, and BOTH Alchemy
+ apps (`ALCHEMY_API_KEY` and the key inside `SOLANA_RPC_FALLBACK_URLS`) return
+ `429 Monthly capacity limit exceeded` (they share one account quota, so the
+ second is not a spare). The dead Alchemy endpoint was also pinned as
+ `SOLANA_RPC_URL`, so every production Solana call began by failing over.
+ Mitigated in config on 2026-07-30 (revision `three-ws-api-00335-ncg`):
+ `SOLANA_RPC_URL` now points at `https://solana-rpc.publicnode.com`, with
+ Leo RPC and MagicBlock as `SOLANA_RPC_FALLBACK_URLS`. All three were burst-
+ probed 12/12 OK on `getBalance`, `getLatestBlockhash` and
+ `getSignatureStatuses`. The exhausted paid lanes stay in the chain and
+ re-enter rotation on their own when quota resets (`QUOTA_COOLDOWN_MS` is 6h).
+ The platform is therefore up but throttled, which shows up as intermittent
+ 5xx and slow settles. Action: top up or upgrade a plan, or cut call volume
+ via the ring cadence knobs. Note GCP credits cannot help here: Blockchain
+ Node Engine is Ethereum-only, so there is no GCP-hosted Solana RPC.
Carried forward from the retired `prompts/x402-catalog/` tracker (campaign
closed 2026-07-28; full history in git):
-4. **No web-search key in prod** (owner action, now non-blocking). `BRAVE_API_KEY` /
+3. **No web-search key in prod** (owner action, now non-blocking). `BRAVE_API_KEY` /
`TAVILY_API_KEY` / `EXA_API_KEY` / `SERPER_API_KEY` are all absent on
`three-ws-api`. This no longer leaves the fact-checker on DuckDuckGo scraps:
the search chain now leads with Vertex-grounded Google Search (service-account
auth, GCP credits, no third-party key) and the keyless Wikipedia rung returns
full intro extracts rather than 150-char highlight fragments. Setting one of
the four keys is still an upgrade, not a prerequisite.
-5. **Fact-check verdict quality — reworked in-repo 2026-07-29, benchmark
+4. **Fact-check verdict quality, reworked in-repo 2026-07-29, benchmark
awaiting a clean run** (code). The chain-level defects behind the 20% score
are fixed: `computeVerdict` now judges direction over stance-BEARING weight
with a coverage gate (all-neutral evidence returns `insufficient` instead of
@@ -68,11 +74,11 @@ closed 2026-07-28; full history in git):
run with >10% errored claims. Action: re-run
`node scripts/fact-check-benchmark.mjs` against production once the deploy
below lands (Vertex answers there, so the chain is not degraded).
-6. **ASR/media backstops unconfigured** (owner action).
+5. **ASR/media backstops unconfigured** (owner action).
`NVIDIA_ASR_FUNCTION_ID` unset in prod (`/api/v1/ai/asr` returns 503
`not_configured`); the Replicate account is out of credit; Upstash Redis is
absent on `three-ws-api`.
-7. **ENS resolution was live-broken; fixed in-repo 2026-07-29, awaiting
+6. **ENS resolution was live-broken; fixed in-repo 2026-07-29, awaiting
deploy.** `GET /api/v1/resolve?name=vitalik.eth` returned 503
`ens_unavailable` (measured 9.7s and 12.4s against the 8s budget) while the
`.sol` lane worked. Two root causes, both fixed: `RPC_URL_ETHEREUM` pointed
@@ -92,6 +98,28 @@ closed 2026-07-28; full history in git):
so it timed out on every name), the x402 identity-claim verifier (5s, which
silently downgraded every ENS claim to "no evidence"), and `/api/v1/resolve`.
All verified resolving keyless end to end.
- Verify after the next deploy, then drop this item. Separately, the operator
- should repoint or unset `RPC_URL_ETHEREUM` on the Cloud Run service, since
- it is dead weight even demoted.
+ Verify after the next deploy, then drop this item. The related operator
+ action is already moot: `RPC_URL_ETHEREUM` is not set on the `three-ws-api`
+ Cloud Run service at all (checked 2026-07-30), so there is nothing to
+ repoint or unset. Re-measured live the same day, production still returns
+ 503 `ens_unavailable` on `vitalik.eth` while `three.sol` resolves in 246ms,
+ which confirms the remaining gap is purely the undeployed fix.
+
+7. **BSC testnet contracts are code-complete but never publicly deployed**
+ (owner action; re-homed here 2026-07-30 when the BNB Chain campaign's work
+ orders were retired). Every contract proof in that campaign ran against an
+ anvil fork or a local instance because no funded deployer key exists:
+ `BNB_TESTNET_DEPLOYER_KEY` is absent from the shell env, the root `.env`, and
+ `contracts/.env`, and the public faucet is reCAPTCHA-gated, so the
+ `GreenfieldVault` and `WorldMoves` deploys and every real Greenfield write
+ never happened. The deploy scripts are dry-run verified and unchanged
+ (`forge script script/DeployGreenfieldVault.s.sol` /
+ `script/DeployWorldMoves.s.sol --broadcast`, both documented in
+ [contracts/DEPLOYMENTS.md](contracts/DEPLOYMENTS.md)). Action: fund a
+ throwaway EOA at `https://www.bnbchain.org/en/testnet-faucet`, set
+ `BNB_TESTNET_DEPLOYER_KEY` (and `GREENFIELD_VAULT_OPERATOR_KEY`, which falls
+ back to the same key), re-run the two scripts, then set
+ `WORLD_MOVES_ADDRESS_TESTNET`. No code change is needed: the moment the
+ address exists, `/api/bnb/world-config` starts returning `deployed:true` for
+ real visitors and the sender/reader/ghost paths light up as already proven.
+ Full history: `prompts/bnb-chain/PROGRESS.md`.
diff --git a/api/_lib/economy-fuel.js b/api/_lib/economy-fuel.js
index f0be98ee0..839cc4b42 100644
--- a/api/_lib/economy-fuel.js
+++ b/api/_lib/economy-fuel.js
@@ -156,18 +156,58 @@ async function secondsSinceLastSwap() {
return secs == null ? Infinity : Number(secs);
}
-/** Read an owner's USDC balance (whole tokens + atomics). */
+/**
+ * Read an owner's USDC balance (whole tokens + atomics).
+ *
+ * A failed read and a genuinely empty wallet are NOT the same thing, and this
+ * used to collapse both into zero. That is a fallback that cannot catch the case
+ * it exists for: reported as 0, the planner answers `no_spare_usdc`, which reads
+ * as "the revenue is already spent, the owner must send funds" when the truth was
+ * "the RPC lane was in cooldown" and nothing needed funding at all. Observed
+ * 2026-07-30: the master held 46 USDC while the refuel lane declined to act, so
+ * the economy stayed flat with its own cure sitting in its own wallet.
+ *
+ * The owner-wide scan runs first (it also sees non-canonical token accounts), the
+ * derived ATA is the fallback for lanes that do not serve the indexed method, and
+ * `readFailed` is set unless the chain actually answered.
+ */
async function readUsdc(connection, owner, network) {
const mint = network === 'devnet' ? USDC_MINT_BY_NETWORK.devnet : USDC_MINT_BY_NETWORK.mainnet;
const { PublicKey } = await import('@solana/web3.js');
- let atomics = 0n;
+ const mintKey = new PublicKey(mint);
+ const shape = (atomics) => ({
+ atomics,
+ usd: Number(atomics) / 10 ** USDC_DECIMALS,
+ readFailed: false,
+ });
+
try {
- const r = await connection.getParsedTokenAccountsByOwner(owner, { mint: new PublicKey(mint) });
+ const r = await connection.getParsedTokenAccountsByOwner(owner, { mint: mintKey });
+ let atomics = 0n;
for (const a of r.value) atomics += BigInt(a.account.data.parsed?.info?.tokenAmount?.amount || '0');
+ return shape(atomics);
} catch {
- /* no ATA ⇒ zero */
+ /* indexed scan unsupported or lane cooling: fall through to the ATA read */
+ }
+
+ try {
+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');
+ const info = await connection.getAccountInfo(getAssociatedTokenAddressSync(mintKey, owner), 'confirmed');
+ // The ATA address is derived, not looked up, so a null account is the chain
+ // stating it does not exist: a real zero, not a read we failed to make.
+ if (!info) return shape(0n);
+ const data = Buffer.isBuffer(info.data) ? info.data : Buffer.from(info.data || []);
+ // SPL token account layout: mint(32) + owner(32) + amount(u64 LE).
+ if (data.length < 72) return shape(0n);
+ return shape(data.readBigUInt64LE(64));
+ } catch (e) {
+ return {
+ atomics: 0n,
+ usd: 0,
+ readFailed: true,
+ error: String(e?.message || 'usdc_read_failed').slice(0, 160),
+ };
}
- return { atomics, usd: Number(atomics) / 10 ** USDC_DECIMALS };
}
/**
@@ -217,7 +257,22 @@ export async function refuelMasterFromUsdc({ connection, deficitSol, network = '
}
await ensureSchema();
- const { usd: usdcUsd } = await readUsdc(connection, master.publicKey, network);
+ const usdc = await readUsdc(connection, master.publicKey, network);
+ // Never let an unread balance be planned as an empty one: "we could not look"
+ // and "there is nothing there" need opposite responses from the operator, and
+ // only the second one costs money to fix.
+ if (usdc.readFailed) {
+ return {
+ acted: false,
+ enabled: true,
+ reason: 'usdc_read_failed',
+ readError: usdc.error,
+ masterSol: round(masterSol),
+ spendableSol: round(spendablePre),
+ gapSol: round(gapPre),
+ };
+ }
+ const usdcUsd = usdc.usd;
const spentToday = await usdcSpentTodayUsd();
const solUsd = await solPriceUsd().catch(() => 0);
diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.js
index 9ddf914c9..9c1fae084 100644
--- a/api/cron/treasury-topup.js
+++ b/api/cron/treasury-topup.js
@@ -282,6 +282,21 @@ export default wrapCron(async (req, res) => {
{ signature: `economy-fuel:${fuel.signature}` },
);
}
+ // A refuel that could not READ the USDC balance is the same class of
+ // look-alike as a reclaim that could not run, and it lands after the
+ // classification above, so it needs to say so itself. Without this the tick
+ // reports the indistinguishable-but-opposite `no_spare_usdc` and the operator
+ // funds a wallet that was never empty.
+ if (!dryRun && fuel.reason === 'usdc_read_failed') {
+ await sendOpsAlert(
+ '⛽ Economy refuel BLOCKED: USDC balance unreadable',
+ `Deficit ${totalDeficitSol.toFixed(4)} SOL and the master's USDC balance could not be read, so no refuel was planned. ` +
+ `First error: ${String(fuel.readError || 'unknown').slice(0, 180)}. ` +
+ 'This is NOT "the revenue is spent": the balance is unknown, not zero. Check the Solana RPC lanes ' +
+ '(healthz rpc_lanes) before sending any funds.',
+ { signature: 'economy-fuel-read-blocked', severity: 'warn' },
+ );
+ }
// Self-healing, step 3 (the USDC side): the steps above keep SOL flowing, but
// the ring/a2a payers SPEND USDC, and their only refill path used to be
diff --git a/data/changelog.json b/data/changelog.json
index 4647187f5..5242105a8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -16938,6 +16938,15 @@
"docs",
"improvement"
]
+ },
+ {
+ "date": "2026-07-30",
+ "title": "The economy's self-refuel can no longer mistake an unreadable balance for an empty wallet",
+ "summary": "When the autonomous economy runs short of SOL it converts a small, capped slice of its own USDC revenue to keep paying agents. That check treated a failed balance lookup exactly like a zero balance, so whenever a Solana data provider was rate-limited the platform concluded its revenue was spent and stopped refuelling, with the funds it needed sitting in its own wallet. The balance read now has a second, cheaper path, and a lookup that genuinely fails is reported as unknown rather than empty, so recovery no longer waits on a human.",
+ "tags": [
+ "fix",
+ "infra"
+ ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 9eb40ed34..2ba79d259 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-30T04:33:39.690Z",
+ "generated_at": "2026-07-30T04:35:53.886Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -81,6 +81,17 @@
"fix"
]
},
+ {
+ "date": "2026-07-30",
+ "type": "update",
+ "title": "The economy's self-refuel can no longer mistake an unreadable balance for an empty wallet",
+ "summary": "When the autonomous economy runs short of SOL it converts a small, capped slice of its own USDC revenue to keep paying agents. That check treated a failed balance lookup exactly like a zero balance, so whenever a Solana data provider was rate-limited the platform concluded its revenue was spent and stopped refuelling, with the funds it needed sitting in its own wallet. The balance read now has a second, cheaper path, and a lookup that genuinely fails is reported as unknown rather than empty, so recovery no longer waits on a human.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-30",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 3a46eba62..1447fe032 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -62,6 +62,14 @@
<category>infra</category>
<description>Everything on the platform that reads the Solana chain (wallet balances, coin prices, launch history, agent payments) goes through a chain of RPC providers, tried in order. All four of our paid providers hit their limits on the same day, so every read started by failing over to a free node before it could succeed. The primary now points at a healthy node directly. The health monitor was also counting whichever node we point at as paid capacity, which meant switching to a free node during an outage would have made the monitor report the paid tier as healthy at the exact moment all of it was down. It now judges a lane by the provider it belongs to, so an exhausted paid tier is always visible on the status page.</description>
</item>
+ <item>
+ <title>The economy's self-refuel can no longer mistake an unreadable balance for an empty wallet</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-30:The economy's self-refuel can no longer mistake an unreadable balance for an empty wallet</guid>
+ <pubDate>Thu, 30 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>When the autonomous economy runs short of SOL it converts a small, capped slice of its own USDC revenue to keep paying agents. That check treated a failed balance lookup exactly like a zero balance, so whenever a Solana data provider was rate-limited the platform concluded its revenue was spent and stopped refuelling, with the funds it needed sitting in its own wallet. The balance read now has a second, cheaper path, and a lookup that genuinely fails is reported as unknown rather than empty, so recovery no longer waits on a human.</description>
+ </item>
<item>
<title>The pages that shipped without docs now have them</title>
<link>https://three.ws/docs/start-here</link>
diff --git a/public/features.json b/public/features.json
index 6073b62af..33fb906eb 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-30T04:33:39.595Z",
+ "generated_at": "2026-07-30T04:35:53.858Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/economy-fuel-usdc-read.test.js b/tests/economy-fuel-usdc-read.test.js
new file mode 100644
index 000000000..01a647bc6
--- /dev/null
+++ b/tests/economy-fuel-usdc-read.test.js
@@ -0,0 +1,133 @@
+// A USDC balance the refuel lane could not READ must never be planned as a
+// wallet that is empty.
+//
+// The two states are indistinguishable in the old return shape and need opposite
+// responses from the operator: `no_spare_usdc` means the revenue is spent and
+// only owner funding fixes it, while an unreadable balance means an RPC lane is
+// cooling and nothing needs funding at all. Production 2026-07-30 hit the second
+// and reported the first: the economy master held 46 USDC while the refuel lane
+// declined to act, so the circulation treasury stayed at 0.012 SOL, the
+// pulse-tick governor held the paid-action budget at zero, and the Money Pulse
+// ran reviews and trials only, with its own cure sitting in its own wallet.
+//
+// Covers the read itself (indexed scan unsupported, lane failure, genuine zero)
+// through the real refuelMasterFromUsdc entrypoint.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { MASTER } = vi.hoisted(() => ({
+ MASTER: 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW',
+}));
+
+vi.mock('../api/_lib/economy-master.js', () => ({
+ loadEconomyMaster: vi.fn(async () => {
+ const { Keypair } = await import('@solana/web3.js');
+ return Keypair.generate();
+ }),
+ RESERVE_SOL: 0.02,
+ RUN_CAP_SOL: 2,
+}));
+
+// The master reads as nearly dry, so there is always a real gap to refuel.
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ getSolBalance: vi.fn(async () => ({ sol: 0.021, lamports: 21_000_000 })),
+}));
+vi.mock('../api/_lib/sol-price.js', () => ({ solPriceUsd: vi.fn(async () => 74) }));
+vi.mock('../api/_lib/solana/confirm.js', () => ({ confirmOrThrow: vi.fn(async () => {}) }));
+vi.mock('../api/_lib/vault-jupiter.js', () => ({
+ USDC_MINT_BY_NETWORK: {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ },
+ USDC_DECIMALS: 6,
+ // A route the lane refuses on price impact: it proves planning got past the
+ // balance read without letting the test broadcast anything.
+ jupQuote: vi.fn(async () => ({ priceImpactPct: 99, outAmount: 0 })),
+ buildSwapTx: vi.fn(async () => { throw new Error('swap must not be reached in these cases'); }),
+}));
+vi.mock('../api/_lib/db.js', () => ({
+ sql: Object.assign(vi.fn(async () => []), { unsafe: vi.fn(async () => []) }),
+}));
+
+import { refuelMasterFromUsdc } from '../api/_lib/economy-fuel.js';
+
+/** A connection whose indexed scan and account read behave as configured. */
+function conn({ scan, account }) {
+ return {
+ getParsedTokenAccountsByOwner: vi.fn(async () => {
+ if (scan === 'throw') throw new Error('410 Gone: getParsedTokenAccountsByOwner is not supported');
+ return { value: scan };
+ }),
+ getAccountInfo: vi.fn(async () => {
+ if (account === 'throw') throw new Error('429 Too Many Requests: lane cooling');
+ return account;
+ }),
+ };
+}
+
+/** An SPL token account buffer holding `whole` USDC (6 decimals). */
+function tokenAccount(whole) {
+ const data = Buffer.alloc(165);
+ data.writeBigUInt64LE(BigInt(Math.round(whole * 1e6)), 64);
+ return { data };
+}
+
+beforeEach(() => {
+ delete process.env.ECONOMY_FUEL_ENABLED;
+});
+
+describe('refuel USDC balance read', () => {
+ it('reports usdc_read_failed (not no_spare_usdc) when every read path fails', async () => {
+ const res = await refuelMasterFromUsdc({
+ connection: conn({ scan: 'throw', account: 'throw' }),
+ deficitSol: 0.99,
+ network: 'mainnet',
+ });
+
+ expect(res.acted).toBe(false);
+ // The whole point: the operator must not be told the wallet is empty.
+ expect(res.reason).toBe('usdc_read_failed');
+ expect(res.reason).not.toBe('no_spare_usdc');
+ expect(res.readError).toMatch(/429|cooling/i);
+ });
+
+ it('falls back to the derived ATA when the indexed scan is unsupported', async () => {
+ const res = await refuelMasterFromUsdc({
+ connection: conn({ scan: 'throw', account: tokenAccount(46.242025) }),
+ deficitSol: 0.99,
+ network: 'mainnet',
+ });
+
+ // 46 USDC is real spendable fuel, so the lane plans a swap rather than
+ // declining. It stops at the quote, which these mocks refuse to serve.
+ expect(res.reason).not.toBe('no_spare_usdc');
+ expect(res.reason).not.toBe('usdc_read_failed');
+ expect(res.usdcAvailable).toBeCloseTo(46.242025, 4);
+ });
+
+ it('still reports no_spare_usdc when the wallet is genuinely empty', async () => {
+ // A null account from a DERIVED address is the chain confirming there is
+ // nothing there, which is the one case that really needs owner funding.
+ const res = await refuelMasterFromUsdc({
+ connection: conn({ scan: 'throw', account: null }),
+ deficitSol: 0.99,
+ network: 'mainnet',
+ });
+
+ expect(res.acted).toBe(false);
+ expect(res.reason).toBe('no_spare_usdc');
+ expect(res.usdcAvailable).toBe(0);
+ });
+
+ it('prefers the indexed scan, summing every USDC account the owner holds', async () => {
+ const acct = (amount) => ({ account: { data: { parsed: { info: { tokenAmount: { amount } } } } } });
+ const res = await refuelMasterFromUsdc({
+ connection: conn({ scan: [acct('40000000'), acct('6242025')], account: 'throw' }),
+ deficitSol: 0.99,
+ network: 'mainnet',
+ });
+
+ expect(res.usdcAvailable).toBeCloseTo(46.242025, 4);
+ expect(res.reason).not.toBe('usdc_read_failed');
+ });
+});