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: add AgoraRoom for city-scale shared space and integrate into game server
nirholasf14d1de1a29d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e1a3ef01d..e6d3d1147 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Coin intelligence engine now backs off cleanly when the database is full** — The pump.fun intelligence firehose — the engine behind the coin-intel feed, the smart-money leaderboard and the oracle scores — used to keep writing to the database even after it hit its storage cap, failing thousands of times an hour and burning compute on work that could never be saved. It now checks free space before each run and pauses ingestion while the automatic cleanup reclaims room, then resumes on its own. The result: the engine self-heals instead of storming its logs, and the feeds it powers recover cleanly the moment space frees up. `[infra]`- **Every coin world now gets the full town experience** — The flagship town's whole cast and economy now travel to every coin world on /play. Walk into any community and you'll find the full crew of twelve townsfolk selling real paid services — market reads, fact checks, security scans, vanity addresses, 3D mesh forging, coin launches and more, each settled on-chain in USDC — plus the ORACLE and NOVA agent exchange striking live x402 deals in the plaza, and an intel kiosk selling live market data for that world's own coin ($0.01 USDC, paid from your own wallet). The $THREE town keeps its signature frontier look and stays the front door of the metaverse. (`/play`) `[feature]`- **Live agent screens now reach the 3D world, and coin art loads everywhere** — The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall — previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail — and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone. (`/play`) `[fix, improvement]`+- **One funding wallet now keeps every economy engine topped up** — The platform's on-chain engines — the buyback relayer, coin-launch funder, treasury signers, subdomain minter and more — each hold their own small SOL balance to pay network fees. A new funding root now watches all of them and automatically tops up any that dip below their floor, from a single master wallet, every 30 minutes. It only ever sends to the platform's own registered engine wallets, never trades or launches, and is bounded by a reserve floor plus per-engine and per-sweep caps so it can't overspend. Until the master is funded it does nothing and the existing low-balance alerts keep running. `[infra]`- **Oracle 3D graph is visible again** — The Oracle's 3D conviction graph — every scored coin as a sphere you can orbit, with size showing the conviction score and brightness showing the tier — was rendering as a black void: the spheres were lit only by a near-black ambient light and carried no glow of their own, so nothing showed even though the data was loading fine. Each coin now self-illuminates in its tier color and feeds the bloom pass, with real key and rim lighting giving the spheres depth. Prime coins burn brightest, and the whole constellation reads clearly against the dark backdrop. Open it from the Oracle's "3D graph" tab. (`/oracle`) `[fix]`- **Oracle coin pages now show full live market data** — Open any coin in the Oracle and you now get its complete live market picture next to the conviction score — real-time price with 5-minute, 1-hour, 6-hour and 24-hour changes, market cap, fully-diluted value, liquidity, 24-hour volume, holder count and supply. Pre-graduation pump.fun coins show a bonding-curve progress bar; graduated coins show their all-time-high market cap. A security panel flags whether the mint and freeze authorities are revoked, whether metadata is locked, any transfer tax, and top-10 holder concentration. Listed coins add their CoinGecko rank plus all-time high and low, and every coin lists its live DEX markets and social links. It's fused in real time from DexScreener, pump.fun, GeckoTerminal, GoPlus, Birdeye and CoinGecko, with graceful fallback if any single source is down. (`/oracle`) `[feature, improvement]`- **Sign-in: fixed a hidden check that could silently block the Sign in button** — The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone. (`/login`) `[fix]`diff --git a/api/_lib/economy-master.js b/api/_lib/economy-master.jsnew file mode 100644index 000000000..2c05af27b--- /dev/null+++ b/api/_lib/economy-master.js@@ -0,0 +1,171 @@+// @ts-check+// api/_lib/economy-master.js+//+// The economy funding root: ONE master wallet that auto-tops-up every other+// engine signer in the SOLANA_SIGNERS registry when it drops below its floor.+//+// Funder-only by construction — it NEVER trades, launches, or settles. Its only+// on-chain action is a System transfer of SOL to a pubkey that is already in the+// registry (that registry IS the allowlist: sweepTopUps only ever pays targets+// the caller derived from SOLANA_SIGNERS). This is the "masters fund engines,+// engines do the work" model applied platform-wide.+//+// Address (mainnet vanity): wwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW+//+// Inert until ECONOMY_MASTER_SECRET_BASE58 is set: loadEconomyMaster() returns+// null when unconfigured, so shipping this changes nothing until the operator+// funds the address and installs the key. When unset, the treasury-topup cron+// falls back to alert-only (the existing relayer-balance-check behaviour).+//+// Guards — enforced on every sweep; the first two are on-chain reads, so they+// hold even with no database:+// • RESERVE FLOOR — never spend the master below ECONOMY_MASTER_RESERVE_SOL.+// • PER-ENGINE CAP — bring an engine up to its refillTo only, and never move+// more than ECONOMY_MASTER_PER_TOPUP_MAX_SOL to one engine+// in a single sweep.+// • PER-RUN CAP — one sweep spends at most ECONOMY_MASTER_RUN_CAP_SOL total+// across all engines.++import { decodeSecretKey } from './solana-signers.js';+import { getSolBalance, sendSol, LAMPORTS_PER_SOL } from './avatar-wallet.js';++// The intended master. A pasted key whose pubkey does not match this is rejected+// (a mis-paste must never silently drain a different wallet). Override with+// ECONOMY_MASTER_ADDRESS if the master is ever rotated.+export const ECONOMY_MASTER_ADDRESS =+ process.env.ECONOMY_MASTER_ADDRESS || 'wwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';++// Dust threshold: skip a top-up smaller than this to avoid fee churn on engines+// that are only a hair under their target.+const MIN_TOPUP_SOL = 0.005;++function num(envName, dflt) {+ const v = Number(process.env[envName]);+ return Number.isFinite(v) && v >= 0 ? v : dflt;+}++/** Never spend the master below this — its own working reserve + rent + fees. */+export const RESERVE_SOL = num('ECONOMY_MASTER_RESERVE_SOL', 1);+/** Most SOL the master will move to any single engine in one sweep. */+export const PER_TOPUP_MAX_SOL = num('ECONOMY_MASTER_PER_TOPUP_MAX_SOL', 0.5);+/** Most SOL the master will move across all engines in one sweep. */+export const RUN_CAP_SOL = num('ECONOMY_MASTER_RUN_CAP_SOL', 2);++/**+ * Load the funding-root keypair, or null when ECONOMY_MASTER_SECRET_BASE58 is+ * unset. Throws (with a coded error) only on a configured-but-broken secret — a+ * bad key is an outage the operator must see, not a silent skip.+ * @returns {Promise<import('@solana/web3.js').Keypair|null>}+ */+export async function loadEconomyMaster() {+ const secret = process.env.ECONOMY_MASTER_SECRET_BASE58;+ if (!secret) return null;+ const bytes = await decodeSecretKey(secret);+ if (!bytes) {+ throw Object.assign(new Error('ECONOMY_MASTER_SECRET_BASE58 did not decode'), {+ code: 'bad_master',+ });+ }+ const { Keypair } = await import('@solana/web3.js');+ const kp = Keypair.fromSecretKey(bytes);+ if (kp.publicKey.toBase58() !== ECONOMY_MASTER_ADDRESS) {+ throw Object.assign(+ new Error(+ `economy-master key pubkey ${kp.publicKey.toBase58()} != expected ${ECONOMY_MASTER_ADDRESS}`,+ ),+ { code: 'master_mismatch' },+ );+ }+ return kp;+}++/**+ * Compute the guarded per-engine top-ups for a set of underfunded targets,+ * applying the reserve floor, per-engine cap, and per-run cap. Pure — no+ * 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+ * @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 - RESERVE_SOL));+ 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),+ );+ const plan = [];+ const skipped = [];+ let total = 0;+ for (const t of ordered) {+ const deficit = round(t.refillToSol - t.currentSol);+ if (deficit < MIN_TOPUP_SOL) {+ skipped.push({ name: t.name, reason: 'below_dust_threshold' });+ continue;+ }+ const want = Math.min(deficit, PER_TOPUP_MAX_SOL);+ if (total + want > runCap + 1e-9) {+ skipped.push({ name: t.name, reason: 'run_cap_reached' });+ continue;+ }+ plan.push({ name: t.name, pubkey: t.pubkey, sol: want });+ total = round(total + want);+ }+ return { plan, skipped, totalSol: total, spendableSol };+}++/**+ * Execute the guarded auto-refill sweep. Reads the master balance on-chain,+ * plans the top-ups, then transfers each. Returns a structured result for the+ * cron to log. Never throws for a business-rule stop (unconfigured / underfunded+ * master) — those come back as `configured:false` / `reason`.+ *+ * @param {object} args+ * @param {import('@solana/web3.js').Connection} args.connection+ * @param {Array<{name:string,pubkey:string,currentSol:number,refillToSol:number}>} args.targets+ * @param {'mainnet'|'devnet'} [args.network]+ * @returns {Promise<object>}+ */+export async function sweepTopUps({ connection, targets, network = 'mainnet' }) {+ const master = await loadEconomyMaster();+ if (!master) {+ return { configured: false, funded: [], failed: [], skipped: [], spentSol: 0 };+ }+ const { sol: masterSol } = await getSolBalance(connection, master.publicKey);+ const { plan, skipped, spendableSol } = planTopUps(masterSol, targets);++ const funded = [];+ const failed = [];+ for (const step of plan) {+ const lamports = Math.round(step.sol * LAMPORTS_PER_SOL);+ try {+ const signature = await sendSol({+ connection,+ fromKeypair: master,+ to: step.pubkey,+ lamports,+ memo: `three.ws economy-master → ${step.name}`,+ network,+ });+ funded.push({ name: step.name, pubkey: step.pubkey, sol: step.sol, signature });+ } catch (e) {+ failed.push({ name: step.name, pubkey: step.pubkey, sol: step.sol, reason: e?.message || 'send_failed' });+ }+ }+ return {+ configured: true,+ master: master.publicKey.toBase58(),+ masterSol: round(masterSol),+ reserveSol: RESERVE_SOL,+ spendableSol,+ funded,+ failed,+ skipped,+ spentSol: round(funded.reduce((s, f) => s + f.sol, 0)),+ };+}++function round(n) {+ return Math.round(n * 1e9) / 1e9;+}diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsindex d17d4f44f..54b26a9d6 100644--- a/api/_lib/solana-signers.js+++ b/api/_lib/solana-signers.js@@ -21,10 +21,26 @@* @property {number} minSol alert/refill threshold in SOL (mainnet)* @property {string} purpose what this keypair pays for* @property {'mainnet'|'devnet'|'both'} network where it spends real SOL+ * @property {string} [fallbackEnv] secondary env var to try when `env` is unset+ * @property {number} [refillTo] SOL to bring this signer up to when the economy+ * 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)*//** @type {SignerSpec[]} */export const SOLANA_SIGNERS = [+ {+ name: 'economy-master',+ env: 'ECONOMY_MASTER_SECRET_BASE58',+ // The funding root. Keeps a large reserve because it tops up every other+ // engine — see ECONOMY_MASTER_RESERVE_SOL in api/_lib/economy-master.js.+ minSol: 1,+ isMaster: true,+ purpose:+ 'economy funding root (wwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW): auto-tops-up every other engine signer below its floor. Funder-only — never trades, launches, or settles.',+ network: 'mainnet',+ },{name: 'pump-cron-relayer',env: 'PUMP_CRON_RELAYER_SECRET_KEY_B64',diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.jsnew file mode 100644index 000000000..51833eee3--- /dev/null+++ b/api/cron/treasury-topup.js@@ -0,0 +1,128 @@+// @ts-check+// GET /api/cron/treasury-topup — economy funding-root auto-refill.+//+// The companion to relayer-balance-check (which only ALERTS). This cron reads+// every configured engine signer's mainnet SOL balance and, for any that has+// dropped below its `minSol` floor, tops it up from the ONE economy master+// wallet (api/_lib/economy-master.js) — the "masters fund engines, engines do+// the work" model applied platform-wide.+//+// Safe by construction:+// • Inert until ECONOMY_MASTER_SECRET_BASE58 is set — with no master it does+// nothing (relayer-balance-check keeps alerting), so shipping it is a no-op+// until the operator funds wwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW.+// • Only ever pays pubkeys derived from SOLANA_SIGNERS (the registry is the+// allowlist). The master never trades, launches, or settles.+// • Reserve floor + per-engine cap + per-run cap (see economy-master.js) bound+// every sweep; the reserve floor is an on-chain read, so it holds with no DB.+//+// Runs every 30 min — fast enough that no engine dries out between sweeps, cheap+// enough (one getBalance per signer + at most a handful of transfers) to stay+// well inside the RPC/Upstash budgets.+//+// Env (reuses existing infra):+// CRON_SECRET — Vercel cron bearer auth (shared with other crons)+// SOLANA_RPC_URL — mainnet RPC (defaults to api.mainnet-beta)+// ECONOMY_MASTER_SECRET_BASE58 — the funding-root key (unset ⇒ inert)+// ECONOMY_MASTER_RESERVE_SOL / _PER_TOPUP_MAX_SOL / _RUN_CAP_SOL — guard caps++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';+import { sweepTopUps } from '../_lib/economy-master.js';++const LAMPORTS_PER_SOL = 1_000_000_000;+// How high to lift an engine when it falls below its floor, unless the spec+// pins its own refillTo. minSol×3 gives comfortable headroom without overfunding+// a hot wallet we deliberately keep thin.+const DEFAULT_REFILL_MULTIPLE = 3;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+ const { PublicKey } = await import('@solana/web3.js');+ const { solanaConnection } = await import('../_lib/solana/connection.js');+ const connection = solanaConnection({ url: rpcUrl, network: 'mainnet', commitment: 'confirmed' });++ // Read every engine signer's balance; collect the ones under floor as refill+ // targets. The master itself (isMaster) and unconfigured/devnet signers are+ // never targets.+ const targets = [];+ const errors = [];+ for (const spec of SOLANA_SIGNERS) {+ if (spec.isMaster || spec.network === 'devnet') continue;+ const resolved = await resolveSignerPubkey(spec);+ if (!resolved.configured) continue;+ if (resolved.decodeError || !resolved.pubkey) {+ errors.push({ name: spec.name, reason: 'secret_decode_failed' });+ continue;+ }+ let lamports;+ try {+ lamports = await connection.getBalance(new PublicKey(resolved.pubkey), 'confirmed');+ } catch (e) {+ errors.push({ name: spec.name, pubkey: resolved.pubkey, reason: `rpc_error: ${e.message}` });+ continue;+ }+ const sol = lamports / LAMPORTS_PER_SOL;+ if (sol >= spec.minSol) continue;+ targets.push({+ name: spec.name,+ pubkey: resolved.pubkey,+ currentSol: Number(sol.toFixed(6)),+ refillToSol: spec.refillTo ?? spec.minSol * DEFAULT_REFILL_MULTIPLE,+ });+ }++ const result = await sweepTopUps({ connection, targets, network: 'mainnet' });++ // Alert when the master is configured but too drained to cover a real+ // deficit — that is the one condition a human must act on (fund the root).+ if (result.configured && targets.length > 0 && result.spentSol === 0 && result.funded.length === 0) {+ await sendOpsAlert(+ `⛽ Economy master could not refill ${targets.length} engine(s)`,+ `master ${result.master} has ${result.masterSol} SOL (reserve ${result.reserveSol}). ` ++ `Underfunded: ${targets.map((t) => t.name).join(', ')}. Fund the master on mainnet.`,+ { signature: `economy-master-empty:${result.master}` },+ );+ }+ for (const f of result.funded) {+ await sendOpsAlert(+ `⛽ Economy master topped up ${f.name}`,+ `+${f.sol} SOL → ${f.pubkey}\ntx: ${f.signature}`,+ { signature: `economy-topup:${f.pubkey}:${f.signature}` },+ );+ }++ return json(res, 200, {+ ok: true,+ rpc: rpcUrl,+ configured: result.configured,+ targets: targets.length,+ funded: result.funded,+ failed: result.failed,+ skipped: result.skipped,+ spent_sol: result.spentSol,+ master_sol: result.masterSol ?? null,+ read_errors: errors,+ });+});diff --git a/content/oracle-conviction-engine.md b/content/oracle-conviction-engine.mdnew file mode 100644index 000000000..9b2411c09--- /dev/null+++ b/content/oracle-conviction-engine.md@@ -0,0 +1,64 @@+# Oracle: one honest number for every pump.fun launch++*Long-form X article. How three.ws fuses who is buying, how a coin is built, what it is, and how it is moving into a single live conviction score, and how your 3D agent acts on it. $THREE is the only coin.*++The first minutes of a new coin are the most asymmetric market on earth. Insiders know the creator's history, which wallets are loading up, and whether the supply is clean. You see a ticker and a green candle. By the time the answer is obvious, the trade is gone.++Oracle is our answer to that. It watches every pump.fun launch, scores it from 0 to 100, and publishes the score, the reasoning, and the track record in public. One honest number, live at [three.ws/oracle](https://three.ws/oracle).++## The four pillars++Every score fuses four independent reads on a coin. Each pillar is scored on its own, then combined, so you can always see why a coin scored what it did.++**WHO, the Pedigree pillar.** Reputation earned on chain. Which smart wallets are in this coin, and what is the creator's launch history? Oracle keeps a ledger of wallets that have proven they win, and a cold start prior for creators it has never seen, so a first launch is treated with honest uncertainty instead of fake confidence.++**HOW, the Structure pillar.** The engineering of the launch itself. Holder distribution, top holder concentration, bundling, mint and freeze authority, mutable metadata. A coin with structural red flags gets capped no matter how good everything else looks. Rugs are a structure problem before they are a price problem.++**WHAT, the Narrative pillar.** What the coin actually is. Oracle classifies every launch into a category and scores it with a model that has the news on its desk, so a coin riding a real, current narrative reads differently from one riding nothing.++**MOVE, the Momentum pillar.** How it is trading right now. Deliberately the lightest pillar, because momentum is the easiest signal to fake and the last to matter.++## Tiers, and why the ladder is strict++The fused score maps to a tier: prime, strong, lean, watch, or avoid. The ladder is conservative by design. Only prime and strong are act signals. Lean means watch for confirmation. Watch means no edge yet. Avoid means pedigree or structure red flags, full stop.++Most launches never get past watch. That is the point. A conviction engine that likes everything is a hype engine.++## The part built for agents++Humans read the coin page. Agents read the signal endpoint.++```+GET three.ws/api/oracle/signal?network=mainnet&min_score=72&limit=5+GET three.ws/api/oracle/signal?mint=<mint>+```++It returns the current highest conviction plays, or a single coin's verdict, with an explicit machine readable recommendation: an action (buy, watch, or skip), a confidence level, and a suggested size factor. Prime maps to full size, strong to three quarters, everything else to zero. Your agent does not have to re-implement the decision rules to know what to do.++This is what powers the agent action loop. Arm your 3D agent at [three.ws/oracle/arm](https://three.ws/oracle/arm), set it to simulate or live, and it polls the signal, acts only on prime and strong, and narrates what it did and why. Every decision it makes shows up in real time at [three.ws/activity](https://three.ws/activity).++## Receipts, in public++A score you cannot audit is an opinion. Oracle publishes its evidence.++The calibration and backtest pages show what win actually means, how often each tier delivers, and how the thresholds were set. Every scored coin is graded after the fact, so the tier ladder is accountable to outcomes, not vibes. The whole data loop, from the pump.fun firehose to the scoring worker, is watchable live at [three.ws/pipeline](https://three.ws/pipeline).++If the engine is wrong, you will see it be wrong. That is the deal.++## The full market picture++Conviction tells you whether to trust a launch. It deliberately says nothing about price. So every Oracle coin page now carries a live market intel aggregator that fans out to six real sources in parallel: DexScreener, the pump.fun API, GeckoTerminal, GoPlus, Birdeye, and CoinGecko. Price, liquidity, FDV, bonding curve progress, holder count, top ten concentration, and the security posture of the mint, all fused into one view, every number traced to a live upstream.++Each source is isolated. If one is down or rate limited, that slice degrades to null and the rest of the page stays live. No mocks, no cached theater.++## Why it compounds++Every coin Oracle watches makes the next score sharper. Every graded outcome tunes the calibration. Every proven wallet added to the pedigree ledger makes WHO harder to fool. The engine is a flywheel: more coverage, better priors, sharper scores, more graded outcomes, better calibration.++That is the bet. Not a hot take generator, but a scoring engine that gets harder to beat every day it runs.++## Where to start++Read the feed at [three.ws/oracle](https://three.ws/oracle). Read the full reference, from the thesis to the exact pillar math to the API, at [three.ws/oracle/docs](https://three.ws/oracle/docs). Then arm your agent at [three.ws/oracle/arm](https://three.ws/oracle/arm) and let it trade conviction instead of noise.++The more data we watch, the sharper every score. Oracle is live now.diff --git a/data/changelog.json b/data/changelog.jsonindex 743379f84..f057c3d5e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$comment": "Curated changelog entries for three.ws \u2014 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-02",+ "title": "One funding wallet now keeps every economy engine topped up",+ "summary": "The platform's on-chain engines — the buyback relayer, coin-launch funder, treasury signers, subdomain minter and more — each hold their own small SOL balance to pay network fees. A new funding root now watches all of them and automatically tops up any that dip below their floor, from a single master wallet, every 30 minutes. It only ever sends to the platform's own registered engine wallets, never trades or launches, and is bounded by a reserve floor plus per-engine and per-sweep caps so it can't overspend. Until the master is funded it does nothing and the existing low-balance alerts keep running.",+ "tags": [+ "infra"+ ]+ },{"date": "2026-07-02","title": "Live agent screens now reach the 3D world, and coin art loads everywhere",diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex e991ee8eb..28b0eb64f 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -20,6 +20,7 @@ import { WebSocketTransport } from '@colyseus/ws-transport';import { monitor } from '@colyseus/monitor';import { WalkRoom } from './rooms/WalkRoom.js';+import { AgoraRoom } from './rooms/AgoraRoom.js';import { IrlRoom } from './rooms/IrlRoom.js';import { ClashRoom } from './rooms/ClashRoom.js';import { StageRoom } from './rooms/StageRoom.js';@@ -231,6 +232,12 @@ const gameServer = new Server({ transport, ...(driver && { driver }), ...(presen// to the shared mainland world; a missing tier is the open General world (see// WalkRoom.onCreate / onAuth / schemas.js).gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);+// The playable Agora Commons (/agora): ONE shared city-scale square for human+// presence only — the AI-citizen NPCs and their on-chain economy are driven by+// the three.ws projection APIs, not this room. No filterBy: every visitor lands+// in the same Commons. See rooms/AgoraRoom.js for why it isn't a walk_world+// coin shard (city-scale movement clamps).+gameServer.define('agora_world', AgoraRoom);// The IRL realtime world (D1): one room instance per precision-6 geocell, so// every viewer standing in the same ~1 km cell shares a live mirror of the pins// there. filterBy(['geocell']) makes joinOrCreate match only rooms for the samediff --git a/multiplayer/src/rooms/AgoraRoom.js b/multiplayer/src/rooms/AgoraRoom.jsindex 8112a7454..8a249a889 100644Binary files a/multiplayer/src/rooms/AgoraRoom.js and b/multiplayer/src/rooms/AgoraRoom.js differdiff --git a/public/changelog.json b/public/changelog.jsonindex 5ae785115..fbc05c014 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-02T08:28:20.331Z",+ "generated_at": "2026-07-02T09:00:32.690Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -101,6 +101,16 @@"improvement"]},+ {+ "date": "2026-07-02",+ "type": "update",+ "title": "One funding wallet now keeps every economy engine topped up",+ "summary": "The platform's on-chain engines — the buyback relayer, coin-launch funder, treasury signers, subdomain minter and more — each hold their own small SOL balance to pay network fees. A new funding root now watches all of them and automatically tops up any that dip below their floor, from a single master wallet, every 30 minutes. It only ever sends to the platform's own registered engine wallets, never trades or launches, and is bounded by a reserve floor plus per-engine and per-sweep caps so it can't overspend. Until the master is funded it does nothing and the existing low-balance alerts keep running.",+ "link": null,+ "tags": [+ "infra"+ ]+ },{"date": "2026-07-02","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 55ee35853..3f6f5fa96 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -78,6 +78,14 @@<category>fix</category><description>The in-world agent desk monitor in /play now renders the same live browser feed as the 2D watch panel and the live wall — previously it could only show the activity fallback because it listened on a stream that was never deployed. Coin art in the world lobby is now served through the platform's own image proxy, so tokens whose images live on flaky or retired IPFS/Arweave gateways still show their art instead of a broken tile. The paid crypto-intel feed also gained a second live price source, so a rate-limited upstream no longer makes paid calls fail — and if both sources are down you are never charged. Assorted console warnings from multiplayer connections closing mid-session are gone.</description></item>+ <item>+ <title>One funding wallet now keeps every economy engine topped up</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-02:One funding wallet now keeps every economy engine topped up</guid>+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>The platform's on-chain engines — the buyback relayer, coin-launch funder, treasury signers, subdomain minter and more — each hold their own small SOL balance to pay network fees. A new funding root now watches all of them and automatically tops up any that dip below their floor, from a single master wallet, every 30 minutes. It only ever sends to the platform's own registered engine wallets, never trades or launches, and is bounded by a reserve floor plus per-engine and per-sweep caps so it can't overspend. Until the master is funded it does nothing and the existing low-balance alerts keep running.</description>+ </item><item><title>Oracle 3D graph is visible again</title><link>https://three.ws/oracle</link>diff --git a/public/features.json b/public/features.jsonindex 927d86150..34142d7f9 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-02T08:28:20.241Z",+ "generated_at": "2026-07-02T09:00:32.621Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/wire-master-wallet.mjs b/scripts/wire-master-wallet.mjsnew file mode 100755index 000000000..7c2aa9b77--- /dev/null+++ b/scripts/wire-master-wallet.mjs@@ -0,0 +1,178 @@+#!/usr/bin/env node+// Wire ONE Solana wallet as the master signer for every autonomous engine.+//+// three.ws has no single "master wallet" env var — each engine loads its own+// keypair from its own env var (see api/_lib/solana-signers.js). This operator+// tool takes a single secret key and writes it into every signer slot, in the+// encoding each slot expects (base58 / base64), so one wallet funds+signs for+// all of them (the "approach A" consolidation).+//+// SECURITY+// - The secret is read from a file or stdin, NEVER a CLI arg (shell history).+// - It is decoded locally, its pubkey derived, and MUST match --pubkey+// (default: the intended master) or the run aborts. This prevents wiring the+// wrong wallet.+// - The secret is never printed or logged. Env vars are set --sensitive.+// - Default is a dry run: it prints the plan and sets nothing. Pass --apply.+//+// USAGE+// # dry run (shows exactly what it would set, sets nothing):+// node scripts/wire-master-wallet.mjs --secret-file ./master.key+//+// # actually set every signer in Vercel production, overwriting existing:+// node scripts/wire-master-wallet.mjs --secret-file ./master.key --apply --overwrite+//+// # also set the preview environment:+// node scripts/wire-master-wallet.mjs --secret-file ./master.key --apply --overwrite --preview+//+// # pipe the secret instead of a file:+// cat master.key | node scripts/wire-master-wallet.mjs --apply --overwrite+//+// After applying, verify balances/pubkeys with:+// node scripts/check-relayer-balances.mjs+//+// The secret file may hold the key as base58, base64, or a JSON array of 64+// ints (Solana CLI keypair file) — all are auto-detected.++import fs from 'node:fs';+import path from 'node:path';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');++const { decodeSecretKey } = await import(path.join(ROOT, 'api/_lib/solana-signers.js'));++// The intended master wallet. Override with --pubkey if you rotate it.+const DEFAULT_MASTER_PUBKEY = 'wwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';++// Every signer slot that should resolve to the master, with the encoding its+// consumer expects. `enc` is what we WRITE; consumers that auto-detect accept+// any form, but slots with a strict decoder (e.g. *_B64 → base64-only) must+// match. Registry slots are documented in api/_lib/solana-signers.js.+const TARGETS = [+ // base64 (…_B64 / …_KEYPAIR consumers)+ { env: 'LAUNCHER_MASTER_SECRET_KEY_B64', enc: 'base64', note: 'autonomous coin launcher master' },+ { env: 'PUMP_X402_LAUNCHER_SECRET_KEY_B64', enc: 'base64', note: 'x402 pay-per-call launches' },+ { env: 'PUMP_CRON_RELAYER_SECRET_KEY_B64', enc: 'base64', note: 'buyback + distribute crons' },+ { env: 'THREE_BUYBACK_SECRET_KEY_B64', enc: 'base64', note: '$THREE buyback cron' },+ { env: 'COIN_TREASURY_SECRET_KEY_B64', enc: 'base64', note: 'coin lottery/reflection payouts (strict base64)' },+ { env: 'CLUB_SOLANA_TREASURY_SECRET_KEY_B64', enc: 'base64', note: 'club tip sweeps' },+ { env: 'PLATFORM_TREASURY_KEYPAIR', enc: 'base64', note: 'shared platform treasury / withdrawal gas' },+ { env: 'MARKETPLACE_PAYER_KEYPAIR', enc: 'base64', note: 'gasless checkout fee-payer' },+ // base58 (…_BASE58 and flexible treasury secrets)+ { env: 'THREEWS_SOL_PARENT_SECRET_BASE58', enc: 'base58', note: 'threews.sol subdomain minting' },+ { env: 'X402_SEED_SOLANA_SECRET_BASE58', enc: 'base58', note: 'x402 autonomous/seed spender' },+ { env: 'LABOR_ESCROW_SECRET_BASE58', enc: 'base58', note: 'labor market escrow (already live — overwrite reroutes it!)' },+ { env: 'VANITY_BOUNTY_PAYOUT_KEY', enc: 'base58', note: 'vanity bounty payouts (strict base58)' },+ { env: 'CIRCULATION_TREASURY_SECRET', enc: 'base58', note: 'circulation engine treasury' },+ { env: 'A2A_PAYER_SOLANA_SECRET', enc: 'base58', note: 'a2a mandate settlements' },+ { env: 'REWARDS_DISTRIBUTOR_SECRET', enc: 'base58', note: '$THREE holder rewards distributor' },+ // Intentionally EXCLUDED:+ // SOLANA_AGENT_COLLECTION_AUTHORITY_KEY — on-chain NFT-collection update+ // authority; must stay the wallet that created the collection or NFT ops+ // break. Do not overwrite with the master. Add --include-collection to force.+];++const argv = process.argv.slice(2);+const has = (f) => argv.includes(f);+const val = (f) => (argv.includes(f) ? argv[argv.indexOf(f) + 1] : undefined);++const APPLY = has('--apply');+const OVERWRITE = has('--overwrite');+const PREVIEW = has('--preview');+const INCLUDE_COLLECTION = has('--include-collection');+const EXPECTED_PUBKEY = val('--pubkey') || DEFAULT_MASTER_PUBKEY;+const secretFile = val('--secret-file');++function readSecret() {+ if (secretFile) {+ if (!fs.existsSync(secretFile)) fail(`--secret-file not found: ${secretFile}`);+ return fs.readFileSync(secretFile, 'utf8').trim();+ }+ if (process.env.MASTER_WALLET_SECRET) return process.env.MASTER_WALLET_SECRET.trim();+ if (!process.stdin.isTTY) return fs.readFileSync(0, 'utf8').trim();+ fail('No secret provided. Use --secret-file <path>, pipe it via stdin, or set MASTER_WALLET_SECRET.');+ return '';+}++function fail(msg) {+ console.error(`\n✗ ${msg}\n`);+ process.exit(1);+}++async function main() {+ const scopes = ['production', ...(PREVIEW ? ['preview'] : [])];+ const targets = INCLUDE_COLLECTION+ ? [...TARGETS, { env: 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY', enc: 'base64', note: 'NFT collection authority (forced)' }]+ : TARGETS;++ const secret = readSecret();+ const bytes = await decodeSecretKey(secret);+ if (!bytes) fail('Could not decode the secret. Expect base58, base64, or a JSON array of 64 ints.');+ if (bytes.length !== 64) fail(`Decoded secret is ${bytes.length} bytes; expected a 64-byte secret key.`);++ const { Keypair } = await import('@solana/web3.js');+ const bs58mod = await import('bs58');+ const bs58 = bs58mod.default || bs58mod;+ const kp = Keypair.fromSecretKey(bytes);+ const pubkey = kp.publicKey.toBase58();++ if (pubkey !== EXPECTED_PUBKEY) {+ fail(+ `Refusing to run: the provided secret derives to\n ${pubkey}\n` ++ `but the expected master wallet is\n ${EXPECTED_PUBKEY}\n` ++ `If this is intentional, re-run with --pubkey ${pubkey}`,+ );+ }++ const encoded = {+ base64: Buffer.from(bytes).toString('base64'),+ base58: bs58.encode(bytes),+ };++ console.log(`\nMaster wallet: ${pubkey}`);+ console.log(`Mode: ${APPLY ? 'APPLY' : 'DRY RUN (nothing will change)'}${OVERWRITE ? ' overwrite=on' : ''}`);+ console.log(`Scopes: ${scopes.join(', ')}`);+ console.log(`Signer slots: ${targets.length}\n`);++ let ok = 0;+ let failed = 0;+ for (const t of targets) {+ const value = encoded[t.enc];+ for (const scope of scopes) {+ const label = `${t.env} [${scope}] (${t.enc})`;+ if (!APPLY) {+ console.log(` would set ${label} — ${t.note}`);+ continue;+ }+ if (OVERWRITE) {+ // Remove first; ignore "not found". add fails if the var exists.+ spawnSync('vercel', ['env', 'rm', t.env, scope, '-y'], { stdio: ['ignore', 'ignore', 'ignore'] });+ }+ const res = spawnSync('vercel', ['env', 'add', t.env, scope, '--sensitive'], {+ input: value,+ encoding: 'utf8',+ });+ if (res.status === 0) {+ console.log(` ✓ set ${label}`);+ ok++;+ } else {+ console.log(` ✗ FAILED ${label} — ${(res.stderr || '').trim().split('\n').pop()}`);+ failed++;+ }+ }+ }++ if (!APPLY) {+ console.log(`\nDry run only. Re-run with --apply --overwrite to write these to Vercel.`);+ } else {+ console.log(`\nDone: ${ok} set, ${failed} failed.`);+ console.log(`Redeploy for changes to take effect, then verify:`);+ console.log(` node scripts/check-relayer-balances.mjs`);+ if (failed) process.exitCode = 1;+ }+}++main().catch((e) => fail(e?.message || String(e)));diff --git a/src/agora/agora-world.js b/src/agora/agora-world.jsindex 2ea4cef51..bd8f87724 100644--- a/src/agora/agora-world.js+++ b/src/agora/agora-world.js@@ -78,14 +78,22 @@ async function main() {}progress(56, 'Building the square…');- buildCity(scene, osmData);+ // Keep the collision AABBs: the spectator never collides, but play mode+ // (player-mode.js) walks the same buildings /city's player does.+ const { buildingBoxes } = buildCity(scene, osmData);// Free-orbit spectator camera over the square. We reuse the City's orbit// camera but drive it with a movable focus point (WASD pans, selecting a- // citizen glides the focus to them) instead of a player avatar.+ // citizen glides the focus to them) instead of a player avatar. Entering play+ // mode retargets the SAME camera at the player's avatar — one rig, two modes.const cityCamera = new CityCamera(camera, canvas);const focus = new THREE.Vector3(0, 0, 0);let focusGoal = null; // when set, focus eases toward it (cleared on manual pan)+ // Play mode (Enter the Commons). null = spectator; otherwise the lazily-loaded+ // player layer ({update, playerPosition, playerHeight, dispose}). Declared here+ // (not at the mount site) so the key handlers below can consult it without a+ // temporal-dead-zone window between listener attach and mount.+ let playerMode = null;camera.position.set(0, 16, 30);const onContextMenu = (e) => e.preventDefault();@@ -97,6 +105,9 @@ async function main() {const PAN_KEYS = new Set(['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright']);const onKeyDown = (e) => {const k = e.key.toLowerCase();+ // In play mode the avatar owns WASD/arrows/Space/E (player-mode.js binds its+ // own listeners); only the I-inspect hotkey stays live on this handler.+ if (playerMode && k !== 'i') return;if (!PAN_KEYS.has(k) && k !== 'i') return;// Don't hijack typing or scrolling: let form fields, editable content, and any// open panel keep arrow/WASD keys. Only pan when the world itself has focus.@@ -104,12 +115,12 @@ async function main() {if (ae && (/^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(ae.tagName) || ae.isContentEditable|| (ae.closest && ae.closest('.agora-passport, .agora-panel, .agora-h-root, [role="dialog"]')))) return;// I inspects a citizen without touching the mouse: the one under the- // pointer if any, else whoever is closest to the camera's focus point.- // Same passport the click path opens — reputation, stake, wallet, timeline.+ // pointer if any, else whoever is closest to the camera's focus point (or+ // to the player, when walking). Same passport the click path opens.if (k === 'i') {if (e.repeat) return;e.preventDefault();- const id = hoverId || nearestCitizenTo(focus);+ const id = hoverId || nearestCitizenTo(playerMode ? playerMode.playerPosition : focus);if (id) openPassport(id, null);return;}@@ -358,6 +369,76 @@ async function main() {crowd,openPassport: (id) => openPassport(id, null),});++ // ── Play mode — Enter the Commons ─────────────────────────────────────────+ // The GTA layer: your avatar walks the square among the working citizens,+ // other humans appear live over the shared 'agora_world' room, and proximity+ // prompts open citizen passports. Lazily imported so the watchable Commons+ // never pays for colyseus.js/nipplejs up front; the citizens' on-chain economy+ // runs identically in both modes.+ const enterBtn = document.getElementById('agora-enter');+ const hintEl = document.getElementById('agora-controls-hint');+ const SPECTATE_HINT = hintEl ? hintEl.innerHTML : '';+ const PLAY_HINT = '<kbd>WASD</kbd> move <kbd>Shift</kbd> run <kbd>Space</kbd> jump <kbd>E</kbd> interact <kbd>Drag</kbd> camera';+ let playBusy = false; // guards double-click while the module/avatar loads++ async function enterPlay() {+ if (playerMode || playBusy) return;+ playBusy = true;+ if (enterBtn) { enterBtn.disabled = true; enterBtn.textContent = 'Entering…'; }+ try {+ const { mountPlayerMode } = await import('./player-mode.js');+ playerMode = await mountPlayerMode({+ scene, camera, population, buildingBoxes,+ getCameraYaw: () => cityCamera.yaw,+ openPassport: (id) => openPassport(id, null),+ });+ focusGoal = null;+ if (enterBtn) {+ enterBtn.disabled = false;+ enterBtn.textContent = 'Leave the square';+ enterBtn.setAttribute('aria-pressed', 'true');+ }+ if (hintEl) hintEl.innerHTML = PLAY_HINT;+ canvas.setAttribute('aria-label',+ 'The Commons — you are walking the square. WASD to move, E to meet the nearest citizen; the citizen list also works.');+ try { localStorage.setItem('agora:mode', 'play'); } catch { /* private mode */ }+ } catch (err) {+ // Honest failure: the world stays watchable, the button invites a retry.+ log.error('[agora] play mode failed to mount', err);+ if (enterBtn) {+ enterBtn.disabled = false;+ enterBtn.textContent = 'Enter failed — retry';+ }+ } finally {+ playBusy = false;+ }+ }++ function leavePlay() {+ if (!playerMode) return;+ try { playerMode.dispose(); } catch (err) { log.warn('[agora] play dispose failed', err?.message); }+ playerMode = null;+ if (enterBtn) {+ enterBtn.textContent = 'Enter the Commons';+ enterBtn.setAttribute('aria-pressed', 'false');+ }+ if (hintEl) hintEl.innerHTML = SPECTATE_HINT;+ canvas.setAttribute('aria-label',+ 'The Commons — a 3D world of citizens. Use the citizen list to inspect individuals.');+ try { localStorage.setItem('agora:mode', 'spectate'); } catch { /* private mode */ }+ }++ enterBtn?.addEventListener('click', () => { playerMode ? leavePlay() : enterPlay(); });+ // Deep link / returning player: ?play=1 (or a remembered choice) walks in+ // directly. Deferred until after boot so entering never delays first paint.+ {+ const params = new URLSearchParams(location.search);+ let remembered = null;+ try { remembered = localStorage.getItem('agora:mode'); } catch { /* private mode */ }+ if (params.get('play') === '1' || remembered === 'play') setTimeout(enterPlay, 400);+ }+// ── Render loop ───────────────────────────────────────────────────────────const clock = new THREE.Timer();let rafId = 0;@@ -372,23 +453,29 @@ async function main() {clock.update();const dt = Math.min(clock.getDelta(), 0.05);- // Spectator panning (camera-relative), unless easing toward a selection.- let px = 0, pz = 0;- const yaw = cityCamera.yaw;- if (keys.has('w') || keys.has('arrowup')) { px -= Math.sin(yaw); pz -= Math.cos(yaw); }- if (keys.has('s') || keys.has('arrowdown')) { px += Math.sin(yaw); pz += Math.cos(yaw); }- if (keys.has('a') || keys.has('arrowleft')) { px -= Math.cos(yaw); pz += Math.sin(yaw); }- if (keys.has('d') || keys.has('arrowright')) { px += Math.cos(yaw); pz -= Math.sin(yaw); }- if (px !== 0 || pz !== 0) {- const len = Math.hypot(px, pz);- focus.x = clampPan(focus.x + (px / len) * PAN_SPEED * dt);- focus.z = clampPan(focus.z + (pz / len) * PAN_SPEED * dt);- } else if (focusGoal) {- focus.lerp(focusGoal, Math.min(1, dt * 4));- if (focus.distanceTo(focusGoal) < 0.15) focusGoal = null;+ if (playerMode) {+ // Play mode: the avatar drives; the orbit camera follows the player the+ // exact way /city's does (same rig, same substrate).+ playerMode.update(dt);+ cityCamera.update(playerMode.playerPosition, playerMode.playerHeight);+ } else {+ // Spectator panning (camera-relative), unless easing toward a selection.+ let px = 0, pz = 0;+ const yaw = cityCamera.yaw;+ if (keys.has('w') || keys.has('arrowup')) { px -= Math.sin(yaw); pz -= Math.cos(yaw); }+ if (keys.has('s') || keys.has('arrowdown')) { px += Math.sin(yaw); pz += Math.cos(yaw); }+ if (keys.has('a') || keys.has('arrowleft')) { px -= Math.cos(yaw); pz += Math.sin(yaw); }+ if (keys.has('d') || keys.has('arrowright')) { px += Math.cos(yaw); pz -= Math.sin(yaw); }+ if (px !== 0 || pz !== 0) {+ const len = Math.hypot(px, pz);+ focus.x = clampPan(focus.x + (px / len) * PAN_SPEED * dt);+ focus.z = clampPan(focus.z + (pz / len) * PAN_SPEED * dt);+ } else if (focusGoal) {+ focus.lerp(focusGoal, Math.min(1, dt * 4));+ if (focus.distanceTo(focusGoal) < 0.15) focusGoal = null;+ }+ cityCamera.update(focus, 1.7);}-- cityCamera.update(focus, 1.7);population.update(dt);economy.update(dt);renderer.render(scene, camera);@@ -415,6 +502,7 @@ async function main() {try { if (offResize) window.removeEventListener('resize', offResize); } catch { /* ignore */ }try { clearTimeout(citizensRefresh); } catch { /* ignore */ }try { window.removeEventListener('agora:citizens-changed', onCitizensChanged); } catch { /* ignore */ }+ try { playerMode?.dispose(); } catch (err) { log.warn('[agora] play dispose failed', err?.message); }try { economy.dispose(); } catch (err) { log.warn('[agora] economy dispose failed', err?.message); }try { population.dispose?.(); } catch (err) { log.warn('[agora] population dispose failed', err?.message); }try { cityCamera.destroy?.(); } catch { /* ignore */ }diff --git a/tasks/onchain-deployment/SOLANA-SIGNERS.md b/tasks/onchain-deployment/SOLANA-SIGNERS.mdnew file mode 100644index 000000000..efc22bd81--- /dev/null+++ b/tasks/onchain-deployment/SOLANA-SIGNERS.md@@ -0,0 +1,64 @@+# Solana signers — funding & wiring runbook++Companion to [`api/_lib/solana-signers.js`](../../api/_lib/solana-signers.js) (the machine-readable registry) and the two operator scripts below. Keep this file in sync with that registry.++three.ws has **no single "master wallet" env var**. Every autonomous engine loads its own Solana keypair from its own env var and pays fees / rent / spend from that wallet. If a wallet runs dry, its flow stops — often silently. This doc lists every signer, what it pays for, the encoding its env var expects, and how to fund or consolidate them.++## The signers++Encodings: `base64` = base64 of the 64 raw secret-key bytes (`…_B64` vars); `base58` = base58 of the same 64 bytes (`…_BASE58` vars); most consumers auto-detect base64 / base58 / JSON-array, but treat the name's suffix as authoritative when writing.++| Env var | Engine / what it pays for | Enc | Min SOL | Network |+|---|---|---|---|---|+| `LAUNCHER_MASTER_SECRET_KEY_B64` | Autonomous coin launcher — tops up the next agent's per-launch SOL (deploy + dev-buy) | base64 | 1.0 | mainnet |+| `PUMP_X402_LAUNCHER_SECRET_KEY_B64` | Fronts the ~0.022 SOL deploy cost for x402 pay-per-call pump.fun launches | base64 | 0.1 | mainnet |+| `PUMP_CRON_RELAYER_SECRET_KEY_B64` | Fees + swap gas for the buyback and distribute-payments crons | base64 | 0.1 | both |+| `THREE_BUYBACK_SECRET_KEY_B64` | Holds USDC revenue; gas for `run-three-buyback` (market-buy $THREE → treasury) | base64 | 0.05 | mainnet |+| `COIN_TREASURY_SECRET_KEY_B64` | Signs lottery/reflection distribution txs for launched coins (strict base64) | base64 | 0.05 | mainnet |+| `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` | USDC tip-sweep transfers + recipient ATA rent (`club-payouts`) | base64 | 0.05 | mainnet |+| `PLATFORM_TREASURY_KEYPAIR` (→ `TREASURY_KEYPAIR`) | Shared platform treasury; SPL withdrawal gas (`process-withdrawals`). Several flows top up **from** this. | base64 | 0.05 | mainnet |+| `MARKETPLACE_PAYER_KEYPAIR` (→ `PLATFORM_TREASURY_KEYPAIR`) | Sponsors network fees for gasless skill/asset checkout | base64 | 0.05 | mainnet |+| `THREEWS_SOL_PARENT_SECRET_BASE58` | Owns threews.sol; rent/fees minting `*.threews.sol` subdomains | base58 | 0.05 | mainnet |+| `X402_SEED_SOLANA_SECRET_BASE58` | x402 autonomous/seed spender (probes 402 endpoints, pays USDC) | base58 | — | mainnet |+| `LABOR_ESCROW_SECRET_BASE58` | Labor market escrow custody + payout release gas | base58 | ~0.05 | mainnet |+| `VANITY_BOUNTY_PAYOUT_KEY` | Vanity grind-bounty payouts + refunds (strict base58) | base58 | — | mainnet |+| `CIRCULATION_TREASURY_SECRET` | Circulation engine treasury (agent↔agent tips/pays/trades) | base58 | — | mainnet |+| `A2A_PAYER_SOLANA_SECRET` (→ `A2A_PAYER_SOLANA_PRIVATE_KEY`) | Co-signs SPL TransferChecked for a2a mandate settlements | base58 | 0.02 | mainnet |+| `REWARDS_DISTRIBUTOR_SECRET` | $THREE holder rewards/reflections distributor | base58 | — | mainnet |+| `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | Creates/manages the three.ws agent NFT collection | base64 | 0.02 | both |++**Do not** overwrite `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` with a different wallet — it is the on-chain update authority for the NFT collection; changing it breaks NFT management. It is excluded from master-wallet consolidation by default.++## Two funding models++- **A — one wallet is every signer.** Put the same secret into every var above. Fast; one balance and one hot key serve everything. Blast radius: if that key leaks, all engines drain; engines compete for one balance. Use [`scripts/wire-master-wallet.mjs`](../../scripts/wire-master-wallet.mjs).+- **B — cold master funds per-engine hot wallets.** Keep the master as a treasury source and top up each engine's own small hot wallet below a floor (the pattern `LABOR_ESCROW` and the sniper auto-funder already use via `PLATFORM_TREASURY_KEYPAIR`). Safer, but there is no universal master→engine top-up cron yet.++**Funding a wallet does not enable an engine.** Most engines also need their own flag (`CIRCULATION_ENABLED`, `THREE_BUYBACK_ENABLED`, `SOLANA_AUTODEPLOY_ENABLED`, …). EVM engines use separate keys (`EVM_TREASURY_PRIVATE_KEY`, `CIRCULATION_EVM_TREASURY_SECRET`).++## Wiring one wallet as the master (approach A)++```bash+# 1. Put the master wallet's secret in a local file (base58, base64, or JSON array).+# NEVER commit it. NEVER paste it into a chat.+echo '<secret-key>' > master.key++# 2. Dry run — prints every var it would set, sets nothing:+node scripts/wire-master-wallet.mjs --secret-file ./master.key++# 3. Apply to Vercel production (overwrite existing), then also preview if wanted:+node scripts/wire-master-wallet.mjs --secret-file ./master.key --apply --overwrite+node scripts/wire-master-wallet.mjs --secret-file ./master.key --apply --overwrite --preview++# 4. Redeploy, then verify pubkeys + balances:+node scripts/check-relayer-balances.mjs++# 5. Shred the local key file.+shred -u master.key+```++The script refuses to run unless the secret derives to the intended master pubkey (guard against wiring the wrong wallet); override with `--pubkey <derived>`. It sets every var `--sensitive`, so keep your own copy — Vercel Sensitive vars are unreadable after save.++## Checking balances++`node scripts/check-relayer-balances.mjs [--network devnet]` reads the registry, derives each pubkey, and prints SOL + USDC balances, flagging any below its documented minimum. Never prints secrets. Non-zero exit if any configured signer is underfunded.diff --git a/tests/economy-master.test.js b/tests/economy-master.test.jsnew file mode 100644index 000000000..2a078ae14--- /dev/null+++ b/tests/economy-master.test.js@@ -0,0 +1,65 @@+// Guard-logic tests for the economy funding root (api/_lib/economy-master.js).+// planTopUps is pure, so we can assert the reserve floor, per-engine cap, per-run+// cap, dust skip, and neediest-first ordering without any RPC or key.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ planTopUps,+ RESERVE_SOL,+ PER_TOPUP_MAX_SOL,+ RUN_CAP_SOL,+} from '../api/_lib/economy-master.js';++// Defaults (no env overrides): reserve 1, per-engine 0.5, run cap 2.+test('defaults are the documented guard values', () => {+ assert.equal(RESERVE_SOL, 1);+ assert.equal(PER_TOPUP_MAX_SOL, 0.5);+ assert.equal(RUN_CAP_SOL, 2);+});++test('reserve floor: a master below reserve funds nothing', () => {+ const { plan, totalSol, spendableSol } = planTopUps(0.5, [+ { name: 'a', pubkey: 'A', currentSol: 0, refillToSol: 0.3 },+ ]);+ assert.equal(spendableSol, 0);+ assert.equal(plan.length, 0);+ assert.equal(totalSol, 0);+});++test('per-engine cap: one engine gets at most PER_TOPUP_MAX_SOL', () => {+ const { plan } = planTopUps(10, [+ { name: 'greedy', pubkey: 'G', currentSol: 0, refillToSol: 3 },+ ]);+ assert.equal(plan.length, 1);+ assert.equal(plan[0].sol, 0.5); // capped from a 3 SOL deficit+});++test('per-run cap: a sweep spends at most RUN_CAP_SOL total', () => {+ const targets = Array.from({ length: 6 }, (_, i) => ({+ name: `e${i}`,+ pubkey: `P${i}`,+ currentSol: 0,+ refillToSol: 0.5,+ }));+ const { plan, totalSol, skipped } = planTopUps(10, targets); // spendable 9, runCap 2+ assert.equal(totalSol, 2);+ assert.equal(plan.length, 4); // 4 × 0.5 = 2.0+ assert.ok(skipped.some((s) => s.reason === 'run_cap_reached'));+});++test('dust: a sub-threshold deficit is skipped, not churned', () => {+ const { plan, skipped } = planTopUps(10, [+ { name: 'hair', pubkey: 'H', currentSol: 0.499, refillToSol: 0.5 },+ ]);+ assert.equal(plan.length, 0);+ assert.deepEqual(skipped, [{ name: 'hair', reason: 'below_dust_threshold' }]);+});++test('neediest first: the most-drained engine wins a tight run cap', () => {+ // spendable makes runCap = 0.5 → only one engine can be funded this sweep.+ const { plan } = planTopUps(1.5, [+ { name: 'small', pubkey: 'S', currentSol: 0.4, refillToSol: 0.5 }, // deficit 0.1+ { name: 'big', pubkey: 'B', currentSol: 0.0, refillToSol: 0.5 }, // deficit 0.5+ ]);+ assert.equal(plan[0].name, 'big');+});diff --git a/vercel.json b/vercel.jsonindex e07d3536c..40821786c 100644--- a/vercel.json+++ b/vercel.json@@ -12,6 +12,9 @@"api/cron/{strategy-fanout,gmgn-seed}.js": {"maxDuration": 300},+ "api/cron/treasury-topup.js": {+ "maxDuration": 120+ },"{api/strategies,api/cron/payment-session-sweep,api/cron/three-market-refresh}.js": {"maxDuration": 30},@@ -4902,6 +4905,10 @@{"path": "/api/cron/solana-agents-crawl","schedule": "*/30 * * * *"+ },+ {+ "path": "/api/cron/treasury-topup",+ "schedule": "*/30 * * * *"}]}