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(economy): fund the settle-critical fee wallets first and skip a swap the wallet cannot pay rent for

nirholas0559bc23facd
diff --git a/api/_lib/economy-master.js b/api/_lib/economy-master.js
index 9e7a02075..14cab26ab 100644
--- a/api/_lib/economy-master.js
+++ b/api/_lib/economy-master.js
@@ -120,19 +120,38 @@ export async function loadEconomyMaster() {
* on-chain writes — so the plan is unit-testable and the cron can log it.
*
* @param {number} masterSol master's current SOL balance
- * @param {Array<{name:string,pubkey:string,currentSol:number,refillToSol:number}>} targets
+ * @param {Array<{name:string,pubkey:string,currentSol:number,refillToSol:number,settleCritical?:boolean}>} targets
* @returns {{ plan: Array<{name:string,pubkey:string,sol:number}>, skipped: Array<{name:string,reason:string}>, totalSol:number, spendableSol:number }}
*/
export function planTopUps(masterSol, targets) {
const spendableSol = Math.max(0, round(masterSol - sweepFloorSol()));
const runCap = Math.min(RUN_CAP_SOL, spendableSol);
- // Neediest first, so a tight run cap protects the most-drained engines.
- const ordered = [...targets].sort(
- (a, b) => b.refillToSol - b.currentSol - (a.refillToSol - a.currentSol),
- );
+ // Settle-critical wallets first, THEN neediest first, so a tight run cap
+ // protects the most-drained engines within each band.
+ //
+ // Absolute deficit alone ranked the wrong wallet first whenever the master
+ // was thin, which is exactly when the ordering decides anything. Measured
+ // against production on 2026-09-04: the relayer/treasury bundle wanted 0.98
+ // SOL and the x402 ring payer 0.18, so a 0.1, 0.2 or even 0.5 SOL top-up
+ // went entirely to the bundle and left the payer at 0.00125 SOL, under the
+ // 0.002 hard floor the self-facilitator fail-closes on. The rail would have
+ // stayed dead through three separate fundings and only recovered at ~1 SOL.
+ // A float wallet running dry slows a feed; a fee wallet under its floor
+ // stops every payment on the platform, so it is funded first even when its
+ // deficit is smaller.
+ const ordered = [...targets].sort((a, b) => {
+ if (!!a.settleCritical !== !!b.settleCritical) return b.settleCritical ? 1 : -1;
+ return b.refillToSol - b.currentSol - (a.refillToSol - a.currentSol);
+ });
const plan = [];
const skipped = [];
let total = 0;
+ // A master with nothing to give and a run cap that genuinely throttled a
+ // later engine both end the loop with no budget left, and reporting both as
+ // `run_cap_reached` sent operators hunting for a cap knob to raise when the
+ // real answer was to fund the master (production 2026-09-04: spendable 0,
+ // both refill targets reported `run_cap_reached`). Name which one bound.
+ const masterDry = spendableSol < MIN_TOPUP_SOL;
for (const t of ordered) {
const deficit = round(t.refillToSol - t.currentSol);
if (deficit < MIN_TOPUP_SOL) {
@@ -141,7 +160,10 @@ export function planTopUps(masterSol, targets) {
}
const remaining = round(runCap - total);
if (remaining < MIN_TOPUP_SOL) {
- skipped.push({ name: t.name, reason: 'run_cap_reached' });
+ skipped.push({
+ name: t.name,
+ reason: masterDry ? 'master_insufficient_spendable' : 'run_cap_reached',
+ });
continue;
}
// Clamp to whatever's left in the run cap rather than skipping the engine
diff --git a/api/_lib/economy-rebalance.js b/api/_lib/economy-rebalance.js
index d20e07f5c..12515d732 100644
--- a/api/_lib/economy-rebalance.js
+++ b/api/_lib/economy-rebalance.js
@@ -26,6 +26,15 @@
import { USDC_MINT_BY_NETWORK, USDC_DECIMALS, jupQuote, buildSwapTx } from './vault-jupiter.js';
export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+
+// Rent-exemption for the 165-byte wSOL account a usdc->sol swap creates to
+// receive its output. The wallet pays it out of its own lamports inside the
+// swap transaction (refunded when the account closes at the end of the same
+// transaction), so a wallet holding less than this cannot buy SOL at all:
+// simulation dies inside the ATA CreateIdempotent and no swap ever lands.
+export const SWAP_OUTPUT_RENT_LAMPORTS = 1_855_569;
+// Signature fee plus headroom for the extra instructions a swap carries.
+const SWAP_FEE_BUFFER_LAMPORTS = 15_000;
const LAMPORTS_PER_SOL = 1_000_000_000;
const USDC_ATOMICS = 10 ** USDC_DECIMALS;
@@ -138,7 +147,7 @@ export function resolveSelfPayFloors({ sol, usdc, solPriceUsd, targetSol, usdcFl
*
* @param {object} p
* @param {number} p.solPriceUsd live SOL/USD price
- * @param {Array<{name:string,pubkey:string,sol:number,usdc:number,wants:'usdc'|'sol',floorUsd:number,solFloor?:number}>} p.wallets
+ * @param {Array<{name:string,pubkey:string,sol:number,usdc:number,wants:'usdc'|'sol',floorUsd:number,solFloor?:number,hasWsolAccount?:boolean}>} p.wallets
* @param {object} [p.bounds] REBALANCE snapshot (injectable for tests)
* @returns {{ plan:Array<{name:string,pubkey:string,dir:'sol->usdc'|'usdc->sol',inUsd:number,reason:string}>,
* skipped:Array<{name:string,reason:string}> }}
@@ -219,6 +228,25 @@ export function planRebalance({ solPriceUsd, wallets, bounds }) {
plannedDir.set(w.pubkey, 'sol->usdc');
runRemainingUsd = round(runRemainingUsd - inUsd);
} else {
+ // A wallet too poor to open the account its own swap output lands in
+ // can never rescue itself, and planning the leg anyway costs a failed
+ // simulation every run while reporting an opaque `failed` that names
+ // neither the shortfall nor the fix. Measured on the ring payer
+ // 2026-09-04: 1,253,408 lamports against a 1,855,569 rent line, with
+ // 4.18 USDC it could not convert and the whole settle rail down
+ // behind it. Skip with the numbers instead, so the surface an
+ // operator reads says exactly how much SOL unlocks that USDC.
+ // Waived when the wallet already holds a wSOL account: the rent is
+ // paid, the create is a no-op, and only fees remain.
+ const rentFloor = Number.isFinite(B.swapRentLamports)
+ ? B.swapRentLamports
+ : SWAP_OUTPUT_RENT_LAMPORTS;
+ const lamports = Math.floor(w.sol * LAMPORTS_PER_SOL);
+ const rentNeeded = rentFloor + SWAP_FEE_BUFFER_LAMPORTS;
+ if (!w.hasWsolAccount && lamports < rentNeeded) {
+ skipped.push({ name: w.name, reason: `below_swap_rent:${lamports}<${rentNeeded}` });
+ continue;
+ }
// Convert USDC → SOL, keeping the USDC reserve untouched.
const swappableUsdcUsd = Math.max(0, w.usdc - B.usdcReserve);
const inUsd = Math.min(shortfallUsd, swappableUsdcUsd, B.perSwapUsd, runRemainingUsd);
diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.js
index 813ef102c..43fdb9f50 100644
--- a/api/_lib/solana-signers.js
+++ b/api/_lib/solana-signers.js
@@ -26,6 +26,9 @@
* master auto-tops it up (defaults to minSol×3 in the treasury-topup cron)
* @property {boolean} [isMaster] the funding root itself — watched for a low
* balance, but never a refill TARGET (it funds the others, not itself)
+ * @property {boolean} [settleCritical] a fee wallet the x402 payment rail pays
+ * from: under its floor the facilitator refuses every settle, so a thin
+ * funding run brings this signer up BEFORE any float or feed wallet
* @property {boolean} [holdsTokens] this wallet operationally HOLDS SPL token
* balances (revenue, payout float, tip inventory). The sweepback module
* (api/_lib/economy-sweepback.js) never takes its tokens in excess mode —
@@ -155,6 +158,7 @@ export const SOLANA_SIGNERS = [
// the topup floor a hair above that hard floor and let the economy master's
// treasury-topup cron refill it before the loop stops.
minSol: 0.03,
+ settleCritical: true,
purpose: 'x402 ring sponsor (fee payer): co-signs + pays SOL on every self-hosted-facilitator settle; below-floor pauses the whole ring',
network: 'mainnet',
},
@@ -167,6 +171,7 @@ export const SOLANA_SIGNERS = [
// Its USDC float is watched separately by the wallet-balance monitor; the
// economy master only ever tops up SOL, never USDC.
minSol: 0.03,
+ settleCritical: true,
holdsTokens: true,
purpose: 'x402 ring payer (self-pay mode): signs + pays its own 1-sig fee on each ring settle; USDC float watched by the balance monitor',
network: 'mainnet',
diff --git a/api/cron/economy-rebalance.js b/api/cron/economy-rebalance.js
index da117e70a..622aa9f88 100644
--- a/api/cron/economy-rebalance.js
+++ b/api/cron/economy-rebalance.js
@@ -8,7 +8,8 @@
//
// SAFE BY DEFAULT: inert unless ECONOMY_REBALANCE_ENABLED=1. Even disabled it
// computes and returns the plan (dry run) so the owner can see what it WOULD do
-// before arming it. Every swap is reserve-, per-swap-, per-run- and slippage-capped
+// before arming it, and `?dry=1` returns that same plan without signing even
+// when it IS armed. Every swap is reserve-, per-swap-, per-run- and slippage-capped
// (see economy-rebalance.js). Read-and-quote only until armed.
//
// Env: CRON_SECRET, SOLANA_RPC_URL, the a2a-payer / x402-ring-payer signer secrets,
@@ -18,7 +19,7 @@ import { env } from '../_lib/env.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { SOLANA_SIGNERS, resolveSignerPubkey, loadSignerKeypair } from '../_lib/solana-signers.js';
import { solUsdPrice } from '../_lib/avatar-wallet.js';
-import { planRebalance, executeSwap, resolveSelfPayFloors, REBALANCE, USDC_WALLETS } from '../_lib/economy-rebalance.js';
+import { planRebalance, executeSwap, resolveSelfPayFloors, REBALANCE, USDC_WALLETS, WSOL_MINT } from '../_lib/economy-rebalance.js';
import { USDC_MINT_BY_NETWORK } from '../_lib/vault-jupiter.js';
import { logAudit } from '../_lib/audit.js';
import { requireCron } from '../_lib/cron-auth.js';
@@ -30,6 +31,11 @@ async function readWallet(connection, pubkey) {
const { PublicKey } = await import('@solana/web3.js');
let sol = 0;
let usdc = 0;
+ // Whether a wSOL account already exists decides whether a usdc->sol swap has
+ // to fund one out of this wallet's own lamports (planRebalance's swap-rent
+ // guard). Read it here rather than assuming: assuming "absent" would block a
+ // wallet that can in fact swap.
+ let hasWsolAccount = false;
try {
const owner = new PublicKey(pubkey);
sol = (await connection.getBalance(owner)) / 1e9;
@@ -38,10 +44,12 @@ async function readWallet(connection, pubkey) {
(a, x) => a + Number(x.account.data.parsed.info.tokenAmount.uiAmount || 0),
0,
);
+ const wsol = await connection.getParsedTokenAccountsByOwner(owner, { mint: new PublicKey(WSOL_MINT) });
+ hasWsolAccount = wsol.value.length > 0;
} catch {
/* an RPC hiccup — report zeros; the plan just skips this wallet honestly */
}
- return { sol, usdc };
+ return { sol, usdc, hasWsolAccount };
}
export default wrapCron(async (req, res) => {
@@ -59,7 +67,7 @@ export default wrapCron(async (req, res) => {
const resolved = await resolveSignerPubkey(spec).catch(() => null);
const pubkey = resolved?.pubkey;
if (!pubkey) continue;
- const { sol, usdc } = await readWallet(connection, pubkey);
+ const { sol, usdc, hasWsolAccount } = await readWallet(connection, pubkey);
const floorUsd = Number(process.env[cfg.floorEnv]) || cfg.floorDflt;
// A self-pay wallet's fee-SOL refill target doubles as the untouchable
// reserve on its sol->usdc leg (see planRebalance), so the USDC floor can
@@ -73,7 +81,7 @@ export default wrapCron(async (req, res) => {
const floors = cfg.selfPayFee
? resolveSelfPayFloors({ sol, usdc, solPriceUsd, targetSol, usdcFloorUsd: floorUsd })
: { solFloor: 0, constrained: false, rescueArmed: false };
- wallets.push({ name: cfg.role, pubkey, sol, usdc, wants: 'usdc', floorUsd, solFloor: floors.solFloor });
+ wallets.push({ name: cfg.role, pubkey, sol, usdc, hasWsolAccount, wants: 'usdc', floorUsd, solFloor: floors.solFloor });
// Self-pay fee wallets get a second row for their SOL need. Same name on
// purpose: the executor resolves the signing key by name, and both legs
@@ -83,18 +91,26 @@ export default wrapCron(async (req, res) => {
// rescue can never overshoot into a level the other leg will claw straight
// back.
if (floors.rescueArmed) {
- wallets.push({ name: cfg.role, pubkey, sol, usdc, wants: 'sol', floorUsd: floors.solFloor * solPriceUsd });
+ wallets.push({ name: cfg.role, pubkey, sol, usdc, hasWsolAccount, wants: 'sol', floorUsd: floors.solFloor * solPriceUsd });
}
}
const { plan, skipped } = planRebalance({ solPriceUsd, wallets });
const armed = REBALANCE.enabled;
+ // ?dry=1 → plan only, no key load and no swap. Being disarmed used to be the
+ // only path that did not sign: with ECONOMY_REBALANCE_ENABLED=1 in
+ // production a ?dry=1 preview built, signed and submitted real swaps (hit
+ // 2026-09-04 while previewing this cron). treasury-topup has honored the
+ // same query flag since it shipped and the triage runbook tells an operator
+ // to preview before firing, so the two crons agreeing is what makes that
+ // instruction safe to follow.
+ const dryRun = /[?&]dry=(1|true)\b/.test(req.url || '');
- // Dry run (disabled) — return the plan without touching a key.
- if (!armed) {
+ // Dry run (disarmed, or asked for): return the plan without touching a key.
+ if (!armed || dryRun) {
return json(res, 200, {
ok: true,
- armed: false,
+ armed,
mode: 'dry_run',
solPriceUsd,
wallets: wallets.map((w) => ({
@@ -102,7 +118,9 @@ export default wrapCron(async (req, res) => {
})),
plan,
skipped,
- note: 'ECONOMY_REBALANCE_ENABLED is not set — no swaps executed',
+ note: armed
+ ? 'dry=1: plan only, no swaps executed'
+ : 'ECONOMY_REBALANCE_ENABLED is not set, so no swaps executed',
});
}
diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.js
index eb83bce00..e15fdeb9a 100644
--- a/api/cron/treasury-topup.js
+++ b/api/cron/treasury-topup.js
@@ -89,11 +89,21 @@ export default wrapCron(async (req, res) => {
const refillToSol = spec.refillTo ?? spec.minSol * DEFAULT_REFILL_MULTIPLE;
const merged = byPubkey.get(resolved.pubkey);
if (!merged) {
- byPubkey.set(resolved.pubkey, { names: [spec.name], minSol: spec.minSol, refillToSol });
+ byPubkey.set(resolved.pubkey, {
+ names: [spec.name],
+ minSol: spec.minSol,
+ refillToSol,
+ // One shared wallet is settle-critical if ANY spec resolving to it
+ // is: the x402 ring payer shares a pubkey with the coin-launcher
+ // master, and the payment rail's claim on it does not weaken
+ // because a launcher happens to spend from the same address.
+ settleCritical: !!spec.settleCritical,
+ });
} else {
merged.names.push(spec.name);
merged.minSol = Math.max(merged.minSol, spec.minSol);
merged.refillToSol = Math.max(merged.refillToSol, refillToSol);
+ merged.settleCritical = merged.settleCritical || !!spec.settleCritical;
}
}
for (const [pubkey, merged] of byPubkey) {
@@ -112,6 +122,7 @@ export default wrapCron(async (req, res) => {
pubkey,
currentSol: Number(sol.toFixed(6)),
refillToSol: merged.refillToSol,
+ settleCritical: merged.settleCritical,
});
}
diff --git a/docs/economy-master.md b/docs/economy-master.md
index e581942a6..228c35ad8 100644
--- a/docs/economy-master.md
+++ b/docs/economy-master.md
@@ -57,13 +57,23 @@ belongs in an engine signer the master funds — not in the master.
|---|---|---|---|
| Reserve floor | `ECONOMY_MASTER_RESERVE_SOL` | `0.02` | Never spend the master below this: its own rent-exemption plus fee headroom. An on-chain read, so it holds even with no database. When the master is also the x402 sponsor fee wallet (`X402_FEE_PAYER_SOLANA` points at it), the sweep floor rises to the sponsor settle floor (0.02 SOL) plus `ECONOMY_MASTER_SPONSOR_HEADROOM_SOL` (default `0.03`), so topping up engines can never starve settlement (`sweepFloorSol()`). |
| Per-engine cap | `ECONOMY_MASTER_PER_TOPUP_MAX_SOL` | `0.5` | Most SOL moved to any single engine in one sweep. |
-| Per-run cap | `ECONOMY_MASTER_RUN_CAP_SOL` | `2` | Most SOL moved across all engines in one sweep. Neediest engine funded first, so a tight cap protects the most-drained flow. |
+| Per-run cap | `ECONOMY_MASTER_RUN_CAP_SOL` | `2` | Most SOL moved across all engines in one sweep. Settle-critical engines are funded first, then the neediest, so a tight cap protects the payment rail and then the most-drained flow. |
| Dust skip | — | `0.005` | Skip a top-up smaller than this to avoid fee churn. |
+| Settle-critical first | `settleCritical` on the signer spec | x402 ring sponsor + payer | A wallet the x402 facilitator pays fees from is funded before any float or feed wallet, regardless of whose deficit is larger. Under its floor the facilitator refuses **every** settle, so the rail's claim on a thin run outranks a bigger number elsewhere. Measured 2026-09-04: without this, a 0.1, 0.2 or 0.5 SOL top-up went entirely to the relayer/treasury bundle (deficit 0.98 SOL) and left the ring payer at 0.00125 SOL, under its 0.002 hard floor, so settlement stayed dead until roughly 1 SOL landed. |
| Pubkey match | `ECONOMY_MASTER_ADDRESS` | the address above | The installed secret must derive to the expected pubkey or `loadEconomyMaster()` throws `master_mismatch` — a mis-paste never silently drains a different wallet. |
`planTopUps()` is pure (no RPC), so all of the above are unit-tested in
[`tests/economy-master.test.js`](../tests/economy-master.test.js) without a key.
+Each skipped engine says which bound stopped it, and the two that look alike
+have opposite fixes:
+
+| `skipped[].reason` | What it means | The fix |
+|---|---|---|
+| `below_dust_threshold` | The engine is under floor by less than 0.005 SOL. | Nothing. Fee churn avoided on purpose. |
+| `run_cap_reached` | Earlier engines in this run consumed the per-run budget. | Nothing, or raise `ECONOMY_MASTER_RUN_CAP_SOL`. The next run funds the rest. |
+| `master_insufficient_spendable` | The master itself has nothing above its sweep floor. No cap was involved. | Fund the master. No knob changes this. |
+
## The leak invariant (no SOL leaves the owner-controlled set)
SOL can **only** move from the master to a wallet the platform holds the key for.
@@ -359,6 +369,20 @@ Set `ECONOMY_USDC_TOPUP_ENABLED=0` to disable. The sizing math is a pure functio
(`planUsdcTopups`) covered by
[`tests/economy-usdc-topup.test.js`](../tests/economy-usdc-topup.test.js).
+### Previewing the rebalancer safely
+
+`?dry=1` returns the plan and signs nothing, whether or not
+`ECONOMY_REBALANCE_ENABLED` is set:
+
+```bash
+curl -s -X POST -H "Authorization: Bearer $CRON_SECRET" \
+ 'https://three.ws/api/cron/economy-rebalance?dry=1' | jq '{mode, plan, skipped}'
+```
+
+`mode` reads `dry_run` and `armed` reports whether the cron would have executed.
+Before 2026-09-04 the only path that did not sign was being **disarmed**, so on
+production (armed) a `?dry=1` preview built, signed and submitted real swaps.
+
### Why the rebalancer alone was not enough
The rebalancer keeps each payer stocked in the asset it spends by swapping its
@@ -368,7 +392,7 @@ USDC, the next sells that SOL back for USDC, forever. That ran 134 reversing
swaps and churned ~$900 of notional in 2.5 hours on 2026-07-28, paying two swap
fees and double slippage per round trip to end where it started.
-Three invariants close it permanently, the first two in `planRebalance`:
+Four invariants close it permanently, three of them in `planRebalance`:
1. **No opposing legs in one run** — the neediest leg wins; the other defers to
the next run against fresh balances.
@@ -404,6 +428,21 @@ Three invariants close it permanently, the first two in `planRebalance`:
to 0.15 that leg was armed permanently. It is how the ring's float turned into
SOL in the first place (2026-07-28: 66 `usdc->sol` swaps, $438 churned).
+4. **A rescue the wallet cannot pay for is never planned.** A `usdc->sol` swap
+ lands its output in a wSOL account the transaction itself creates, and the
+ wallet funds that account's rent-exemption (1,855,569 lamports on mainnet)
+ out of its own balance for the life of the transaction. A wallet holding less
+ than that cannot buy the SOL it needs: the swap dies inside the ATA
+ `CreateIdempotent` with system error `0x1` and nothing ever lands. Mainnet
+ 2026-09-04: the x402 ring payer held 1,253,408 lamports and 4.18 USDC it
+ could not convert, and the rebalancer re-planned the same doomed leg every 30
+ minutes, reporting a truncated `failed` that named neither the shortfall nor
+ the fix. `planRebalance` now skips with
+ `below_swap_rent:<have><<need>` instead, so the number an operator reads is
+ the SOL that unlocks the wallet's own USDC. The guard is waived when the
+ wallet already holds a wSOL account, where the rent is paid and the create is
+ a no-op.
+
Step 4 is what makes those invariants affordable: a payer that is genuinely short
of both assets is now refilled from the root instead of being asked to
manufacture one asset out of the other. **Check `ECONOMY_USDC_TOPUP_ENABLED` is
diff --git a/tests/economy-master.test.js b/tests/economy-master.test.js
index ce9d079ba..a9886d2a0 100644
--- a/tests/economy-master.test.js
+++ b/tests/economy-master.test.js
@@ -87,6 +87,50 @@ test('dust: a sub-threshold deficit is skipped, not churned', () => {
assert.deepEqual(skipped, [{ name: 'hair', reason: 'below_dust_threshold' }]);
});
+// The ordering only decides anything when the master is thin, and that is
+// exactly when it used to decide wrong: production 2026-09-04 held a
+// relayer/treasury bundle wanting 0.98 SOL and the x402 ring payer wanting 0.18,
+// so every top-up under ~1 SOL went entirely to the bundle and left the payer
+// under the hard floor the self-facilitator refuses to settle beneath.
+test('settle-critical first: a thin master funds the fee wallet before a needier float', () => {
+ const targets = [
+ { name: 'relayer+treasury', pubkey: 'W', currentSol: 0.016894, refillToSol: 1 },
+ { name: 'x402-ring-payer', pubkey: 'X', currentSol: 0.001253, refillToSol: 0.18, settleCritical: true },
+ ];
+ // master 0.1015 → spendable ~0.0695 (reserve 0.02): only one engine fits.
+ const { plan, skipped } = planTopUps(0.101508, targets);
+ assert.equal(plan.length, 1);
+ assert.equal(plan[0].pubkey, 'X');
+ // And the top-up clears the 0.002 SOL settle floor by a wide margin.
+ assert.ok(plan[0].sol + 0.001253 > 0.002);
+ assert.deepEqual(skipped, [{ name: 'relayer+treasury', reason: 'run_cap_reached' }]);
+});
+
+test('settle-critical does not reorder anything once the budget covers both', () => {
+ const targets = [
+ { name: 'relayer+treasury', pubkey: 'W', currentSol: 0, refillToSol: 1 },
+ { name: 'x402-ring-payer', pubkey: 'X', currentSol: 0, refillToSol: 0.18, settleCritical: true },
+ ];
+ const { plan, skipped } = planTopUps(10, targets);
+ assert.equal(plan.length, 2);
+ assert.equal(plan[0].pubkey, 'X');
+ assert.equal(skipped.length, 0);
+});
+
+// "run_cap_reached" on a master with nothing to give sent operators looking for
+// a cap knob to raise; the fix is capital, and the reason has to say so.
+test('a dry master says it is dry, not that a cap was reached', () => {
+ const { plan, skipped } = planTopUps(0.001508, [
+ { name: 'relayer+treasury', pubkey: 'W', currentSol: 0.016894, refillToSol: 1 },
+ { name: 'x402-ring-payer', pubkey: 'X', currentSol: 0.001253, refillToSol: 0.18, settleCritical: true },
+ ]);
+ assert.equal(plan.length, 0);
+ assert.deepEqual(
+ skipped.map((s) => s.reason),
+ ['master_insufficient_spendable', 'master_insufficient_spendable'],
+ );
+});
+
test('neediest first: the most-drained engine is planned before a less-needy one', () => {
const { plan } = planTopUps(1.5, [
{ name: 'small', pubkey: 'S', currentSol: 0.4, refillToSol: 0.5 }, // deficit 0.1
diff --git a/tests/economy-rebalance.test.js b/tests/economy-rebalance.test.js
index f6d53247f..6602cac22 100644
--- a/tests/economy-rebalance.test.js
+++ b/tests/economy-rebalance.test.js
@@ -63,12 +63,43 @@ describe('planRebalance', () => {
const { plan } = planRebalance({
solPriceUsd: SOL,
bounds,
- wallets: [{ name: 'gas', pubkey: 'G', sol: 0.0, usdc: 20, wants: 'sol', floorUsd: 5 }],
+ // 0.01 SOL: under its floor, but still able to fund the wSOL account
+ // the swap output lands in (see the rent guard below).
+ wallets: [{ name: 'gas', pubkey: 'G', sol: 0.01, usdc: 20, wants: 'sol', floorUsd: 5 }],
});
expect(plan[0].dir).toBe('usdc->sol');
expect(plan[0].inUsd).toBe(3); // per-swap cap
});
+ // The ring payer deadlock of 2026-09-04: 1,253,408 lamports, 4.18 USDC it
+ // could not convert, and a usdc->sol leg planned every 30 minutes that died
+ // in simulation creating the wSOL account it could not afford. A plan that
+ // cannot execute is worse than an honest skip, because the reason an
+ // operator reads has to name the SOL that unlocks the USDC.
+ it('skips a USDC → SOL rescue the wallet cannot pay the output rent for', () => {
+ const { plan, skipped } = planRebalance({
+ solPriceUsd: SOL,
+ bounds,
+ wallets: [{ name: 'ring-payer', pubkey: 'X', sol: 0.001253408, usdc: 4.18, wants: 'sol', floorUsd: 5 }],
+ });
+ expect(plan).toHaveLength(0);
+ expect(skipped[0].name).toBe('ring-payer');
+ expect(skipped[0].reason).toBe('below_swap_rent:1253408<1870569');
+ });
+
+ it('plans the rescue anyway when the wallet already holds a wSOL account', () => {
+ // The rent is already paid, so the create is a no-op and only fees remain.
+ const { plan } = planRebalance({
+ solPriceUsd: SOL,
+ bounds,
+ wallets: [
+ { name: 'ring-payer', pubkey: 'X', sol: 0.001253408, usdc: 4.18, wants: 'sol', floorUsd: 5, hasWsolAccount: true },
+ ],
+ });
+ expect(plan).toHaveLength(1);
+ expect(plan[0].dir).toBe('usdc->sol');
+ });
+
it('never plans opposing swaps on the same wallet in one run', () => {
// The 2026-07-28 churn: the ring payer sat below BOTH floors, so the cron
// submitted a wants:'usdc' row and a wants:'sol' row for the same pubkey.