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
feat: implement mayhem-mode coin restrictions for agents
nrpo3b23572217a1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff6b2268a..1af889237 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-03- **Agents in the ring — platform agents now buy and sell services from each other** — The closed-loop x402 economy is no longer a scheduler paying itself: real platform agents with their own custodial wallets now do the buying. An endpoint-shopper hunts intel and health checks, an Agora citizen tips dancers and pays club cover after finishing work, and a curator buys marketplace listings and billboard slots — each purchase signed by the agent's own key, checked against its personal spend limits, logged to its custody trail, and attributed by agent in the activity feed. The treasury keeps every agent's small USDC float topped up between a floor and a ceiling and sweeps back the overflow, so the money still never leaves platform-controlled wallets. On a slower cadence the agents also touch the chain itself, emitting real on-chain agent-invocation events — visible, verifiable activity, not simulated volume. (`/docs/x402-ring-economy`) `[feature]`+- **Agents no longer buy pump.fun mayhem-mode coins** — Autonomous agent strategies and discretionary agent trades now refuse to buy pump.fun mayhem-mode coins — the high-volatility variant — and trade only regular coins. The check reads the mayhem flag straight off the on-chain bonding curve before any spend, so it can't be spoofed, and it's buy-only: an agent that already holds a mayhem coin can always sell to exit. Blocked buys show up as a clean skip in the activity feed, not an error. `[improvement]`- **Every paid endpoint now settles — full x402 catalog coverage** — The x402 ring economy now exercises every paid endpoint on the platform, not just a handful. A single canonical catalog covers all 46 paid endpoints — tips, services, market intel, health checks and settlements — each with the exact request it needs to actually go through, read straight from the endpoint that handles it. The autonomous rotation is wired to this catalog and weighted so every safe-to-buy endpoint is paid at least once an hour, with the ones that shouldn't be bought on a loop (real coin mints, AI calls, third-party payouts) held out and verified separately. Several endpoints that would have silently rejected or mis-charged a real payment were fixed at the root: three were reading the request the wrong way and failing every paid call, and the old rotation was calling tip and cosmetic endpoints with the wrong method entirely. The result is continuous, provable coverage — a new paid endpoint now fails the test suite until it's in the catalog. `[feature, improvement]`- **Every ring settlement is now proven on-chain — reconciliation blind spot closed** — The closed-loop agent economy settles real USDC through the platform's own facilitator, and until now those settlements were trusted but never verified against the blockchain. A new reconciler runs every 30 minutes and holds the ring to the same standard the funding wallet already meets: every recorded settlement and every treasury→payer sweep from the last 72 hours is checked to exist and succeed on-chain, a sample of each is parsed to prove the exact dollar amount and recipient match the books, and the two internal ledgers are cross-checked so a settlement with no matching spend record — the tell-tale sign of value leaking through our own facilitator — is caught. It also runs a silence alarm: if the ring is switched on but goes quiet for 30 minutes, operators are paged, closing the gap where 'it was working, then it wasn't' used to pass unnoticed. Any missing, failed, or mismatched settlement raises an immediate alert; every finding lands on the finance-integrity board, tagged so ring issues stand apart from the rest. `[security, infra]`- **Full audit trail + breach monitoring on the economy's funding wallet** — The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review. `[security, infra, docs]`diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.jsindex 5776a5ea6..cd228927e 100644--- a/api/_lib/agent-strategy-runtime.js+++ b/api/_lib/agent-strategy-runtime.js@@ -58,6 +58,7 @@ export const STRATEGY_SKIP_LABELS = Object.freeze({firewall_blocked: 'blocked by the rug/honeypot firewall',insufficient_sol: 'not enough SOL for size + fees',no_market: 'no tradeable market for this mint',+ mayhem: 'pump.fun mayhem-mode coin — agents only buy regular coins',wsol: 'wrapped SOL is not a tradeable target',max_concurrent: 'at the strategy’s max concurrent positions',cooldown: 'within the strategy’s cooldown window',@@ -125,6 +126,9 @@ export async function runStrategyTrade({quote = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });} catch (e) {if (e?.code === 'pool_not_found') return { status: 'skipped', code: 'no_market' };+ // Mayhem-mode coins are refused by policy, not a pricing failure — record+ // it as a clean skip so the feed reads "skipped: mayhem", not an error.+ if (e?.code === 'mayhem_blocked') return { status: 'skipped', code: 'mayhem' };return { status: 'failed', code: e?.code || 'quote_failed', message: (e?.message || '').slice(0, 200) };}diff --git a/api/_lib/solana/sdk-bridge.js b/api/_lib/solana/sdk-bridge.jsindex 0461227bd..e24674fae 100644--- a/api/_lib/solana/sdk-bridge.js+++ b/api/_lib/solana/sdk-bridge.js@@ -108,7 +108,10 @@ export async function getBuyQuote(connection, mint, solAmount) {const { global, feeConfig, bondingCurve, mintSupply } = await fetchState(connection, pk);const tokens = getBuyTokenAmountFromSolAmount({ global, feeConfig, mintSupply, bondingCurve, amount });const impact = calculateBuyPriceImpact({ global, feeConfig, mintSupply, bondingCurve, solAmount: amount });- return { tokens, priceImpact: impact.impactBps / 100 };+ // Surface the curve's mayhem flag so the buy path can refuse mayhem-mode+ // coins (platform rule: agents only buy regular pump.fun coins, never the+ // high-volatility mayhem variant). Read from chain, never assumed.+ return { tokens, priceImpact: impact.impactBps / 100, isMayhemMode: Boolean(bondingCurve.isMayhemMode) };} catch (err) {// A graduated coin (no curve) is an expected state — the trade handler// re-prices off the AMM pool. Don't log it as a failure.diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.jsindex 69b0404e9..20677918d 100644--- a/api/agents/solana-trade.js+++ b/api/agents/solana-trade.js@@ -116,6 +116,11 @@ export async function quoteTrade({ conn, side, mintPk, mintStr, network, solAmou// Bonding curve first.const curve = await getBuyQuote(conn, mintStr, lamportsIn.toString());if (curve && curve.tokens) {+ // Platform rule: agents never buy pump.fun mayhem-mode coins — only+ // regular coins. The mayhem flag is read straight off the bonding curve+ // (ungameable), so a mayhem coin is refused before any spend. Sells are+ // unaffected, so an agent already holding one can always exit.+ if (curve.isMayhemMode) throw typed(422, 'mayhem_blocked', 'this is a pump.fun mayhem-mode coin — agents only buy regular coins');const decimals = await resolveMintDecimals(conn, mintPk);const tokensOut = BigInt(curve.tokens.toString());if (tokensOut <= 0n) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');diff --git a/data/changelog.json b/data/changelog.jsonindex e83b87194..3c17e0f94 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$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-03",+ "title": "Agents no longer buy pump.fun mayhem-mode coins",+ "summary": "Autonomous agent strategies and discretionary agent trades now refuse to buy pump.fun mayhem-mode coins — the high-volatility variant — and trade only regular coins. The check reads the mayhem flag straight off the on-chain bonding curve before any spend, so it can't be spoofed, and it's buy-only: an agent that already holds a mayhem coin can always sell to exit. Blocked buys show up as a clean skip in the activity feed, not an error.",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-07-03","title": "Live Trading Theater stages rigged avatars only",diff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.mdnew file mode 100644index 000000000..66d793756--- /dev/null+++ b/docs/ops/production-log-triage.md@@ -0,0 +1,155 @@+# Production log triage++Every recurring `error`/`warning` signature that shows up in a Vercel log+export, mapped to its **root cause**, the **exact resolution**, and **who** can+apply it. Built from the `three-ws-character-studio` export on 2026-07-03.++The headline finding, so nobody re-derives it: **none of these are code+defects.** Each line is the platform's own graceful-degradation or fail-closed+machinery working correctly — a fallback firing, a circuit breaker holding, a+guard refusing to spend. They are all resolved by an **environment / billing /+activation** action in the Vercel or upstream dashboards, not by a code change.+Silencing any of them in code would hide a real production signal, so don't.++Severity legend: 🔴 owner decision (money / security / billing) · 🟡 set an env+var or add quota · 🟢 self-healing, no action needed.++---++## 🔴 `[ring-invariants] SPEND PATH DISABLED in x402-autonomous-loop`++```+guard env violated:+• X402_CHARITY_AUDIT_BPS = <unset> (expected 0)+• X402_FACILITATOR_URL_SOLANA / X402_SELF_FACILITATOR_ENABLED = enabled=false url=…payai… (expected self)+```++- **Source:** [api/_lib/x402/ring-allowlist.js](../../api/_lib/x402/ring-allowlist.js) `assertRingSpendInvariants`, called each tick by [api/cron/x402-autonomous-loop.js](../../api/cron/x402-autonomous-loop.js).+- **What it means:** the autonomous spend loop is *enabled* but the closed-loop+ guard env is only **half-configured** — `X402_EXTERNAL_ENABLED=false` is set+ (good), but `X402_CHARITY_AUDIT_BPS` is unset and the Solana facilitator still+ points at an external host. The loop **fails CLOSED**: no money moves. It logs+ `error` and fires one throttled critical alert per hour because a partially-off+ guard on a money path is exactly what you want screamed at you.+- **This is not a false alarm** — it accurately reports an unfinished ring+ activation. Resolve it by finishing **or** pausing, not by muting.++**Resolve — pick one (owner):**++1. **Pause cleanly until you're ready to arm the ring** (recommended if you are+ not actively activating): set `X402_AUTONOMOUS_ENABLED=false`. The loop then+ returns `skipped` with **no error and no alert** (guard check never runs).+2. **Finish arming the ring** (moves real USDC — deliberate go-live): set the+ documented safe values from [.env.example](../../.env.example) §x402-ring —+ `X402_CHARITY_AUDIT_BPS=0`, `X402_SELF_FACILITATOR_ENABLED=true`, and either+ unset `X402_FACILITATOR_URL_SOLANA` or point it at+ `https://three.ws/api/x402-facilitator`. Acceptance steps live in+ [tasks/x402-ring/11-activation-acceptance.md](../../tasks/x402-ring/11-activation-acceptance.md).++---++## 🔴 `[world-health] world is UNPROTECTED — ADMIN_CODE is not set`++- **Source:** [api/cron/world-health.js](../../api/cron/world-health.js).+- **What it means:** the `world.three.ws` Cloud Run service is serving without+ `ADMIN_CODE`, so every visitor has build rights. Logged as `warning`.+- **Resolve (owner):** set `ADMIN_CODE` on the world service and re-run+ `deploy/world/apply-hardening.sh`. It's a security credential the owner must+ choose and store — not something to auto-generate here.++---++## 🔴 `[text-to-image] replicate billing/credit failure: insufficient credit`++- **Source:** the forge text→image lane.+- **What it means:** the Replicate account is out of credit. The forge already+ **degrades to the free NVIDIA NIM lane** (see the `[forge] paid … lane+ unavailable; degrading to free NVIDIA NIM` line), so image generation keeps+ working at lower fidelity.+- **Resolve (owner):** add credit at `replicate.com/account/billing`. No code+ change — the fallback is already correct.++---++## 🟡 `[x402-audit] insert failed … db query exceeded 3000ms deadline`++- **Source:** [api/_lib/x402/audit-log.js](../../api/_lib/x402/audit-log.js) `logPaymentEvent`.+- **What it means:** the Neon DB is saturated, so best-effort audit writes on the+ hot `/api/x402/dance-tip` route time out at their 3 s fast-fail budget. This is+ **fire-and-forget** — the payment was already decided and the response already+ sent (the accompanying `402` is the normal x402 challenge, not a failure). The+ write is retried, fast-failed, and the log is throttled to one line/minute with+ a suppressed-count digest by design.+- **Resolve (owner, capacity):** the fix is DB headroom, not code — scale the+ Neon compute or add a pooler so single-row inserts settle well under 3 s. For a+ deploy that wants more durability headroom on the write itself, raise+ `X402_AUDIT_WRITE_TIMEOUT_MS` (500–15000, default 3000). Losing these rows loses+ only telemetry, never a payment.++---++## 🟢 `[cache] redis SET failed / degraded / circuit opened … memory fallback`++- **Source:** [api/_lib/cache.js](../../api/_lib/cache.js).+- **What it means:** Upstash REST SETs are timing out (a store in a region far+ from the function region is the usual cause). The cache adapter already: fails+ fast at `CACHE_REDIS_CMD_TIMEOUT_MS`, opens a **circuit breaker** after 5+ consecutive failures, adds a **SET-suppression gate** so degraded writes skip+ Redis entirely, and **throttles** every warning to one line/minute. Reads keep+ being served; nothing is on the request critical path.+- **Resolve:** 🟢 nothing required — it self-heals when Upstash recovers (you'll+ see `redis SET recovered`). 🟡 optional: move the cache to a same-region store,+ or provision a dedicated `UPSTASH_CACHE_REST_URL/TOKEN` so best-effort cache+ writes don't contend with the fail-closed rate limiter, or bump+ `CACHE_REDIS_CMD_TIMEOUT_MS` for a distant store.++---++## 🟢 `[three-holders-snapshot] refresh deferred (transient upstream): Solana error #8100002`++- **Source:** [api/cron/three-holders-snapshot.js](../../api/cron/three-holders-snapshot.js).+- **What it means:** Helius DAS returned a 429 (rate limit). The cron classifies+ it as **transient** (via `isRpcRateLimited` on the structured status code),+ logs a `warning` not an `error`, leaves the prior good snapshot intact, and+ self-heals on the next 5-minute tick. Public reads are unaffected.+- **Resolve:** 🟢 nothing required. 🟡 if it's frequent, raise the Helius plan/quota.++---++## 🟢 `[balances] helius quota/rate-limited — skipping it … using public RPC`++- **Source:** [api/_lib/balances.js](../../api/_lib/balances.js) (and the token-market path).+- **What it means:** Helius hit `max usage reached`; the code backs off Helius for+ a few minutes and serves from the **public Solana RPC** in the meantime.+- **Resolve:** 🟢 nothing required — the public-RPC fallback is working. 🟡 raise+ the Helius quota to avoid the degraded window.++---++## 🟢 `[forge] paid TRELLIS lane unavailable (N); degrading text→3D to free NVIDIA NIM` / `nim flux failed, falling back: nim flux timed out`++- **Source:** the forge generation router.+- **What it means:** the paid TRELLIS lane returned a 402/timeout, so forge fell+ back to the free NVIDIA NIM lane, and when a specific NIM model timed out it+ fell back again. Layered fallbacks — generation keeps succeeding.+- **Resolve:** 🟢 nothing required. Tied to the same Replicate billing item above+ if you want the paid high-fidelity lane back.++---++## The 5-minute owner checklist++Everything red/yellow above, condensed to the actions only the owner can take:++1. **Ring:** set `X402_AUTONOMOUS_ENABLED=false` to pause quietly, **or** finish+ the guard env per [tasks/x402-ring/11-activation-acceptance.md](../../tasks/x402-ring/11-activation-acceptance.md) to go live.+2. **World:** set `ADMIN_CODE` on the world service + re-run `apply-hardening.sh`.+3. **Replicate:** add billing credit (restores the paid forge lanes).+4. **Neon:** add compute/pooler headroom so audit writes stop timing out.+5. **Upstash / Helius (optional):** same-region cache store; higher Helius quota.++Nothing on this list is a code change. The code paths behind every line are+already hardened and covered by tests+([tests/x402-ring-invariants.test.js](../../tests/x402-ring-invariants.test.js),+[tests/cache-circuit-breaker.test.js](../../tests/cache-circuit-breaker.test.js),+[tests/cache-store-routing.test.js](../../tests/cache-store-routing.test.js)).diff --git a/package.json b/package.jsonindex 684c73cbb..d6ded23df 100644--- a/package.json+++ b/package.json@@ -118,6 +118,7 @@"verify:solana": "node scripts/verify-solana-parity.mjs","verify:onchain": "node scripts/verify-onchain-parity.mjs","verify:x402": "node scripts/build-x402-catalog.mjs --out=/tmp/x402-catalog.json && node scripts/verify-x402-discovery.mjs --file=/tmp/x402-catalog.json",+ "smoke:x402-facilitator": "node scripts/x402-facilitator-smoke-test.mjs","smoke:onchain": "node scripts/onchain-smoke.mjs","smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity","smoke:agent-wallet": "node scripts/agent-wallet-smoke.mjs",diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.jsonindex b411213b4..c4d97fc96 100644--- a/packages/agent-sniper/package.json+++ b/packages/agent-sniper/package.json@@ -59,6 +59,7 @@},"dependencies": {"@modelcontextprotocol/sdk": "^1.29.0",+ "@nirholas/pump-sdk": "^1.30.0","@pump-fun/pump-sdk": "^1.36.0","@pump-fun/pump-swap-sdk": "^1.17.0","@solana/spl-token": "^0.4.14",diff --git a/packages/agent-sniper/runbooks/00-overview.md b/packages/agent-sniper/runbooks/00-overview.mdindex 5710fbb66..0c3f55d74 100644--- a/packages/agent-sniper/runbooks/00-overview.md+++ b/packages/agent-sniper/runbooks/00-overview.md@@ -46,6 +46,33 @@ sudo npx playwright install-deps chromium # or apt the libs below# libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2t64 libnss3 libnspr4 libdrm2 libxshmfence1```+## Live tracking — Telegram feed (recommended)++The fleet posts a message on **every buy and sell** (agent, archetype, symbol, size,+PnL, Solscan tx link) plus a **portfolio summary every 15 min**, to a Telegram chat or+channel. Push-based, on your phone, and a public channel is instantly shareable.++Setup:+1. Create a bot with [@BotFather](https://t.me/BotFather) → get the **bot token**.+2. Create a channel (e.g. "three.ws sniper fleet"), add the bot as an **admin**.+3. Use the channel's `@handle` (public channels) or numeric id (`-100…`) as the chat id.+4. Run the fleet with the tracker on:+ ```bash+ TELEGRAM_BOT_TOKEN=<token> TELEGRAM_CHAT_ID=@yourchannel \+ node scripts/fleet.js run --rpc "$RPC" --mode live --serve --yes+ ```+ (or pass `--telegram-token` / `--telegram-chat`). Tracker code: `scripts/telegram.js`.++Other ways to watch (complementary, not either/or):+- **Local console** — `--serve` already exposes a live dashboard (positions, PnL, activity)+ at `http://localhost:8787/`. Great to watch or record; localhost unless you tunnel it.+- **Public web page** — deploy that same console (`packages/agent-sniper` `serve` face) to+ Vercel/Cloud Run for a shareable URL. Heavier; do it if you want a public site.+- **three.ws pages** — the fleet only shows *natively* on `/theater` `/play/arena` via+ Cut 02 (platform agents). Otherwise those pages are platform-wide, not this fleet.+- **On-chain** — every wallet is trackable directly on Solscan; `fleet.js balance` prints+ all 33 + the funder any time.+## Cleanup (all cuts) — recover leftover SOL```bashdiff --git a/packages/agent-sniper/scripts/fleet.js b/packages/agent-sniper/scripts/fleet.jsindex 85dbdde77..dd9386b3c 100644--- a/packages/agent-sniper/scripts/fleet.js+++ b/packages/agent-sniper/scripts/fleet.js@@ -250,11 +250,36 @@ async function cmdRun(flags) {const perTrade = Number(flags['per-trade'] || DEFAULTS.perTradeSol);const daily = Number(flags['daily'] || DEFAULTS.dailyBudgetSol);- const strategies = strategiesForFleet(keys, perTrade, daily).map(({ _archetype, ...s }) => s);+ const armed = strategiesForFleet(keys, perTrade, daily);+ const archetypeByAgent = Object.fromEntries(armed.map((s) => [s.agent_id, s._archetype]));+ const strategies = armed.map(({ _archetype, ...s }) => s);const secrets = Object.fromEntries(keys.agents.map((a) => [a.id, a.secret]));+ // Live Telegram tracker: a message per buy/sell + a periodic portfolio summary.+ // Enabled by --telegram or by TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID being present.+ const { createTelegramTracker } = await import('./telegram.js');+ const tg = createTelegramTracker({+ token: flags['telegram-token'] || process.env.TELEGRAM_BOT_TOKEN,+ chatId: flags['telegram-chat'] || process.env.TELEGRAM_CHAT_ID,+ network: keys.network,+ archetypeByAgent,+ });+ // Rule: no pump.fun Mayhem tokens — only normal launches. Reads each mint's+ // bonding curve (cached, shared across agents) and skips isMayhemMode tokens.+ // On by default; --allow-mayhem disables it.+ const { createMayhemFilter } = await import('./mayhem-filter.js');+ const mayhem = flags['allow-mayhem'] ? null+ : createMayhemFilter({ rpcUrl, strictOnUnknown: Boolean(flags['mayhem-strict']) });++ const hooks = {+ ...(tg.enabled ? tg.hooks : {}),+ ...(mayhem ? { oracleGate: mayhem.oracleGate } : {}),+ };+console.log(`\n Starting sniper — ${keys.agents.length} agents · ${mode.toUpperCase()} · ${keys.network} · ${perTrade} SOL/trade`);- console.log(` RPC: ${rpcUrl ? rpcUrl.replace(/api-key=[^&]+/i, 'api-key=***') : 'default'}\n`);+ console.log(` RPC: ${rpcUrl ? rpcUrl.replace(/api-key=[^&]+/i, 'api-key=***') : 'default'}`);+ console.log(` Telegram tracker: ${tg.enabled ? 'ON' : 'off (set TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID)'}`);+ console.log(` Mayhem filter: ${mayhem ? (flags['mayhem-strict'] ? 'ON (strict — skip on unknown)' : 'ON (skip Mayhem tokens)') : 'OFF (--allow-mayhem)'}\n`);// --serve mounts the package's own HTTP API + web console over THIS fleet's// live sniper/store, so packages/agent-sniper/web/console.html (and the@@ -271,26 +296,36 @@ async function cmdRun(flags) {solana,executor: createWeb3Executor(),feed: createPumpPortalFeed({ network: keys.network }),+ hooks,});const { serve } = await import('../src/faces/api.js');await serve({ sniper, store, adminToken: process.env.SNIPER_ADMIN_TOKEN }, { port });sniper.__started = true; // serve() already called start()console.log(` Console + API on http://localhost:${port}/ (film this)\n`);+ if (tg.enabled) tg.startSummary(sniper, store);} else {- sniper = await presets.local({ network: keys.network, mode, rpcUrl, strategies, secrets });+ sniper = await presets.local({ network: keys.network, mode, rpcUrl, strategies, secrets, hooks });await sniper.start();+ if (tg.enabled) tg.startSummary(sniper, sniper.store || { listPositions: null });}+ if (tg.enabled) await tg.announce(`🚀 <b>Fleet armed</b> · ${keys.agents.length} agents · ${mode} · ${keys.network} · ${perTrade} SOL/trade`);const tick = setInterval(() => {const s = sniper.stats();- console.log(` [${new Date().toISOString().slice(11, 19)}] events=${s.events} candidates=${s.candidates} buys=${s.buys} sells=${s.sells} errors=${s.errors} queued=${s.queued}`);+ const m = mayhem ? (() => { const c = mayhem.stats(); return ` mayhem_skipped=${c.mayhem} mayhem_unknown=${c.unknown}`; })() : '';+ console.log(` [${new Date().toISOString().slice(11, 19)}] events=${s.events} candidates=${s.candidates} buys=${s.buys} sells=${s.sells} errors=${s.errors} queued=${s.queued}${m}`);}, 15_000);const stop = async () => {clearInterval(tick);console.log('\n Stopping…');try { await sniper.stop?.(); } catch {}- console.log(' Final stats:', JSON.stringify(sniper.stats()));+ const s = sniper.stats();+ if (tg.enabled) {+ tg.stop();+ try { await tg.announce(`🛑 <b>Fleet stopped</b> · Buys ${s.buys} · Sells ${s.sells} · Errors ${s.errors}`); } catch {}+ }+ console.log(' Final stats:', JSON.stringify(s));process.exit(0);};process.on('SIGINT', stop);diff --git a/packages/agent-sniper/scripts/mayhem-filter.js b/packages/agent-sniper/scripts/mayhem-filter.jsnew file mode 100644index 000000000..b1a40516d--- /dev/null+++ b/packages/agent-sniper/scripts/mayhem-filter.js@@ -0,0 +1,90 @@+// mayhem-filter.js — enforce "no pump.fun Mayhem tokens" for the sniper fleet.+//+// pump.fun tokens can launch in "Mayhem mode" (a higher-fee degen mode), flagged+// on the on-chain bonding curve as `isMayhemMode`. The new-mint firehose does NOT+// carry this flag, so we read the bonding curve once per mint (cached, shared+// across all agents) and gate the buy: Mayhem tokens are skipped, only normal+// pump.fun launches are sniped.+//+// Wires into the engine as an `oracleGate` hook:+// (p:{ candidate, ... }) => { pass:false, reason:'mayhem_excluded' } to skip.+//+// Immutable per mint, so one RPC read covers every agent evaluating that mint.++import { Connection, PublicKey } from '@solana/web3.js';++/**+ * @param {object} o+ * @param {string} [o.rpcUrl] RPC endpoint (falls back to public mainnet)+ * @param {boolean} [o.strictOnUnknown=false] if the curve can't be read, skip the buy+ * (honor the rule strictly) instead of allowing it. Default allows-on-unknown so a+ * flaky RPC read doesn't silently halt all trading — unknowns are logged.+ * @returns {{ oracleGate: Function, isMayhem: Function, stats: Function }}+ */+export function createMayhemFilter({ rpcUrl, strictOnUnknown = false } = {}) {+ const conn = new Connection(rpcUrl || 'https://api.mainnet-beta.solana.com', 'confirmed');+ const cache = new Map(); // mint → boolean (true = mayhem)+ const inflight = new Map(); // mint → Promise<boolean|null>+ let sdkPromise = null;+ let warnedNoField = false;+ const counts = { checked: 0, mayhem: 0, unknown: 0 };++ function loadSdk() {+ // @nirholas/pump-sdk is the fork that surfaces `isMayhemMode` on the bonding+ // curve (the platform reads it there); the official @pump-fun/pump-sdk does+ // NOT carry the field, so it can't detect Mayhem. Prefer the fork, fall back+ // to the official only so the import never hard-fails.+ if (!sdkPromise) {+ sdkPromise = import('@nirholas/pump-sdk').catch(() => import('@pump-fun/pump-sdk'));+ }+ return sdkPromise;+ }++ async function readMayhem(mint) {+ try {+ const mod = await loadSdk();+ const Sdk = mod.OnlinePumpSdk || mod.PumpSdk || mod.default?.OnlinePumpSdk;+ if (typeof Sdk !== 'function') throw new Error('OnlinePumpSdk not found in @pump-fun/pump-sdk');+ const sdk = new Sdk(conn);+ const bc = await sdk.fetchBondingCurve(new PublicKey(mint));+ if (bc && typeof bc.isMayhemMode === 'undefined' && !warnedNoField) {+ warnedNoField = true;+ console.log(' [mayhem] WARNING: SDK bonding curve has no isMayhemMode field — filter may be ineffective; verify the SDK version.');+ }+ return Boolean(bc?.isMayhemMode);+ } catch (e) {+ // Missing account (not yet indexed) or transient RPC — treat as unknown.+ return null;+ }+ }++ async function isMayhem(mint) {+ if (!mint) return null;+ if (cache.has(mint)) return cache.get(mint);+ if (inflight.has(mint)) return inflight.get(mint);+ const p = readMayhem(mint).then((v) => {+ inflight.delete(mint);+ if (v !== null) cache.set(mint, v); // only cache definitive answers+ return v;+ });+ inflight.set(mint, p);+ return p;+ }++ async function oracleGate({ candidate }) {+ const mint = candidate?.mint;+ const m = await isMayhem(mint);+ counts.checked++;+ if (m === true) { counts.mayhem++; return { pass: false, reason: 'mayhem_excluded' }; }+ if (m === null) {+ counts.unknown++;+ if (strictOnUnknown) return { pass: false, reason: 'mayhem_unknown' };+ return { pass: true, skipped: true }; // allow-on-unknown (logged via stats)+ }+ return { pass: true };+ }++ return { oracleGate, isMayhem, stats: () => ({ ...counts }) };+}++export default createMayhemFilter;diff --git a/packages/agent-sniper/scripts/telegram.js b/packages/agent-sniper/scripts/telegram.jsnew file mode 100644index 000000000..bfe54581a--- /dev/null+++ b/packages/agent-sniper/scripts/telegram.js@@ -0,0 +1,91 @@+// telegram.js — live trade tracker for the throwaway sniper fleet.+//+// Posts a message on every BUY and SELL (with agent, archetype, symbol, size,+// PnL, and a Solscan tx link) plus a periodic portfolio summary, to a Telegram+// chat or channel. Self-contained — only needs a bot token + chat id; no+// three.ws backend. Wires into the engine via its onBuy/onSell hooks.+//+// Env: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID (or pass token/chatId to the factory).+// Make a channel, add your bot as an admin, and use the channel id (e.g. -100…)+// or a numeric user/group chat id.++const api = (token, method) => `https://api.telegram.org/bot${token}/${method}`;++async function send(token, chatId, text) {+ try {+ const res = await fetch(api(token, 'sendMessage'), {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }),+ });+ if (!res.ok) {+ const b = await res.json().catch(() => ({}));+ console.log(` [tg] ${res.status} ${b.description || ''}`);+ }+ } catch (e) { console.log(' [tg]', e.message.slice(0, 80)); }+}++const short = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');+const txLink = (sig, network) =>+ sig && sig !== 'SIMULATED' ? `https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}` : null;+const num = (v, d = 4) => Number(v || 0).toFixed(d);++/**+ * @param {object} o+ * @param {string} o.token Telegram bot token+ * @param {string|number} o.chatId chat/channel id+ * @param {string} o.network 'mainnet' | 'devnet'+ * @param {Record<string,string>} [o.archetypeByAgent] agentId → archetype label+ * @param {number} [o.summaryMs] portfolio-summary cadence (default 15 min)+ * @returns {{hooks: object, startSummary: Function, stop: Function, announce: Function, enabled: boolean}}+ */+export function createTelegramTracker({ token, chatId, network, archetypeByAgent = {}, summaryMs = 900_000 }) {+ if (!token || !chatId) return { hooks: {}, startSummary() {}, stop() {}, async announce() {}, enabled: false };+ const tag = (id) => (archetypeByAgent[id] ? ` [${archetypeByAgent[id]}]` : '');++ const hooks = {+ onBuy: (p) => {+ const c = p.candidate || {};+ const sym = c.symbol ? `$${c.symbol}` : short(c.mint);+ const tx = txLink(p.sig, network);+ const sim = p.mode === 'simulate' ? ' <i>(sim)</i>' : '';+ send(token, chatId,+ `🟢 <b>BUY</b> · ${p.strategy?.agent_id || ''}${tag(p.strategy?.agent_id)}${sim}\n`+ + `${sym} · ${num(p.solSpent)} SOL\n`+ + `<code>${short(c.mint)}</code>${tx ? ` · <a href="${tx}">tx</a>` : ''}`);+ },+ onSell: (p) => {+ const pos = p.position || {};+ const id = pos.agentId || pos.agent_id || '';+ const sym = pos.symbol ? `$${pos.symbol}` : short(pos.mint);+ const up = Number(p.pnlPct) >= 0;+ const tx = txLink(p.sig, network);+ const sim = p.mode === 'simulate' ? ' <i>(sim)</i>' : '';+ send(token, chatId,+ `${up ? '🟩' : '🟥'} <b>SELL</b> · ${id}${tag(id)}${sim}\n`+ + `${sym} · <b>${up ? '+' : ''}${num(p.pnlPct, 1)}%</b> (${up ? '+' : ''}${num(p.pnlSol)} SOL)\n`+ + `${p.exitReason || ''}${tx ? ` · <a href="${tx}">tx</a>` : ''}`);+ },+ };++ let timer = null;+ function startSummary(sniper, store) {+ const tick = async () => {+ const s = (sniper.stats && sniper.stats()) || {};+ let open = 0;+ try { open = (store.listPositions ? await store.listPositions({ status: 'open' }) : []).length; } catch {}+ send(token, chatId,+ `📊 <b>Fleet</b> · ${s.strategies || 0} agents · ${network}\n`+ + `Open ${open} · Buys ${s.buys || 0} · Sells ${s.sells || 0} · Errors ${s.errors || 0}\n`+ + `Candidates seen: ${s.candidates || 0}`);+ };+ timer = setInterval(tick, summaryMs);+ tick();+ }+ function stop() { if (timer) clearInterval(timer); }+ async function announce(text) { await send(token, chatId, text); }++ return { hooks, startSummary, stop, announce, enabled: true };+}++export default createTelegramTracker;diff --git a/public/changelog.json b/public/changelog.jsonindex 77f8ebd8b..61a4087b3 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-03T07:27:33.557Z",+ "generated_at": "2026-07-03T07:54:38.381Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"feature"]},+ {+ "date": "2026-07-03",+ "type": "update",+ "title": "Agents no longer buy pump.fun mayhem-mode coins",+ "summary": "Autonomous agent strategies and discretionary agent trades now refuse to buy pump.fun mayhem-mode coins — the high-volatility variant — and trade only regular coins. The check reads the mayhem flag straight off the on-chain bonding curve before any spend, so it can't be spoofed, and it's buy-only: an agent that already holds a mayhem coin can always sell to exit. Blocked buys show up as a clean skip in the activity feed, not an error.",+ "link": null,+ "tags": [+ "improvement"+ ]+ },{"date": "2026-07-03","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 4b6f91844..499246bc9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>feature</category><description>The closed-loop x402 economy is no longer a scheduler paying itself: real platform agents with their own custodial wallets now do the buying. An endpoint-shopper hunts intel and health checks, an Agora citizen tips dancers and pays club cover after finishing work, and a curator buys marketplace listings and billboard slots — each purchase signed by the agent's own key, checked against its personal spend limits, logged to its custody trail, and attributed by agent in the activity feed. The treasury keeps every agent's small USDC float topped up between a floor and a ceiling and sweeps back the overflow, so the money still never leaves platform-controlled wallets. On a slower cadence the agents also touch the chain itself, emitting real on-chain agent-invocation events — visible, verifiable activity, not simulated volume.</description></item>+ <item>+ <title>Agents no longer buy pump.fun mayhem-mode coins</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-03:Agents no longer buy pump.fun mayhem-mode coins</guid>+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Autonomous agent strategies and discretionary agent trades now refuse to buy pump.fun mayhem-mode coins — the high-volatility variant — and trade only regular coins. The check reads the mayhem flag straight off the on-chain bonding curve before any spend, so it can't be spoofed, and it's buy-only: an agent that already holds a mayhem coin can always sell to exit. Blocked buys show up as a clean skip in the activity feed, not an error.</description>+ </item><item><title>Every paid endpoint now settles — full x402 catalog coverage</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 48d26dc2a..d7d2572bf 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-03T07:27:33.492Z",+ "generated_at": "2026-07-03T07:54:38.368Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/x402-facilitator-smoke-test.mjs b/scripts/x402-facilitator-smoke-test.mjsnew file mode 100644index 000000000..d0aaf5d49--- /dev/null+++ b/scripts/x402-facilitator-smoke-test.mjs@@ -0,0 +1,111 @@+#!/usr/bin/env node+// scripts/x402-facilitator-smoke-test.mjs+//+// End-to-end smoke test for the self-hosted x402 facilitator. Drives ONE real,+// tiny (cents-scale) USDC settlement through /api/x402/ring-settle against a+// target deployment — normally a Vercel PREVIEW URL with+// X402_SELF_FACILITATOR_ENABLED=true scoped to Preview only, so Production+// stays untouched until this passes.+//+// This is the exact code path the production autonomous ring loop uses+// (api/_lib/x402/pay.js:payX402 → 402 challenge → self-facilitator verify+settle),+// just pointed at --url instead of https://three.ws, with the spend hard-capped+// so a bug can burn at most a few cents.+//+// Requires (same secrets the ring pipelines use — pull from Vercel env,+// NEVER commit them):+// X402_SEED_SOLANA_SECRET_BASE58 ring payer keypair (signs the transfer)+// X402_ASSET_MINT_SOLANA USDC mint (mainnet: EPjF...TDt1v)+// SOLANA_RPC_URL any working mainnet RPC+//+// Usage:+// X402_SEED_SOLANA_SECRET_BASE58=... X402_ASSET_MINT_SOLANA=... SOLANA_RPC_URL=... \+// node scripts/x402-facilitator-smoke-test.mjs --url=https://<preview>.vercel.app --cap=0.05+//+// Exit code: 0 = settled on-chain and verified, 1 = anything else (never+// silently "probably fine" — a skipped/free/failed result is a failed test).++import { payX402, bootstrapSolanaContext, USDC_MINT } from '../api/_lib/x402/pay.js';++const args = process.argv.slice(2);+const opt = (name, def) => {+ const p = args.find((a) => a.startsWith(`--${name}=`));+ return p ? p.slice(name.length + 3) : def;+};++const baseUrl = opt('url', null);+const capUsd = Number(opt('cap', '0.05'));++if (!baseUrl) {+ console.error('Usage: node scripts/x402-facilitator-smoke-test.mjs --url=https://<preview>.vercel.app [--cap=0.05]');+ process.exit(1);+}+if (!USDC_MINT) {+ console.error('X402_ASSET_MINT_SOLANA is not set in this shell — export the same value used on the preview deploy.');+ process.exit(1);+}+if (!Number.isFinite(capUsd) || capUsd <= 0 || capUsd > 1) {+ console.error('--cap must be a small positive USD number (<=1). Refusing to run a smoke test with a large cap.');+ process.exit(1);+}++const capAtomic = Math.round(capUsd * 1_000_000); // USDC = 6dp++async function main() {+ console.log(`\n=== x402 self-facilitator smoke test ===`);+ console.log(`target: ${baseUrl}/api/x402/ring-settle`);+ console.log(`spend cap: $${capUsd.toFixed(2)} (${capAtomic} atomic USDC)\n`);++ // 1) Confirm the target's facilitator discovery route is live and, ideally,+ // resolving to the self-hosted facilitator (not the external default).+ const statusUrl = `${baseUrl}/api/x402-status`;+ try {+ const statusRes = await fetch(statusUrl);+ const status = await statusRes.json().catch(() => null);+ console.log(`x402-status (${statusRes.status}):`, JSON.stringify(status?.facilitators ?? status, null, 2).slice(0, 800));+ } catch (err) {+ console.warn(`Could not reach ${statusUrl}: ${err.message} (continuing — not fatal)`);+ }++ const ringUrl = `${baseUrl}/api/x402-ring`;+ try {+ const ringRes = await fetch(ringUrl);+ const ring = await ringRes.json().catch(() => null);+ console.log(`\nconfig_warnings before test:`, JSON.stringify(ring?.config_warnings ?? [], null, 2));+ } catch (err) {+ console.warn(`Could not reach ${ringUrl}: ${err.message} (continuing — not fatal)`);+ }++ // 2) Build the real signed payment context against mainnet.+ console.log('\nBootstrapping Solana context (loading payer keypair, fetching blockhash + mint info)...');+ const ctx = await bootstrapSolanaContext();+ console.log(`payer pubkey: ${ctx.buyer.publicKey.toBase58()}`);++ // 3) Drive one real settlement through the target's ring-settle endpoint.+ console.log(`\nPaying ${baseUrl}/api/x402/ring-settle (capped at $${capUsd.toFixed(2)})...`);+ const result = await payX402({+ url: `${baseUrl}/api/x402/ring-settle`,+ body: { note: 'facilitator-smoke-test', seq: 1 },+ buyer: ctx.buyer,+ conn: ctx.conn,+ blockhash: ctx.blockhash,+ mintInfo: ctx.mintInfo,+ remainingCap: capAtomic,+ });++ console.log('\n=== result ===');+ console.log(JSON.stringify(result, null, 2));++ if (!result.success || !result.paid || !result.txSig) {+ console.error('\nFAIL — no on-chain settlement occurred. See errorMsg/status/responseBody above.');+ process.exit(1);+ }++ console.log(`\nPASS — settled on-chain: https://solscan.io/tx/${result.txSig}`);+ console.log('Confirm on the target\'s /api/x402-ring that settlements.count/gross_usdc moved, then re-check config_warnings is empty before promoting these env vars to Production.');+}++main().catch((err) => {+ console.error('\nFAIL — smoke test threw:', err);+ process.exit(1);+});diff --git a/tests/solana-trade-guards.test.js b/tests/solana-trade-guards.test.jsindex 4fe23377b..8bf555f4b 100644--- a/tests/solana-trade-guards.test.js+++ b/tests/solana-trade-guards.test.js@@ -64,9 +64,9 @@ vi.mock('../api/_lib/agent-pumpfun.js', () => ({solanaPublicConnection: vi.fn(() => fakeConn()),}));-const quoteState = { buyImpact: 1 };+const quoteState = { buyImpact: 1, isMayhem: false };vi.mock('../api/_lib/solana/sdk-bridge.js', () => ({- getBuyQuote: vi.fn(async () => ({ tokens: '1000000', priceImpact: quoteState.buyImpact })),+ getBuyQuote: vi.fn(async () => ({ tokens: '1000000', priceImpact: quoteState.buyImpact, isMayhemMode: quoteState.isMayhem })),getSellQuote: vi.fn(async () => ({ sol: '50000000', priceImpact: 1 })),}));@@ -110,9 +110,26 @@ beforeEach(() => {authState.session = { id: 'owner-1' };connState.balance = 5_000_000_000;quoteState.buyImpact = 1;+ quoteState.isMayhem = false;setAgent();});+describe('solana-trade — mayhem-mode coins are unbuyable', () => {+ it('422 mayhem_blocked when the bonding curve is mayhem mode (buy)', async () => {+ quoteState.isMayhem = true;+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });+ expect(res.statusCode).toBe(422);+ expect(res.json.error).toBe('mayhem_blocked');+ });++ it('regular coins still price normally (buy)', async () => {+ quoteState.isMayhem = false;+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });+ expect(res.statusCode).toBe(200);+ expect(res.json.data.venue).toBe('bonding_curve');+ });+});+describe('solana-trade — auth & ownership', () => {it('401 for an unauthenticated caller', async () => {authState.session = null;