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.

Aggregate split-sweep totals in SQL; drop em-dashes from new text

nirholasd70a32fda684
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 598429aa0..e1797323f 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -2721,7 +2721,7 @@ const SELF_ENDPOINTS = [
pipeline: 'volume',
enabled: true,
// Reserved-slot maintenance: recirculation must never compete with (and
- // lose to) paid entries for tick slots — see the loop's selection step.
+ // lose to) paid entries for tick slots; see the loop's selection step.
maintenance: true,
run: (ctx) => ringRebalance(ctx),
},
diff --git a/api/_lib/x402/pipelines/ring-rebalance.js b/api/_lib/x402/pipelines/ring-rebalance.js
index f75c40ff5..88543b236 100644
--- a/api/_lib/x402/pipelines/ring-rebalance.js
+++ b/api/_lib/x402/pipelines/ring-rebalance.js
@@ -53,7 +53,7 @@ const TREASURY_BUFFER_ATOMIC = BigInt(process.env.X402_RING_TREASURY_BUFFER_ATOM
const MIN_SWEEP_ATOMIC = BigInt(process.env.X402_RING_MIN_SWEEP_ATOMIC || 100_000);
// Revenue share routed to the economy master on every sweep, in basis points.
// The master's fuel module (economy-fuel.js) was built on the assumption that
-// "the master accumulates USDC revenue (x402, marketplace)" — but nothing ever
+// "the master accumulates USDC revenue (x402, marketplace)", but nothing ever
// delivered that revenue, so the funding root could never refuel SOL and every
// engine below it starved. This cut closes the loop: treasury → master USDC →
// fuel swap → SOL → treasury-topup → circulation/sponsor floors. Still wallet-
diff --git a/api/_lib/x402/ring-reconciliation.js b/api/_lib/x402/ring-reconciliation.js
index bcacc4238..c4d337e32 100644
--- a/api/_lib/x402/ring-reconciliation.js
+++ b/api/_lib/x402/ring-reconciliation.js
@@ -204,6 +204,30 @@ async function loadSweepRows(db) {
}
}
+// Per-tx totals across ALL legs of every sweep signature, aggregated in SQL so
+// the MAX_SWEEP_ROWS page can never truncate one leg of a split sweep (payer +
+// revshare share a tx_sig) and hand verifySweepMovement a partial sum, which
+// would raise a false-positive critical mismatch. No LIMIT: the aggregate runs
+// over the same lookback window and both legs of a tx always share one ts.
+async function loadSweepTxTotals(db) {
+ const totals = new Map();
+ try {
+ const rows = await db`
+ SELECT tx_sig, SUM(amount_atomic)::bigint AS total
+ FROM x402_ring_ledger
+ WHERE kind IN ('sweep', 'revshare') AND tx_sig IS NOT NULL
+ AND ts > now() - (${LOOKBACK_HOURS} || ' hours')::interval
+ GROUP BY tx_sig
+ `;
+ for (const r of rows) totals.set(r.tx_sig, BigInt(r.total ?? 0));
+ } catch (err) {
+ if (!err?.message?.includes('does not exist')) {
+ log.warn('ring_reconcile_sweep_totals_failed', { message: err?.message });
+ }
+ }
+ return totals;
+}
+
// Buyer-side rows for cross-log coherence: every successful autonomous payment
// with a signature (any endpoint — a settle matched by ANY buyer row is
// coherent), plus the endpoint so ring-settle buyer rows can be isolated for the
@@ -286,7 +310,7 @@ export function verifySettleAmount(row, parsedTx) {
// and that the source is the configured treasury (treasury→payer and
// treasury→master revshare are the only legal directions). A single sweep tx
// may carry MULTIPLE ledger legs (payer sweep + master revshare), so the
-// treasury's total on-chain delta is checked against `txTotalAtomic` — the sum
+// treasury's total on-chain delta is checked against `txTotalAtomic`: the sum
// of every ledger row sharing this tx_sig (defaults to the row's own amount for
// the single-leg case). The recipient check stays per-row. Pure; exported for
// tests.
@@ -437,11 +461,8 @@ export async function run(ctx = {}) {
const treasuryAddress = env.X402_PAY_TO_SOLANA || process.env.X402_PAY_TO_SOLANA || null;
// A split sweep (payer leg + master revshare leg) shares one tx_sig; the
// treasury's on-chain delta must match the SUM of its legs, not each row.
- const sweepTxTotals = new Map();
- for (const row of sweeps) {
- if (!row.tx_sig) continue;
- sweepTxTotals.set(row.tx_sig, (sweepTxTotals.get(row.tx_sig) ?? 0n) + BigInt(row.amount_atomic ?? 0));
- }
+ // SQL-aggregated so a page-truncated leg can never yield a partial sum.
+ const sweepTxTotals = await loadSweepTxTotals(db);
for (const row of sweeps) {
const ref = String(row.id);
if (!row.tx_sig) {
diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.js
index 9f6f827fe..22510d564 100644
--- a/api/cron/x402-autonomous-loop.js
+++ b/api/cron/x402-autonomous-loop.js
@@ -317,7 +317,7 @@ export default wrapCron(async (req, res) => {
// Maintenance entries (recirculation: treasury→payer sweep, agent float
// top-up, pool funding) get RESERVED slots outside MAX_PER_TICK. They move
// zero net spend, are cooldown-gated at 120s, and are the only thing keeping
- // the payer float alive — when they competed on priority alone, a wave of
+ // the payer float alive. When they competed on priority alone, a wave of
// failing high-priority paid entries starved them for days and the whole
// ring drained (July 2026 flat-line).
const readyAll = readyChecks.filter((e) => e.ready).map((e) => e.entry);
@@ -494,7 +494,7 @@ export default wrapCron(async (req, res) => {
if (!accept) {
errorMsg = 'no_solana_accept';
results.push({ id: entry.id, status: 'skip', reason: errorMsg });
- await setCooldown(redis, entry); // endpoint misconfigured — don't re-probe every tick
+ await setCooldown(redis, entry); // endpoint misconfigured; don't re-probe every tick
continue;
}
if (!USDC_MINT || accept.asset !== USDC_MINT) {
diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.md
index a3b7cf017..f60a72daa 100644
--- a/docs/x402-ring-economy.md
+++ b/docs/x402-ring-economy.md
@@ -424,7 +424,7 @@ Every treasury sweep routes a bounded cut (`X402_RING_MASTER_REVSHARE_BPS`,
default 20%) to the **economy master wallet** instead of the payer. That cut is
the funding root's only USDC inflow: `economy-fuel.js` converts it to SOL (a
self-swap, per-run and per-day capped) and `treasury-topup` distributes that SOL
-to every engine below its floor — the circulation treasury that drives the
+to every engine below its floor: the circulation treasury that drives the
Money Pulse (tips, trades, agent-to-agent payments), the ring sponsor whose SOL
floor gates settlement, and the rest of `SOLANA_SIGNERS`. Without this leg the
master starves, the sponsor slips under its floor, settles 502, and the pulse
@@ -436,11 +436,11 @@ against the *sum* of the legs, each recipient against its own row.
Two scheduling guarantees keep the recirculation alive regardless of what else
the autonomous loop is doing:
-1. **Reserved maintenance slots** — registry entries tagged `maintenance: true`
+1. **Reserved maintenance slots**: registry entries tagged `maintenance: true`
(ring-rebalance, ring-float-topup, ring-pool-fund) are selected *outside*
`X402_AUTONOMOUS_MAX_PER_TICK`, so a wave of failing high-priority paid
entries can never starve them out of the rotation.
-2. **Cooldown on failure** — a paid entry that errors now backs off for its full
+2. **Cooldown on failure**: a paid entry that errors now backs off for its full
cooldown exactly like a success. Before this, a failing entry retried every
tick forever, pinning all tick slots and generating thousands of junk
settle-502 rows per day.
diff --git a/tests/x402-ring-reconciliation.test.js b/tests/x402-ring-reconciliation.test.js
index 7d44cc995..89a61466f 100644
--- a/tests/x402-ring-reconciliation.test.js
+++ b/tests/x402-ring-reconciliation.test.js
@@ -27,6 +27,15 @@ function mockSql({ settle = [], sweep = [], buyer = [], feeLogged = 0, feeAudit
const text = strings.join('?').replace(/\s+/g, ' ').trim();
calls.push({ text, values });
if (/FROM x402_self_facilitator_log[\s\S]*action = 'settle'[\s\S]*ORDER BY ts/i.test(text)) return Promise.resolve(settle);
+ if (/FROM x402_ring_ledger[\s\S]*GROUP BY tx_sig/i.test(text)) {
+ // The per-tx totals aggregate: derive from the same sweep fixtures.
+ const totals = new Map();
+ for (const r of sweep) {
+ if (!r.tx_sig) continue;
+ totals.set(r.tx_sig, (totals.get(r.tx_sig) || 0) + Number(r.amount_atomic || 0));
+ }
+ return Promise.resolve([...totals].map(([tx_sig, total]) => ({ tx_sig, total })));
+ }
if (/FROM x402_ring_ledger/i.test(text)) return Promise.resolve(sweep);
if (/FROM x402_autonomous_log[\s\S]*success = true/i.test(text)) return Promise.resolve(buyer);
if (/COALESCE\(sum\(fee_lamports\)/i.test(text)) return Promise.resolve([{ total: feeLogged }]);
@@ -145,7 +154,7 @@ describe('ring-reconciliation — pure helpers', () => {
it('verifySweepMovement verifies each leg of a split sweep (payer + master revshare) via txTotal', () => {
const MASTER = 'MasterWallet1111111111111111111111111111111';
- // One tx: treasury sends 1.0 USDC total — 0.8 to payer, 0.2 to master.
+ // One tx: treasury sends 1.0 USDC total (0.8 to payer, 0.2 to master).
const tx = {
meta: {
preTokenBalances: [