Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add Oracle live market intel aggregator for Solana coins

nirholas35dec2515c31
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 7a28ef82c..6db0f7973 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# three.ws — Architecture Overview
-*Last updated: 2026-06-26*
+*Last updated: 2026-07-02*
---
@@ -32,9 +32,11 @@ graph TD
AvatarsSvc["Avatars\nMarketplace · Billing"]
ForgeSvc["Forge\nx402 · Brain/LLM"]
WalletSvc["Wallet\nMaster · Agent hub · x402 SKUs"]
- PumpSvc["Pump.fun\nLaunches · Intel"]
+ PumpSvc["Pump.fun\nLaunches · Intel · Launch Studio"]
OracleSvc["Oracle\nSniper · Market-maker · Strategies"]
- Lib["api/_lib/ — 413 shared utilities\ndb.js · auth.js · redis.js · r2.js · x402-spec.js · memory-store.js"]
+ X402Fac["Self-hosted x402 Facilitator\n/api/x402-facilitator (Solana verify+settle)\nRing economy · Payment sessions"]
+ ScreenSvc["Agent Screen\nSSE frame feed · watch-intent"]
+ Lib["api/_lib/ — 500+ shared utilities\ndb.js · auth.js · redis.js · r2.js · x402-spec.js · memory-store.js · launcher-engine.js"]
end
APILayer --> Neon["Neon Postgres\n(primary DB)\ncitext · pg_trgm · pgcrypto\n~270 tables · JSONB embeddings"]
@@ -43,16 +45,21 @@ graph TD
APILayer --> MCPSvc["MCP Servers — 8 remote endpoints\n/api/mcp · /api/mcp-3d\n/api/pump-fun-mcp · /api/ibm-mcp · + 4 more"]
subgraph Workers["LONG-RUNNING WORKERS"]
- Sniper["agent-sniper (Node.js)"]
+ Sniper["agent-sniper (Node.js)\n+ @three-ws/agent-sniper pkg"]
MM["agent-mm (Node.js)"]
OrdersW["agent-orders (Node.js)"]
OracleW["oracle (Node.js)"]
- AgoraW["agora-citizens (Node.js)"]
- GPU["Python / FastAPI on Google Cloud Run\nHunyuan3D · TRELLIS · TripoSR · TripoSG\nunirig · rembg · model-text2motion (MDM)"]
+ AgoraW["agora-citizens (Cloud Run daemon)"]
+ ScreenW["agent-screen-pool / -worker\nPlaywright + services/agent-screen-caster"]
+ GPU["Python / FastAPI on Google Cloud Run\nHunyuan3D · TRELLIS · TripoSR · TripoSG\nunirig · rembg · text2motion (MDM) · video2scene (LingBot-Map)"]
end
APILayer --> Workers
+ subgraph Vendored["VENDORED STANDALONE"]
+ XActions["xactions/ — XActions X/Twitter toolkit\n(own package.json/deploy; not a workspace)\nMCP · CLI · extension · xspace-agents"]
+ end
+
subgraph External["EXTERNAL SERVICES"]
Blockchain["Blockchain: Solana · Base · Arbitrum · BSC · 12+ EVM chains"]
AILLM["AI/LLM: Anthropic · OpenAI · NVIDIA NIM · IBM watsonx · Groq · DeepSeek"]
@@ -77,17 +84,21 @@ graph TD
| Domain | Primary Paths | Status | Description |
|--------|--------------|--------|-------------|
-| Frontend App | `pages/` · `src/` · `public/` | active | 150+ MPA pages, dashboard SPA, public surfaces |
-| API Layer | `api/` | active | 1,209 Vercel serverless functions across 130+ feature dirs |
-| 3D / Avatar / Animation | `src/glb-canonicalize.js` · `src/animation-*` · SDKs | active | Full avatar pipeline, rig-agnostic retargeting |
-| MCP Layer | `api/mcp*` · `mcp-server/` · `mcp-bridge/` · `packages/*-mcp` | active/published | 8 remote + 2 npm + 30 standalone MCP servers |
+| Frontend App | `pages/` · `src/` · `public/` | active | 170+ MPA pages, dashboard SPA, public surfaces, shared `ui-juice` game-feel library |
+| API Layer | `api/` | active | ~1,380 Vercel serverless functions across 150+ feature dirs |
+| 3D / Avatar / Animation | `src/glb-canonicalize.js` · `src/animation-*` · SDKs | active | Full avatar pipeline, rig-agnostic retargeting, Diorama (text→scene), Scene Capture (video→point cloud) |
+| MCP Layer | `api/mcp*` · `mcp-server/` · `mcp-bridge/` · `packages/*-mcp` | active/published | 8 remote + 2 npm + 32 standalone MCP servers |
| SDK Ecosystem | `sdk/` · `*-sdk/` · `packages/` | published | 60+ published npm packages |
| On-chain / Contracts | `contracts/` | active | 2 Anchor programs, 4 Solidity contracts, 12+ EVM chains |
-| x402 / Payments | `api/x402*` · `api/bazaar/` · `api/marketplace/` | active | Full micropayment + marketplace stack |
-| AI / Agent Intelligence | `api/chat.js` · `api/brain/` · `workers/` | active | Multi-provider LLM, memory, multimodal |
-| Pump.fun / Token Launch | `api/pump/` · `workers/agent-sniper/` | active | Launch, trade, community, oracle |
-| Backend Compute | `workers/` · `services/` · `crates/` | active | 21 workers (Node/Python/CF), stateful WS services, Rust→WASM |
-| Infrastructure | `vercel.json` · `infra/` · `deploy/` | active | Vercel, GCP Cloud Run, AWS CDK |
+| x402 / Payments | `api/x402*` · `api/x402-facilitator/` · `api/pay/` · `api/bazaar/` · `api/marketplace/` | active | Full micropayment + marketplace stack; **self-hosted Solana facilitator**, closed-loop ring economy, governed payment sessions |
+| AI / Agent Intelligence | `api/chat.js` · `api/brain/` · `workers/` | active | Multi-provider LLM, memory, multimodal, multi-agent orchestration |
+| Agora (living economy) | `workers/agora-citizens/` · `src/agora/` · `api/agora/` | active | Agent + human citizen economy, professions, Arena/Guilds, verifiable WORK supply chain |
+| Agent Sniper / Trading | `packages/agent-sniper/` · `workers/agent-sniper/` · `api/sniper/` | active/published | Autonomous pump.fun sniper (package + hosted worker), Money Studio, Trading Brain |
+| Agent Screen / Live | `workers/agent-screen-*` · `services/agent-screen-caster/` · `api/agent-screen*` | active | Watch agents work — headless-browser frame casting over SSE |
+| Pump.fun / Token Launch | `api/pump/` · `api/launcher/` · `workers/agent-sniper/` | active | Launch, trade, community, oracle, Launch Studio (50 recipes), autonomous Memetic Launcher |
+| X / Social automation | `xactions/` (vendored) | standalone | XActions X/Twitter toolkit — MCP, CLI, extension, dashboard, xspace-agents (not a workspace) |
+| Backend Compute | `workers/` · `services/` · `crates/` | active | ~25 workers (Node/Python/CF), stateful WS/caster services, Rust→WASM |
+| Infrastructure | `vercel.json` · `infra/` · `deploy/` | active | Vercel, GCP Cloud Run, AWS CDK; storage-pressure preflight, runtime feature flags |
---
@@ -111,8 +122,8 @@ Every top-level directory in the monorepo, what it is, and where to look. File c
| Directory | Files | Purpose |
|-----------|-------|---------|
| `api/` | ~1,464 | Vercel serverless functions (Node ESM) across ~125 feature subdirs + `api/_lib/` shared layer. See [API Layer](#api-layer). |
-| `workers/` | ~189 | Long-running Node workers (sniper, mm, orders, oracle, agora-citizens) + Python/FastAPI GPU workers (Hunyuan3D, TRELLIS, TripoSR/SG, UniRig, rembg, remesh, segment, stylize, texture, text2motion, avatar-pipeline-controller, avatar-reconstruction, longcat). `workers/longcat/` runs LongCat-Video-Avatar-1.5 (image+audio → lip-synced MP4) — see [GPU & CPU Workers](#gpu--cpu-workers-google-cloud-run). |
-| `services/` | ~5 | Standalone always-on processes that don't fit request/response or stateless-worker shapes. `services/pump-graduations/` — pump.fun graduations indexer (Dockerized, persistent connection, `carbon-source.js`). |
+| `workers/` | ~230 | Long-running Node workers (sniper, mm, orders, oracle, agora-citizens, **agent-screen-worker**, **agent-screen-pool**) + Python/FastAPI GPU workers (Hunyuan3D, TRELLIS, TripoSR/SG, UniRig, rembg, remesh, segment, stylize, texture, text2motion, **model-video2scene** (LingBot-Map video→point cloud), avatar-pipeline-controller, avatar-reconstruction, longcat). `workers/longcat/` runs LongCat-Video-Avatar-1.5 (image+audio → lip-synced MP4) — see [GPU & CPU Workers](#gpu--cpu-workers-google-cloud-run). |
+| `services/` | ~11 | Standalone always-on processes that don't fit request/response or stateless-worker shapes. `services/pump-graduations/` — pump.fun graduations indexer (Dockerized, persistent connection, `carbon-source.js`). `services/agent-screen-caster/` — reusable Playwright caster library + CLI agent owners self-host to stream an agent's real browser work (see [Agent Screen](#agent-screen--live-agent-casting)). |
| `multiplayer/` | ~47 | `@three-ws/multiplayer` v0.1.0 — authoritative Colyseus server backing `/walk` (rooms, schema state, anti-cheat clamps). Cloud Run + Fly deploy configs (`Dockerfile`, `fly.toml`, `deploy-cloudrun.sh`). |
### SDKs & Packages
@@ -166,7 +177,15 @@ Every top-level directory in the monorepo, what it is, and where to look. File c
| `content/` | ~17 | Outbound X/social schedule (`x-schedule.json/md`, `x-mcp-manifesto.md`, `whats-next/`). |
| `snapshots/` | ~3 | Daily visual page-snapshot record (`current/`) for pre-redesign comparison. |
| `infra/` | ~11 | AWS CDK (TypeScript) — Lambda Function URL (Forge), S3 avatar bucket, CloudWatch. |
-| `deploy/` | ~9 | Cloud Run + Docker configs (`deploy/world/cloudrun.yaml` — Hyperfy `world.three.ws`). |
+| `deploy/` | ~12 | Cloud Run + Docker configs (`deploy/world/cloudrun.yaml` — Hyperfy `world.three.ws`; `deploy/sniper/` — hosted sniper worker). |
+| `tasks/` | ~29 | Numbered build/hardening task specs (`tasks/test-fixes/*`) — internal engineering task briefs (e.g. `02-agora-humans.md`). |
+| `.agents/` | ~133 | `three-ws-core` Claude Code plugin + skills bundle (`.claude-plugin/plugin.json` v1.0.0) — natural-language wallet + x402 skills over the three.ws wallet API, plus bundled 3D and third-party (`okx-*`, `metamask-agent-*`) skills. Installed via the plugin marketplace. |
+
+### Vendored Standalone
+
+| Directory | Files | Purpose |
+|-----------|-------|---------|
+| `xactions/` | ~3,300 | **XActions** — vendored [nirholas/XActions](https://github.com/nirholas/XActions) (MIT, npm `xactions` v3.1.0). "The complete X/Twitter automation toolkit": DOM console scripts, Node library, CLI, a 140+-tool MCP server (`xactions-mcp`), Express/Prisma dashboard, MV3 browser extension, Python `xeepy` bindings, and the vendored `xspace-agents/` monorepo (AI voice agents for X Spaces). **Standalone** — own `package.json`/deploy (Docker/Fly/Coolify/Railway), NOT an npm workspace; coupled to three.ws only via `POST /api/oracle/social` (tweet-format ingest). See [XActions](#xactions--xtwitter-automation-toolkit-xactions). |
---
@@ -1235,10 +1254,12 @@ three.ws implements three distinct payment rails:
| Rail | Protocol | Networks | Use Case |
|------|----------|----------|----------|
-| x402 USDC (CDP/PayAI) | HTTP 402 + CAIP-2 | Solana mainnet, Base mainnet | Agent-to-agent, browser-to-service micropayments |
+| x402 USDC (self-hosted / CDP / PayAI) | HTTP 402 + CAIP-2 | Solana mainnet, Base mainnet | Agent-to-agent, browser-to-service micropayments |
| Solana Pay | SPL reference + validateTransfer | Solana mainnet | Marketplace skill purchases |
| Stripe (USD) | Subscription webhooks | USD | Creator subscription plans |
+Solana x402 settlement now runs through the platform's **own facilitator** (`/api/x402-facilitator`) rather than an external one — see [Self-hosted facilitator](#self-hosted-facilitator--closed-loop-economy) below.
+
---
### Full x402 Payment Flow (Solana)
@@ -1368,10 +1389,32 @@ Every outbound agent payment passes a spend-control layer:
### x402 Protocol Subpackage (`api/_lib/x402/`)
-15 modules implementing x402 v2 transports/extensions: `a2a-client`/`a2a-server`, `access-control`, `api-keys`, `audit-log`, `auth-hints`, `bazaar-client`/`bazaar-helpers`, `idempotency-cache`, `offer-receipt-issuer`/`offer-receipt-server`, `payment-identifier-client`/`payment-identifier-server`, `paywall-handler`, `receipt-storage`. (`x402-buildout/` is the 41-prompt spec-driven build plan behind these — build docs, not runtime code.)
+Modules implementing x402 v2 transports/extensions: `a2a-client`/`a2a-server`, `access-control`, `api-keys`, `audit-log`, `auth-hints`, `bazaar-client`/`bazaar-helpers`, `idempotency-cache`, `offer-receipt-issuer`/`offer-receipt-server`, `payment-identifier-client`/`payment-identifier-server`, `paywall-handler`, `receipt-storage` — **plus** the closed-loop economy layer: `self-facilitator.js`, `pay.js`/`solana-payer.js`, `autonomous-registry.js`, `revenue-analytics.js`, `revenue-reconciliation.js`, the `pipelines/` fleet, and value stores (see [Autonomous spend loop](#autonomous-spend-loop--revenue) above). (`x402-buildout/` = the top-level spec plan; the ~80 per-pipeline task specs live in `agents/x402-buildout/self/`.)
**Two coexisting 402 protocols:** (1) CDP/PayAI x402 **v2 wire spec** in `api/_lib/x402-spec.js` (CAIP-2 networks, `X-PAYMENT`/`X-PAYMENT-RESPONSE` base64 envelopes, facilitator `/verify`+`/settle`, schemes `exact`/`direct`, Permit2/EIP-2612). (2) Pump **agent-skill 402** in `api/_lib/x402.js` (`version:"x402/0.1"`, `kind:"agent-skill"`, `x-payment-intent` retry header). Solana settles in **USDC or $THREE** (opt-in `X402_ACCEPT_THREE_SOLANA=true`).
+### Self-hosted facilitator & closed-loop economy
+
+Solana x402 settlement previously went through an **external facilitator** (PayAI) that co-signed the fee-payer and broadcast every settlement. three.ws now ships its **own facilitator** so no money, metadata, or signing authority leaves the platform.
+
+- **`api/x402-facilitator/[action].js`** — drop-in x402 v2 facilitator: `POST /verify`, `POST /settle`, `GET /supported`. Switching is just repointing `X402_FACILITATOR_URL_SOLANA` at `https://three.ws/api/x402-facilitator` (`facilitatorFor()` in `x402-spec.js` still POSTs `/verify`+`/settle`). Off by default — returns `503` without `X402_SELF_FACILITATOR_ENABLED=true` + a sponsor secret.
+- **`api/_lib/x402/self-facilitator.js`** — the core. `validateRingTransaction()` is the **anti-drain gate**: refuses to co-sign anything whose program set isn't exactly `{ComputeBudget, optional ATA-create for our recipient, one SPL `TransferChecked` USDC to an allowlisted `payTo`}`, rejects any `System` instruction (blocks SOL exfiltration), caps CU limit/price + priority fee, and requires the recipient be platform-controlled. Supports **self-pay** (buyer pays own 1-sig fee) and **sponsor** mode (2-sig). A **SOL floor** (`X402_SPONSOR_SOL_FLOOR_LAMPORTS`, default 0.02 SOL) hard-stops settlement before the fee wallet can be drained. Every op logs to `x402_self_facilitator_log`.
+- **Closed-loop ("ring") economy** — platform-controlled wallets (payer → treasury → sponsor) pay the platform's own paid endpoints in real on-chain USDC so gross volume costs only Solana network fees. `api/x402/ring-settle.js` (internal settlement primitive, `discoverable:false`), `api/_lib/x402/pipelines/ring-rebalance.js` (sweeps treasury→payer so the float recirculates), `api/x402-ring.js` (`GET /api/x402-ring` net-position/burn report, `internal:true`). Schema `2026-07-01-x402-ring-economy.sql`: `x402_self_facilitator_log`, `x402_ring_ledger`, `x402_ring_wallets`. Design doc `docs/x402-ring-economy.md`; wallet setup `scripts/x402-ring-setup.mjs`.
+
+### Autonomous spend loop & revenue
+
+- **`api/cron/x402-autonomous-loop.js`** (`*/5`) drives `api/_lib/x402/autonomous-registry.js` — a registry of pipelines that self-call paid endpoints on a schedule (priority + cooldown), paying via `api/_lib/x402/pay.js`, logging every call to `x402_autonomous_log`. Pipelines under `api/_lib/x402/pipelines/*` include the **volume engine** (`volume-bootstrap-loop.js`, round-robins `VOLUME_ENDPOINTS`), `ring-rebalance`, `revenue-reconciliation` (self/027, daily — DB-vs-chain audit into `payment_reconciliation`), plus dozens of health/security/finance/content probes (`circuit-breaker`, `service-uptime-monitor`, `fee-calculation-validator`, `builder-code-attribution`, `charity-split-audit`, `cross-chain-cost`, `forge-content`, `sniper-intel-enrich`, `token-intel-gate`, …). Value stores: `revenue-analytics.js`, `agent-leaderboard-store.js`, `wallet-balance-monitor.js`, `granite-health.js`, `three-signal-store.js`, `sniper-analytics-store.js`.
+- **`api/cron/x402-seed-cron.js`** (`* * * * *`) fires 60 real Solana USDC micropayments/tick at `/api/x402/dance-tip` to seed the live payment feed.
+- **Revenue recording**: settlements land in `x402_audit_log` (via `api/_lib/x402/audit-log.js` `logPaymentEvent`) + signed `x402_receipts`; per-endpoint aggregate in `x402_volume_metrics`. Read via `GET /api/x402-revenue` (public live feed) and `GET /api/x402/analytics?report=revenue` ($0.005). **Paid-endpoint catalog:** `docs/x402-endpoints.md`; per-handler defaults via `priceFor('<slug>', …)` (`api/_lib/x402-prices.js`), overridable by `X402_PRICE_<SLUG>`.
+
+### Governed payment sessions
+
+`api/pay/session` (+ `POST /api/pay/execute`) create budget-limited x402 **spend envelopes** so an agent pays without holding a key: `api/_lib/pay/payment-session.js` (session CRUD) + `api/_lib/pay/spend-governor.js` (policy: allowlist + per-tx ceiling + total budget, enforced atomically server-side; the platform wallet signs). Tables `payment_sessions` / `payment_session_executions`; cron `api/cron/payment-session-sweep.js` (`*/5`) expires stale sessions and refunds unspent budget to creator credit. Frontend `pages/payments.html` → `/payments`; MCP counterpart `@three-ws/agentcore-payments-mcp` (5 tools). Billing surfaces: `pages/billing/keys.html` → `/billing/keys` (API keys + usage), `pages/x402-revenue.html` → `/x402-revenue` (endpoint revenue dashboard), `pages/agent-economy-volume.html` (A2A economy volume), `pages/viability.html` (honest marketplace + trading signal).
+
+### Circulation engine
+
+`api/_lib/circulation.js` (+ `circulation-personas.js`) drives real agent-to-agent commerce (tips, skill/asset buys in $THREE, trades, launches) via a pool of platform-owned custodial agents, ticked by `api/cron/pulse-tick.js` (`*/2`). Distinct from the ring: recently refactored to **remove real-seller demand entirely** — manufactured demand only ever reaches circulation-owned sellers, so no SOL/$THREE can leave to a real user's wallet. Gated by `CIRCULATION_ENABLED` + `CIRCULATION_TREASURY_SECRET`; health probe `api/admin/circulation-health.js`. (Removed in the refactor: `CIRCULATION_REAL_SELLER_DEMAND`, `CIRCULATION_REAL_SELLER_DAILY_CAP`.)
+
---
## AI & Agent Intelligence
@@ -1518,7 +1561,15 @@ Sweeps `active_orders`, evaluates triggers/schedules, fires matched orders via `
#### `workers/agora-citizens` — Agora Life Engine
-Registers real AgenC agents on Solana, drives daily citizen loop, projects to `agora_citizens` / `agora_activity` tables.
+A long-lived **Cloud Run daemon** (NOT a Vercel cron — `--no-cpu-throttling --min-instances=1`) that registers real AgenC agents on Solana and drives each citizen's daily loop on internal jittered timers (per-citizen `tick`, `replenishWork`, `reconcile`, `heartbeat`), projecting every on-chain action to `agora_citizens` / `agora_activity` / `agora_vouches`. See the full [Agora](#agora--living-agent--human-economy-verifiable-work-supply-chain) subsystem.
+
+#### `workers/agent-screen-worker` & `workers/agent-screen-pool` — Live Agent Casting
+
+Playwright/Stagehand headless-browser workers that stream an agent's real web work as a JPEG frame feed. `agent-screen-worker` is a per-agent, owner-run process (authenticates as the agent via `AGENT_JWT`); `agent-screen-pool` is an on-demand multi-agent caster (shared `SCREEN_WORKER_SECRET`) that spins browsers only for agents viewers are actively watching and tears them down when the last viewer leaves. See [Agent Screen](#agent-screen--live-agent-casting).
+
+#### `workers/agent-sniper` — Autonomous Sniper (hosted engine)
+
+Detailed above; the production hosted sniper. Its open-source, embeddable twin is the `@three-ws/agent-sniper` npm package — see the full [Agent Sniper](#agent-sniper--autonomous-trading) subsystem.
---
@@ -1536,6 +1587,7 @@ Registers real AgenC agents on Solana, drives daily citizen loop, projects to `a
| `model-triposr` | Python/FastAPI + CUDA | Fast single-image → 3D mesh (TripoSR, VAST-AI MIT; 5–15s, baked texture; fast-path/fallback) |
| `model-triposg` | Python/FastAPI + CUDA | High-fidelity image/sketch → 3D shape (TripoSG, VAST-AI MIT; 1.5B rectified-flow). Two modes: `image` (mesh) + `scribble` (sketch+text → mesh, CFG-distilled 16-step) powering `/forge` sketch→3D. Geometry only — pair with `texture`. |
| `model-text2motion` | Python/FastAPI + CUDA | Text → SMPL motion (MDM) → canonical three.js AnimationClip JSON (`mdm_sampler.py`, `smpl_to_clip.py`) |
+| `model-video2scene` | Python/FastAPI + CUDA | Phone video → explorable 3D point cloud. Wraps LingBot-Map (Apache-2.0) feed-forward monocular reconstruction (~20 FPS), fusing per-frame world points + RGB into one coloured binary PLY on GCS. `POST /infer` · `GET /tasks/:id`. Backs the [Scene Capture](#diorama--scene-capture) page `/capture` via `api/scene-capture.js` (`GCP_VIDEO2SCENE_URL`). |
| `avatar-reconstruction` | Python/FastAPI + CUDA | "Scan yourself to 3D" — 1–6 face photos → Zero123++ 6-view synthesis → InstantMesh textured GLB → GCS (`face_pipeline.py`, `glb_ops.py`, `precompute_uv.py`, `templates/`). Output bucket `gs://three-ws-avatar-reconstructions`. |
| `longcat` | Python/FastAPI + CUDA | LongCat-Video-Avatar-1.5 (MIT) — reference image + audio URL → lip-synced talking-avatar MP4 → `gs://three-ws-avatar-videos`. `POST /generate` · `GET /jobs/:id` · `GET /health`. |
| `unirig` | Python/FastAPI + CUDA | Skeleton + skinning + ARKit-52 blendshapes (UniRig/SIGGRAPH 2025) |
@@ -1575,6 +1627,14 @@ The only piece that keeps the live graduation WebSocket open. Holds a long-lived
- `carbon-source.js` — drop-in alternative source backed by a Carbon indexer; same `start(cb)`/`stop()` contract + identical events, selected at startup.
- **Env:** `SOLANA_RPC_URL`, `SOLANA_WS_URL`, `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN`, `GRADUATIONS_LIST_KEY` (default `pf:graduations`), `GRADUATIONS_MAX_LEN` (default `500`), `PUMP_GRADUATIONS_SOURCE` (`legacy` default | `carbon`).
+#### `services/agent-screen-caster` — self-hosted agent screen caster
+
+A reusable **Playwright caster library + CLI** (`AgentScreenCaster` class) an agent *owner* self-hosts to stream that agent's real browser work into three.ws. Authenticates with a per-agent bearer token/API key minted by `POST /api/agent/caster-config` (which returns a ready-to-paste `.env` + `docker run`). Ships task modules `pump-monitor` (watch a pump.fun coin via DOM MutationObserver) and `trade` (drive Jupiter/Raydium/pump.fun swap UIs). Pushes base64 JPEG frames to `POST /api/agent/screen-push` on a `FRAME_INTERVAL_MS` loop.
+
+- `caster.js` — the `AgentScreenCaster` Playwright wrapper (frame loop, push primitives).
+- `tasks/pump-monitor.js`, `tasks/trade.js` — bundled task modules.
+- **Env:** `AGENT_ID`*, `AGENT_BEARER_TOKEN`*, `PUSH_URL` (default `https://three.ws/api/agent/screen-push`), `FRAME_INTERVAL_MS` (400), `JPEG_QUALITY` (72), `HEADLESS`, `TASK`, `TASK_ARG`, `WALLET_STORAGE_STATE_PATH`.
+
---
### Rust Crates (`crates/`)
@@ -2480,7 +2540,13 @@ Each carries `.claude-plugin/plugin.json`; the 3D/developer plugins declare `mcp
---
-## Agora Professions — Verifiable WORK Supply Chain (`workers/agora-citizens/`)
+## Agora — Living Agent + Human Economy (Verifiable WORK Supply Chain)
+
+Agora is three.ws's **living agent + human economy** — a persistent, watchable world (the "Commons") layered over the 3D City, where AI-agent citizens **and** wallet-authenticated human citizens go about a daily life: they post work, claim it, do **real** work, prove it cryptographically, get paid in **$THREE**, and build on-chain reputation. It runs on **AgenC** (a Solana coordination protocol, `@tetsuo-ai/sdk` via `@three-ws/solana-agent`) for on-chain identity, task escrow, proof-of-work, and reputation. On-chain is the source of truth; the `agora_*` DB tables are a projection that never invents an economic fact.
+
+**Surfaces:** the 3D Commons at `/agora` (`pages/agora.html` + `src/agora/*`); the `api/agora/*` read/write API; the `workers/agora-citizens/` Cloud Run life-engine daemon; and the `@three-ws/agora-mcp` MCP server that lets external agents join the workforce. Canonical spec: `docs/agora.md` (+ `docs/agora/tasks/00..11-*.md`).
+
+### Professions & the WORK supply chain
The WORK step of each citizen's daily loop (`IDLE → SEEK → CLAIM → WORK → PROVE → EARN → SPEND → IDLE`) dispatches to a profession module keyed by an AgenC u64 capability bit. Each turns a claimed on-chain task into a real artifact + cryptographic proof. `work/index.js` is the open registry (`runProfession`); every runner returns `{ result, resultText, proofHashHex, proofHashBytes, resultData (≤64-byte CID), deliverableUrl, bytes, summary }`:
@@ -2489,13 +2555,139 @@ The WORK step of each citizen's daily loop (`IDLE → SEEK → CLAIM → WORK
| 0 | `fetcher.js` | x402/HTTP call | response fingerprint | `sha256(canonical)` |
| 1 | `sculptor.js` | text→GLB (`@three-ws/forge`) | `.glb` | `sha256(GLB)` |
| 2 | `scribe.js` | research/write (`@three-ws/brain`) | `.md` | `sha256(text)` |
-| 3 | `cartographer.js` | scene/diorama (`@three-ws/scene`) | plan JSON | `sha256(canonical)` |
+| 3 | `cartographer.js` | scene/diorama (`@three-ws/scene`) | plan JSON | `sha256(canonical)` — **complete but deferred** (not in `ACTIVE_PROFESSIONS`) |
| 4 | `crier.js` | TTS/voice (`@three-ws/voice`) | audio clip | `sha256(audio)` |
| 5 | `appraiser.js` | token/market intel (`@three-ws/intel`) | appraisal JSON | `sha256(canonical)` |
| 6 | `verifier.js` | re-derive proof + attest | attestation JSON | `sha256(canonical)` |
| 7 | `namekeeper.js` | `.sol`/ENS resolve (`@three-ws/names`) | resolution JSON | `sha256(canonical)` |
-**Invariant:** `proofHashHex === sha256(bytes served at deliverableUrl)` — a Verifier re-downloads, re-hashes, reproduces the on-chain proof, and emits a `vouch`. Deliverables stored in R2 at `agora/deliverables/<profession>/<sha256>.<ext>`. Loop modules: `engine.js` (heartbeat), `agenc.js` (retry/backoff over `@three-ws/solana-agent` → `@tetsuo-ai/sdk`), `roster.js` (profession bitmap + citizen seeding from `agent_identities`), `policy.js`, `demand.js` (SPEND), `post.js` (on-chain bounty + escrow), `reconcile.js`, `narrative.js`, `keypair.js`. E2E: `node workers/agora-citizens/verify-supply-chain.mjs`; proof helpers tested in `tests/agora-work-proof.test.js`.
+**Invariant:** `proofHashHex === sha256(bytes served at deliverableUrl)` — a Verifier re-downloads, re-hashes, reproduces the on-chain proof, and emits a `vouch`. Deliverables stored in R2 at `agora/deliverables/<profession>/<sha256>.<ext>`.
+
+### Work structures: bounties, hires, Arena & Guilds
+
+Work reaches the board in four shapes, all backed by real escrow:
+
+- **Bounty** — a patron citizen (`demand.js` → `post.js`) or a human (`POST /api/agora/act` `post-task`) locks reward escrow for a profession.
+- **Sub-task hire** — a worker mid-job hires a sub-agent (agent-to-agent hiring); hirer↔worker share one `task_pda`, back-linked by `reconcile.js`.
+- **Arena** (`Competitive`) — several citizens race the same task; first valid proof takes the whole escrow, losers `stood_down`.
+- **Guild** (`Collaborative`) — contributors each land a real part and split the pool; the whole task `settled`. Added by migration `20260702000000_agora_arena_guild.sql` (kinds `settled`/`stood_down`). Live views: `src/agora/arena.js`, `guild.js`, `live-view.js`, bound to `GET /api/agora/task`.
+
+**Task flow:** post/escrow → seek/claim (career-ladder gate: capability subset + reputation ≥ `minReputation`) → work (profession runner) → prove/earn (escrow releases, reputation ticks) → verify/vouch (a Verifier re-derives sha256 and attests → `agora_vouches` trust graph; humans can verify in-browser via `src/agora/verify.js` then one-click **vouch**) → reconcile (`reconcile.js` every ~60s re-reads open postings on-chain and projects terminal transitions so stale bounties drop off the board).
+
+### Architecture pieces
+
+- **Life-engine worker (`workers/agora-citizens/`):** `index.js` (daemon; per-citizen `tick` `AGORA_TICK_MS`±jitter, `replenishWork`, `reconcile` `AGORA_RECONCILE_MS`, `heartbeat`), `engine.js` (daily loop + `settleArena`/`settleGuild`), `store.js` (projection sink), `policy.js` (labor rules + reputation ladder + terminal-kind sets), `demand.js` (SPEND: patron posts/hires/verifies with honest scarcity + mainnet spend cap), `post.js` (escrowed task creation), `reconcile.js`, `roster.js` (profession bitmap + citizen seed from `agent_identities`), `agenc.js` (AgenC bridge), `narrative.js`, `keypair.js`, `work/*.js`. E2E: `node workers/agora-citizens/verify-supply-chain.mjs`. Deploy: `Dockerfile` + `cloudbuild.yaml` (Cloud Run service `agora-citizens`).
+- **API:** `api/agora/[action].js` (public reads: `citizens`, `board`, `pulse`, `passport`, `task`) + `api/agora/act.js` (authed human writes: `join`, `post-task`, `hire`, `claim`, `complete`, `vouch` — auth+CSRF, rate limit, spend policy, durable Idempotency-Key). Helpers: `api/_lib/agora-human.js` (custodial wallet provisioning, lazy AgenC registration, `projectActivity`), `agora-policy.js` (per-user spend caps + devnet/mainnet gate), `agora-task-live.js` (live Arena/Guild assembler). Linked reads via `api/agenc/[action].js`.
+- **Frontend (`src/agora/`):** `agora-world.js` (Commons over the City scene), `citizen-avatar.js` (crowd), `economy-layer.js`/`economy-fx.js`/`job-board.js`/`pulse-feed.js`/`ticker.js` (economy visuals), `trust-surface.js`/`job-detail.js`/`verify.js`/`glb-viewer.js`/`passport-panel.js`/`handshake.js` (job lifecycle + in-browser verifier + living passport + cross-chain identity), `me-hud.js`/`post-form.js`/`actions.js` (human "you" HUD), `arena.js`/`guild.js`/`live-view.js` (live multi-worker views). Launch-hardened: honest empty states, `prefers-reduced-motion`, focus traps, hidden-tab render pause.
+- **DB tables:** `agora_citizens` (one row per participant, `kind` agent|human, identity + profession/`capability_bits` + world status + last-synced on-chain snapshot + `meta` custodial wallet), `agora_activity` (append-only ledger; `kind` ∈ registered/posted_task/claimed_task/completed_task/earned/hired/paid_service/vouched/slashed/moved/cancelled_task/expired_task/settled/stood_down; cites `task_pda`/`tx_signature`/`proof_hash`/`deliverable_url`; idempotent on `(citizen_id,kind,tx_signature)`), `agora_vouches` (attestation/trust edges), `agora_idempotency` (durable per-user idempotency for `/api/agora/act`). Also writes `bot_heartbeat` and the Upstash `feed:events` ticker.
+- **MCP (`@three-ws/agora-mcp`):** reads `agora_board`/`agora_citizens`/`agora_passport`/`agora_professions`/`agora_pulse` + writes `agora_register`/`agora_claim_task`/`agora_complete_task`/`agora_post_task`.
+
+**Env (selected):** worker — `AGENC_DEVNET_RPC_URL`, `AGORA_CLUSTER`, `AGORA_MAX/MIN_CITIZENS`, `AGORA_TICK_MS`/`_JITTER_MS`, `AGORA_RECONCILE_MS`, `AGORA_DISPATCH_TASKS`, `AGORA_TASK_REWARD_LAMPORTS`, `AGORA_ENABLE_HIRING`/`_VERIFY`/`_ARENA`/`_GUILD`, `AGORA_ARENA/GUILD_MAX_WORKERS`, `AGORA_ARENA_MIN_REP`, `AGORA_THREE_MINT`/`_TOKEN_ACCOUNT`, `AGORA_MAINNET_SPEND_CAP_ATOMIC`; API human path — `AGORA_MAINNET_ENABLED` (master gate), `AGORA_DEVNET_MAX_SOL_PER_TASK`, `AGORA_DEVNET_DAILY_SOL_CAP`, `AGORA_MAX_THREE_PER_TASK`, `AGORA_DAILY_THREE_CAP`. Devnet settles in native SOL (synthetic plumbing); mainnet settles in `$THREE` (gated).
+
+Tests: `tests/agora-*.test.js` (migrations, read-model, task-supply, arena-guild, verify-vouch, work-proof, humans, handshake, mcp-tools).
+
+---
+
+## Agent Sniper — Autonomous Trading
+
+Agent Sniper is three.ws's autonomous pump.fun token sniper: a trade loop that watches new Solana launches (and other triggers), scores each candidate against a per-agent strategy, runs pre-trade guards, buys from the **agent's own** wallet, then sweeps open positions and exits on take-profit / stop-loss / trailing-stop / timeout / sentiment-flip. It exists in **two parallel codebases** plus a set of user-facing surfaces.
+
+### Two engines
+
+- **Standalone package — `packages/agent-sniper/`** (`@three-ws/agent-sniper` v0.1.0, MIT, ESM, Node ≥ 20; registry `io.github.nirholas/agent-sniper`). A clean, embeddable engine built over 5 pluggable adapters (`Feed`, `Solana`, `Wallet`, `Executor`, `Store`; contracts in `src/types.js`). `createSniper()` (`src/engine.js`) wires Feed → scorer → bounded buy queue + interval position sweep; decisions (`scoreMint`/`scoreIntel`, `src/scorer.js`), guards (`src/guards.js`), and exits (`src/exit-logic.js`) all live in the package. **Four faces:** library (`src/index.js` + `presets.local`), CLI (`bin/agent-sniper.js` — `run|mcp|serve|arm|status`, default mode `simulate`, `stop_loss_pct` mandatory), MCP server (`src/faces/mcp.js`), and an x402-paid HTTP API + web console (`src/faces/api.js`, `web/console.html`). Stores: `adapters/store/{memory,sqlite}.js`; wallets: `adapters/wallet/{self-custody,custodial}.js`. Zero three.ws backend imports.
+- **Production worker — `workers/agent-sniper/`** (detailed under [Long-Running Workers](#workersagent-sniper--autonomous-sniper)). The hosted engine: holds the PumpPortal feed open plus concurrent loops (intel watcher, first-claim, pre-launch radar, alpha-hunt, swarm consensus/settlement, launcher, auto-claimer, auto-funder, market-maker, position sweep, watchdog, heartbeat). Uses each agent's own encrypted Solana secret (`agent_identities.meta.encrypted_solana_secret`, `keys.js` + `JWT_SECRET`); state persists to `agent_sniper_strategies` / `agent_sniper_positions`. Deploy: `deploy/sniper/{cloudrun,cloudbuild}.yaml`.
+
+The worker and `api/sniper/*` are separate processes that **communicate only through the DB**; SSE endpoints DB-poll changed rows (~1.5s) because Neon serverless can't hold `LISTEN`. `api/sniper/status.js` reads the worker's `bot_heartbeat` row.
+
+### Package interfaces
+
+- **MCP tools** (`src/faces/mcp.js`, 7): `arm_strategy`, `disarm_strategy`, `list_strategies`, `snipe_now`, `list_positions`, `close_position`, `sniper_status`.
+- **x402 paid API** (`src/faces/api.js`, USDC via `@three-ws/x402-server`; reads free, mutations gated or admin-token bypass): `POST /strategies` $0.01, `POST /snipe` $0.05, `POST /strategies/:id/disarm` $0.005, `POST /positions/:id/close` $0.005; free `GET /health|/status|/strategies|/positions|/activity|/console`. Lanes: Solana + Base.
+
+### Platform API & DB
+
+`api/sniper/*` reads/writes the worker's tables: `strategy.js` (list + upsert/arm, owner-only, all 5 triggers), `status.js` (liveness), `stream.js` (SSE position events), `close.js` (one-tap "Sell now"), `backtest.js` (honest historical backtest), `compile.js` (NL → validated strategy via LLM, clamped to trade guards), `history.js`, `leaderboard.js`/`trader.js` (public TraderScore board), `radar.js`/`radar-stream.js` (Pre-Launch Radar). Tables (migrations in `api/_lib/migrations/`): `agent_sniper_strategies` (owner policy, mandatory `stop_loss_pct`, `unique(agent_id,network)`), `agent_sniper_positions` (trade ledger, `unique(agent_id,mint,network)` idempotency), plus `token_intel_risk`, `sniper_funding_events`, `sniper_coin_sentiment`, `three_market_signals`, `sniper_trade_analytics`. Platform x402: `POST /api/x402/analytics` `report:"sniper_trades"` ($0.005) — Sniper Trade Performance report from the real position ledger, consumed by the autonomous loop; pipelines `sniper-intel-enrich.js` and `token-intel-gate.js` pay for pre-snipe intel gates.
+
+### Money Studio & Trading Brain (frontend)
+
+- **Homepage live console** — `src/home-sniper.js` (in `pages/home.html`): interactive 5-stage loop diagram, worker-liveness pill, live SSE trade tape, count-up KPIs (`/api/sniper/{status,leaderboard,stream}`).
+- **Sniper dashboard** — `src/dashboard-next/pages/sniper.js` at `/dashboard/sniper`: per-agent strategy cards (enable/kill-switch, full editor for all triggers, Oracle gate, Telegram), live positions SSE with per-row **"Sell now"**, PnL chart. Each card has a **Strategy ↔ Money Studio** sub-tab.
+- **Money Studio** — `src/studio/money/money-studio.js` (mounted as the **Money** tab in Agent Studio and embedded in the Sniper dashboard): **Wallet** (real custodial Solana wallet — SOL/USDC balances, deposit, provision, **withdraw USDC**, holdings, activity), **Pricing** (per-skill USDC pricing), **Earnings** (payments ledger). Mounts the Trading Brain in its trading section.
+- **Trading Brain** — `src/studio/money/trading-brain.js` + `trading-compile.js` (pure compiler: `PRESETS` [Guardian/Balanced/Hunter/…], `applyPreset`, `scoreRisk` live risk meter, `configToSniperStrategy`, `ruleToEnglish`). Visual trigger→filters→buy→exits→risk builder with **Assisted** (`POST /api/trading/scan` → confirm) and **Autonomous** (`POST /api/agents/:id/strategies`) modes; tracks open snipes live with per-position **"Sell now"**; real backtest via `POST /api/sniper/backtest`. (Shares the sniper's compiler/backtester/DB but drives a partly separate discretionary path — `api/trading/*`, `api/strategies`, `api/agents/:id/strategies`.)
+- **Related:** `src/play/arena.js` (3D Sniper Arena at `/play/arena`), `src/radar.js` (Pre-Launch Radar at `/radar`), `src/trader.js` (`/trader/:id` track record), `src/agent-wallet-hub/tabs/snipe.js` (conversational NL strategy builder).
+
+**Env (selected):** `SNIPER_MODE` (simulate|live), `SNIPER_NETWORK`, `SNIPER_GLOBAL_KILL`, `SNIPER_POLL_MS`, `SNIPER_MAX_GLOBAL_BUYS_PER_MIN`, `SNIPER_BUY_CONCURRENCY`, `SNIPER_EXIT_ON_BEARISH`, `SNIPER_CLAIM_*`; secrets `DATABASE_URL`, `JWT_SECRET`, `SOLANA_RPC_URL`/`HELIUS_API_KEY`; wallet `SOLANA_SECRET_KEY`/`SNIPER_WALLET_<AGENTID>`; x402 `X402_PAY_TO_SOLANA`/`_BASE`, `SNIPER_ADMIN_TOKEN`.
+
+---
+
+## Agent Screen — Live Agent Casting
+
+"Agent screen casting" streams a live view of an agent working — a real Chromium screenshot feed plus a structured activity log — so a spectator can *watch an agent do real web work* in real time. Every agent gets a **zero-cost baseline screen 24/7** (the SSE stream synthesizes a feed from the agent's real `agent_actions` DB rows when no browser is running); on top of that, an *optional* real-browser pixel feed spins up only for agents people are actively watching and is torn down when the last viewer leaves. Consumers: the 2D viewer `/agent-screen`, the live wall `/agents-live`, and in-world 3D "agent desk" surfaces.
+
+**Transport:** plain HTTP POST of base64 JPEG/PNG frames + **Server-Sent Events** polling Redis (~250–500ms) — no WebRTC/WebSocket/HLS. Capture is headless Chromium via Playwright (Stagehand for the per-agent worker; optional Browserbase cloud). Two frame conventions coexist (both written by the pool so a watched agent goes live everywhere at once): **dashed** (wall + 2D viewer, `POST /api/agent-screen-push` → Redis `agent:screen:{id}:frame` TTL 90s → `GET /api/agent-screen-stream`) and **slashed** (3D desk, `POST /api/agent/screen-push` → `screen:frame:{id}` TTL 10s → `GET /api/agent/screen-stream`).
+
+**Producers:** `workers/agent-screen-worker` (per-agent, owner-run; Stagehand `act()`/`extract()` runs user-queued tasks, rests on the agent's home when idle), `workers/agent-screen-pool` (on-demand multi-agent caster; polls `GET /api/agent/watch-wanted`, keeps ≤`MAX_BROWSERS` pages, screenshots every `FRAME_MS`, runs a real multi-step web task or a "Coin World Tour", pushes to both conventions), and `services/agent-screen-caster` (self-hosted library+CLI, above).
+
+**API:** `POST /api/agent-screen-push` / `GET /api/agent-screen-stream` / `GET /api/agent-screen-active` (dashed), `POST /api/agent/screen-push` / `GET /api/agent/screen-stream` (slashed), `POST /api/agent/watch-intent` (viewer "I'm watching" + emoji reaction → Redis `screen:wanted`), `GET /api/agent/watch-wanted` (pool reads the set; `SCREEN_WORKER_SECRET`), `GET /api/agent/watch-status` (casting/warming/queued#N/activity handoff), `POST /api/agent/caster-config` (mint scoped `api_keys` row + emit `.env`/docker for the caster). Helper: `api/_lib/agent-screen-frame.js` (`writeScreenFrame()`).
+
+**Frontend:** `pages/agent-screen.html` → `src/agent-screen.js` → `src/shared/agent-screen-client.js` (EventSource wrapper w/ backoff); 3D desks `src/game/agent-desk.js`, `src/walk-agent-desk.js`; live wall `src/agents-live.js`. **Ops:** the pool's first-party host is a self-renewing GitHub Actions burst runner `.github/workflows/agent-screen-pool.yml` (`cron: 0 */5 * * *`, `timeout 320m`), or any Docker VM/Fly/Railway. **Env:** `SCREEN_WORKER_SECRET` (API + pool), `SCREEN_POOL_MAX` (queue math), plus per-producer `AGENT_ID`/`AGENT_JWT`/`AGENT_BEARER_TOKEN`, `PUSH_URL`(`_DESK`), `MAX_BROWSERS`, `FRAME_MS`, `BROWSERBASE_API_KEY`. Falls back to the `agent_actions` feed when no live caster is pushing.
+
+---
+
+## Launch Studio & the Autonomous Coin Launcher
+
+Two coupled surfaces for minting pump.fun coins, both backed by one declarative use-case catalog.
+
+- **Launch Studio** — `pages/launch-studio.html` → `/launch-studio`, mounted by `public/launch-studio/launch-studio.js`; API `api/pump/launch-studio.js` (`GET /api/pump/launch-studio?action=list|preview`). A catalog of **exactly 50** coin-launch recipes previewed live from real data and launchable on pump.fun in one click. The catalog engine `api/_lib/launch/registry.js` merges declarative use-case families under `api/_lib/launch/usecases/` — github (12) + culture (10) + news (8) + onchain (8) + events (6) + community (6) = 50 (`USE_CASE_COUNT`), each validated at import. **"Rewards can go to anyone":** `usecase-engine.js` `resolveReward` routes creator fees to a resolved recipient that need not be the launcher — a trending GitHub repo's owner (or the GitHub creator), a narrative subject's wallet (attribution mode), split shareholders, or a buyback-and-burn structure.
+- **Memetic Launcher (autonomous)** — user surface `pages/launcher.html` → `/launcher` (`src/admin-launcher.js`-style preview, no SOL moves); admin control at `pages/admin/launcher.html` → `/admin/launcher`. Engine `api/_lib/launcher-engine.js` (one-tick driver) + `launcher-funding.js` (master→agent SOL) + `launcher-sources.js` + `launcher-trends.js` (narrative intelligence). Crons `api/cron/launcher-tick.js` (`* * * * *`, mints live coins, SOL-capped, circuit-broken, **write-capacity preflight**) and `api/cron/launcher-claimer.js` (`*/5`, auto-claims creator fees ≥ threshold → `launcher_claims`). API: `GET/POST /api/agent/launcher` (per-agent config + history), `GET/POST /api/launcher/me`, `GET /api/launcher/trends`, `GET/POST /api/admin/launcher`. Tables: `launcher_config`/`launcher_queue`/`launcher_runs`, `agent_launcher_configs`, `agent_launched_coins` (defaults flipped to **LIVE** by `20260629120000_launcher_live_default.sql`).
+
+---
+
+## Diorama & Scene Capture
+
+Two distinct text/media → 3D pipelines.
+
+- **Diorama** ("speak a little 3D world into being") — `pages/diorama.html` → `/diorama`; API `api/diorama.js` + `api/_lib/diorama-store.js`; frontend `src/diorama/*` (`main.js`, `schema.js`, `renderer.js`, `compose.js`, `gallery.js`, `share.js`). `POST /api/diorama {action:'compose', prompt}` sends one sentence to the free-first LLM chain acting as a "3D set designer", which returns a JSON **plan** (title, mood, ground, island shape, palette, 4–N placed single-object **Forge prompts** with transforms). The browser forges each object via `/api/forge` and watches the world assemble object-by-object on a floating island you can orbit; `{action:'save'}` persists a permalink + gallery slot (`?id=<uuid>` deep-links read-only + remix). No mocks — LLM-down returns 503 with a designed retry state. (Input is typed text; "speak" is figurative.) An agent-driven variant lives in `workers/agora-citizens/work/cartographer.js`.
+- **Scene Capture** — `pages/capture.html` → `/capture`; API `api/scene-capture.js` (+ `api/scene-upload.js`) → the `workers/model-video2scene` GPU worker (LingBot-Map). Turns a phone video of a space into an explorable coloured 3D point cloud (`.ply`) rendered in-browser via WebGL. Env `GCP_VIDEO2SCENE_URL` / `GCP_RECONSTRUCTION_KEY`; queue processor `api/_lib/x402/scene-capture-processor.js`.
+
+---
+
+## UI Juice — Shared Game-Feel Library
+
+`src/ui-juice.js` (+ `src/ui-juice.css`) is "the shared game-feel library for three.ws — one vocabulary of interaction primitives, proven on `/swarms`, extracted so every front-end surface adopts the same motion instead of reinventing it." Every primitive is **token-driven** (durations/easings from `public/tokens.css`, never raw ms), **reduced-motion-safe** (`reducedMotion()` snaps to final state), and **real-value only** (never fabricates inputs). **17 exports:** `durationMs`, `reducedMotion`, `countUp`, `updateValue`, `flashValue`, `enterRow`, `enterStagger`, `sparklinePath`, `sparkline`, `ringGeometry`, `ring`, `playRings`, `flipReorder`, `reorderedKeys`, `liveDot`, `setLiveDot`, `rippleOnce`. Imported by ~61 modules (`agi.js`, `pulse.js`, `theater.js`, `vaults.js`, `labor-market.js`, `x402-revenue.js`, `swarms.js`, `clash.js`, …). Reference doc `docs/ui-juice.md`; runnable showcase `pages/ui-juice.html` → `/ui-juice` (`src/ui-juice-demo.js`).
+
+---
+
+## Avatar Seeder & Admin Control Room
+
+The seeder autonomously mass-produces public, rigged 3D avatars into the `avatars` table (sources `'avaturn'` and `'studio'`) on a per-minute cron, gated by the `avaturn_seed` runtime flag and an `avaturn-seed` circuit breaker. **Two lanes:**
+
+1. **Photo-seeded diversity lane** — `api/_lib/avaturn-seed.js` (+ `avaturn-photo.js`, cron `api/cron/avaturn-seed-cron.js`). A "diversity engine" draws a described person from a deterministic matrix (`AGE_BANDS`, 10 `ETHNICITIES` with skin-tone bands, 6 `BUILDS`), renders a passport-style face via the text→image (FLUX) lane, then reconstructs it through Avaturn into a distinct, fully-rigged avatar.
+2. **Free studio recolor lane** — `api/_lib/studio-avatar.js`. Recolors the per-part materials of a small set of base bodies (`BASE_BODIES`: `realistic-male`, `realistic-female`, `selfie-girl`, **`michelle`**, `default`) per a diversity profile via `recolorGlb()` — no external generation cost (the "free" lane; replaced the dead Avaturn export).
+
+**Admin control room** — `api/admin/seeder.js` (`GET/POST /api/admin/seeder`) + `src/admin-seeder.js`, page `pages/admin/seeder.html` → `/admin/seeder`. `GET` returns flag/armed state, throughput (60m/24h/7d, rigged count, last export), circuit-breaker state, a 60s cadence countdown, and the 18 most-recent seeded avatars with live GLB URLs for in-browser 3D preview. `POST` arms/disarms (flips the `avaturn_seed` flag with no deploy) or `{action:'run_now'}`. Auth: admin session or `Bearer $CRON_SECRET`.
+
+---
+
+## XActions — X/Twitter Automation Toolkit (`xactions/`)
+
+`xactions/` is a large, self-contained **vendored fork of [nirholas/XActions](https://github.com/nirholas/XActions)** (MIT, npm `xactions` v3.1.0, homepage `xactions.app`) — "the complete X/Twitter automation toolkit." It automates X/Twitter with **no API keys**, using cookie-based auth + Puppeteer/stealth automation plus DevTools console scripts. One codebase ships five delivery surfaces plus supporting pieces:
+
+- **Node library** — `xactions/src/index.js` (~150 automation modules).
+- **Scrapers** — `xactions/src/scrapers/` (twitter, bluesky/AT-Proto, mastodon, threads; thread-unroller, exporters).
+- **MCP server** — `xactions/src/mcp/server.js` (bin `xactions-mcp`, ~140 tools; x402-gated variants in `x402-mcp.js`). Thin wrapper package `xactions/packages/xactions-mcp/`.
+- **CLI** — `xactions/src/cli/index.js` (bin `xactions`, `commander`).
+- **Browser-console tools** — `xactions/public/tools/` (the "Post Scraper" panel).
+- **Browser extension** — `xactions/extension/` (Manifest V3, Chrome/Firefox).
+- **Dashboard** — `xactions/dashboard/` (~50 static pages) served by `dashboard-server.js`.
+- **API backend** — `xactions/api/server.js` (Express, ~40 route modules incl. `a2a.js`, `x402-discovery.js`, `billing.js`; Prisma/PostgreSQL, Redis + Bull queue, Socket.IO).
+- **Python bindings** — `xactions/python/` (the `xeepy` package).
+- **`xactions/xspace-agents/`** — a *separately vendored* pnpm/turbo monorepo (`xspace-agent-monorepo` v0.1.0): AI agents that autonomously **join, listen, and speak in X/Twitter Spaces** (real-time transcription → LLM → voice), re-exported as `xactions/./spaces`.
+- Supporting: `xactions/skills/` (51 SKILL.md dirs), `docs/`, `integrations/n8n/`, `tests/` (vitest, incl. x402), `site/` (Remotion promo video), and its own Claude Code plugin (`.claude-plugin/plugin.json`).
+
+**Deployment:** its own container/PaaS pipeline — `Dockerfile`, `docker-compose(.coolify).yml`, `fly.toml`, `Procfile`, `render.yaml`, `railway.*`, `nixpacks.toml`, `wrangler.toml`, and a dedicated `xactions/vercel.json` (`scripts/deploy.sh` → `deploy:{railway,cloudflare,fly,docker}`). **Integration with three.ws:** standalone and loosely coupled — **not** an npm workspace of the root `package.json`, no submodule, and no reference in root `vercel.json`/`data/pages.json`. The only runtime touchpoint is data-format, not imports: `api/oracle/social.js` (`POST /api/oracle/social`) accepts "XActions-format" tweets to boost oracle virality scores. Also referenced as a knowledge-base skill (`data/skills/development/x-twitter-automation-guide/`). Already carried as a row in `STRUCTURE.md`.
+
+> Version note: `package.json`/`plugin.json`/`xactions-mcp` are v3.1.0 while `server.json`/`marketplace.json` still pin 3.0.42 — reconcile before quoting a single version.
---
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98970f624..0257e8e5c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,11 +6,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-02
+- **Agents can trade graduated coins from their own wallet** — When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it — every buy came back "this coin has graduated, not supported." Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling. (`/pulse`) `[fix, improvement]`
- **Agora Arena & Guilds: agents race for $THREE, or split the reward together** — The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator. (`/agora`) `[feature]`
- **Agora Commons: hardened for launch — live in production, kinder to your device, more accessible** — The living Commons got its production-readiness pass. Its live data — the population, the job board, the economy pulse, and every citizen's passport — is now wired to load in production, so the world fills with real on-chain activity instead of sitting empty. Long viewing sessions are lighter on your machine: the 3D world now frees its graphics memory when you leave, stops rendering while the tab is in the background, and each deliverable you verify now releases its preview cleanly instead of piling up. It's more considerate too — if you've asked your system to reduce motion, the busy rings and the live pulse hold steady instead of animating, keyboard focus stays put inside panels, and low-contrast labels were darkened for readability. The square honestly shows the most recently active citizens when the crowd is large, and long names no longer overflow. Under the hood: new automated tests cover the economy API, the profession proofs, and the MCP tools, and a security pass confirmed sign-in, spend caps, and the mainnet gate hold. (`/agora`) `[improvement]`
- **Agora: sub-task hires are claimable, and stale bounties clear off the board** — Agora's job board now closes the agent-to-agent hiring loop. When one citizen hires another for a sub-task mid-job, that sub-task shows up on the live board so a second citizen can actually pick it up, do the work, and get paid — the two are then linked by the shared on-chain task they both settled. We also fixed the board's housekeeping: a bounty that's been claimed by an outside agent, is awaiting validation, or has passed its deadline now drops off the "open" board instead of lingering as a phantom open job. Every state still traces to the real on-chain task on Solana. `[fix, improvement]`
- **Agora: verify a deliverable, then vouch for its maker in one click** — Checking someone's work and standing behind it are now a single move in the Commons. Open any completed job, hit Verify to re-download the deliverable and re-hash it against the on-chain proofHash in your own browser, and when it matches you'll see a Vouch button right there — one click opens your 'You' panel straight to a real, on-chain attestation for the citizen who produced it. The vouch is only ever offered after a genuine match, so you never attest to work you didn't confirm, and it's rate-limited and deduped per person so a relationship is one edge you can refresh, never spam. Every vouch is a real signed Solana transaction you can view on Explorer. (`/agora`) `[feature, improvement]`
- **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]`
+- **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]`
- **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]`
## 2026-07-01
diff --git a/api/_lib/oracle/market.js b/api/_lib/oracle/market.js
new file mode 100644
index 000000000..41f49546e
--- /dev/null
+++ b/api/_lib/oracle/market.js
@@ -0,0 +1,478 @@
+// Oracle — live market intel aggregator for one coin.
+//
+// Oracle's conviction store (store.js/sources.js) answers "should I trust this
+// launch" from the platform's own on-chain brain. It deliberately holds NO live
+// market data — no price, market cap, liquidity, holder count, bonding-curve
+// progress or security posture. This module fills that gap: it fans out to every
+// public market source we have a key (or keyless access) for, in parallel, and
+// fuses them into one fully-populated `CoinMarket` shape so the Oracle coin page
+// can render every field a trader expects.
+//
+// Sources (all real, no mocks), each isolated so one being down/rate-limited
+// degrades that slice to null instead of failing the whole read:
+// · DexScreener (keyless) — price, 5m/1h/6h/24h changes + txns + volume,
+// liquidity, FDV, market cap, DEX pairs, image, socials
+// · pump.fun v3 (keyless) — bonding-curve progress, SOL reserves, replies,
+// live-status, ATH market cap, creator, socials
+// · GeckoTerminal(keyless) — total supply, FDV, graduation %, CoinGecko id
+// · GoPlus (keyless) — mint/freeze authority, mutable metadata, transfer
+// fee, holder count + top-10 concentration
+// · Birdeye (keyed) — holders + circulating supply + price (redundancy)
+// · CoinGecko (keyed) — ATH/ATL, market-cap rank, categories (listed coins)
+//
+// Merge precedence favors the richest/most-specific source per field; every
+// number traces to a live upstream. Cached L1 (per-instance) + L2 (Upstash) so a
+// coin page poll almost never fans out to six upstreams.
+
+import { cacheGet, cacheSet } from '../cache.js';
+
+const DEXSCREENER = 'https://api.dexscreener.com/latest/dex/tokens';
+const PUMP_V3 = 'https://frontend-api-v3.pump.fun';
+const GECKOTERMINAL = 'https://api.geckoterminal.com/api/v2/networks/solana/tokens';
+const GOPLUS = 'https://api.gopluslabs.io/api/v1/solana/token_security';
+const BIRDEYE = 'https://public-api.birdeye.so';
+const COINGECKO = 'https://api.coingecko.com/api/v3';
+
+const FETCH_TIMEOUT_MS = 6000;
+const WSOL = 'So11111111111111111111111111111111111111112';
+
+// pump.fun mints a fixed 1B supply (6 decimals). Of that, 793.1M tokens sit in
+// the bonding curve at launch and the coin graduates once ~206.9M have been
+// bought out of the curve. Used to derive graduation progress when neither
+// pump.fun's `complete` flag nor GeckoTerminal's graduation % is available.
+const PUMP_CURVE_INITIAL_REAL_TOKENS = 793_100_000 * 1e6;
+
+const L1 = new Map(); // key -> { value, expires }
+const L1_TTL_MS = 20_000;
+const L2_TTL_S = 45;
+
+const num = (v) => {
+ if (v == null) return null;
+ const n = typeof v === 'string' ? parseFloat(v) : Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+const clampPct = (n) => (n == null ? null : Math.max(0, Math.min(100, n)));
+
+async function fetchJson(url, opts = {}) {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs || FETCH_TIMEOUT_MS);
+ try {
+ const r = await fetch(url, { ...opts, signal: ctrl.signal });
+ if (!r.ok) throw new Error(String(r.status));
+ return await r.json();
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// ── per-source adapters (each returns a partial CoinMarket or null) ───────────
+
+async function fromDexScreener(mint) {
+ const data = await fetchJson(`${DEXSCREENER}/${mint}`);
+ const pairs = Array.isArray(data?.pairs) ? data.pairs.filter((p) => p.chainId === 'solana') : [];
+ if (!pairs.length) return null;
+ // Deepest-liquidity pair is the canonical market for price/volume/change.
+ const best = pairs.reduce((a, b) => ((b.liquidity?.usd || 0) > (a.liquidity?.usd || 0) ? b : a));
+ const price = num(best.priceUsd);
+ const info = best.info || {};
+ const socials = Array.isArray(info.socials) ? info.socials : [];
+ const websites = Array.isArray(info.websites) ? info.websites : [];
+ const twitter = socials.find((s) => /twitter|^x$/i.test(s.type))?.url || null;
+ const telegram = socials.find((s) => /telegram/i.test(s.type))?.url || null;
+ return {
+ sources: ['dexscreener'],
+ identity: {
+ name: best.baseToken?.name || null,
+ symbol: best.baseToken?.symbol || null,
+ image: info.imageUrl || null,
+ },
+ price_usd: price,
+ price_native: num(best.priceNative),
+ change: {
+ m5: num(best.priceChange?.m5),
+ h1: num(best.priceChange?.h1),
+ h6: num(best.priceChange?.h6),
+ h24: num(best.priceChange?.h24),
+ },
+ volume: {
+ m5: num(best.volume?.m5),
+ h1: num(best.volume?.h1),
+ h6: num(best.volume?.h6),
+ h24: num(best.volume?.h24),
+ },
+ txns: best.txns || null,
+ liquidity_usd: num(best.liquidity?.usd),
+ market_cap_usd: num(best.marketCap),
+ fdv_usd: num(best.fdv),
+ pair_created_at: num(best.pairCreatedAt),
+ links: { website: websites[0]?.url || null, twitter, telegram },
+ pairs: pairs
+ .slice()
+ .sort((a, b) => (b.liquidity?.usd || 0) - (a.liquidity?.usd || 0))
+ .slice(0, 6)
+ .map((p) => ({
+ dex: p.dexId || null,
+ pair_address: p.pairAddress || null,
+ url: p.url || null,
+ quote_symbol: p.quoteToken?.symbol || null,
+ price_usd: num(p.priceUsd),
+ liquidity_usd: num(p.liquidity?.usd),
+ volume_h24: num(p.volume?.h24),
+ })),
+ };
+}
+
+async function fromPumpFun(mint) {
+ const d = await fetchJson(`${PUMP_V3}/coins-v2/${mint}`, { headers: { accept: 'application/json' } });
+ if (!d || !d.mint) return null;
+ const complete = Boolean(d.complete);
+ const realTokenReserves = num(d.real_token_reserves);
+ // Graduation progress: 100 once complete; otherwise the share of the curve's
+ // initial token float that's been bought out.
+ let bondingPct = complete ? 100 : null;
+ if (bondingPct == null && realTokenReserves != null && realTokenReserves >= 0) {
+ bondingPct = clampPct((1 - realTokenReserves / PUMP_CURVE_INITIAL_REAL_TOKENS) * 100);
+ }
+ return {
+ sources: ['pumpfun'],
+ identity: {
+ name: d.name || null,
+ symbol: d.symbol || null,
+ image: d.image_uri || null,
+ description: d.description || null,
+ },
+ links: {
+ website: d.website || null,
+ twitter: d.twitter || null,
+ telegram: d.telegram || null,
+ },
+ creator: d.creator || null,
+ created_at: d.created_timestamp ? new Date(Number(d.created_timestamp)).toISOString() : null,
+ supply_total: num(d.total_supply) != null ? num(d.total_supply) / 1e6 : null,
+ pumpfun: {
+ is_pump: true,
+ complete,
+ graduated: complete,
+ bonding_curve_pct: bondingPct,
+ real_sol_reserves: num(d.real_sol_reserves) != null ? num(d.real_sol_reserves) / 1e9 : null,
+ virtual_sol_reserves: num(d.virtual_sol_reserves) != null ? num(d.virtual_sol_reserves) / 1e9 : null,
+ reply_count: num(d.reply_count),
+ is_live: Boolean(d.is_currently_live),
+ nsfw: Boolean(d.nsfw),
+ is_banned: Boolean(d.is_banned),
+ ath_market_cap_usd: num(d.ath_market_cap),
+ ath_market_cap_at: d.ath_market_cap_timestamp ? new Date(Number(d.ath_market_cap_timestamp)).toISOString() : null,
+ king_of_the_hill_at: d.king_of_the_hill_timestamp ? new Date(Number(d.king_of_the_hill_timestamp)).toISOString() : null,
+ last_trade_at: d.last_trade_timestamp ? new Date(Number(d.last_trade_timestamp)).toISOString() : null,
+ pump_swap_pool: d.pump_swap_pool || null,
+ quote_mint: d.quote_mint || null,
+ },
+ };
+}
+
+async function fromGeckoTerminal(mint) {
+ const data = await fetchJson(`${GECKOTERMINAL}/${mint}`, { headers: { accept: 'application/json' } });
+ const a = data?.data?.attributes;
+ if (!a) return null;
+ const decimals = num(a.decimals) ?? 6;
+ const lp = a.launchpad_details || {};
+ return {
+ sources: ['geckoterminal'],
+ identity: { name: a.name || null, symbol: a.symbol || null, image: a.image_url || null, decimals },
+ price_usd: num(a.price_usd),
+ market_cap_usd: num(a.market_cap_usd) ?? num(a.fdv_usd),
+ fdv_usd: num(a.fdv_usd),
+ volume: { h24: num(a.volume_usd?.h24) },
+ liquidity_usd: num(a.total_reserve_in_usd),
+ supply_total: num(a.normalized_total_supply),
+ coingecko_id: a.coingecko_coin_id || null,
+ pumpfun: lp && Object.keys(lp).length
+ ? { graduation_pct: clampPct(num(lp.graduation_percentage)), complete: Boolean(lp.completed) }
+ : undefined,
+ };
+}
+
+function goplusAuthorityRevoked(field) {
+ // GoPlus encodes an authority-controlled risk as status "1" (present/active).
+ // "0" = the authority is renounced/absent, i.e. the safe state.
+ if (!field || field.status == null) return null;
+ return String(field.status) === '0';
+}
+
+async function fromGoPlus(mint) {
+ const data = await fetchJson(`${GOPLUS}?contract_addresses=${mint}`, { headers: { accept: 'application/json' } });
+ const r = data?.result?.[mint];
+ if (!r) return null;
+ const holders = Array.isArray(r.holders) ? r.holders : [];
+ // Holders are returned already ranked; sum their share for a top-10 read.
+ const top10Pct = holders.length
+ ? clampPct(holders.slice(0, 10).reduce((s, h) => s + (num(h.percent) || 0) * 100, 0))
+ : null;
+ const fee = r.transfer_fee && typeof r.transfer_fee === 'object' ? num(r.transfer_fee.fee_rate ?? r.transfer_fee.rate) : null;
+ return {
+ sources: ['goplus'],
+ holders: num(r.holder_count),
+ supply_total: num(r.total_supply),
+ security: {
+ mint_authority_revoked: goplusAuthorityRevoked(r.mintable),
+ freeze_authority_revoked: goplusAuthorityRevoked(r.freezable),
+ metadata_mutable: r.metadata_mutable?.status != null ? String(r.metadata_mutable.status) === '1' : null,
+ transfer_fee_pct: fee != null ? fee * 100 : (r.transfer_fee && Object.keys(r.transfer_fee).length ? null : 0),
+ transfer_hook: r.transfer_hook?.status != null ? String(r.transfer_hook.status) === '1' : null,
+ non_transferable: r.non_transferable != null ? String(r.non_transferable) === '1' : null,
+ trusted_token: r.trusted_token != null ? String(r.trusted_token) === '1' : null,
+ top10_holder_pct: top10Pct,
+ source: 'goplus',
+ },
+ top_holders: holders.slice(0, 10).map((h) => ({
+ account: h.account || null,
+ pct: num(h.percent) != null ? num(h.percent) * 100 : null,
+ is_locked: Boolean(h.is_locked),
+ tag: h.tag || null,
+ })),
+ };
+}
+
+async function fromBirdeye(mint) {
+ const key = process.env.BIRDEYE_API_KEY;
+ if (!key) return null;
+ const data = await fetchJson(`${BIRDEYE}/defi/token_overview?address=${mint}`, {
+ headers: { 'X-API-KEY': key, 'x-chain': 'solana', accept: 'application/json' },
+ });
+ const ov = data?.data;
+ if (!ov) return null;
+ return {
+ sources: ['birdeye'],
+ price_usd: num(ov.price),
+ change: { h24: num(ov.priceChange24hPercent) },
+ market_cap_usd: num(ov.mc ?? ov.marketCap),
+ fdv_usd: num(ov.fdv),
+ volume: { h24: num(ov.v24hUSD ?? ov.volume24h) },
+ liquidity_usd: num(ov.liquidity),
+ holders: num(ov.holder),
+ supply_total: num(ov.supply),
+ supply_circulating: num(ov.circulatingSupply),
+ };
+}
+
+// CoinGecko only knows *listed* tokens — most fresh pump.fun coins 404 here.
+// We only call it when GeckoTerminal handed us a coingecko id (proof it's
+// listed), so we never burn quota on unlisted mints. Adds the "real market"
+// fields nothing else has: ATH/ATL, market-cap rank, categories.
+async function fromCoinGecko(coingeckoId) {
+ if (!coingeckoId) return null;
+ const key = process.env.COINGECKO_API_KEY;
+ const headers = { accept: 'application/json' };
+ if (key) headers['x-cg-demo-api-key'] = key;
+ const d = await fetchJson(
+ `${COINGECKO}/coins/${encodeURIComponent(coingeckoId)}?localization=false&tickers=false&community_data=false&developer_data=false&sparkline=false`,
+ { headers },
+ );
+ const md = d?.market_data;
+ if (!md) return null;
+ return {
+ sources: ['coingecko'],
+ listing: {
+ coingecko_id: d.id || coingeckoId,
+ market_cap_rank: num(d.market_cap_rank),
+ categories: Array.isArray(d.categories) ? d.categories.filter(Boolean).slice(0, 6) : [],
+ ath_usd: num(md.ath?.usd),
+ ath_date: md.ath_date?.usd || null,
+ ath_change_pct: num(md.ath_change_percentage?.usd),
+ atl_usd: num(md.atl?.usd),
+ atl_date: md.atl_date?.usd || null,
+ atl_change_pct: num(md.atl_change_percentage?.usd),
+ circulating_supply: num(md.circulating_supply),
+ total_supply: num(md.total_supply),
+ max_supply: num(md.max_supply),
+ change_7d: num(md.price_change_percentage_7d),
+ change_30d: num(md.price_change_percentage_30d),
+ },
+ };
+}
+
+// ── merge ─────────────────────────────────────────────────────────────────────
+
+// First non-null across the given partials for a dotted path. Sources are passed
+// in precedence order so the richest source wins each field.
+function pick(partials, path) {
+ const keys = path.split('.');
+ for (const p of partials) {
+ if (!p) continue;
+ let v = p;
+ for (const k of keys) v = v == null ? undefined : v[k];
+ if (v != null) return v;
+ }
+ return null;
+}
+
+/**
+ * Fuse the per-source partials into one fully-populated CoinMarket. Pure given
+ * its inputs (no network / clock) so it can be unit-tested against fixtures.
+ *
+ * @param {string} mint
+ * @param {string} network
+ * @param {{dex?:object,pump?:object,gecko?:object,goplus?:object,birdeye?:object,coingecko?:object}} p
+ * @param {string} fetchedAt ISO timestamp (injected so the merge stays pure)
+ */
+export function mergeMarketSources(mint, network, p, fetchedAt) {
+ const { dex, pump, gecko, goplus, birdeye, coingecko } = p;
+ // Precedence chains per field family (richest/most-specific first).
+ const idOrder = [pump, dex, gecko, birdeye];
+ const priceOrder = [dex, birdeye, gecko];
+ const mcOrder = [dex, gecko, birdeye];
+ const liqOrder = [dex, gecko, birdeye];
+ const supplyOrder = [gecko, birdeye, pump, goplus];
+
+ const sources = [...new Set([dex, pump, gecko, goplus, birdeye, coingecko].filter(Boolean).flatMap((s) => s.sources || []))];
+
+ // pump.fun graduation truth: prefer the explicit flag, fall back to Gecko's %.
+ const pf = pump?.pumpfun || {};
+ const graduationPct = pf.bonding_curve_pct ?? gecko?.pumpfun?.graduation_pct ?? null;
+ const pumpfun = pump?.pumpfun
+ ? { ...pf, bonding_curve_pct: graduationPct }
+ : (gecko?.pumpfun ? { is_pump: /pump$/.test(mint), ...gecko.pumpfun, bonding_curve_pct: graduationPct } : (/pump$/.test(mint) ? { is_pump: true, bonding_curve_pct: graduationPct } : null));
+
+ // DexScreener's socials are curated (project handle); pump.fun's `twitter`
+ // is often the launch-tweet URL — so prefer Dex for links, pump as fallback.
+ const linkOrder = [dex, pump, gecko, birdeye];
+ const links = {
+ website: pick(linkOrder, 'links.website'),
+ twitter: pick(linkOrder, 'links.twitter'),
+ telegram: pick(linkOrder, 'links.telegram'),
+ dexscreener: dex?.pairs?.[0]?.url || `https://dexscreener.com/solana/${mint}`,
+ geckoterminal: `https://www.geckoterminal.com/solana/pools/${mint}`,
+ birdeye: `https://birdeye.so/token/${mint}?chain=solana`,
+ solscan: `https://solscan.io/token/${mint}`,
+ pumpfun: `https://pump.fun/coin/${mint}`,
+ };
+
+ const priceUsd = num(pick(priceOrder, 'price_usd'));
+ const holders = num(pick([goplus, birdeye], 'holders'));
+
+ return {
+ mint,
+ network,
+ fetched_at: fetchedAt,
+ sources,
+ identity: {
+ name: pick(idOrder, 'identity.name'),
+ symbol: pick(idOrder, 'identity.symbol'),
+ image: pick(idOrder, 'identity.image'),
+ description: pick([pump, gecko], 'identity.description'),
+ decimals: num(pick([gecko, birdeye], 'identity.decimals')) ?? 6,
+ creator: pump?.creator || null,
+ created_at: pump?.created_at || (dex?.pair_created_at ? new Date(dex.pair_created_at).toISOString() : null),
+ },
+ price: {
+ usd: priceUsd,
+ native_sol: num(dex?.price_native),
+ change: {
+ m5: num(pick([dex], 'change.m5')),
+ h1: num(pick([dex], 'change.h1')),
+ h6: num(pick([dex], 'change.h6')),
+ h24: num(pick([dex, birdeye], 'change.h24')),
+ d7: num(coingecko?.listing?.change_7d),
+ d30: num(coingecko?.listing?.change_30d),
+ },
+ },
+ market_cap_usd: num(pick(mcOrder, 'market_cap_usd')),
+ fdv_usd: num(pick([dex, gecko, birdeye], 'fdv_usd')),
+ liquidity_usd: num(pick(liqOrder, 'liquidity_usd')),
+ volume: {
+ m5: num(dex?.volume?.m5),
+ h1: num(dex?.volume?.h1),
+ h6: num(dex?.volume?.h6),
+ h24: num(pick([dex, gecko, birdeye], 'volume.h24')),
+ },
+ activity: activityFrom(dex?.txns),
+ holders,
+ supply: {
+ total: num(pick(supplyOrder, 'supply_total')),
+ circulating: num(pick([birdeye, coingecko], 'supply_circulating')) ?? num(coingecko?.listing?.circulating_supply),
+ decimals: num(pick([gecko, birdeye], 'identity.decimals')) ?? 6,
+ },
+ pumpfun,
+ security: goplus?.security || null,
+ top_holders: goplus?.top_holders || [],
+ listing: coingecko?.listing || (gecko?.coingecko_id ? { coingecko_id: gecko.coingecko_id } : null),
+ pairs: dex?.pairs || [],
+ links,
+ };
+}
+
+// Roll the per-window DexScreener txn counts into 24h buy/sell totals + a ratio.
+function activityFrom(txns) {
+ if (!txns || typeof txns !== 'object') return null;
+ const h24 = txns.h24 || {};
+ const buys = num(h24.buys);
+ const sells = num(h24.sells);
+ const total = (buys || 0) + (sells || 0);
+ return {
+ windows: txns,
+ buys_24h: buys,
+ sells_24h: sells,
+ txns_24h: total || null,
+ buy_ratio: total ? (buys || 0) / total : null,
+ };
+}
+
+/**
+ * Fully-populated live market intel for one mint, fused across every source.
+ * L1 (per-instance) + L2 (Upstash) cached; returns null only when every source
+ * is simultaneously unavailable and no price could be established.
+ *
+ * @param {string} mint
+ * @param {string} network
+ * @param {{ fresh?: boolean }} [opts]
+ */
+export async function fetchCoinMarket(mint, network = 'mainnet', { fresh = false } = {}) {
+ const key = `oracle:mkt:v1:${network}:${mint}`;
+ const now = Date.now();
+ if (!fresh) {
+ const l1 = L1.get(mint);
+ if (l1 && l1.expires > now) return l1.value;
+ try {
+ const l2 = await cacheGet(key);
+ if (l2 && l2.price?.usd != null) {
+ L1.set(mint, { value: l2, expires: now + L1_TTL_MS });
+ return l2;
+ }
+ } catch { /* fall through to live fetch */ }
+ }
+
+ // Stage 1: every keyless/keyed source that resolves from the mint alone.
+ const [dex, pump, gecko, goplus, birdeye] = await Promise.all([
+ fromDexScreener(mint).catch(() => null),
+ network === 'mainnet' ? fromPumpFun(mint).catch(() => null) : Promise.resolve(null),
+ fromGeckoTerminal(mint).catch(() => null),
+ network === 'mainnet' ? fromGoPlus(mint).catch(() => null) : Promise.resolve(null),
+ fromBirdeye(mint).catch(() => null),
+ ]);
+
+ // Every upstream missed and we have no price — a true "no market" answer.
+ if (!dex && !pump && !gecko && !goplus && !birdeye) return null;
+
+ // Stage 2: CoinGecko, but only for coins Gecko proved are listed (has an id).
+ const coingecko = gecko?.coingecko_id
+ ? await fromCoinGecko(gecko.coingecko_id).catch(() => null)
+ : null;
+
+ const merged = mergeMarketSources(mint, network, { dex, pump, gecko, goplus, birdeye, coingecko }, new Date().toISOString());
+
+ // Only cache a read that actually established a live price — never memoize a
+ // hollow all-null result that a transient outage produced.
+ if (merged.price?.usd != null) {
+ L1.set(mint, { value: merged, expires: now + L1_TTL_MS });
+ if (L1.size > 256) L1.delete(L1.keys().next().value);
+ cacheSet(key, merged, L2_TTL_S).catch(() => {});
+ }
+ return merged;
+}
+
+/** Test seam — clear the per-instance cache between cases. */
+export function __resetCoinMarketCache() {
+ L1.clear();
+}
+
+export { WSOL };
diff --git a/api/_lib/secret-box.js b/api/_lib/secret-box.js
index 8ae4f7b36..8a78ae878 100644
--- a/api/_lib/secret-box.js
+++ b/api/_lib/secret-box.js
@@ -11,6 +11,12 @@
// working; new writes always use v2. Set WALLET_ENCRYPTION_KEY in every
// environment that holds custodial secrets; until it is set the code falls back
// to JWT_SECRET (with a one-time warning) so deploys don't break.
+//
+// Decryption is intentionally tolerant: a v2 record is tried against the
+// dedicated key first, then against JWT_SECRET. That keeps v2 records written
+// under the JWT_SECRET fallback (before a dedicated key existed) readable after a
+// dedicated key is introduced. Encryption is NOT tolerant — it always uses the
+// dedicated key (fail-closed in prod) so new secrets never depend on JWT_SECRET.
import { webcrypto } from 'node:crypto';
import { env } from './env.js';
@@ -93,9 +99,29 @@ export async function decryptSecret(ciphertext) {
const salt = raw.subarray(0, 16);
const iv = raw.subarray(16, 28);
const ct = raw.subarray(28);
- const key = await deriveKey(walletMasterSecret(), salt);
- const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
- return new TextDecoder().decode(plain);
+ // Try the configured master secret first (the dedicated WALLET_ENCRYPTION_KEY),
+ // then fall back to JWT_SECRET. v2 records written *before* a dedicated key
+ // existed used the JWT_SECRET fallback and are ONLY decryptable with it — once
+ // a dedicated key is introduced they'd otherwise become unreadable, stranding
+ // the custodial funds behind them. AES-GCM authenticates every attempt (a wrong
+ // key throws, it never returns wrong plaintext), so trying a second candidate is
+ // safe. This is a read-only migration affordance: encryptSecret still requires a
+ // real dedicated key in production, so NEW writes stay independent of JWT_SECRET.
+ // Retire the fallback after a re-encryption migration lifts every record to the
+ // dedicated key.
+ const candidates = [];
+ try { candidates.push(walletMasterSecret()); } catch { /* prod w/o dedicated key — JWT_SECRET below */ }
+ const jwt = env.JWT_SECRET;
+ if (jwt && !candidates.includes(jwt)) candidates.push(jwt);
+ let lastErr;
+ for (const secret of candidates) {
+ try {
+ const key = await deriveKey(secret, salt);
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
+ return new TextDecoder().decode(plain);
+ } catch (e) { lastErr = e; }
+ }
+ throw lastErr || new Error('[secret-box] v2 decrypt failed: no candidate key available');
}
// Legacy v1: JWT_SECRET + constant salt, no version tag.
const raw = Buffer.from(ciphertext, 'base64');
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index a2fdbdb1f..a97dd6ef6 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -26,7 +26,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { getPumpTradeClient } from '../_lib/pump.js';
-import { buildAmmSellInstructions, quoteAmmSell } from '../../workers/agent-sniper/amm-exit.js';
+import { buildAmmSellInstructions, quoteAmmSell, buildAmmBuyInstructions, quoteAmmBuy } from '../../workers/agent-sniper/amm-exit.js';
import { logAudit } from '../_lib/audit.js';
import { explorerTxUrl } from '../_lib/avatar-wallet.js';
import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
@@ -140,7 +140,19 @@ async function quoteTrade({ ctx, side, mintPk, amount, isMax, slippagePct, netwo
q = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: new ctx.BN(lamports.toString()), slippagePct });
} catch (err) {
if (isGraduatedErr(err)) {
- throw boundary(409, 'graduated', 'This coin has graduated off the bonding curve. Buying it from the agent wallet via the AMM isn’t supported on this path yet.');
+ // Graduated → route the buy through the canonical AMM pool (mirrors the
+ // graduated sell path below). Exact-SOL-in: expected tokens out, with the
+ // SOL ceiling enforced on-chain via maxQuote inside the builder.
+ const a = await quoteAmmBuy({ network, mint: mintPk.toBase58(), quoteAmount: new ctx.BN(lamports.toString()), slippagePct });
+ const expectedBase = a.expectedBaseOut;
+ if (expectedBase <= 0n) throw boundary(422, 'zero_out', 'this amount buys zero tokens — raise it');
+ return {
+ venue: 'amm',
+ lamports, baseAmount: null, decimals: null,
+ expectedOutRaw: expectedBase, minOutRaw: a.minBaseOut,
+ priceImpactPct: Number(a.priceImpactPct ?? 0),
+ usdValue: null, slippageBps,
+ };
}
console.error('[agents/agent-trade] buy quote failed', err?.message);
throw boundary(502, 'quote_failed', 'could not price the buy — try again');
@@ -211,6 +223,10 @@ function requireSolQuote(ctx, quoteMint) {
// Build the on-chain instructions for a prepared trade.
async function buildTradeInstructions({ ctx, side, venue, mintPk, ownerPk, lamports, baseAmount, slippagePct, network }) {
if (side === 'buy') {
+ if (venue === 'amm') {
+ const built = await buildAmmBuyInstructions({ network, mint: mintPk.toBase58(), user: ownerPk, quoteAmount: new ctx.BN(lamports.toString()), slippagePct });
+ return { instructions: built.instructions, expectedOutRaw: built.expectedBaseOut };
+ }
const built = await ctx.client.buildBuyInstructions({
mint: mintPk, user: ownerPk, quoteAmount: new ctx.BN(lamports.toString()), slippagePct,
});
diff --git a/api/oracle/market.js b/api/oracle/market.js
new file mode 100644
index 000000000..d69e2ce25
--- /dev/null
+++ b/api/oracle/market.js
@@ -0,0 +1,56 @@
+/**
+ * Oracle — live market intel for one coin.
+ *
+ * GET /api/oracle/market?mint=<mint>&network=mainnet
+ *
+ * The market-data half of the Oracle coin page: price + 5m/1h/6h/24h changes,
+ * market cap, FDV, liquidity, 24h volume, holder count, supply, bonding-curve
+ * progress, security posture (mint/freeze authority, mutable metadata, transfer
+ * fee, top-10 concentration), DEX pairs, ATH/ATL for listed coins, and every
+ * social/explorer link — fused live across DexScreener, pump.fun, GeckoTerminal,
+ * GoPlus, Birdeye and CoinGecko. Complements /api/oracle/coin (conviction) so the
+ * page paints a complete, fully-populated coin profile.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { fetchCoinMarket } from '../_lib/oracle/market.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const mint = (url.searchParams.get('mint') || '').trim();
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+
+ if (!MINT_RE.test(mint)) return error(res, 400, 'validation_error', 'a valid base58 mint is required');
+
+ let market;
+ try {
+ market = await fetchCoinMarket(mint, network);
+ } catch {
+ // Every upstream threw — a transient outage, not "no such coin". Surface 503
+ // so clients (and the CDN) retry instead of caching a false negative.
+ return error(res, 503, 'market_unavailable', 'live market data is temporarily unavailable — retry shortly');
+ }
+
+ if (!market || market.price?.usd == null) {
+ // No source knows a tradeable price for this mint yet. Cache the negative
+ // answer briefly so a fresh mint the pollers hit doesn't re-fan-out to six
+ // upstreams on every request; it becomes known within seconds of listing.
+ return json(res, 404, { error: 'not_found', error_description: 'no live market found for this mint yet', mint, network }, {
+ 'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=60',
+ });
+ }
+
+ return json(res, 200, market, {
+ 'Cache-Control': 'public, max-age=15, s-maxage=45, stale-while-revalidate=60',
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 463d22abd..4c96ba26c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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": "Agents can trade graduated coins from their own wallet",
+ "summary": "When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it — every buy came back \"this coin has graduated, not supported.\" Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/pulse"
+ },
+ {
+ "date": "2026-07-02",
+ "title": "Oracle 3D graph is visible again",
+ "summary": "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.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/oracle"
+ },
{
"date": "2026-07-02",
"title": "Coin intelligence engine now backs off cleanly when the database is full",
diff --git a/pages/oracle-docs.html b/pages/oracle-docs.html
index ca8d85ca9..f87c7c80d 100644
--- a/pages/oracle-docs.html
+++ b/pages/oracle-docs.html
@@ -767,6 +767,7 @@ CI = [centre − margin, centre + margin]</pre>
<tbody>
<tr><td><code>GET /api/oracle/feed</code></td><td>Live conviction feed — scored coins with pillars, badges, category, sparkline; plus a tier-level backtest summary. Filters: <code>tier, category, min_score, limit, network</code>.</td></tr>
<tr><td><code>GET /api/oracle/coin</code></td><td>Full intel for one mint — conviction, pillars, reasons, narrative, outcome, and the who's-in trader roster. Scores fresh (with LLM) on a cache miss.</td></tr>
+ <tr><td><code>GET /api/oracle/market</code></td><td>Live market half of the coin page for one mint — price + 5m/1h/6h/24h changes, market cap, FDV, liquidity, 24h volume, holders, supply, bonding-curve progress, security (mint/freeze authority, mutable metadata, transfer fee, top-10 concentration), DEX pairs, ATH/ATL for listed coins, and every social/explorer link. Fused live across DexScreener, pump.fun, GeckoTerminal, GoPlus, Birdeye and CoinGecko.</td></tr>
<tr><td><code>GET /api/oracle/signal</code></td><td><b>Machine-ready.</b> A buy/watch/skip recommendation with confidence and a size factor, per mint or as the top N plays — built for agent polling.</td></tr>
<tr><td><code>GET /api/oracle/batch</code></td><td>Conviction for up to 20 mints at once.</td></tr>
<tr><td><code>GET /api/oracle/backtest</code></td><td>Win rate by tier with Wilson CIs, calibration ladder, Brier, and the edge summary. Filters: <code>period, tier, network</code>.</td></tr>
diff --git a/pages/oracle.html b/pages/oracle.html
index d4348a24a..c620ec3e1 100644
--- a/pages/oracle.html
+++ b/pages/oracle.html
@@ -381,6 +381,55 @@
.str-fill { height: 100%; border-radius: 3px; transition: width .5s cubic-bezier(.22,1,.36,1); }
.str-val { font: 700 11px/1 var(--mono); text-align: right; }
+ /* live market intel */
+ .mkt-up { color: var(--up); }
+ .mkt-down { color: var(--down); }
+ .mkt-flat { color: var(--muted); }
+ .mkt-faint { color: var(--faint); }
+ .mkt-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 4px 0 2px; }
+ .mkt-tile { display: flex; flex-direction: column; gap: 4px; padding: 10px 11px; border: 1px solid var(--line);
+ border-radius: 10px; background: rgba(255,255,255,0.025); min-width: 0; }
+ .mkt-tile-lbl { font: 600 9.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .06em; color: var(--faint); }
+ .mkt-tile-val { font: 700 16px/1.1 var(--mono); color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .mkt-tile-sub { font: 600 10.5px/1 var(--mono); color: var(--muted); }
+ .mkt-chg-row { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0 2px; }
+ .mkt-chg { display: inline-flex; align-items: baseline; gap: 5px; padding: 5px 8px; border-radius: 8px;
+ background: rgba(255,255,255,0.04); border: 1px solid var(--line); }
+ .mkt-chg-lbl { font: 600 9.5px/1 var(--mono); text-transform: uppercase; letter-spacing: .05em; color: var(--faint); }
+ .mkt-chg b { font: 700 12px/1 var(--mono); }
+ .mkt-chg.mkt-up b { color: var(--up); } .mkt-chg.mkt-down b { color: var(--down); } .mkt-chg.mkt-flat b { color: var(--muted); }
+ .mkt-row { display: flex; flex-wrap: wrap; gap: 7px; margin: 12px 0 2px; }
+ .mkt-curve { margin: 14px 0 4px; }
+ .mkt-curve-top { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px;
+ font: 600 11px/1 var(--mono); color: var(--muted); }
+ .mkt-curve-top b { color: var(--ink); }
+ .mkt-curve-track { height: 7px; border-radius: 4px; background: rgba(255,255,255,0.07); overflow: hidden; }
+ .mkt-curve-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg, var(--muted), var(--up));
+ transition: width .6s cubic-bezier(.22,1,.36,1); }
+ .mkt-curve-sub { margin-top: 6px; font: 600 10.5px/1 var(--mono); color: var(--faint); }
+ .mkt-act { margin: 14px 0 4px; }
+ .mkt-act-top { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px;
+ font: 600 11px/1 var(--mono); color: var(--muted); }
+ .mkt-act-track { height: 7px; border-radius: 4px; overflow: hidden; background: var(--down); display: flex; }
+ .mkt-act-buy { height: 100%; background: var(--up); transition: width .6s cubic-bezier(.22,1,.36,1); }
+ .mkt-act-legend { display: flex; justify-content: space-between; margin-top: 6px; font: 600 10.5px/1 var(--mono); }
+ .mkt-pairs { display: flex; flex-direction: column; gap: 6px; }
+ .mkt-pair { display: flex; align-items: center; gap: 10px; padding: 8px 11px; border-radius: 9px;
+ background: rgba(255,255,255,0.03); border: 1px solid var(--line); text-decoration: none; transition: background .12s; }
+ .mkt-pair:hover { background: rgba(255,255,255,0.06); }
+ .mkt-pair-dex { flex: 1; min-width: 0; font: 700 12px/1 var(--mono); color: var(--ink); text-transform: capitalize;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .mkt-pair-liq { font: 600 11px/1 var(--mono); color: var(--muted); flex: none; }
+ .mkt-pair-arrow { color: var(--cyan); font-size: 12px; flex: none; }
+ .mkt-src { margin-top: 12px; font: 600 9.5px/1 var(--mono); color: var(--faint); text-transform: capitalize; letter-spacing: .03em; }
+ .mkt-skel { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
+ .mkt-skel span { height: 58px; border-radius: 10px; border: 1px solid var(--line);
+ background: linear-gradient(100deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.03) 70%);
+ background-size: 200% 100%; animation: mktShimmer 1.2s linear infinite; }
+ @keyframes mktShimmer { to { background-position: -200% 0; } }
+ @media (max-width: 420px) { .mkt-stats, .mkt-skel { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+ @media (prefers-reduced-motion: reduce) { .mkt-skel span { animation: none; } }
+
/* live trade tape */
.dr-ptrade { display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;background:var(--surface2,rgba(255,255,255,.04));font-size:13px; }
.dr-ptrade-mult { font:700 13px/1 var(--mono);min-width:52px;flex-shrink:0; }
diff --git a/public/changelog.json b/public/changelog.json
index dd80620de..ac1f96522 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,22 @@
{
- "generated_at": "2026-07-02T05:57:24.614Z",
+ "generated_at": "2026-07-02T07:36:15.624Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "title": "Agents can trade graduated coins from their own wallet",
+ "summary": "When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it — every buy came back \"this coin has graduated, not supported.\" Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling.",
+ "link": "/pulse",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-02",
"type": "update",
@@ -58,6 +69,16 @@
"infra"
]
},
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "title": "Oracle 3D graph is visible again",
+ "summary": "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.",
+ "link": "/oracle",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-07-02",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index d4b4a3b29..326479b68 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Agents can trade graduated coins from their own wallet</title>
+ <link>https://three.ws/pulse</link>
+ <guid isPermaLink="false">2026-07-02:Agents can trade graduated coins from their own wallet</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>When a coin graduates off the pump.fun bonding curve onto its AMM pool, the agent-wallet trade path could still sell it but refused to buy it — every buy came back &quot;this coin has graduated, not supported.&quot; Buys now route through the same canonical AMM pool the sell side already uses, with real slippage protection (a maximum-SOL ceiling enforced on-chain) and the identical spend caps, daily budget, price-impact breaker, and rug/honeypot firewall. This unblocks agents and the platform's autonomous activity engine from buying $THREE and other graduated coins, so trades and marketplace purchases flow again instead of stalling.</description>
+ </item>
<item>
<title>Agora Arena &amp; Guilds: agents race for $THREE, or split the reward together</title>
<link>https://three.ws/agora</link>
@@ -46,6 +54,14 @@
<category>infra</category>
<description>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.</description>
</item>
+ <item>
+ <title>Oracle 3D graph is visible again</title>
+ <link>https://three.ws/oracle</link>
+ <guid isPermaLink="false">2026-07-02:Oracle 3D graph is visible again</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>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 &quot;3D graph&quot; tab.</description>
+ </item>
<item>
<title>Sign-in: fixed a hidden check that could silently block the Sign in button</title>
<link>https://three.ws/login</link>
diff --git a/public/features.json b/public/features.json
index 798721459..36ca532bc 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-02T05:57:24.593Z",
+ "generated_at": "2026-07-02T07:36:15.605Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/oracle-graph.js b/src/oracle-graph.js
index 5f196424c..a801fcd0e 100644
--- a/src/oracle-graph.js
+++ b/src/oracle-graph.js
@@ -9,6 +9,7 @@
import {
AmbientLight,
Color,
+ DirectionalLight,
FogExp2,
Group,
InstancedMesh,
@@ -84,7 +85,16 @@ export function mountOracleGraph(canvas, labelContainer) {
const scene = new Scene();
scene.background = new Color(0x05060c);
scene.fog = new FogExp2(0x05060c, 0.012);
- scene.add(new AmbientLight(0x24262e, 1.2));
+ // Fill + key + rim so the metallic spheres read as 3D from every orbit
+ // angle. The emissive glow (below) carries the tier color and feeds bloom;
+ // these lights give the spheres form so they don't look like flat discs.
+ scene.add(new AmbientLight(0x3a3f4d, 1.6));
+ const keyLight = new DirectionalLight(0xffffff, 1.7);
+ keyLight.position.set(6, 10, 8);
+ scene.add(keyLight);
+ const rimLight = new DirectionalLight(0x8894ff, 0.7);
+ rimLight.position.set(-8, -4, -6);
+ scene.add(rimLight);
const camera = new PerspectiveCamera(50, W() / H(), 0.1, 500);
camera.position.set(0, 0, 55);
@@ -117,7 +127,23 @@ export function mountOracleGraph(canvas, labelContainer) {
const _s = new Vector3();
const geo = new SphereGeometry(1, 12, 8);
- const mat = new MeshStandardMaterial({ roughness: 0.35, metalness: 0.6 });
+ const mat = new MeshStandardMaterial({
+ roughness: 0.4,
+ metalness: 0.15,
+ emissive: 0xffffff,
+ emissiveIntensity: 1.0,
+ });
+ // Drive the emissive channel from each instance's color so every sphere
+ // self-illuminates in its tier color and feeds the bloom pass — this is
+ // what makes the graph visible against the near-black background instead
+ // of a dim, light-starved void. `vColor` carries the per-instance color
+ // whenever USE_INSTANCING_COLOR is defined, which it is once setColorAt runs.
+ mat.onBeforeCompile = (shader) => {
+ shader.fragmentShader = shader.fragmentShader.replace(
+ '#include <emissivemap_fragment>',
+ '#include <emissivemap_fragment>\n\ttotalEmissiveRadiance *= vColor.rgb;',
+ );
+ };
function buildMesh(count) {
imesh?.parent?.remove(imesh);
@@ -170,10 +196,14 @@ export function mountOracleGraph(canvas, labelContainer) {
buildMesh(nodes.length);
buildLabels(nodes);
- // Assign instance colors.
+ // Assign instance colors, scaled by the tier's glow so prime coins burn
+ // brighter than avoid coins. The scaled color drives both the diffuse
+ // tint and the emissive glow (see the material's onBeforeCompile), so a
+ // factor above 1 pushes prime tiers into HDR and blooms harder.
const col = new Color();
nodes.forEach((n, i) => {
- col.setHex(TIER_COLOR[n.tier] ?? 0xffffff);
+ const glow = TIER_GLOW[n.tier] ?? 0.5;
+ col.setHex(TIER_COLOR[n.tier] ?? 0xffffff).multiplyScalar(0.6 + glow * 0.7);
imesh.setColorAt(i, col);
});
imesh.instanceColor.needsUpdate = true;
diff --git a/src/oracle.js b/src/oracle.js
index cfc1769c4..75587f07d 100644
--- a/src/oracle.js
+++ b/src/oracle.js
@@ -43,6 +43,34 @@ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '
const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
const fmtSol = (n) => (n == null ? '—' : `${Number(n) < 0.01 && Number(n) > 0 ? Number(n).toFixed(4) : Number(n).toFixed(2)}◎`);
const fmtPct = (n) => (n == null ? '—' : `${Math.round(Number(n))}%`);
+// Compact USD for market stats: $2.1M, $465K, $1.2B, $0.00.
+function fmtUsd(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ if (abs >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;
+ if (abs >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;
+ if (abs >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;
+ return `$${v.toFixed(2)}`;
+}
+// Token price: keep 3–4 significant figures for sub-cent memecoins.
+function fmtPrice(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ if (v === 0) return '$0';
+ if (v >= 1) return `$${v.toLocaleString(undefined, { maximumFractionDigits: 4 })}`;
+ const decimals = Math.min(12, Math.max(4, 3 - Math.floor(Math.log10(v))));
+ return `$${v.toFixed(decimals)}`;
+}
+const fmtInt = (n) => (n == null || !Number.isFinite(Number(n)) ? '—' : Math.round(Number(n)).toLocaleString());
+// Signed percent with an up/down class — for price-change chips.
+function changeStr(n) {
+ if (n == null || !Number.isFinite(Number(n))) return { txt: '—', cls: 'flat' };
+ const v = Number(n);
+ const cls = v > 0 ? 'up' : v < 0 ? 'down' : 'flat';
+ const txt = `${v > 0 ? '+' : ''}${v.toFixed(v <= -100 || v >= 100 ? 0 : 2)}%`;
+ return { txt, cls };
+}
const tierClass = (t) => `t-${t || 'avoid'}`;
const tierPill = (t) => `tp-${t || 'avoid'}`;
function ago(ts) {
@@ -1639,6 +1667,10 @@ function renderDrawer(d) {
${c.structure_cap != null && c.structure_cap < 60 ? `<span class="note warn">structural cap ${c.structure_cap}</span>` : ''}
</div>
<div id="scoreHistoryWrap" style="margin-top:12px"></div>
+ <div id="marketWrap" class="mkt-loading" aria-busy="true">
+ <div class="dr-sec">Market <span style="color:var(--faint);font-weight:400;font-size:10px">live</span></div>
+ <div class="mkt-skel"><span></span><span></span><span></span><span></span><span></span><span></span></div>
+ </div>
${narr ? `<div class="dr-sec">Narrative</div><div style="font-size:13.5px;color:var(--ink)">${esc(narr.narrative || '')}</div>
<div class="coin-meta" style="margin-top:8px"><span class="chip cat">${esc(narr.category)}</span><span class="chip">virality <b>${narr.virality ?? '—'}</b></span><span class="chip">${esc(narr.source || '')}</span></div>` : ''}
<div class="dr-sec">Why this score</div>${reasons}
@@ -1655,6 +1687,7 @@ function renderDrawer(d) {
// Fetch and render conviction score history sparkline + community sentiment.
loadScoreHistory(c.mint);
+ loadCoinMarket(c.mint);
loadSentimentPulse(c.mint);
loadProofTrades(c.mint);
@@ -1814,6 +1847,164 @@ async function loadScoreHistory(mint) {
wrap.innerHTML = renderSparkline(data.points, data.trend);
}
+// Live market intel — the fully-populated market half of the coin page. Fused
+// server-side across DexScreener / pump.fun / GeckoTerminal / GoPlus / Birdeye /
+// CoinGecko (/api/oracle/market). Lazy so the conviction verdict paints first.
+async function loadCoinMarket(mint) {
+ const wrap = $('#marketWrap');
+ if (!wrap) return;
+ const { ok, status, data } = await api(`/api/oracle/market?mint=${encodeURIComponent(mint)}&network=${NETWORK}`, { timeout: 15000 });
+ if (!$('#marketWrap')) return; // drawer closed mid-fetch
+ wrap.classList.remove('mkt-loading');
+ wrap.removeAttribute('aria-busy');
+ if (!ok || !data || data.price?.usd == null) {
+ // 404 = no live market yet (brand-new mint); anything else = upstreams down.
+ wrap.innerHTML = status === 404
+ ? `<div class="dr-sec">Market</div><div class="state" style="padding:14px 0">No live market yet — this mint hasn't started trading. Price, liquidity and holders appear the moment it does.</div>`
+ : `<div class="dr-sec">Market</div><div class="state" style="padding:14px 0">Live market data is momentarily unavailable. <button type="button" class="dr-act" id="mktRetry" data-mint="${esc(mint)}">Retry</button></div>`;
+ const retry = $('#mktRetry');
+ if (retry) retry.addEventListener('click', () => { wrap.classList.add('mkt-loading'); wrap.setAttribute('aria-busy', 'true'); loadCoinMarket(mint); });
+ return;
+ }
+ wrap.innerHTML = renderMarket(data);
+}
+
+function statTile(label, value, sub = '') {
+ return `<div class="mkt-tile"><span class="mkt-tile-lbl">${esc(label)}</span><span class="mkt-tile-val">${value}</span>${sub ? `<span class="mkt-tile-sub">${sub}</span>` : ''}</div>`;
+}
+function changeChip(label, n) {
+ const c = changeStr(n);
+ return `<span class="mkt-chg mkt-${c.cls}"><span class="mkt-chg-lbl">${esc(label)}</span><b>${c.txt}</b></span>`;
+}
+function secChip(ok, label, warnLabel = null) {
+ if (ok == null) return `<span class="chip" title="not measured">${esc(label)} <b>?</b></span>`;
+ return ok
+ ? `<span class="chip sm" title="safe">✓ ${esc(label)}</span>`
+ : `<span class="chip flag" title="risk">⚠ ${esc(warnLabel || label)}</span>`;
+}
+
+function renderMarket(m) {
+ const p = m.price || {};
+ const ch = p.change || {};
+ const changeH24 = changeStr(ch.h24);
+
+ const tiles = [
+ statTile('Price', fmtPrice(p.usd), `<span class="mkt-${changeH24.cls}">${changeH24.txt} 24h</span>`),
+ statTile('Market cap', fmtUsd(m.market_cap_usd)),
+ m.fdv_usd != null && m.fdv_usd !== m.market_cap_usd ? statTile('FDV', fmtUsd(m.fdv_usd)) : '',
+ statTile('Liquidity', fmtUsd(m.liquidity_usd)),
+ statTile('24h volume', fmtUsd(m.volume?.h24)),
+ statTile('Holders', fmtInt(m.holders)),
+ ].filter(Boolean).join('');
+
+ // Price-change chips across every window we have.
+ const changeWins = [['5m', ch.m5], ['1h', ch.h1], ['6h', ch.h6], ['24h', ch.h24], ['7d', ch.d7]]
+ .filter(([, v]) => v != null);
+ const changeRow = changeWins.length
+ ? `<div class="mkt-chg-row">${changeWins.map(([l, v]) => changeChip(l, v)).join('')}</div>` : '';
+
+ // Bonding-curve progress (un-graduated pump coins) or a graduated badge.
+ const pf = m.pumpfun;
+ let curveHtml = '';
+ if (pf?.is_pump) {
+ if (pf.graduated || pf.complete) {
+ curveHtml = `<div class="mkt-row"><span class="chip sm">Graduated to DEX ✓</span>${pf.ath_market_cap_usd ? `<span class="chip">ATH mcap <b>${fmtUsd(pf.ath_market_cap_usd)}</b></span>` : ''}</div>`;
+ } else if (pf.bonding_curve_pct != null) {
+ const pct = Math.round(pf.bonding_curve_pct);
+ curveHtml = `<div class="mkt-curve">
+ <div class="mkt-curve-top"><span>Bonding curve</span><b>${pct}% to graduation</b></div>
+ <div class="mkt-curve-track"><div class="mkt-curve-fill" style="width:${Math.max(2, Math.min(100, pct))}%"></div></div>
+ ${pf.real_sol_reserves != null ? `<div class="mkt-curve-sub">${pf.real_sol_reserves.toFixed(1)} ◎ in curve${pf.reply_count ? ` · ${fmtInt(pf.reply_count)} replies` : ''}${pf.is_live ? ' · <span class="mkt-up">live now</span>' : ''}</div>` : ''}
+ </div>`;
+ }
+ }
+
+ // 24h buy/sell activity split.
+ const act = m.activity;
+ let activityHtml = '';
+ if (act && act.txns_24h) {
+ const buyPct = Math.round((act.buy_ratio ?? 0.5) * 100);
+ activityHtml = `<div class="mkt-act">
+ <div class="mkt-act-top"><span>24h activity</span><span class="mkt-faint">${fmtInt(act.txns_24h)} txns</span></div>
+ <div class="mkt-act-track"><div class="mkt-act-buy" style="width:${buyPct}%"></div></div>
+ <div class="mkt-act-legend"><span class="mkt-up">${fmtInt(act.buys_24h)} buys</span><span class="mkt-down">${fmtInt(act.sells_24h)} sells</span></div>
+ </div>`;
+ }
+
+ // Supply.
+ const sup = m.supply || {};
+ const supplyChips = [
+ sup.total != null ? `<span class="chip">supply <b>${fmtInt(sup.total)}</b></span>` : '',
+ sup.circulating != null && Math.abs((sup.circulating || 0) - (sup.total || 0)) > (sup.total || 0) * 0.01
+ ? `<span class="chip">circulating <b>${fmtInt(sup.circulating)}</b></span>` : '',
+ m.identity?.created_at ? `<span class="chip" title="First trade / launch">age <b>${ago(m.identity.created_at)}</b></span>` : '',
+ ].filter(Boolean).join('');
+
+ // Security posture.
+ const sec = m.security;
+ const secHtml = sec
+ ? `<div class="dr-sec">Security <span style="color:var(--faint);font-weight:400;font-size:10px">GoPlus</span></div>
+ <div class="coin-meta">
+ ${secChip(sec.mint_authority_revoked, 'Mint revoked', 'Mint authority live')}
+ ${secChip(sec.freeze_authority_revoked, 'Freeze revoked', 'Can freeze')}
+ ${secChip(sec.metadata_mutable === false ? true : (sec.metadata_mutable === true ? false : null), 'Metadata locked', 'Mutable metadata')}
+ ${sec.transfer_fee_pct != null ? (sec.transfer_fee_pct > 0 ? `<span class="chip flag" title="transfer tax">⚠ ${sec.transfer_fee_pct}% fee</span>` : `<span class="chip sm">No transfer fee</span>`) : ''}
+ ${sec.top10_holder_pct != null ? `<span class="chip ${sec.top10_holder_pct > 50 ? 'flag' : ''}" title="Top 10 holder concentration">top 10 <b>${Math.round(sec.top10_holder_pct)}%</b></span>` : ''}
+ ${sec.trusted_token ? '<span class="chip sm" title="GoPlus verified list">Trusted ✓</span>' : ''}
+ </div>` : '';
+
+ // Listing — only for coins CoinGecko tracks (rank / ATH / ATL / categories).
+ const lst = m.listing;
+ let listingHtml = '';
+ if (lst && (lst.market_cap_rank != null || lst.ath_usd != null || (lst.categories && lst.categories.length))) {
+ const athChg = changeStr(lst.ath_change_pct);
+ listingHtml = `<div class="dr-sec">Listed market <span style="color:var(--faint);font-weight:400;font-size:10px">CoinGecko</span></div>
+ <div class="coin-meta">
+ ${lst.market_cap_rank != null ? `<span class="chip">rank <b>#${lst.market_cap_rank}</b></span>` : ''}
+ ${lst.ath_usd != null ? `<span class="chip" title="All-time high (${lst.ath_date ? new Date(lst.ath_date).toLocaleDateString() : ''})">ATH <b>${fmtPrice(lst.ath_usd)}</b> <span class="mkt-${athChg.cls}">${athChg.txt}</span></span>` : ''}
+ ${lst.atl_usd != null ? `<span class="chip" title="All-time low">ATL <b>${fmtPrice(lst.atl_usd)}</b></span>` : ''}
+ </div>
+ ${lst.categories && lst.categories.length ? `<div class="coin-meta" style="margin-top:6px">${lst.categories.slice(0, 5).map((c) => `<span class="chip cat">${esc(c)}</span>`).join('')}</div>` : ''}`;
+ }
+
+ // DEX pairs.
+ const pairs = Array.isArray(m.pairs) ? m.pairs.filter((pr) => pr.url) : [];
+ const pairsHtml = pairs.length
+ ? `<div class="dr-sec">Markets <span style="color:var(--faint);font-weight:400;font-size:10px">${pairs.length} pair${pairs.length > 1 ? 's' : ''}</span></div>
+ <div class="mkt-pairs">${pairs.slice(0, 5).map((pr) => `
+ <a class="mkt-pair" href="${esc(pr.url)}" target="_blank" rel="noopener">
+ <span class="mkt-pair-dex">${esc(pr.dex || 'dex')}${pr.quote_symbol ? ` <span class="mkt-faint">/${esc(pr.quote_symbol)}</span>` : ''}</span>
+ <span class="mkt-pair-liq">${fmtUsd(pr.liquidity_usd)} liq</span>
+ <span class="mkt-pair-arrow">↗</span>
+ </a>`).join('')}</div>` : '';
+
+ // Chart + explorer + social links.
+ const lk = m.links || {};
+ const linkBtns = [
+ lk.dexscreener ? `<a class="dr-act" href="${esc(lk.dexscreener)}" target="_blank" rel="noopener">DexScreener ↗</a>` : '',
+ lk.geckoterminal ? `<a class="dr-act" href="${esc(lk.geckoterminal)}" target="_blank" rel="noopener">GeckoTerminal ↗</a>` : '',
+ lk.birdeye ? `<a class="dr-act" href="${esc(lk.birdeye)}" target="_blank" rel="noopener">Birdeye ↗</a>` : '',
+ lk.website ? `<a class="dr-act" href="${esc(lk.website)}" target="_blank" rel="noopener">Website ↗</a>` : '',
+ lk.twitter ? `<a class="dr-act" href="${esc(lk.twitter)}" target="_blank" rel="noopener">X ↗</a>` : '',
+ lk.telegram ? `<a class="dr-act" href="${esc(lk.telegram)}" target="_blank" rel="noopener">Telegram ↗</a>` : '',
+ ].filter(Boolean).join('');
+
+ const srcNote = Array.isArray(m.sources) && m.sources.length
+ ? `<div class="mkt-src">Live · ${m.sources.map(esc).join(' · ')}</div>` : '';
+
+ return `<div class="dr-sec">Market <span style="color:var(--faint);font-weight:400;font-size:10px">live${p.native_sol ? ` · ${p.native_sol < 0.0001 ? p.native_sol.toExponential(2) : p.native_sol.toFixed(6)} ◎` : ''}</span></div>
+ <div class="mkt-stats">${tiles}</div>
+ ${changeRow}
+ ${curveHtml}
+ ${activityHtml}
+ ${supplyChips ? `<div class="coin-meta" style="margin-top:10px">${supplyChips}</div>` : ''}
+ ${secHtml}
+ ${listingHtml}
+ ${pairsHtml}
+ ${linkBtns ? `<div class="dr-actions" style="margin-top:12px">${linkBtns}</div>` : ''}
+ ${srcNote}`;
+}
+
async function loadSentimentPulse(mint) {
const wrap = $('#communityPulseWrap');
if (!wrap) return;
diff --git a/tests/agent-sniper-amm-exit.test.js b/tests/agent-sniper-amm-exit.test.js
index f6703efb9..5d984048d 100644
--- a/tests/agent-sniper-amm-exit.test.js
+++ b/tests/agent-sniper-amm-exit.test.js
@@ -10,8 +10,10 @@ import BN from 'bn.js';
const mockGetAmmPoolState = vi.fn();
const mockSellBaseInput = vi.fn();
+const mockBuyQuoteInput = vi.fn();
const mockSwapSolanaState = vi.fn();
const mockOfflineSellBaseInput = vi.fn();
+const mockOfflineBuyQuoteInput = vi.fn();
const MOCK_POOL = '9WZDXbs5da3XuBTOBiGHqKkqFGC4j2HJvBQKzXAMsRg';
vi.mock('../api/_lib/pump.js', () => ({
@@ -21,10 +23,14 @@ vi.mock('../api/_lib/pump.js', () => ({
vi.mock('@pump-fun/pump-swap-sdk', () => ({
sellBaseInput: (...a) => mockSellBaseInput(...a),
+ buyQuoteInput: (...a) => mockBuyQuoteInput(...a),
PumpAmmSdk: class {
sellBaseInput(...a) {
return mockOfflineSellBaseInput(...a);
}
+ buyQuoteInput(...a) {
+ return mockOfflineBuyQuoteInput(...a);
+ }
},
OnlinePumpAmmSdk: class {
swapSolanaState(...a) {
@@ -34,7 +40,7 @@ vi.mock('@pump-fun/pump-swap-sdk', () => ({
}));
// Import AFTER mocks are registered.
-const { isGraduated, quoteAmmSell, buildAmmSellInstructions } = await import(
+const { isGraduated, quoteAmmSell, buildAmmSellInstructions, quoteAmmBuy, buildAmmBuyInstructions } = await import(
'../workers/agent-sniper/amm-exit.js'
);
@@ -209,3 +215,132 @@ describe('buildAmmSellInstructions — build the on-chain AMM exit', () => {
).rejects.toMatchObject({ code: 'pool_not_found' });
});
});
+
+describe('quoteAmmBuy — re-quote a graduated coin buy off the AMM', () => {
+ beforeEach(() => {
+ mockGetAmmPoolState.mockReset();
+ mockBuyQuoteInput.mockReset();
+ });
+
+ it('returns expected + min token out, the SOL ceiling, and the pool key', async () => {
+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());
+ // Spend 10_000 lamports; SDK prices 5_000 tokens out and a 10_300 lamport ceiling.
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(5_000), maxQuote: new BN(10_300) });
+
+ const r = await quoteAmmBuy({
+ network: 'mainnet',
+ mint: MINT,
+ quoteAmount: new BN(10_000),
+ slippagePct: 5,
+ });
+
+ expect(r.expectedBaseOut).toBe(5_000n);
+ // 5% slippage → floor = 5000 × (10000−500)/10000 = 4750.
+ expect(r.minBaseOut).toBe(4_750n);
+ expect(r.maxQuoteIn).toBe(10_300n);
+ expect(r.poolKey).toBe(MOCK_POOL);
+ expect(typeof r.priceImpactPct).toBe('number');
+ expect(r.priceImpactPct).toBeGreaterThanOrEqual(0);
+ });
+
+ it('forwards the quote amount, slippage, and live reserves to the SDK', async () => {
+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(50), maxQuote: new BN(105) });
+
+ await quoteAmmBuy({ network: 'mainnet', mint: MINT, quoteAmount: new BN(100), slippagePct: 5 });
+
+ expect(mockBuyQuoteInput).toHaveBeenCalledOnce();
+ const call = mockBuyQuoteInput.mock.calls[0][0];
+ expect(call.quote.toString()).toBe('100');
+ expect(call.slippage).toBe(5);
+ expect(call.baseReserve.toString()).toBe('1000000000');
+ expect(call.quoteReserve.toString()).toBe('1000000000');
+ expect(call.globalConfig).toEqual({ mock: true });
+ });
+
+ it('computes a non-trivial price impact for a buy that moves the pool', async () => {
+ // baseReserve=1e6, quoteReserve=1e6, spend 100_000 quote, get 90_000 base.
+ // spot value = 100_000 × (1e6/1e6) = 100_000; impact = (100k−90k)/100k = 10%.
+ mockGetAmmPoolState.mockResolvedValueOnce(
+ poolState({ baseReserve: 1_000_000, quoteReserve: 1_000_000 }),
+ );
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(90_000), maxQuote: new BN(105_000) });
+
+ const r = await quoteAmmBuy({
+ network: 'mainnet',
+ mint: MINT,
+ quoteAmount: new BN(100_000),
+ slippagePct: 5,
+ });
+ expect(r.priceImpactPct).toBeCloseTo(10, 5);
+ });
+
+ it('falls back to the spent amount as the ceiling when the SDK omits maxQuote', async () => {
+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(5_000) });
+ const r = await quoteAmmBuy({ network: 'mainnet', mint: MINT, quoteAmount: new BN(10_000), slippagePct: 5 });
+ expect(r.maxQuoteIn).toBe(10_000n);
+ });
+
+ it('propagates pool_not_found so callers know the coin is still on the curve', async () => {
+ mockGetAmmPoolState.mockRejectedValueOnce(poolNotFound());
+ await expect(
+ quoteAmmBuy({ network: 'mainnet', mint: MINT, quoteAmount: new BN(1), slippagePct: 5 }),
+ ).rejects.toMatchObject({ code: 'pool_not_found' });
+ });
+
+ it('refuses a non-SOL-quoted pool (this path trades in lamports)', async () => {
+ mockGetAmmPoolState.mockResolvedValueOnce(poolState({ quoteMint: USDC }));
+ await expect(
+ quoteAmmBuy({ network: 'mainnet', mint: MINT, quoteAmount: new BN(1), slippagePct: 5 }),
+ ).rejects.toMatchObject({ code: 'amm_quote_not_sol' });
+ });
+});
+
+describe('buildAmmBuyInstructions — build the on-chain AMM entry', () => {
+ beforeEach(() => {
+ mockGetAmmPoolState.mockReset();
+ mockBuyQuoteInput.mockReset();
+ mockSwapSolanaState.mockReset();
+ mockOfflineBuyQuoteInput.mockReset();
+ });
+
+ it('builds instructions via swapSolanaState + offline buyQuoteInput and surfaces the quote', async () => {
+ mockGetAmmPoolState.mockResolvedValue(poolState());
+ mockBuyQuoteInput.mockReturnValue({ base: new BN(5_000), maxQuote: new BN(10_300) });
+ mockSwapSolanaState.mockResolvedValueOnce({ pool: {} });
+ const fakeIxs = [{ programId: 'buy1' }, { programId: 'buy2' }];
+ mockOfflineBuyQuoteInput.mockResolvedValueOnce(fakeIxs);
+
+ const r = await buildAmmBuyInstructions({
+ network: 'mainnet',
+ mint: MINT,
+ user: { toBase58: () => 'user' },
+ quoteAmount: new BN(10_000),
+ slippagePct: 5,
+ });
+
+ expect(r.instructions).toBe(fakeIxs);
+ expect(r.expectedBaseOut).toBe(5_000n);
+ expect(r.minBaseOut).toBe(4_750n);
+ expect(r.maxQuoteIn).toBe(10_300n);
+ expect(r.poolKey).toBe(MOCK_POOL);
+ expect(mockOfflineBuyQuoteInput).toHaveBeenCalledOnce();
+ const offCall = mockOfflineBuyQuoteInput.mock.calls[0];
+ expect(offCall[1].toString()).toBe('10000');
+ expect(offCall[2]).toBe(5);
+ });
+
+ it('propagates pool_not_found (cannot build against a curve that has not graduated)', async () => {
+ mockGetAmmPoolState.mockRejectedValueOnce(poolNotFound());
+ await expect(
+ buildAmmBuyInstructions({
+ network: 'mainnet',
+ mint: MINT,
+ user: { toBase58: () => 'user' },
+ quoteAmount: new BN(1),
+ slippagePct: 5,
+ }),
+ ).rejects.toMatchObject({ code: 'pool_not_found' });
+ });
+});
diff --git a/tests/api/oracle-market.test.js b/tests/api/oracle-market.test.js
new file mode 100644
index 000000000..cbde75069
--- /dev/null
+++ b/tests/api/oracle-market.test.js
@@ -0,0 +1,163 @@
+// Unit tests for the Oracle live-market aggregator (api/_lib/oracle/market.js).
+// mergeMarketSources is pure (no network/clock), so it's tested directly against
+// fixtures; fetchCoinMarket is exercised with a URL-routing fetch mock so no
+// network is touched and per-source failover / precedence is verified.
+//
+// Mints used are $THREE (the platform's own promoted coin) and a clearly
+// synthetic non-pump address — never a real third-party mint.
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mergeMarketSources, fetchCoinMarket, __resetCoinMarketCache } from '../../api/_lib/oracle/market.js';
+
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const SYNTH = 'SoMeSyntheticNonPumpMint1111111111111111111';
+const AT = '2026-07-02T00:00:00.000Z';
+
+const realFetch = global.fetch;
+afterAll(() => { global.fetch = realFetch; });
+
+describe('mergeMarketSources', () => {
+ it('fuses fields with source precedence (Dex price/change, Gecko supply, GoPlus security, CG listing, pump curve)', () => {
+ const dex = {
+ sources: ['dexscreener'],
+ identity: { name: 'three.ws', symbol: 'three', image: 'dex.png' },
+ price_usd: 0.0021, price_native: 0.000027,
+ change: { m5: -1, h1: -3, h6: -2, h24: 5 },
+ volume: { m5: 10, h1: 100, h6: 1000, h24: 465000 },
+ txns: { h24: { buys: 20, sells: 5 } },
+ liquidity_usd: 223000, market_cap_usd: 2100000, fdv_usd: 2100000,
+ links: { website: 'https://three.ws/', twitter: 'https://x.com/trythreews', telegram: null },
+ pairs: [{ dex: 'pumpswap', url: 'https://dexscreener.com/solana/x', liquidity_usd: 223000 }],
+ };
+ const pump = {
+ sources: ['pumpfun'], identity: { name: 'three.ws', symbol: 'three', description: 'give your ai model a life' },
+ links: { website: 'https://three.ws/', twitter: 'https://x.com/launch/status/1', telegram: null },
+ creator: 'CreatorWallet', created_at: '2026-04-29T05:41:49.000Z', supply_total: 1_000_000_000,
+ pumpfun: { is_pump: true, complete: true, graduated: true, bonding_curve_pct: 100, ath_market_cap_usd: 16_000_000 },
+ };
+ const gecko = {
+ sources: ['geckoterminal'], identity: { decimals: 6 },
+ price_usd: 0.00211, market_cap_usd: 2_105_000, fdv_usd: 2_105_000,
+ volume: { h24: 769000 }, liquidity_usd: 158000, supply_total: 999_687_956, coingecko_id: 'three-ws',
+ };
+ const goplus = {
+ sources: ['goplus'], holders: 12943, supply_total: 999_688_101,
+ security: { mint_authority_revoked: true, freeze_authority_revoked: true, metadata_mutable: false, transfer_fee_pct: 0, top10_holder_pct: 17.34, source: 'goplus' },
+ top_holders: [{ account: 'poolAcct', pct: 3.37, is_locked: false, tag: null }],
+ };
+ const birdeye = { sources: ['birdeye'], price_usd: 0.0020, holders: 12000, supply_circulating: 999_000_000 };
+ const coingecko = { sources: ['coingecko'], listing: { coingecko_id: 'three-ws', market_cap_rank: 2181, categories: ['AI'], ath_usd: 0.0149, ath_change_pct: -85, atl_usd: 0.00005 } };
+
+ const m = mergeMarketSources(THREE, 'mainnet', { dex, pump, gecko, goplus, birdeye, coingecko }, AT);
+
+ // Price + native from DexScreener (highest precedence), not Birdeye/Gecko.
+ expect(m.price.usd).toBe(0.0021);
+ expect(m.price.native_sol).toBe(0.000027);
+ // Every change window threads through.
+ expect(m.price.change).toMatchObject({ m5: -1, h1: -3, h6: -2, h24: 5 });
+ // Market cap/liquidity/volume from richest source.
+ expect(m.market_cap_usd).toBe(2100000);
+ expect(m.liquidity_usd).toBe(223000);
+ expect(m.volume.h24).toBe(465000);
+ // Supply prefers Gecko's normalized value.
+ expect(m.supply.total).toBe(999_687_956);
+ expect(m.supply.circulating).toBe(999_000_000);
+ // Holders from GoPlus (over Birdeye).
+ expect(m.holders).toBe(12943);
+ // Activity rolled up from Dex txns.
+ expect(m.activity.buys_24h).toBe(20);
+ expect(m.activity.txns_24h).toBe(25);
+ expect(m.activity.buy_ratio).toBeCloseTo(0.8, 5);
+ // Security from GoPlus.
+ expect(m.security.mint_authority_revoked).toBe(true);
+ expect(m.security.top10_holder_pct).toBe(17.34);
+ // Listing from CoinGecko.
+ expect(m.listing.market_cap_rank).toBe(2181);
+ expect(m.listing.ath_usd).toBe(0.0149);
+ // pump.fun graduated truth.
+ expect(m.pumpfun.graduated).toBe(true);
+ expect(m.pumpfun.bonding_curve_pct).toBe(100);
+ // Links: DexScreener's curated handle wins over pump's launch-tweet URL.
+ expect(m.links.twitter).toBe('https://x.com/trythreews');
+ expect(m.links.solscan).toContain(THREE);
+ // Identity name/description fused across sources.
+ expect(m.identity.name).toBe('three.ws');
+ expect(m.identity.description).toContain('give your ai model');
+ expect(m.identity.creator).toBe('CreatorWallet');
+ expect(m.sources).toEqual(expect.arrayContaining(['dexscreener', 'pumpfun', 'geckoterminal', 'goplus', 'coingecko']));
+ });
+
+ it('degrades gracefully when only one source is present', () => {
+ const dex = { sources: ['dexscreener'], identity: { symbol: 'X' }, price_usd: 0.5, change: {}, volume: {}, pairs: [], links: {} };
+ const m = mergeMarketSources(SYNTH, 'mainnet', { dex, pump: null, gecko: null, goplus: null, birdeye: null, coingecko: null }, AT);
+ expect(m.price.usd).toBe(0.5);
+ expect(m.holders).toBeNull();
+ expect(m.security).toBeNull();
+ expect(m.listing).toBeNull();
+ // Non-pump synthetic mint → no pumpfun block fabricated.
+ expect(m.pumpfun).toBeNull();
+ expect(m.links.dexscreener).toContain(SYNTH);
+ });
+
+ it('marks a *pump mint as a pump coin even without a pump.fun read', () => {
+ const dex = { sources: ['dexscreener'], identity: {}, price_usd: 1, change: {}, volume: {}, pairs: [], links: {} };
+ const m = mergeMarketSources(THREE, 'mainnet', { dex, pump: null, gecko: null, goplus: null, birdeye: null, coingecko: null }, AT);
+ expect(m.pumpfun).toMatchObject({ is_pump: true });
+ });
+});
+
+// ── fetchCoinMarket: URL-routing fetch mock ──────────────────────────────────
+
+function jres(obj, ok = true, status = 200) {
+ return { ok, status, json: async () => obj, text: async () => JSON.stringify(obj) };
+}
+
+describe('fetchCoinMarket', () => {
+ beforeEach(() => { __resetCoinMarketCache(); process.env.BIRDEYE_API_KEY = 'test-key'; });
+
+ it('fuses live sources and only calls CoinGecko once Gecko proves a listing', async () => {
+ const cgCalls = [];
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('dexscreener.com')) return jres({ pairs: [{ chainId: 'solana', dexId: 'pumpswap', url: 'https://d/x', pairAddress: 'P', baseToken: { name: 'three.ws', symbol: 'three' }, quoteToken: { symbol: 'SOL' }, priceUsd: '0.0021', priceNative: '0.000027', priceChange: { h24: 3 }, volume: { h24: 465000 }, txns: { h24: { buys: 20, sells: 5 } }, liquidity: { usd: 223000 }, marketCap: 2100000, fdv: 2100000, info: { imageUrl: 'i.png', socials: [{ type: 'twitter', url: 'https://x.com/trythreews' }], websites: [{ url: 'https://three.ws/' }] } }] });
+ if (u.includes('frontend-api-v3.pump.fun')) return jres({ mint: THREE, name: 'three.ws', symbol: 'three', complete: true, total_supply: 1_000_000_000_000_000, real_token_reserves: 0, creator: 'C', created_timestamp: 1777441309000, ath_market_cap: 16_000_000 });
+ if (u.includes('geckoterminal.com')) return jres({ data: { attributes: { decimals: 6, coingecko_coin_id: 'three-ws', normalized_total_supply: '999687956', price_usd: '0.00211', market_cap_usd: '2105000', fdv_usd: '2105000', volume_usd: { h24: '769000' }, total_reserve_in_usd: '158000' } } });
+ if (u.includes('gopluslabs.io')) return jres({ result: { [THREE]: { holder_count: 12943, total_supply: 999688101, mintable: { status: '0' }, freezable: { status: '0' }, metadata_mutable: { status: '0' }, transfer_fee: {}, holders: [{ account: 'a', percent: '0.05' }, { account: 'b', percent: '0.03' }] } } });
+ if (u.includes('birdeye.so')) return jres({ data: { price: 0.002, holder: 12000, supply: 1_000_000_000, mc: 2_000_000, v24hUSD: 460000, liquidity: 220000 } });
+ if (u.includes('api.coingecko.com')) { cgCalls.push(u); return jres({ id: 'three-ws', market_cap_rank: 2181, categories: ['AI'], market_data: { ath: { usd: 0.0149 }, ath_change_percentage: { usd: -85 }, atl: { usd: 0.00005 }, circulating_supply: 999000000 } }); }
+ throw new Error(`unexpected url ${u}`);
+ });
+
+ const m = await fetchCoinMarket(THREE, 'mainnet', { fresh: true });
+ expect(m.price.usd).toBe(0.0021);
+ expect(m.holders).toBe(12943);
+ expect(m.security.mint_authority_revoked).toBe(true);
+ expect(m.pumpfun.graduated).toBe(true);
+ expect(m.listing.market_cap_rank).toBe(2181);
+ expect(cgCalls.length).toBe(1); // called exactly once, gated on the gecko id
+ });
+
+ it('skips CoinGecko when the token is unlisted (no gecko coingecko_id)', async () => {
+ let cgHit = false;
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('dexscreener.com')) return jres({ pairs: [{ chainId: 'solana', dexId: 'raydium', url: 'https://d/y', baseToken: { symbol: 'NEW' }, quoteToken: { symbol: 'SOL' }, priceUsd: '0.001', priceChange: {}, volume: {}, liquidity: { usd: 5000 } }] });
+ if (u.includes('geckoterminal.com')) return jres({ data: { attributes: { decimals: 6, price_usd: '0.001' } } }); // no coingecko_coin_id
+ if (u.includes('gopluslabs.io')) return jres({ result: {} });
+ if (u.includes('birdeye.so')) return jres({ data: {} });
+ if (u.includes('frontend-api-v3.pump.fun')) return jres({}, false, 404);
+ if (u.includes('api.coingecko.com')) { cgHit = true; return jres({}); }
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchCoinMarket(SYNTH, 'mainnet', { fresh: true });
+ expect(m.price.usd).toBe(0.001);
+ expect(cgHit).toBe(false);
+ expect(m.listing).toBeNull();
+ });
+
+ it('returns null when every source is down', async () => {
+ global.fetch = vi.fn(async () => { throw new Error('network down'); });
+ const m = await fetchCoinMarket(SYNTH, 'mainnet', { fresh: true });
+ expect(m).toBeNull();
+ });
+});
diff --git a/tests/secret-box.test.js b/tests/secret-box.test.js
new file mode 100644
index 000000000..8b71cd63f
--- /dev/null
+++ b/tests/secret-box.test.js
@@ -0,0 +1,53 @@
+import { describe, it, expect, beforeAll, afterEach } from 'vitest';
+
+// secret-box freezes IS_PROD at import time; keep the test env non-prod so the
+// JWT_SECRET fallback path (the thing under test) is reachable. walletMasterSecret
+// and env.JWT_SECRET are read live per call, so we can flip keys between calls
+// without re-importing the module.
+const JWT = 'test-jwt-secret-value-1234567890-abcdef_'; // >=32
+const DEDICATED = 'dedicated-wallet-encryption-key-0987654321-XYZ'; // >=32, distinct
+
+beforeAll(() => {
+ process.env.NODE_ENV = 'test';
+ delete process.env.VERCEL_ENV;
+ process.env.JWT_SECRET = JWT;
+});
+
+afterEach(() => {
+ delete process.env.WALLET_ENCRYPTION_KEY;
+});
+
+const load = () => import('../api/_lib/secret-box.js');
+
+describe('secret-box encrypt/decrypt', () => {
+ it('round-trips with a dedicated WALLET_ENCRYPTION_KEY', async () => {
+ const { encryptSecret, decryptSecret } = await load();
+ process.env.WALLET_ENCRYPTION_KEY = DEDICATED;
+ const ct = await encryptSecret('super-secret-plaintext');
+ expect(ct.startsWith('v2:')).toBe(true);
+ expect(await decryptSecret(ct)).toBe('super-secret-plaintext');
+ });
+
+ it('decrypts a JWT_SECRET-keyed v2 record even after a dedicated key is introduced', async () => {
+ const { encryptSecret, decryptSecret } = await load();
+ // (1) Write while only JWT_SECRET exists — the record is keyed by JWT_SECRET.
+ delete process.env.WALLET_ENCRYPTION_KEY;
+ const legacyV2 = await encryptSecret('funds-behind-this-key');
+ expect(legacyV2.startsWith('v2:')).toBe(true);
+ // (2) A dedicated key is later introduced. The primary key no longer matches,
+ // but the fallback to JWT_SECRET must still recover the record.
+ process.env.WALLET_ENCRYPTION_KEY = DEDICATED;
+ expect(await decryptSecret(legacyV2)).toBe('funds-behind-this-key');
+ });
+
+ it('throws (never returns garbage) when no candidate key matches', async () => {
+ const { encryptSecret, decryptSecret } = await load();
+ // Encrypt under an unrelated key, then present neither that key nor JWT_SECRET.
+ process.env.WALLET_ENCRYPTION_KEY = 'unrelated-key-that-will-be-lost-0000000000';
+ const ct = await encryptSecret('unrecoverable');
+ process.env.WALLET_ENCRYPTION_KEY = DEDICATED; // primary mismatch
+ process.env.JWT_SECRET = 'a-different-jwt-secret-value-000000000000'; // fallback mismatch
+ await expect(decryptSecret(ct)).rejects.toBeTruthy();
+ process.env.JWT_SECRET = JWT; // restore for other tests
+ });
+});
diff --git a/workers/agent-sniper/amm-exit.js b/workers/agent-sniper/amm-exit.js
index 02764cb52..672a07c7c 100644
--- a/workers/agent-sniper/amm-exit.js
+++ b/workers/agent-sniper/amm-exit.js
@@ -1,16 +1,20 @@
-// agent-sniper — post-graduation AMM exit.
+// agent-sniper — post-graduation AMM entry + exit.
//
-// When a position's coin graduates off the pump.fun bonding curve onto the
-// canonical pump AMM pool, the bonding-curve sell path (PumpTradeClient
-// quoteForSell / buildSellInstructions) can no longer price or close it. This
-// module re-quotes and builds the sell against the AMM pool instead, so a
-// graduated position still exits on stop-loss / trailing / take-profit /
-// timeout with a real fill — never parked.
+// When a coin graduates off the pump.fun bonding curve onto the canonical pump
+// AMM pool, the bonding-curve trade path (PumpTradeClient quoteForBuy/quoteForSell
+// / build*Instructions) can no longer price or execute against it. This module
+// re-quotes and builds trades against the AMM pool instead:
//
-// It reuses the SAME pool resolution + SDK calls the user-driven sell path uses
-// (api/pump/[action].js → getAmmPoolState + PumpAmmSdk.sellBaseInput), so there
-// is one source of truth for AMM pricing across the platform. All amounts are
-// quote atomics; the sniper trades SOL-quoted curves (require_sol_quote), so the
+// · SELL (quoteAmmSell / buildAmmSellInstructions) — a graduated position still
+// exits on stop-loss / trailing / take-profit / timeout with a real fill.
+// · BUY (quoteAmmBuy / buildAmmBuyInstructions) — a graduated coin is still
+// buyable from an agent's own wallet (the discretionary + circulation trade
+// path), instead of hard-failing with "graduated, not supported".
+//
+// It reuses the SAME pool resolution + SDK calls the user-driven trade path uses
+// (api/pump/[action].js → getAmmPoolState + PumpAmmSdk.{buyQuoteInput,sellBaseInput}),
+// so there is one source of truth for AMM pricing across the platform. All amounts
+// are quote atomics; these paths trade SOL-quoted curves (require_sol_quote), so the
// quote currency on the resolved pool is wSOL and atomics are lamports.
import { getAmmPoolState, getConnection } from '../../api/_lib/pump.js';
@@ -129,6 +133,91 @@ export async function buildAmmSellInstructions({ network, mint, user, baseAmount
return { instructions, poolKey: amm.poolKey.toString(), ...priced };
}
+/**
+ * Re-quote a graduated coin's buy off the AMM pool. Mirrors quoteAmmSell but for
+ * an exact-SOL-in entry (buyQuoteInput): given `quoteAmount` lamports to spend,
+ * returns the expected token base units out, a base-unit min-out floor derived
+ * from slippage, the on-chain SOL ceiling (maxQuote), and a price-impact figure.
+ *
+ * @param {object} p
+ * @param {'mainnet'|'devnet'} p.network
+ * @param {string} p.mint
+ * @param {import('bn.js')} p.quoteAmount lamports (SOL) to spend (BN)
+ * @param {number} p.slippagePct
+ * @returns {Promise<{ poolKey: string, expectedBaseOut: bigint, minBaseOut: bigint, maxQuoteIn: bigint, priceImpactPct: number }>}
+ * @throws {Error} { code: 'pool_not_found' } when the coin has not graduated.
+ */
+export async function quoteAmmBuy({ network, mint, quoteAmount, slippagePct }) {
+ const { amm, sdk } = await resolvePool(network, mint);
+ const priced = priceBuyFromPool(amm, sdk, quoteAmount, slippagePct);
+ return { poolKey: amm.poolKey.toString(), ...priced };
+}
+
+// Price a SOL-in buy against a resolved AMM pool. Mirrors priceSellFromPool: the
+// SDK's slippage protection for a quote-in buy is expressed on the INPUT side as
+// `maxQuote` (the most SOL you'll pay), so the base-unit floor is derived from the
+// slippage percentage for the ledger/guards while the on-chain bound stays maxQuote.
+function priceBuyFromPool(amm, sdk, quoteAmount, slippagePct) {
+ const { pool, baseReserve, quoteReserve, baseMintAccount, globalConfig, feeConfig } = amm;
+
+ const resolvedQuoteMint = pool.quoteMint?.toString?.() ?? WSOL_MINT;
+ if (resolvedQuoteMint !== WSOL_MINT) {
+ const e = new Error(`amm pool quote is ${resolvedQuoteMint}, expected wSOL`);
+ e.code = 'amm_quote_not_sol';
+ throw e;
+ }
+
+ const r = sdk.buyQuoteInput({
+ quote: quoteAmount,
+ slippage: slippagePct,
+ baseReserve,
+ quoteReserve,
+ globalConfig,
+ baseMintAccount,
+ baseMint: pool.baseMint,
+ coinCreator: pool.coinCreator,
+ creator: pool.creator,
+ feeConfig,
+ });
+ const expectedBaseOut = BigInt((r.base ?? 0).toString());
+ const maxQuoteIn = BigInt((r.maxQuote ?? quoteAmount).toString());
+ // Base-unit floor from the slippage tolerance (bps): expected × (1 − slippage).
+ const slippageBps = Math.max(0, Math.min(10000, Math.round(slippagePct * 100)));
+ const minBaseOut = (expectedBaseOut * BigInt(10000 - slippageBps)) / 10000n;
+
+ // SOL in, tokens out → input reserve is quote, output reserve is base.
+ const priceImpactPct = derivePriceImpact(quoteReserve, baseReserve, quoteAmount, expectedBaseOut);
+
+ return { expectedBaseOut, minBaseOut, maxQuoteIn, priceImpactPct };
+}
+
+/**
+ * Build the AMM buy instructions for a graduated coin. Mirrors
+ * buildAmmSellInstructions (swapSolanaState + offline buyQuoteInput, which embeds
+ * the slippage-derived maxQuote SOL ceiling on-chain). Returns the instructions
+ * plus the expected/min token out and the SOL ceiling.
+ *
+ * @param {object} p
+ * @param {'mainnet'|'devnet'} p.network
+ * @param {string} p.mint
+ * @param {import('@solana/web3.js').PublicKey} p.user
+ * @param {import('bn.js')} p.quoteAmount lamports (SOL) to spend (BN)
+ * @param {number} p.slippagePct
+ * @returns {Promise<{ instructions: import('@solana/web3.js').TransactionInstruction[], poolKey: string, expectedBaseOut: bigint, minBaseOut: bigint, maxQuoteIn: bigint, priceImpactPct: number }>}
+ * @throws {Error} { code: 'pool_not_found' } when the coin has not graduated.
+ */
+export async function buildAmmBuyInstructions({ network, mint, user, quoteAmount, slippagePct }) {
+ const { amm, sdk } = await resolvePool(network, mint);
+ const priced = priceBuyFromPool(amm, sdk, quoteAmount, slippagePct);
+
+ const offline = new sdk.PumpAmmSdk();
+ const online = new sdk.OnlinePumpAmmSdk(getConnection({ network }));
+ const swapState = await online.swapSolanaState(amm.poolKey, user);
+ const instructions = await offline.buyQuoteInput(swapState, quoteAmount, slippagePct);
+
+ return { instructions, poolKey: amm.poolKey.toString(), ...priced };
+}
+
// Constant-product price impact for selling `baseIn` into a pool, as a percent
// of the no-impact (spot) value. Clamped to [0, 100]; returns 0 if reserves are
// missing so a quote can't be falsely rejected by the breaker.