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: world service, walk companion, pump dashboard + bonding-curve widget, brand system, alerts

nirholas46ea32654655
diff --git a/.env.example b/.env.example
index 50a89c534..7e5ca4e1d 100644
--- a/.env.example
+++ b/.env.example
@@ -292,6 +292,18 @@ X402_MAX_PER_DAY_ATOMIC=100000000
# POST /api/x402/admin/subscriptions and stored hashed in x402_subscriptions.
INTERNAL_API_KEY=
+# ── multiplayer ↔ API shared secret (presence + world persistence) ─────────
+# One HMAC secret shared between this API and the standalone Colyseus server
+# (multiplayer/). The API mints presence tickets the realm rooms verify, and the
+# server signs world-persistence writes (api/world/[action]) the API verifies.
+# Falls back to HOLDER_PASS_SECRET so a single secret can configure every gate.
+# Generate: openssl rand -base64 32
+MULTIPLAYER_SHARED_SECRET=
+# Base URL the multiplayer server uses to reach the persistence API for durable
+# per-world saves. Defaults to https://three.ws; set to http://localhost:3000 in
+# local dev so room builds persist against your dev API. (multiplayer-side env.)
+WORLD_API_BASE=
+
# ── x402 Offer & Receipt extension (USE-17) ────────────────────────────────
# Signs every 402 offer and every settled-payment receipt so buyers get
# cryptographic proof of the interaction. Verifiers resolve the signer key via
diff --git a/README.md b/README.md
index 1ed1d5bcd..61febfc80 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,12 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
- [Launchpad](#launchpad)
- [The Club](#the-club)
- [Walk & Multiplayer](#walk--multiplayer)
+- [Coin Communities](#coin-communities)
+- [Adventure — Onchain RPG](#adventure--onchain-rpg)
+- [City](#city)
+- [Friends, Presence & Social](#friends-presence--social)
+- [In-Game Economy](#in-game-economy)
+- [Voice Lab & Mocap Studio](#voice-lab--mocap-studio)
- [x402 Payments](#x402-payments)
- [A2A — Agent-to-Agent Protocol](#a2a--agent-to-agent-protocol)
- [Talk Mode & Lip-Sync](#talk-mode--lip-sync)
@@ -282,11 +288,15 @@ If you want to support the project — compute credits, grants, partnerships, or
- Open Graph metadata and oEmbed support for rich social previews when links are shared
- Versioned CDN bundles at `/agent-3d/x.y.z/agent-3d.js`
-**Multi-User 3D**
+**Social & Multiplayer 3D**
+- **Coin Communities** at `/communities` + `/play` — every Solana token gets a live 3D world; pick the same coin and land together, with peer avatars, chat, emotes, voxel building, and a live market-cap screen
+- **Adventure** at `/game` — an authoritative onchain RPG: trainable skills, gathering, combat, banking, mounts, multi-realm world, daily quests, cosmetics shop, player marketplace, and $THREE/gold economy
+- **City** at `/city` — free-roam walkable 3D city scene
+- **Friends, presence & DMs** — account-level social graph with live presence ("Online · Mainland"), direct messages, and a per-account realtime delivery hub
- **The Club** at `/club` — multiplayer venue with rigged dancers, audio tracks, tips, leaderboard, payouts cron, perf-aware renderer that auto-downgrades on slow frames
- **Walk** at `/walk` — authoritative multiplayer walk scene backed by a Colyseus server in `multiplayer/` (deployable on Fly.io)
-- **Pose Studio** at `/pose-studio` — author and export reusable avatar poses
+- **Pose Studio** at `/pose-studio`, **Voice Lab** at `/voice`, **Mocap Studio** at `/mocap-studio` — author poses, bind voices, and capture/retarget motion into reusable clips
**Backend & Integrations**
@@ -323,11 +333,14 @@ A map of every user-facing route. Full detail (source files, feature description
| **Profile** | `/profile`, `/u/[username]`, `/avatars/[id]` | User and avatar public pages — SNS badge + pay-by-name modal when `[username].threews.sol` is claimed |
| **SNS Subdomain** | `/threews/claim` | Mint `[label].threews.sol`, set the URL record to your showcase, transfer ownership — single tx, platform pays |
| **Dashboard** | `/dashboard`, `/dashboard/actions`, `/dashboard/wallets`, `/dashboard/usage`, `/dashboard/x402` | Account management, settings, and x402 receipts/payouts |
-| **Studio / Tools** | `/studio`, `/embed-editor`, `/pose-studio`, `/hydrate`, `/validation`, `/strategy-lab` | Widget Studio, WYSIWYG embed editor, pose authoring, on-chain import, glTF validator, DCA |
+| **Studio / Tools** | `/studio`, `/embed-editor`, `/pose-studio`, `/voice`, `/mocap-studio`, `/hydrate`, `/validation`, `/strategy-lab` | Widget Studio, WYSIWYG embed editor, pose authoring, Voice Lab, Mocap Studio, on-chain import, glTF validator, DCA |
| **Widgets** | `/widgets`, `/w/[id]` | Widget gallery and public widget pages (OG + oEmbed) |
| **Launchpad** | `/launchpad`, `/p/[slug]` | Launchpad Studio + hosted launch pages (token, agent, drop campaigns) |
| **Club** | `/club` | Multiplayer 3D venue — tips, leaderboard, audio tracks, perf-aware renderer |
| **Walk** | `/walk` | Authoritative multiplayer walk scene (Colyseus on Fly.io) |
+| **Coin Communities** | `/communities`, `/communities/[mint]`, `/worlds`, `/play` | Live 3D world per Solana token — lobby, coin profile, and the shared coin-keyed world |
+| **Adventure** | `/game` | Onchain RPG — skills, gathering, combat, quests, cosmetics, player marketplace, $THREE/gold economy |
+| **City** | `/city` | Free-roam walkable 3D city scene |
| **Bazaar (x402)** | `/x402`, `/x402-discover`, `/x402-pay` | Paid-API marketplace, discovery, Stripe-style checkout |
| **Artifacts** | `/artifact`, `/artifact/snippet`, `/artifact-example` | Claude Artifact viewer |
| **Solana / DeFi** | `/pumpfun`, `/pump-visualizer`, `/vanity-wallet` | pump.fun launcher, live token visualizer, WASM vanity grinder |
@@ -788,14 +801,14 @@ For sandboxed iframes use the widget embed path instead — it runs in its own b
## Project Structure
-- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`).
-- `api/`: Vercel serverless functions that form the backend API. Subdirectories include `x402/`, `a2a/`, `club/`, `pump/`, `persona/`, `news/`, `admin/`, `agents/`, `auth/`, `oauth/`, `cron/`.
+- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`). Social/gameplay surfaces live in `game/` (Coin Communities + Adventure RPG: `coincommunities*`, `iso-game*`, `game-hud`, `spin-wheel-ui`, `cosmetics-visual`, `avatar-rig`), `city/` (the `/city` world), `social/` (sentiment, X-post impact), `community/` (coin lobby/town), plus `friends.js`, `communities.js`, `marketplace*.js`, and `token-pay.js`.
+- `api/`: Vercel serverless functions that form the backend API. Subdirectories include `x402/`, `a2a/`, `club/`, `pump/`, `persona/`, `news/`, `admin/`, `agents/`, `auth/`, `oauth/`, `cron/`, plus the social/game surfaces `play/`, `token/`, `three-token/`, `friends/`, `social/`, `community/`, `marketplace/`, and `mocap/`.
- `public/`: Static assets and various sub-applications (`club/`, `seeker/`, `news/`, `persona/`, `vanity-wallet.html`, `pumpfun.html`).
- `chat/`: A standalone Svelte application for the chat interface.
- `character-studio/`: A sub-project for in-browser character creation; also serves the rebranded **Avatar Studio** marketplace.
- `rider/`: A-Frame WebVR music visualization experiment.
- `contracts/`: Solidity smart contracts for on-chain identity (ERC-8004) and the multichain payment factory.
-- `multiplayer/`: Colyseus WebSocket server for `/walk` and other realtime rooms; deployable on Fly.io.
+- `multiplayer/`: Colyseus WebSocket server for `/walk`, `/play` (WalkRoom), and `/game` (GameRoom); deployable on Fly.io. Holds the authoritative game logic and single sources of truth — `items.js`, `quests.js`, `cosmetics.js`, `spin-wheel.js`, `marketplaceStore.js`, `playerStore.js`, `realms.js`, `game-token.js`, `play-pass.js`, `holder-pass.js`, and the per-account `social-hub.js`.
- `sdk/`: `@nirholas/agent-kit` and the Avatar SDK (`sdk/agent-sdk/`).
- `agent-payments-sdk/`: EVM agent payments SDK (Base / BSC / other EVM chains).
- `solana-agent-sdk/`: SDK for Solana blockchain interactions (Metaplex Core mints, SIWS, attestations).
@@ -1190,7 +1203,105 @@ Vercel doesn't host long-lived WebSockets, so the multiplayer server lives in it
npm run dev:walk-all # Vite (:3000) + Colyseus (:2567)
```
-**WalkRoom** (`multiplayer/src/rooms/WalkRoom.js`) is the authoritative state container — position, rotation, gesture, presence. Origin allow-listing is enforced at the WS upgrade (`ALLOWED_ORIGINS` env, with `*.vercel.app` and `*.three.ws` always permitted for preview deploys). The same Colyseus server can host additional rooms (DJ-set sync, group dance, drop-events) without redeploying the static site.
+**WalkRoom** (`multiplayer/src/rooms/WalkRoom.js`) is the authoritative state container — position, rotation, gesture, presence. Origin allow-listing is enforced at the WS upgrade (`ALLOWED_ORIGINS` env, with `*.vercel.app` and `*.three.ws` always permitted for preview deploys). The same Colyseus server now hosts a second authoritative room — **GameRoom** (the Adventure RPG, see below) — alongside WalkRoom, plus a per-account **social hub** (`multiplayer/src/social-hub.js`) for presence and live event delivery.
+
+---
+
+## Coin Communities
+
+Every Solana token gets a **live 3D world**. Coin Communities turns a mint address into a shared multiplayer space: pick the same coin as someone else and you land together, walk around, emote, voice-chat, build with voxels, and watch the live market-cap chart on an in-world screen.
+
+| Surface | Route | What it does |
+| ----------------- | --------------------------- | --------------------------------------------------------------------------------------------------- |
+| Lobby | `/communities`, `/worlds` | Browse real pump.fun trending coins + search, pick an avatar, drop into a world |
+| Coin profile | `/communities/[mint]` | Deep-linkable coin page — metadata, bonding-curve price, graduation progress, recent trades |
+| 3D world | `/play` | The shared coin-keyed world — peer avatars, name labels, chat, emotes, voxel building, market screen |
+
+**How it works**
+
+- **Real pump.fun data, no mocks.** The lobby and coin profiles pull live trending coins, search results, bonding-curve pricing, and recent trades from the pump.fun feed.
+- **Bring any avatar.** Use a default, an uploaded GLB/VRM, or paste a model URL. The same rig (`src/game/avatar-rig.js`) drives `/play` and `/game` with no drift.
+- **Realtime presence + chat.** Each coin is its own room. Town chat is backed by the [CoinCommunities](https://coin-communities.xyz) service — reads work out of the box; posting unlocks behind X-OAuth sign-in + a linked wallet. If `CC_API_KEY` is unset, chat renders its designed locked state.
+- **Voxel building & spatial voice.** Collaborative block placement (server-capped) and optional geofenced WebRTC voice (`src/game/voice-chat.js`).
+- **Holder-gated rooms.** A coin can require token holders (tier `holders` vs general); gating is enforced server-side via a sealed play-pass.
+
+**Key files:** `src/communities.js` (lobby), `src/game/coincommunities.js` + `coincommunities-ui.js` (3D scene + HUD), `src/game/community-net.js` (socket bridge), `api/community/*` (worlds, messages, ws-ticket, capabilities, me), `api/_lib/coin-communities.js` (CoinCommunities SDK client).
+
+---
+
+## Adventure — Onchain RPG
+
+`/game` is an authoritative multiplayer RPG. It's a tile-stepped isometric world with trainable skills, gathering, combat, banking, quests, cosmetics, a player-to-player marketplace, and onchain payments — all validated server-side so nothing can be spoofed by the client.
+
+**Core loop**
+
+| System | What it is |
+| -------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| **Skills** | Five trainable skills (combat, woodcutting, mining, fishing, cooking), level 1–99, XP-gated |
+| **Gathering** | Resource nodes (trees, rocks, coal, fishing spots) worked with the right tool; server-authoritative loot rolls |
+| **Inventory** | 6-slot hotbar, 24-slot backpack, 48-slot account bank; stackable resources, non-stackable tools |
+| **Combat & death** | Mobs drop trophies; in danger realms death drops a lootable tombstone (TTL), safe realms preserve inventory |
+| **Cooking** | Raw fish → cooked food at a roast pit; heal value scales with cooking level |
+| **Mounts** | Rare drops (dire wolf, war boar) — non-stackable, rideable for faster travel |
+| **Realms** | Multi-realm world (Mainland, Wilderness, Whisperwood, Pond, Mine, Arena…), each a 48×48 grid with portals and stat gates |
+| **Quests** | An 8-step tutorial + 3 deterministic daily quests per UTC day, with gold/XP/item/badge rewards |
+
+**Wallet-first entry (play-gate).** There's no password. `GET /api/play/nonce` issues a nonce + gate config; `POST /api/play/verify` checks the wallet signature and on-chain token balance, then mints a short-lived HMAC-sealed **play-pass** the game server trusts without re-querying the RPC. Gating is configured via `PLAY_GATE_MINT` / `PLAY_GATE_MIN` and `HOLDER_PASS_SECRET`.
+
+**Server-authoritative.** `multiplayer/src/rooms/GameRoom.js` owns all state; `multiplayer/src/` holds the single sources of truth — `items.js` (item registry, loot tables, mount stats), `quests.js` (tutorial + daily pool + badges), `cosmetics.js` (shop catalog + rotation), `spin-wheel.js`, `marketplaceStore.js`, `playerStore.js`, and `realms.js`/`realm-transfer.js` (layouts, portals, signed stat-gated transfers).
+
+**Client:** `src/game/iso-game.js` (scene), `iso-controls.js` + `keybindings.js` (input), `game-hud.js` (hotbar, skills, quests, bank, shop, marketplace panels), `game-net.js` (socket bridge), `spin-wheel-ui.js`, `cosmetics-visual.js`.
+
+---
+
+## City
+
+`/city` is a free-roam 3D city scene — a walkable urban world with a follow camera, map, and player controller, built on the same Three.js stack as the rest of the platform.
+
+**Key files:** `src/city/city-world.js` (scene + render loop), `city-map.js` (layout), `city-player.js` (movement/controller), `city-camera.js` (follow cam), `city.css`.
+
+---
+
+## Friends, Presence & Social
+
+A full account-level social layer spans the multiplayer surfaces. Friendships are durable; presence is volatile — and both are keyed to the account, not the ephemeral session, so they survive reconnects and realm changes.
+
+| Capability | Backed by |
+| -------------- | --------------------------------------------------------------------------------------------------------------- |
+| **Friends graph** | `POST /api/friends` (request, accept, decline, remove, mute, unmute), `GET /api/friends` (graph + live presence) |
+| **User search** | `GET /api/friends/search?q=` — find accounts by display name, relationship status inline |
+| **Direct messages** | `GET`/`POST /api/friends/messages` — DM threads, live delivery when online + durable queue for offline |
+| **Presence** | Short-lived signed ticket (`GET /api/friends/presence-ticket`) → multiplayer server writes `presence:<uid>` to Redis (75s TTL, 30s heartbeat) |
+| **Live delivery** | The social hub (`multiplayer/src/social-hub.js`) pushes DM + friend events to every open socket for an account |
+
+Friends are stored in Postgres (`friendships`, `direct_messages`, `user_mutes` — see migration `api/_lib/migrations/2026-06-01-friends.sql`); presence lives in Upstash Redis and self-heals if a process dies. Muting is send-side only — a muted account is never told it was muted. The friends panel UI (`src/friends.js`, `src/game/friends-panel.js`) surfaces requests, DM threads, and "Online · Mainland" / "Offline" status inside `/play` and `/game`. The `src/social/` module adds sentiment + X-post-impact scoring used by community surfaces.
+
+---
+
+## In-Game Economy
+
+The game runs on two currencies and a real onchain settlement path.
+
+**Gold (soft currency)** — earned from quests, gathering, and combat; spent in the cosmetics shop and the player marketplace. Used for fee-free trades.
+
+**$THREE (onchain, Solana)** — an SPL token with a server-authoritative **quote → sign → settle** flow (`api/token/*`, `src/token-pay.js`, `api/_lib/token/`). The server issues a purpose-scoped, HMAC-sealed quote (`spin`, `marketplace_sale`); the client signs an atomic split transaction; the server verifies it on-chain (destination + amount + memo) before crediting. Live USD pricing comes from Jupiter (primary, pump.fun-aware) with a Birdeye fallback. The **$THREE protocol** layer (`api/three-token/*`) tracks holder revenue-share, a deploy-to-burn ledger, and an activity feed. Game-server config: `GAME_TOKEN_MINT`, `GAME_TOKEN_TREASURY`, `GAME_TOKEN_BURN`, `GAME_TOKEN_SECRET`.
+
+| Sink | Detail |
+| --------------- | ------------------------------------------------------------------------------------------------------------ |
+| **Cosmetics shop** | ~15-item catalog across five rarity tiers; daily (3) + weekly (2) rotations are seeded and deterministic per UTC day. Cosmetics are visual only — tints, props (`.glb` accessories at head/face anchors), and auras. High-price buys gate behind a two-click confirm. |
+| **Player marketplace** | Peer-to-peer listing board (`multiplayer/src/marketplaceStore.js`). List items or gold; settle in gold (fee-free) or $THREE (95% seller / 5% treasury). Offline sellers receive pending payouts on next login; Redis-persisted across restarts. |
+| **Spin wheel** | A Mainland wheel — one free spin every 12h or a paid spin in $THREE. The outcome is rolled and sealed server-side before the client animates, so the wheel can't be gamed. |
+
+The separate **agent/avatar marketplace** at `/marketplace` (discovery, fork, bookmark, Solana-Pay asset purchase, skill pricing) is documented under [API Reference](#api-reference); the in-game economy above is distinct and lives in the Colyseus rooms.
+
+---
+
+## Voice Lab & Mocap Studio
+
+Two creator tools sit alongside [Pose Studio](#pose-studio):
+
+- **Voice Lab** (`/voice`, `src/voice-lab.js`) — audition and bind voices to an agent, building on the [Voice & Persona Hub](#voice--persona-hub-phase-2).
+- **Mocap Studio** (`/mocap-studio`, `src/mocap-studio.js`, `api/mocap/`) — capture and retarget motion onto a rigged avatar, exporting reusable animation clips.
---
@@ -2311,8 +2422,15 @@ RPC_URL_8453=https://mainnet.base.org
# IPFS pinning
PINATA_JWT=...
WEB3_STORAGE_TOKEN=... # Fallback
+
+# Coin Communities chat (reads work without keys; posting needs these)
+CC_API_KEY=... # read + WebSocket tickets
+CC_SERVER_KEY=... # server-attributed posts (optional)
+CC_SERVER_SECRET=...
```
+> **Multiplayer / game server.** The Colyseus server in `multiplayer/` reads its own config — `PLAY_GATE_MINT` / `PLAY_GATE_MIN` and `HOLDER_PASS_SECRET` for the play-gate, and `GAME_TOKEN_MINT` / `GAME_TOKEN_TREASURY` / `GAME_TOKEN_BURN` / `GAME_TOKEN_SECRET` for the in-game $THREE economy. These belong to the game server's environment, not the Vercel function pool.
+
### Optional (Frontend, prefixed `VITE_`)
```env
diff --git a/api/_lib/migrations/2026-05-04-create-skill-prices.sql b/api/_lib/migrations/2026-05-04-create-skill-prices.sql
deleted file mode 100644
index ea1b17c48..000000000
--- a/api/_lib/migrations/2026-05-04-create-skill-prices.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-CREATE TABLE agent_skill_prices (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
- creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- amount BIGINT NOT NULL,
- currency_mint VARCHAR(44) NOT NULL, -- Solana public key length
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-
- -- A skill should only have one price set by its creator
- UNIQUE (skill_id, creator_id)
-);
-
--- Create an index for efficient price lookups by skill
-CREATE INDEX idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);
-
--- Optional: Trigger to auto-update updated_at timestamp
-CREATE TRIGGER set_timestamp
-BEFORE UPDATE ON agent_skill_prices
-FOR EACH ROW
-EXECUTE PROCEDURE trigger_set_timestamp();
diff --git a/api/_lib/migrations/2026-06-01-pump-alerts.sql b/api/_lib/migrations/2026-06-01-pump-alerts.sql
new file mode 100644
index 000000000..fedb0a324
--- /dev/null
+++ b/api/_lib/migrations/2026-06-01-pump-alerts.sql
@@ -0,0 +1,47 @@
+-- Pump dashboard: server-side alert configuration + delivery, and a real
+-- heartbeat the pumpfun-monitor cron writes so /api/healthz can report live
+-- bot status instead of a hardcoded constant.
+--
+-- Idempotent: safe to re-run.
+
+-- ── Per-user alert rules ────────────────────────────────────────────────────
+-- One row per user. Edited via PUT /api/alerts/config; evaluated server-side by
+-- the pumpfun-monitor cron so alerts fire even when no dashboard tab is open.
+create table if not exists user_alert_configs (
+ user_id uuid primary key references users(id) on delete cascade,
+ graduation boolean not null default true,
+ whale boolean not null default false,
+ fees boolean not null default false,
+ launch boolean not null default false,
+ whale_threshold numeric not null default 10, -- SOL
+ claim_threshold numeric not null default 0.5, -- SOL
+ cooldown_seconds integer not null default 30,
+ webhook_url text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- ── Cooldown tracker ────────────────────────────────────────────────────────
+-- Per (user, rule_type) last-fired timestamp. The evaluator skips delivery when
+-- now() - last_fired_at < cooldown_seconds, so a busy feed can't spam a user.
+create table if not exists user_alert_fires (
+ user_id uuid not null references users(id) on delete cascade,
+ rule_type text not null,
+ last_fired_at timestamptz not null default now(),
+ last_event_id text,
+ primary key (user_id, rule_type)
+);
+
+-- ── Bot heartbeat ───────────────────────────────────────────────────────────
+-- The pumpfun-monitor cron upserts its row each run. /api/healthz reads the
+-- freshest row to report monitor.running / monitor.mode for real.
+create table if not exists bot_heartbeat (
+ worker text primary key,
+ mode text not null default 'cron',
+ last_beat_at timestamptz not null default now(),
+ meta jsonb not null default '{}'::jsonb
+);
+
+create index if not exists user_alert_configs_enabled
+ on user_alert_configs (user_id)
+ where graduation or whale or fees or launch;
diff --git a/api/_lib/migrations/2026-06-01-world-docs.sql b/api/_lib/migrations/2026-06-01-world-docs.sql
new file mode 100644
index 000000000..83fe2ef77
--- /dev/null
+++ b/api/_lib/migrations/2026-06-01-world-docs.sql
@@ -0,0 +1,39 @@
+-- world_docs — generic per-world persistence index (T3 of the 3D-world roadmap).
+--
+-- Stores one durable JSON document per world, keyed by an opaque world id
+-- (a coin mint, a "<mint>#holders" tier key, a realm id, etc.). The building
+-- system (T11/T12) and the creator economy (T21/T24) layer on top of this.
+--
+-- Storage split (mirrors the documented split in api/_lib/world-store.js):
+-- • Small docs live INLINE in `inline_doc` (jsonb) so the common case is a
+-- single indexed round-trip with no object-store hop.
+-- • Large docs (placed-object payloads past the inline cap) are written to R2
+-- at a content-addressed key in `r2_key`; this row is the queryable index +
+-- the optimistic-concurrency gate.
+--
+-- Optimistic concurrency: `etag` is a content hash of the stored bytes. A writer
+-- passes the etag it last read; a conditional UPDATE that no longer matches means
+-- someone else wrote first (HTTP 409). `doc_version` is a monotonic counter for
+-- humans/telemetry.
+
+CREATE TABLE IF NOT EXISTS world_docs (
+ world_id text PRIMARY KEY,
+ schema_version int NOT NULL DEFAULT 1,
+ doc_version bigint NOT NULL DEFAULT 1,
+ etag text NOT NULL,
+ size_bytes int NOT NULL DEFAULT 0,
+ inline_doc jsonb,
+ r2_key text,
+ owner_id text,
+ updated_by text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ -- A row always carries its body exactly one way: inline or offloaded to R2.
+ CONSTRAINT world_docs_body_present CHECK (inline_doc IS NOT NULL OR r2_key IS NOT NULL)
+);
+
+-- "What worlds does this account own?" (permission model, T16/T24).
+CREATE INDEX IF NOT EXISTS world_docs_owner_idx ON world_docs (owner_id) WHERE owner_id IS NOT NULL;
+
+-- "Most recently edited worlds" (activity feeds, admin tooling).
+CREATE INDEX IF NOT EXISTS world_docs_updated_idx ON world_docs (updated_at DESC);
diff --git a/api/_lib/world-service-auth.js b/api/_lib/world-service-auth.js
new file mode 100644
index 000000000..ae6908bb4
--- /dev/null
+++ b/api/_lib/world-service-auth.js
@@ -0,0 +1,35 @@
+// world-service-auth — verify that a world-persistence write came from the
+// authoritative multiplayer server (not a browser forging a service write).
+//
+// The Colyseus server signs a short-lived service token and sends it as
+// `Authorization: Bearer <token>` when it saves a world doc. Format mirrors the
+// presence ticket (api/_lib/presence-store.js) byte-for-byte, with `svc:'world'`
+// marking it as a service principal rather than a user identity:
+//
+// token = base64url(JSON{svc:'world', exp}) + '.' + base64url(HMAC_SHA256(secret, payload))
+// secret = MULTIPLAYER_SHARED_SECRET (→ HOLDER_PASS_SECRET → dev fallback)
+//
+// The signer is multiplayer/src/persistence.js; keep the two in sync.
+
+import { env } from './env.js';
+import { hmacSha256, constantTimeEquals } from './crypto.js';
+
+// Resolve the verified service principal, or null if the token is missing,
+// forged, malformed, or expired. Returns `{ svc: 'world' }` on success so callers
+// can branch on the principal kind.
+export async function verifyWorldServiceToken(token) {
+ if (typeof token !== 'string' || !token.includes('.')) return null;
+ const [payload, sig] = token.split('.');
+ if (!payload || !sig) return null;
+ const expected = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, payload);
+ if (!constantTimeEquals(sig, expected)) return null;
+ let data;
+ try {
+ data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
+ } catch {
+ return null;
+ }
+ if (!data || data.svc !== 'world' || !data.exp) return null;
+ if (data.exp < Math.floor(Date.now() / 1000)) return null;
+ return { svc: 'world' };
+}
diff --git a/api/_lib/world-store.js b/api/_lib/world-store.js
new file mode 100644
index 000000000..a376bed94
--- /dev/null
+++ b/api/_lib/world-store.js
@@ -0,0 +1,314 @@
+// world-store — generic, durable per-world JSON persistence (T3).
+//
+// A "world" is any place that needs to remember its state across room disposal
+// and server restarts: a coin's collaborative build, a realm's mutable layout, a
+// gated world's pass roster. Each world is one JSON document addressed by an
+// opaque `worldId` (e.g. a coin mint, "<mint>#holders", or a realm id).
+//
+// ── Storage split ────────────────────────────────────────────────────────────
+// The roadmap calls for R2 for large blob docs and Postgres for indexed/queried
+// data; this module honours that split per-document by size:
+//
+// • Postgres `world_docs` is ALWAYS the source of truth for the index row —
+// etag, version, owner, timestamps — and is the single linearization point
+// for optimistic concurrency. Small docs are stored inline (`inline_doc`
+// jsonb) so the hot path is one indexed round-trip.
+// • Docs past INLINE_MAX_BYTES are offloaded to R2 at a CONTENT-ADDRESSED key
+// (`worlds/<id>/<etag>.json`). Because the key embeds the content hash,
+// concurrent writers never clobber each other's bytes; the committed index
+// row decides which blob is canonical. The previous blob is GC'd after a
+// successful supersede.
+//
+// ── Optimistic concurrency ───────────────────────────────────────────────────
+// `etag` is a content hash. A writer reads (gets an etag), mutates, and saves
+// with `ifMatch: <that etag>`. If the stored etag has since changed, the
+// conditional commit affects zero rows and we throw ConflictError (HTTP 409).
+// • ifMatch omitted/null → "create": succeeds only if no row exists yet
+// (a concurrent create surfaces as a conflict).
+// • ifMatch === '*' → unconditional overwrite (last-writer-wins).
+//
+// ── Testability ──────────────────────────────────────────────────────────────
+// All storage goes through a tiny BACKEND interface (readRow/readBlob/writeBlob/
+// deleteBlob/upsert/remove). The default backend is Postgres + R2; tests inject
+// an in-memory backend with the same compare-and-set contract. The CAS semantics
+// live in the backend (it's an atomicity concern); the orchestration — size
+// limits, hashing, inline/offload routing, blob GC, conflict mapping — lives in
+// createWorldStore() and is exercised by the unit tests.
+//
+// ── Auth ─────────────────────────────────────────────────────────────────────
+// Reads are public (worlds are shared, visible places). Writes go through
+// canWriteWorld() — the permission hook T16 tightens. The authoritative game
+// server writes as a service principal (always permitted); a browser session
+// writes subject to ownership.
+
+import { sql } from './db.js';
+import { putObject, getObjectBuffer, deleteObject } from './r2.js';
+import { createHash } from 'node:crypto';
+
+export const SCHEMA_VERSION = 1;
+
+// A whole world doc is capped so one save is one bounded write. Placed-object
+// builds at the catalog's per-world object cap serialize well under this.
+export const MAX_DOC_BYTES = 2 * 1024 * 1024; // 2 MB
+// Below this a doc rides inline in Postgres; above it goes to R2.
+export const INLINE_MAX_BYTES = 96 * 1024; // 96 KB
+
+// worldId is used in an R2 object key and a primary key — keep it to a tight,
+// path-safe alphabet (base58 mints, realm slugs, the "#holders" tier suffix).
+const WORLD_ID_RE = /^[A-Za-z0-9:_#.-]{1,128}$/;
+
+export class ConflictError extends Error {
+ constructor(message = 'world changed since last read') {
+ super(message);
+ this.name = 'ConflictError';
+ this.status = 409;
+ this.code = 'world_conflict';
+ }
+}
+
+export class TooLargeError extends Error {
+ constructor(message = 'world document exceeds size limit') {
+ super(message);
+ this.name = 'TooLargeError';
+ this.status = 413;
+ this.code = 'world_too_large';
+ }
+}
+
+export class PermissionError extends Error {
+ constructor(message = 'not permitted to write this world') {
+ super(message);
+ this.name = 'PermissionError';
+ this.status = 403;
+ this.code = 'forbidden';
+ }
+}
+
+export function isValidWorldId(worldId) {
+ return typeof worldId === 'string' && WORLD_ID_RE.test(worldId);
+}
+
+function assertWorldId(worldId) {
+ if (!isValidWorldId(worldId)) {
+ const e = new Error('invalid worldId');
+ e.status = 400;
+ e.code = 'validation_error';
+ throw e;
+ }
+}
+
+// Deterministic bytes for a doc. Stable enough that an unchanged doc hashes the
+// same across saves, so a no-op save keeps the etag steady.
+function serialize(doc) {
+ return Buffer.from(JSON.stringify(doc), 'utf8');
+}
+
+export function etagOf(bytes) {
+ return createHash('sha256').update(bytes).digest('hex').slice(0, 24);
+}
+
+function r2KeyFor(worldId, etag) {
+ // Mints/tier keys can contain ':' and '#'; encode so the key is path-clean.
+ return `worlds/${encodeURIComponent(worldId)}/${etag}.json`;
+}
+
+// Forward-migrate a doc loaded under an older schema. Identity today; this is the
+// seam that keeps old builds loadable when the doc shape evolves.
+export function migrateDoc(doc /* , fromVersion */) {
+ return doc;
+}
+
+// The permission hook. T16 replaces the body with the real model (holder
+// threshold, owner allowlist, open) — keep the signature stable.
+// isService — the request came from the authoritative game server.
+// account — the authenticated user id, or null for anonymous.
+// currentOwner — owner_id on the existing row, or null for a new/unowned world.
+export function canWriteWorld({ isService = false, account = null, currentOwner = null } = {}) {
+ if (isService) return true; // the game server is authoritative
+ if (!account) return false; // anonymous browsers can't write
+ if (!currentOwner) return true; // unclaimed world — first writer may seed it
+ return account === currentOwner; // otherwise owner-only (T16 widens this)
+}
+
+// ── orchestration (storage-agnostic) ─────────────────────────────────────────
+// Build a world store over any backend implementing the contract below.
+export function createWorldStore(backend) {
+ // Load a world's current document, or null if it has never been saved.
+ async function loadWorld(worldId) {
+ assertWorldId(worldId);
+ const row = await backend.readRow(worldId);
+ if (!row) return null;
+
+ let doc;
+ if (row.inline_doc != null) {
+ doc = typeof row.inline_doc === 'string' ? JSON.parse(row.inline_doc) : row.inline_doc;
+ } else {
+ const buf = await backend.readBlob(row.r2_key);
+ doc = JSON.parse(Buffer.from(buf).toString('utf8'));
+ }
+ if (row.schema_version < SCHEMA_VERSION) doc = migrateDoc(doc, row.schema_version);
+
+ return {
+ worldId,
+ schemaVersion: SCHEMA_VERSION,
+ version: Number(row.doc_version),
+ etag: row.etag,
+ size: row.size_bytes,
+ ownerId: row.owner_id ?? null,
+ updatedAt: row.updated_at,
+ doc,
+ };
+ }
+
+ // Persist a world document. Throws TooLargeError or ConflictError.
+ // ifMatch — the etag the caller last read (see concurrency notes above).
+ // writer — the principal recorded as updated_by (account id or 'service').
+ // owner — owner_id to set ON CREATE only; ignored for existing rows.
+ async function saveWorld({ worldId, doc, ifMatch = null, writer = null, owner = null }) {
+ assertWorldId(worldId);
+
+ const bytes = serialize(doc);
+ if (bytes.length > MAX_DOC_BYTES) {
+ throw new TooLargeError(`world document is ${bytes.length} bytes (max ${MAX_DOC_BYTES})`);
+ }
+ const etag = etagOf(bytes);
+ const inline = bytes.length <= INLINE_MAX_BYTES;
+ const r2Key = inline ? null : r2KeyFor(worldId, etag);
+
+ // Look up the prior blob key so we can GC it after a successful supersede.
+ const prior = await backend.readRow(worldId);
+ const priorR2 = prior ? prior.r2_key : null;
+
+ // Offloaded body lands first (content-addressed → no clobber), so the index
+ // row we commit next always points at bytes that already exist.
+ if (!inline) {
+ await backend.writeBlob(r2Key, bytes);
+ }
+
+ const res = await backend.upsert({
+ worldId,
+ schemaVersion: SCHEMA_VERSION,
+ etag,
+ size: bytes.length,
+ inlineDoc: inline ? doc : null,
+ r2Key,
+ owner,
+ writer,
+ ifMatch,
+ });
+
+ if (!res.committed) {
+ // A row exists but the guard failed → someone wrote between read and save.
+ // Drop the orphan blob this losing write may have created.
+ if (!inline && r2Key !== priorR2) {
+ try { await backend.deleteBlob(r2Key); } catch { /* best-effort */ }
+ }
+ throw new ConflictError();
+ }
+
+ // Supersede succeeded — retire the previous distinct blob.
+ if (priorR2 && priorR2 !== r2Key) {
+ try { await backend.deleteBlob(priorR2); } catch { /* best-effort GC */ }
+ }
+
+ return {
+ worldId,
+ schemaVersion: SCHEMA_VERSION,
+ version: Number(res.version),
+ etag: res.etag,
+ size: bytes.length,
+ ownerId: res.ownerId ?? null,
+ updatedAt: res.updatedAt,
+ };
+ }
+
+ // Remove a world entirely (its index row and any offloaded blob).
+ async function deleteWorld(worldId) {
+ assertWorldId(worldId);
+ const r2Key = await backend.remove(worldId);
+ if (r2Key === false) return false;
+ if (r2Key) {
+ try { await backend.deleteBlob(r2Key); } catch { /* best-effort */ }
+ }
+ return true;
+ }
+
+ return { loadWorld, saveWorld, deleteWorld };
+}
+
+// ── default backend: Postgres index + R2 blob ────────────────────────────────
+export const postgresR2Backend = {
+ async readRow(worldId) {
+ const rows = await sql`
+ SELECT world_id, schema_version, doc_version, etag, size_bytes,
+ inline_doc, r2_key, owner_id, updated_at
+ FROM world_docs
+ WHERE world_id = ${worldId}
+ LIMIT 1
+ `;
+ return rows.length ? rows[0] : null;
+ },
+
+ async readBlob(r2Key) {
+ return getObjectBuffer(r2Key);
+ },
+
+ async writeBlob(r2Key, bytes) {
+ await putObject({ key: r2Key, body: bytes, contentType: 'application/json' });
+ },
+
+ async deleteBlob(r2Key) {
+ await deleteObject(r2Key);
+ },
+
+ // Compare-and-set upsert. The WHERE guard on DO UPDATE is the concurrency
+ // gate: '*' overwrites unconditionally; otherwise the stored etag must equal
+ // ifMatch (NULL for a create → never matches an existing row → conflict).
+ async upsert({ worldId, schemaVersion, etag, size, inlineDoc, r2Key, owner, writer, ifMatch }) {
+ const guard = ifMatch === '*' ? sql`TRUE` : sql`world_docs.etag = ${ifMatch}`;
+ const inlineParam = inlineDoc == null ? null : JSON.stringify(inlineDoc);
+ const rows = await sql`
+ INSERT INTO world_docs (
+ world_id, schema_version, doc_version, etag, size_bytes,
+ inline_doc, r2_key, owner_id, updated_by, created_at, updated_at
+ ) VALUES (
+ ${worldId}, ${schemaVersion}, 1, ${etag}, ${size},
+ ${inlineParam}::jsonb, ${r2Key}, ${owner}, ${writer}, now(), now()
+ )
+ ON CONFLICT (world_id) DO UPDATE SET
+ schema_version = ${schemaVersion},
+ doc_version = world_docs.doc_version + 1,
+ etag = EXCLUDED.etag,
+ size_bytes = EXCLUDED.size_bytes,
+ inline_doc = EXCLUDED.inline_doc,
+ r2_key = EXCLUDED.r2_key,
+ updated_by = EXCLUDED.updated_by,
+ updated_at = now()
+ WHERE ${guard}
+ RETURNING doc_version, etag, owner_id, updated_at
+ `;
+ if (!rows.length) return { committed: false };
+ const row = rows[0];
+ return {
+ committed: true,
+ version: Number(row.doc_version),
+ etag: row.etag,
+ ownerId: row.owner_id ?? null,
+ updatedAt: row.updated_at,
+ };
+ },
+
+ async remove(worldId) {
+ const rows = await sql`
+ DELETE FROM world_docs WHERE world_id = ${worldId}
+ RETURNING r2_key
+ `;
+ if (!rows.length) return false;
+ return rows[0].r2_key;
+ },
+};
+
+const defaultStore = createWorldStore(postgresR2Backend);
+export const loadWorld = defaultStore.loadWorld;
+export const saveWorld = defaultStore.saveWorld;
+export const deleteWorld = defaultStore.deleteWorld;
diff --git a/api/agents/_id/pricing/[skill].js b/api/agents/_id/pricing/[skill].js
index d4b310cf7..6b4cc4fb6 100644
--- a/api/agents/_id/pricing/[skill].js
+++ b/api/agents/_id/pricing/[skill].js
@@ -4,6 +4,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib
import { cors, json, method, readJson, wrap, error } from '../../../_lib/http.js';
import { parse } from '../../../_lib/validate.js';
import { limits, clientIp } from '../../../_lib/rate-limit.js';
+import { requireCsrf } from '../../../_lib/csrf.js';
// First char must be alphanumeric; rest may include hyphens; total 1–64 chars.
const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;
@@ -41,6 +42,9 @@ export default wrap(async (req, res) => {
const userId = await resolveUserId(req);
if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+ // CSRF on state-changing session-cookie requests; bearer tokens are exempt.
+ if (!(await requireCsrf(req, res, userId))) return;
+
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
diff --git a/api/agents/featured.js b/api/agents/featured.js
new file mode 100644
index 000000000..2dbb21e2f
--- /dev/null
+++ b/api/agents/featured.js
@@ -0,0 +1,84 @@
+// GET /api/agents/featured
+// -------------------------
+// Public, read-only. Picks ONE real agent to feature on the pump dashboard,
+// chosen deterministically from real data — never a hardcoded id or sample:
+// 1. The public, non-deleted agent with the highest aggregate
+// agent_revenue_events.net_amount over the last 30 days.
+// 2. If no revenue events fall in that window, the most-recently-created
+// public, non-deleted agent.
+// Both rules collapse into a single ORDER BY (net_total DESC, created_at DESC)
+// so a zero-revenue platform still surfaces the newest agent.
+//
+// Returns { data: { id, slug, display_name, bio, avatar_url, detail_url } }
+// or 404 when there are zero eligible agents.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { publicUrl } from '../_lib/r2.js';
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [row] = await sql`
+ WITH revenue AS (
+ SELECT re.agent_id, SUM(re.net_amount)::bigint AS net_total
+ FROM agent_revenue_events re
+ WHERE re.created_at > now() - interval '30 days'
+ GROUP BY re.agent_id
+ )
+ SELECT
+ i.id,
+ i.name,
+ i.description,
+ i.avatar_url,
+ i.profile_image_url,
+ i.home_url,
+ a.thumbnail_key AS avatar_thumbnail_key,
+ a.storage_key AS avatar_storage_key,
+ a.visibility AS avatar_visibility,
+ COALESCE(r.net_total, 0)::bigint AS net_total
+ FROM agent_identities i
+ LEFT JOIN revenue r ON r.agent_id = i.id
+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL
+ WHERE i.deleted_at IS NULL
+ AND i.is_public = true
+ ORDER BY net_total DESC, i.created_at DESC
+ LIMIT 1
+ `;
+
+ if (!row) return error(res, 404, 'no_agents', 'No agents available yet');
+
+ // Prefer an explicitly-set avatar/profile image, then the linked avatar's
+ // public thumbnail. Never substitute a stock placeholder — the client renders
+ // initials when avatar_url is null.
+ const avatarPublic =
+ row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';
+ const avatar_url =
+ row.avatar_url ||
+ row.profile_image_url ||
+ (row.avatar_thumbnail_key ? publicUrl(row.avatar_thumbnail_key) : null) ||
+ (row.avatar_storage_key && avatarPublic ? publicUrl(row.avatar_storage_key) : null) ||
+ null;
+
+ return json(
+ res,
+ 200,
+ {
+ data: {
+ id: row.id,
+ slug: row.id,
+ display_name: row.name,
+ bio: row.description || null,
+ avatar_url,
+ detail_url: row.home_url || `/agent/${row.id}`,
+ net_30d: Number(row.net_total),
+ },
+ },
+ { 'cache-control': 'public, max-age=30, s-maxage=60' },
+ );
+});
diff --git a/api/alerts/config.js b/api/alerts/config.js
new file mode 100644
index 000000000..9f1f12a03
--- /dev/null
+++ b/api/alerts/config.js
@@ -0,0 +1,108 @@
+// GET /api/alerts/config — the signed-in user's pump alert rules.
+// PUT /api/alerts/config — upsert those rules.
+//
+// Server-persisted so alerts survive across devices and so the pumpfun-monitor
+// cron can evaluate them when no dashboard tab is open. The frontend treats
+// localStorage as a render cache only; this endpoint is the source of truth.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { z } from 'zod';
+
+const DEFAULTS = {
+ graduation: true,
+ whale: false,
+ fees: false,
+ launch: false,
+ whaleThreshold: 10,
+ claimThreshold: 0.5,
+ cooldown: 30,
+ webhookUrl: null,
+};
+
+const putSchema = z.object({
+ graduation: z.boolean(),
+ whale: z.boolean(),
+ fees: z.boolean(),
+ launch: z.boolean(),
+ whaleThreshold: z.coerce.number().min(0).max(1_000_000),
+ claimThreshold: z.coerce.number().min(0).max(1_000_000),
+ cooldown: z.coerce.number().int().min(5).max(86_400),
+ webhookUrl: z
+ .string()
+ .trim()
+ .max(2048)
+ .url()
+ .refine((u) => /^https:\/\//i.test(u), 'webhook must be https')
+ .optional()
+ .nullable()
+ .or(z.literal('').transform(() => null)),
+});
+
+function rowToConfig(row) {
+ if (!row) return { ...DEFAULTS };
+ return {
+ graduation: row.graduation,
+ whale: row.whale,
+ fees: row.fees,
+ launch: row.launch,
+ whaleThreshold: Number(row.whale_threshold),
+ claimThreshold: Number(row.claim_threshold),
+ cooldown: row.cooldown_seconds,
+ webhookUrl: row.webhook_url || null,
+ updated_at: row.updated_at || null,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.prefsWrite(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const [row] = await sql`
+ SELECT graduation, whale, fees, launch, whale_threshold, claim_threshold,
+ cooldown_seconds, webhook_url, updated_at
+ FROM user_alert_configs
+ WHERE user_id = ${user.id}
+ `;
+ return json(res, 200, { data: rowToConfig(row) });
+ }
+
+ // PUT — upsert
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const body = parse(putSchema, await readJson(req));
+ const webhook = body.webhookUrl ?? null;
+
+ const [row] = await sql`
+ INSERT INTO user_alert_configs
+ (user_id, graduation, whale, fees, launch, whale_threshold, claim_threshold, cooldown_seconds, webhook_url, updated_at)
+ VALUES
+ (${user.id}, ${body.graduation}, ${body.whale}, ${body.fees}, ${body.launch},
+ ${body.whaleThreshold}, ${body.claimThreshold}, ${body.cooldown}, ${webhook}, now())
+ ON CONFLICT (user_id) DO UPDATE SET
+ graduation = excluded.graduation,
+ whale = excluded.whale,
+ fees = excluded.fees,
+ launch = excluded.launch,
+ whale_threshold = excluded.whale_threshold,
+ claim_threshold = excluded.claim_threshold,
+ cooldown_seconds = excluded.cooldown_seconds,
+ webhook_url = excluded.webhook_url,
+ updated_at = now()
+ RETURNING graduation, whale, fees, launch, whale_threshold, claim_threshold,
+ cooldown_seconds, webhook_url, updated_at
+ `;
+
+ return json(res, 200, { data: rowToConfig(row) });
+});
diff --git a/api/animations/[id].js b/api/animations/[id].js
index b2646234e..84caea61c 100644
--- a/api/animations/[id].js
+++ b/api/animations/[id].js
@@ -10,6 +10,7 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getObjectBuffer, publicUrl } from '../_lib/r2.js';
+import { clipSchema, editorDocSchema, validateClipTrackStrides, materializeClip } from './clips.js';
import { z } from 'zod';
const patchSchema = z.object({
@@ -19,7 +20,13 @@ const patchSchema = z.object({
visibility: z.enum(['private', 'unlisted', 'public']).optional(),
kind: z.enum(['animation', 'loop', 'sequence']).optional(),
loop: z.boolean().optional(),
+ fps: z.number().int().min(1).max(240).nullable().optional(),
avatar_id: z.string().uuid().nullable().optional(),
+ // Re-saving edited keyframes: the studio sends the re-baked clip and the
+ // editable source so reopening stays lossless. Persisted with the same
+ // stride validation + R2 offload as create (POST /api/animations/clips).
+ clip: clipSchema.optional(),
+ editor_doc: editorDocSchema.optional(),
});
export default wrap(async (req, res) => {
@@ -138,6 +145,29 @@ async function handlePatch(req, res, auth, id) {
if (patch.visibility !== undefined) sets.push(sql`visibility = ${patch.visibility}`);
if (patch.kind !== undefined) sets.push(sql`kind = ${patch.kind}`);
if (patch.loop !== undefined) sets.push(sql`loop = ${patch.loop}`);
+ if (patch.fps !== undefined) sets.push(sql`fps = ${patch.fps}`);
+
+ // Re-bake the animation body. Recompute duration/frame_count from the new
+ // clip, re-run stride validation, and offload to R2 (or inline) exactly as
+ // create does — clearing storage_key when the new clip fits inline.
+ if (patch.clip !== undefined) {
+ const strideErr = validateClipTrackStrides(patch.clip);
+ if (strideErr) return error(res, 400, 'validation_error', strideErr);
+ const { inlineClip, storageKey, error: clipErr } = await materializeClip(patch.clip, {
+ userId: auth.userId,
+ slug: id,
+ });
+ if (clipErr) return error(res, 502, 'storage_error', clipErr);
+ sets.push(sql`clip = ${inlineClip}::jsonb`);
+ sets.push(sql`storage_key = ${storageKey}`);
+ sets.push(sql`duration_ms = ${Math.round(patch.clip.duration * 1000)}`);
+ const frameCount =
+ patch.editor_doc?.keyframes?.length || patch.clip.tracks[0]?.times?.length || 0;
+ sets.push(sql`frame_count = ${frameCount}`);
+ }
+ if (patch.editor_doc !== undefined) {
+ sets.push(sql`editor_doc = ${JSON.stringify(patch.editor_doc)}::jsonb`);
+ }
if (patch.avatar_id !== undefined) {
if (patch.avatar_id) {
const ok = await sql`
@@ -196,3 +226,6 @@ async function resolveAuth(req) {
};
return await authenticateBearer(extractBearer(req));
}
+
+// Exported for contract tests (PATCH schema) without a live DB.
+export const __test__ = { patchSchema };
diff --git a/api/animations/clips.js b/api/animations/clips.js
index 1135d9678..7f2fe8e16 100644
--- a/api/animations/clips.js
+++ b/api/animations/clips.js
@@ -29,14 +29,14 @@ const trackSchema = z.object({
times: z.array(z.number()).max(200_000),
values: z.array(z.number()).max(4_000_000),
});
-const clipSchema = z.object({
+export const clipSchema = z.object({
name: z.string().trim().min(1).max(120),
duration: z.number().nonnegative().max(3600),
tracks: z.array(trackSchema).min(1).max(MAX_TRACKS),
});
// The editable keyframe document the studio round-trips (src/pose-animation.js).
-const editorDocSchema = z.object({
+export const editorDocSchema = z.object({
name: z.string().max(120).optional(),
duration: z.number().nonnegative().max(3600),
fps: z.number().int().min(1).max(240).optional(),
@@ -166,13 +166,8 @@ async function handleCreate(req, res, auth) {
const input = parsed.data;
const clip = input.clip;
- // Every quaternion track must carry 4 floats per time sample, position 3.
- for (const t of clip.tracks) {
- const stride = /\.quaternion$/.test(t.name) ? 4 : t.name.endsWith('.position') || t.name.endsWith('.scale') ? 3 : 0;
- if (stride && t.times.length && t.values.length !== t.times.length * stride) {
- return error(res, 400, 'validation_error', `track ${t.name}: values length must be times×${stride}`);
- }
- }
+ const strideErr = validateClipTrackStrides(clip);
+ if (strideErr) return error(res, 400, 'validation_error', strideErr);
if (input.avatar_id) {
const ok = await sql`
@@ -201,19 +196,11 @@ async function handleCreate(req, res, auth) {
const editorJson = input.editor_doc ? JSON.stringify(input.editor_doc) : null;
// Inline small clips as JSONB; offload large ones to R2 and keep the pointer.
- const clipJson = JSON.stringify(clip);
- let inlineClip = clipJson;
- let storageKey = null;
- if (clipJson.length > MAX_BYTES_INLINE) {
- try {
- storageKey = `u/${auth.userId}/animations/clip-${slug}-${Date.now()}.json`;
- await putObject({ key: storageKey, body: clipJson, contentType: 'application/json' });
- inlineClip = null;
- } catch (err) {
- console.error('[animations/clips/create] R2 offload failed', err?.message || err);
- return error(res, 502, 'storage_error', 'Failed to store large clip');
- }
- }
+ const { inlineClip, storageKey, error: clipErr } = await materializeClip(clip, {
+ userId: auth.userId,
+ slug,
+ });
+ if (clipErr) return error(res, 502, 'storage_error', clipErr);
let row;
try {
@@ -279,6 +266,37 @@ async function resolveAuth(req, requiredScope) {
return bearer;
}
+// Every quaternion track must carry 4 floats per time sample, position/scale 3.
+// Returns an error message string when a track is malformed, else null.
+export function validateClipTrackStrides(clip) {
+ for (const t of clip.tracks) {
+ const stride = /\.quaternion$/.test(t.name)
+ ? 4
+ : t.name.endsWith('.position') || t.name.endsWith('.scale')
+ ? 3
+ : 0;
+ if (stride && t.times.length && t.values.length !== t.times.length * stride) {
+ return `track ${t.name}: values length must be times×${stride}`;
+ }
+ }
+ return null;
+}
+
+// Inline small clips as JSONB; offload large ones to R2 and return the pointer.
+// On R2 failure returns { error } so callers can surface a 502 without throwing.
+export async function materializeClip(clip, { userId, slug }) {
+ const clipJson = JSON.stringify(clip);
+ if (clipJson.length <= MAX_BYTES_INLINE) return { inlineClip: clipJson, storageKey: null };
+ const storageKey = `u/${userId}/animations/clip-${slug}-${Date.now()}.json`;
+ try {
+ await putObject({ key: storageKey, body: clipJson, contentType: 'application/json' });
+ return { inlineClip: null, storageKey };
+ } catch (err) {
+ console.error('[animations/clips] R2 offload failed', err?.message || err);
+ return { error: 'Failed to store large clip' };
+ }
+}
+
function autoSlug(name) {
const base = String(name)
.toLowerCase()
diff --git a/api/billing/payout-wallets/index.js b/api/billing/payout-wallets/index.js
index 714aa5de8..947f84322 100644
--- a/api/billing/payout-wallets/index.js
+++ b/api/billing/payout-wallets/index.js
@@ -3,6 +3,7 @@ import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
import { parse, isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { z } from 'zod';
const postBody = z.object({
@@ -32,7 +33,9 @@ export default wrap(async (req, res) => {
return json(res, 200, { wallets });
}
- // POST
+ // POST — CSRF on state-changing session-cookie request.
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const body = parse(postBody, await readJson(req));
const { address, chain, agent_id = null, is_default } = body;
diff --git a/api/community/wallet/unlink.js b/api/community/wallet/unlink.js
new file mode 100644
index 000000000..3de4a5242
--- /dev/null
+++ b/api/community/wallet/unlink.js
@@ -0,0 +1,51 @@
+// POST /api/community/wallet/unlink
+// Unlinks the signed-in user's Solana (svm) wallet(s) so they can link a
+// different one — e.g. when the wallet they linked first doesn't hold the coin
+// and they need to switch to the one that does. Idempotent: succeeds (unlinked:0)
+// when nothing is linked, so the gate's "use a different wallet" path is safe to
+// call from any state.
+import { cors, error, json, method, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const headers = userAuthHeaders(req);
+ if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ const w = await api.getWallets({ headers });
+ if (w.error) {
+ if (w.error.statusCode === 401) {
+ return error(res, 401, 'unauthorized', 'session expired — sign in again');
+ }
+ return error(res, 502, 'upstream_error', w.error.message || 'failed to read wallets');
+ }
+
+ // The holder check reads the first svm wallet, so removing every linked svm
+ // wallet guarantees the next link is the one that gets verified.
+ const svm = (w.data?.wallets ?? []).filter((x) => x.chainType === 'svm' && x.id);
+ for (const wallet of svm) {
+ const { error: delErr } = await api.unlinkWallet({ path: { id: wallet.id }, headers });
+ // 404 — already gone; treat as success and keep going. Anything else is real.
+ if (delErr && delErr.statusCode !== 404) {
+ return error(res, 502, 'unlink_failed', delErr.message || 'failed to unlink wallet');
+ }
+ }
+
+ return json(res, 200, { data: { unlinked: svm.length } });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index ea53f0735..4bd04e0f9 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -47,6 +47,7 @@ import { crawlAgentAttestations } from '../_lib/solana-attestations.js';
import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';
import { sendEmail } from '../_lib/email.js';
+import { fetchSafePublicUrl } from '../_lib/ssrf-guard.js';
// ─── Dispatcher ──────────────────────────────────────────────────────────────
@@ -937,10 +938,22 @@ async function handlePumpfunMonitor(req, res) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
+ // Heartbeat + per-user alert evaluation run on every tick regardless of
+ // attester provisioning, so /api/healthz reports real bot status and the
+ // dashboard's server-side alerts fire even when no tab is open.
+ await writeBotHeartbeat();
+ const alertReport = await evaluateUserAlerts().catch((e) => ({ error: e?.message || String(e) }));
+
if (!process.env.ATTEST_AGENT_SECRET_KEY) {
- // Skip cleanly when the attester key isn't provisioned — returning 503
- // every 3 min would mark the cron job as failing in the dashboard.
- return json(res, 200, { skipped: true, reason: 'attester_not_configured' });
+ // Skip the attestation work cleanly when the attester key isn't
+ // provisioned — returning 503 every 3 min would mark the cron job as
+ // failing in the dashboard. Heartbeat + alerts above already ran.
+ return json(res, 200, {
+ skipped: true,
+ reason: 'attester_not_configured',
+ heartbeat: true,
+ alerts: alertReport,
+ });
}
// Pull the latest stats joined with the agent's Metaplex Core asset and
@@ -1019,9 +1032,148 @@ async function handlePumpfunMonitor(req, res) {
`;
}
+ report.alerts = alertReport;
+ report.heartbeat = true;
return json(res, 200, report);
}
+// ── Bot heartbeat ───────────────────────────────────────────────────────────
+// Records that the monitor ran so /api/healthz can report real bot status.
+// Best-effort: a heartbeat failure must never fail the cron run.
+async function writeBotHeartbeat() {
+ try {
+ await sql`
+ insert into bot_heartbeat (worker, mode, last_beat_at)
+ values ('pumpfun-monitor', 'cron', now())
+ on conflict (worker) do update set last_beat_at = now(), mode = excluded.mode
+ `;
+ } catch (e) {
+ console.error('[pumpfun-monitor] heartbeat failed:', e?.message || e);
+ }
+}
+
+// ── Server-side alert delivery ──────────────────────────────────────────────
+// Evaluates each user's graduation alert rule against the real pumpfun_graduations
+// table and delivers via an in-app notification (user_notifications, type
+// 'pump_alert') plus the per-rule webhook when set. Honors cooldown_seconds and
+// dedupes via user_alert_fires.last_event_id so the same graduation is never
+// delivered twice. Whale / launch / fee rules are evaluated client-side from the
+// live feed for immediate, tab-open feedback; graduation is the persisted,
+// cross-session channel because it's the event type recorded server-side.
+const ALERT_GRADS_PER_RUN = 50;
+const ALERT_DELIVER_CAP = 10;
+
+async function evaluateUserAlerts() {
+ const report = { users: 0, delivered: 0, webhooks: 0, errors: 0 };
+
+ let configs;
+ try {
+ configs = await sql`
+ SELECT user_id, cooldown_seconds, webhook_url
+ FROM user_alert_configs
+ WHERE graduation = true
+ `;
+ } catch (e) {
+ // Table not migrated yet — skip cleanly.
+ return { skipped: 'alert_config_unavailable', detail: e?.message || String(e) };
+ }
+ if (!configs.length) return report;
+
+ const grads = await sql`
+ SELECT tx_signature, mint, name, symbol, amount_sol, market_cap_usd, seen_at
+ FROM pumpfun_graduations
+ WHERE seen_at > now() - interval '15 minutes'
+ ORDER BY seen_at ASC
+ LIMIT ${ALERT_GRADS_PER_RUN}
+ `;
+ if (!grads.length) return report;
+
+ for (const cfg of configs) {
+ report.users++;
+ try {
+ const [fire] = await sql`
+ SELECT last_fired_at, last_event_id FROM user_alert_fires
+ WHERE user_id = ${cfg.user_id} AND rule_type = 'graduation'
+ `;
+
+ // Cooldown gate.
+ if (fire?.last_fired_at) {
+ const sinceMs = Date.now() - new Date(fire.last_fired_at).getTime();
+ if (sinceMs < (cfg.cooldown_seconds || 30) * 1000) continue;
+ }
+
+ // Only graduations newer than the last delivered event.
+ let fresh = grads;
+ if (fire?.last_event_id) {
+ const idx = grads.findIndex((g) => g.tx_signature === fire.last_event_id);
+ if (idx >= 0) fresh = grads.slice(idx + 1);
+ }
+ if (!fresh.length) continue;
+
+ const toDeliver = fresh.slice(-ALERT_DELIVER_CAP);
+ for (const g of toDeliver) {
+ const payload = {
+ kind: 'graduation',
+ mint: g.mint,
+ name: g.name,
+ symbol: g.symbol,
+ amount_sol: g.amount_sol != null ? Number(g.amount_sol) : null,
+ market_cap_usd: g.market_cap_usd != null ? Number(g.market_cap_usd) : null,
+ tx: g.tx_signature,
+ at: g.seen_at,
+ };
+ try {
+ await sql`
+ insert into user_notifications (user_id, type, payload)
+ values (${cfg.user_id}, 'pump_alert', ${JSON.stringify(payload)}::jsonb)
+ `;
+ report.delivered++;
+ } catch {
+ report.errors++;
+ }
+ if (cfg.webhook_url) {
+ const ok = await postAlertWebhook(cfg.webhook_url, payload);
+ if (ok) report.webhooks++;
+ }
+ }
+
+ const latest = toDeliver[toDeliver.length - 1];
+ await sql`
+ insert into user_alert_fires (user_id, rule_type, last_fired_at, last_event_id)
+ values (${cfg.user_id}, 'graduation', now(), ${latest.tx_signature})
+ on conflict (user_id, rule_type) do update set
+ last_fired_at = now(),
+ last_event_id = excluded.last_event_id
+ `;
+ } catch (e) {
+ report.errors++;
+ console.error('[pumpfun-monitor] alert eval failed for user', cfg.user_id, e?.message || e);
+ }
+ }
+
+ return report;
+}
+
+// SSRF-guarded webhook POST. Returns true on a 2xx delivery.
+async function postAlertWebhook(url, payload) {
+ try {
+ const resp = await fetchSafePublicUrl(
+ url,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ type: 'pump_alert', data: payload }),
+ signal: AbortSignal.timeout(8000),
+ },
+ { allowHttp: false },
+ );
+ return resp.ok;
+ } catch (e) {
+ console.error('[pumpfun-monitor] webhook delivery failed:', e?.message || e);
+ return false;
+ }
+}
+
/** Map a single (stats, cursor) row to the attestation events to emit. */
function detectEvents(r) {
const out = [];
diff --git a/api/healthz.js b/api/healthz.js
index 7c26a98c6..f1b527a09 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -15,8 +15,14 @@ const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_ver
const CACHE_TTL_MS = 5 * 60 * 1000;
const RESEND_CACHE_TTL_MS = CACHE_TTL_MS;
+// The pumpfun-monitor cron runs every 3 min and upserts bot_heartbeat. Allow 2×
+// the interval before declaring the worker stopped, so a single skipped tick
+// doesn't flap the status.
+const HEARTBEAT_FRESH_MS = 6 * 60 * 1000;
+const MONITOR_CACHE_TTL_MS = 8 * 1000;
let _resendCache = { value: null, expiresAt: 0 };
let _x402Cache = { value: null, expiresAt: 0 };
+let _monitorCache = { value: null, expiresAt: 0 };
// Exported for tests so each case starts with a cold cache.
export function _resetResendCache() {
@@ -25,6 +31,60 @@ export function _resetResendCache() {
export function _resetX402Cache() {
_x402Cache = { value: null, expiresAt: 0 };
}
+export function _resetMonitorCache() {
+ _monitorCache = { value: null, expiresAt: 0 };
+}
+
+// Real bot/monitor status, sourced from Postgres:
+// running — a bot_heartbeat row written by the pumpfun-monitor cron within
+// the freshness window. When no row exists yet (or the DB is
+// unreachable, e.g. in unit tests) we fall back to the serverless
+// liveness signal: the function answering IS a liveness proof.
+// mode — the worker's reported mode (the cron writes 'cron').
+// claimsDetected — count of real graduation events the monitor has recorded.
+// watches.total — users with at least one alert rule armed (server-side
+// watchers that fire even with no tab open).
+async function probeMonitor() {
+ const now = Date.now();
+ if (_monitorCache.value && _monitorCache.expiresAt > now) return _monitorCache.value;
+
+ let value;
+ try {
+ const { sql } = await import('./_lib/db.js');
+ const [beat] = await sql`
+ SELECT mode, last_beat_at FROM bot_heartbeat
+ ORDER BY last_beat_at DESC LIMIT 1
+ `;
+ const [{ graduations }] = await sql`
+ SELECT count(*)::int AS graduations FROM pumpfun_graduations
+ `;
+ const [{ watches }] = await sql`
+ SELECT count(*)::int AS watches FROM user_alert_configs
+ WHERE graduation OR whale OR fees OR launch
+ `;
+ const beatMs = beat?.last_beat_at ? new Date(beat.last_beat_at).getTime() : 0;
+ const fresh = beatMs > 0 && now - beatMs < HEARTBEAT_FRESH_MS;
+ value = {
+ monitor: {
+ // If a heartbeat row exists, trust its freshness. If none exists yet,
+ // the dedicated worker hasn't reported — report the serverless API's
+ // own liveness rather than a false "stopped".
+ running: beat ? fresh : true,
+ mode: beat?.mode || 'serverless',
+ claimsDetected: graduations,
+ },
+ watches: { total: watches, active: watches },
+ };
+ } catch {
+ value = {
+ monitor: { running: true, mode: 'serverless', claimsDetected: 0 },
+ watches: { total: 0, active: 0 },
+ };
+ }
+
+ _monitorCache = { value, expiresAt: now + MONITOR_CACHE_TTL_MS };
+ return value;
+}
async function probeResend() {
const now = Date.now();
@@ -119,7 +179,11 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
const uptimeMs = Date.now() - STARTED_AT;
- const [resend, x402] = await Promise.all([probeResend(), probeX402()]);
+ const [resend, x402, monitorBlock] = await Promise.all([
+ probeResend(),
+ probeX402(),
+ probeMonitor(),
+ ]);
return json(res, 200, {
status: 'ok',
service: '3d-agent',
@@ -128,9 +192,10 @@ export default wrap(async (req, res) => {
uptimeMs,
resend,
x402,
- // Match the pump-dashboard health shape so the existing UI binding works
- // without conditional logic.
- monitor: { running: true, mode: 'serverless', claimsDetected: 0 },
- watches: { total: 0, active: 0 },
+ // Real bot/monitor status for the pump-dashboard stat cards (see
+ // probeMonitor). Falls back to serverless liveness when no worker
+ // heartbeat exists or the DB is unreachable.
+ monitor: monitorBlock.monitor,
+ watches: monitorBlock.watches,
}, { 'cache-control': 'public, max-age=2, s-maxage=2' });
});
diff --git a/api/monetization/prices.js b/api/monetization/prices.js
index 6283ff76a..a5ff46468 100644
--- a/api/monetization/prices.js
+++ b/api/monetization/prices.js
@@ -11,6 +11,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -86,6 +87,10 @@ export default wrap(async (req, res) => {
const userId = await resolveUserId(req);
if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');
+ // CSRF on state-changing session-cookie requests; bearer tokens are exempt
+ // (the token itself proves intent and isn't auto-attached by browsers).
+ if (!(await requireCsrf(req, res, userId))) return;
+
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
diff --git a/api/notifications/index.js b/api/notifications/index.js
index c689b0b64..6b9b4f05b 100644
--- a/api/notifications/index.js
+++ b/api/notifications/index.js
@@ -17,14 +17,26 @@ export default wrap(async (req, res) => {
const params = new URL(req.url, 'http://x').searchParams;
const limit = Math.min(50, Math.max(1, parseInt(params.get('limit') || '20', 10)));
-
- const notifications = await sql`
- select id, type, payload, read_at, created_at
- from user_notifications
- where user_id = ${user.id}
- order by created_at desc
- limit ${limit}
- `;
+ // Optional type filter (e.g. ?type=pump_alert). Validated against a strict
+ // shape so the parameter can't smuggle anything unexpected into the query.
+ const typeRaw = (params.get('type') || '').trim();
+ const type = /^[a-z0-9_]{1,40}$/.test(typeRaw) ? typeRaw : null;
+
+ const notifications = type
+ ? await sql`
+ select id, type, payload, read_at, created_at
+ from user_notifications
+ where user_id = ${user.id} and type = ${type}
+ order by created_at desc
+ limit ${limit}
+ `
+ : await sql`
+ select id, type, payload, read_at, created_at
+ from user_notifications
+ where user_id = ${user.id}
+ order by created_at desc
+ limit ${limit}
+ `;
const [{ unread_count }] = await sql`
select count(*)::int as unread_count
diff --git a/api/pump/price-history.js b/api/pump/price-history.js
new file mode 100644
index 000000000..3a0f35753
--- /dev/null
+++ b/api/pump/price-history.js
@@ -0,0 +1,106 @@
+// GET /api/pump/price-history?mint=<mint>&interval=15m&from=<unix>&to=<unix>
+// --------------------------------------------------------------------------
+// Server-side proxy for Birdeye OHLCV. Keeps BIRDEYE_API_KEY on the server.
+// Returns the upstream error verbatim on failure — never fabricates candles.
+//
+// Response: { data: [ { t, o, h, l, c, v }, ... ] } (t = unix seconds)
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
+
+const VALID_INTERVALS = new Set([
+ '1m', '3m', '5m', '15m', '30m', '1H', '2H', '4H', '6H', '8H', '12H', '1D', '3D', '1W', '1M',
+]);
+
+// Birdeye uses uppercase hour/day codes (1H, 1D). Accept the common lowercase
+// forms from the client and normalize so callers don't have to care.
+function normalizeInterval(raw) {
+ if (!raw) return '15m';
+ const map = { '1h': '1H', '2h': '2H', '4h': '4H', '6h': '6H', '8h': '8H', '12h': '12H', '1d': '1D', '3d': '3D', '1w': '1W' };
+ const v = map[raw] || raw;
+ return VALID_INTERVALS.has(v) ? v : '15m';
+}
+
+function isPlausibleMint(s) {
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
+}
+
+let _cache = new Map(); // key → { value, expiresAt }
+const TTL_MS = 30_000;
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const mint = (params.get('mint') || '').trim();
+ if (!isPlausibleMint(mint)) {
+ return error(res, 400, 'bad_mint', 'mint must be a base58 Solana address (32–44 chars)');
+ }
+ const interval = normalizeInterval(params.get('interval'));
+
+ const nowSec = Math.floor(Date.now() / 1000);
+ const to = Math.min(nowSec, parseInt(params.get('to') || String(nowSec), 10) || nowSec);
+ const defaultFrom = nowSec - 24 * 3600;
+ let from = parseInt(params.get('from') || String(defaultFrom), 10);
+ if (!Number.isFinite(from) || from <= 0 || from >= to) from = defaultFrom;
+ // Cap the window at 30 days to keep upstream payloads bounded.
+ if (to - from > 30 * 86400) from = to - 30 * 86400;
+
+ if (!BIRDEYE_API_KEY) {
+ return error(res, 503, 'not_configured', 'On-chain data provider is not configured');
+ }
+
+ const key = `${mint}:${interval}:${from}:${to}`;
+ const now = Date.now();
+ const hit = _cache.get(key);
+ if (hit && hit.expiresAt > now) {
+ return json(res, 200, { data: hit.value }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
+ }
+
+ const url =
+ `https://public-api.birdeye.so/defi/ohlcv` +
+ `?address=${encodeURIComponent(mint)}&type=${interval}&time_from=${from}&time_to=${to}`;
+
+ let upstream;
+ try {
+ upstream = await fetch(url, {
+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ } catch (e) {
+ return error(res, 502, 'bad_gateway', `Birdeye unreachable: ${e.message}`);
+ }
+
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ return error(res, 502, 'upstream_error', `Birdeye ${upstream.status}: ${body.slice(0, 200)}`);
+ }
+
+ const payload = await upstream.json().catch(() => null);
+ const items = payload?.data?.items;
+ if (!Array.isArray(items)) {
+ return error(res, 502, 'upstream_error', 'Birdeye returned an unexpected payload');
+ }
+
+ const data = items
+ .map((it) => ({
+ t: Number(it.unixTime),
+ o: Number(it.o),
+ h: Number(it.h),
+ l: Number(it.l),
+ c: Number(it.c),
+ v: Number(it.v ?? 0),
+ }))
+ .filter((d) => Number.isFinite(d.t) && Number.isFinite(d.c));
+
+ _cache.set(key, { value: data, expiresAt: now + TTL_MS });
+ if (_cache.size > 128) _cache.delete(_cache.keys().next().value);
+
+ return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
+});
diff --git a/api/pump/trending.js b/api/pump/trending.js
new file mode 100644
index 000000000..cd1850707
--- /dev/null
+++ b/api/pump/trending.js
@@ -0,0 +1,79 @@
+// GET /api/pump/trending?limit=25
+// -------------------------------
+// Server-side proxy for Birdeye's trending-tokens feed. Keeps BIRDEYE_API_KEY
+// on the server — the browser never sees it. Returns the upstream error verbatim
+// on failure so the UI can surface it; never falls back to a hardcoded list.
+//
+// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const BIRDEYE_API_KEY = process.env.BIRDEYE_API_KEY;
+
+// Process-local cache. Trending shifts slowly; many tabs polling on nav into the
+// dashboard would otherwise hammer Birdeye. Warm-starts share this map.
+let _cache = { value: null, expiresAt: 0, limit: 0 };
+const TTL_MS = 30_000;
+
+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.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '25');
+ const limit = Math.min(50, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 25));
+
+ if (!BIRDEYE_API_KEY) {
+ return error(res, 503, 'not_configured', 'Trending data provider is not configured');
+ }
+
+ const now = Date.now();
+ if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {
+ return json(res, 200, { data: _cache.value.slice(0, limit) }, {
+ 'cache-control': 'public, max-age=15, s-maxage=30',
+ });
+ }
+
+ const url =
+ `https://public-api.birdeye.so/defi/token_trending` +
+ `?sort_by=rank&sort_type=asc&offset=0&limit=${limit}`;
+
+ let upstream;
+ try {
+ upstream = await fetch(url, {
+ headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
+ signal: AbortSignal.timeout(8000),
+ });
+ } catch (e) {
+ return error(res, 502, 'bad_gateway', `Birdeye unreachable: ${e.message}`);
+ }
+
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ return error(res, 502, 'upstream_error', `Birdeye ${upstream.status}: ${body.slice(0, 200)}`);
+ }
+
+ const payload = await upstream.json().catch(() => null);
+ const tokens = payload?.data?.tokens;
+ if (!Array.isArray(tokens)) {
+ return error(res, 502, 'upstream_error', 'Birdeye returned an unexpected payload');
+ }
+
+ const data = tokens
+ .map((t) => ({
+ mint: t.address,
+ symbol: t.symbol || '?',
+ name: t.name || t.symbol || '',
+ logo: t.logoURI || null,
+ price_usd: typeof t.price === 'number' ? t.price : null,
+ rank: typeof t.rank === 'number' ? t.rank : null,
+ }))
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+
+ _cache = { value: data, expiresAt: now + TTL_MS, limit };
+
+ return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
+});
diff --git a/api/widgets/_demo-fixtures.js b/api/widgets/_demo-fixtures.js
index d18027778..b495d9293 100644
--- a/api/widgets/_demo-fixtures.js
+++ b/api/widgets/_demo-fixtures.js
@@ -200,6 +200,26 @@ export const DEMO_WIDGETS = {
minUsd: 0,
},
}),
+
+ wdgt_demo_bondcrv: fixture({
+ id: 'wdgt_demo_bondcrv',
+ type: 'bonding-curve',
+ name: 'Bonding Curve',
+ modelUrl: CZ,
+ config: {
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: false,
+ autoRotate: true,
+ rotationSpeed: 0.4,
+ envPreset: 'neutral',
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ network: 'mainnet',
+ refreshMs: 15_000,
+ showUsd: true,
+ },
+ }),
};
export function isDemoWidgetId(id) {
diff --git a/api/world/[action].js b/api/world/[action].js
new file mode 100644
index 000000000..c8a8c6fc3
--- /dev/null
+++ b/api/world/[action].js
@@ -0,0 +1,138 @@
+// api/world/[action] — the generic per-world persistence service (T3).
+//
+// GET /api/world/load?worldId=<id>
+// Public. Returns the world's current document + concurrency metadata, or
+// { doc: null } if it has never been saved. Builds are shared, visible
+// places, so reads are open (rate-limited by IP).
+//
+// POST /api/world/save { worldId, doc, ifMatch?, owner? }
+// Authenticated. The authoritative multiplayer server writes with a service
+// token (Authorization: Bearer <world-service-token>); a browser session may
+// write subject to the per-world permission model (world-store.canWriteWorld,
+// the hook T16 tightens). `ifMatch` carries the etag the caller last read for
+// optimistic concurrency — a stale etag returns 409.
+//
+// Storage lives in api/_lib/world-store.js (Postgres index + R2 blob offload).
+
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { extractBearer } from '../_lib/auth.js';
+import { resolveAccount } from '../_lib/account-auth.js';
+import { verifyWorldServiceToken } from '../_lib/world-service-auth.js';
+import {
+ loadWorld,
+ saveWorld,
+ canWriteWorld,
+ isValidWorldId,
+ ConflictError,
+ TooLargeError,
+ PermissionError,
+ MAX_DOC_BYTES,
+} from '../_lib/world-store.js';
+
+function actionOf(req) {
+ return (req.query?.action || new URL(req.url, 'http://x').pathname.split('/').pop() || '').toLowerCase();
+}
+
+export default wrap(async (req, res) => {
+ // Public reads + server-to-server writes use a wildcard origin. Browser saves
+ // are same-origin (three.ws → three.ws), so the session cookie rides along
+ // without needing credentialed CORS.
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ const action = actionOf(req);
+ if (action === 'load') return handleLoad(req, res);
+ if (action === 'save') return handleSave(req, res);
+ return error(res, 404, 'not_found', 'unknown world action');
+});
+
+async function handleLoad(req, res) {
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const worldId = new URL(req.url, 'http://x').searchParams.get('worldId') || '';
+ if (!isValidWorldId(worldId)) return error(res, 400, 'validation_error', 'invalid or missing worldId');
+
+ const world = await loadWorld(worldId);
+ if (!world) return json(res, 200, { worldId, doc: null, version: 0, etag: null });
+
+ return json(res, 200, {
+ worldId: world.worldId,
+ doc: world.doc,
+ version: world.version,
+ etag: world.etag,
+ schemaVersion: world.schemaVersion,
+ ownerId: world.ownerId,
+ updatedAt: world.updatedAt,
+ });
+}
+
+async function handleSave(req, res) {
+ if (!method(req, res, ['POST'])) return;
+
+ // Principal resolution: a valid service token outranks a session and marks the
+ // write as authoritative (the game server). Otherwise fall back to the caller's
+ // browser session / bearer identity.
+ const service = await verifyWorldServiceToken(extractBearer(req));
+ let writer = null;
+ let account = null;
+ if (service) {
+ writer = 'service';
+ } else {
+ account = await resolveAccount(req, res);
+ if (!account) return error(res, 401, 'unauthorized', 'authentication required to write a world');
+ writer = account.userId;
+ const rl = await limits.prefsWrite(account.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many world saves');
+ }
+
+ let body;
+ try {
+ body = await readJson(req, MAX_DOC_BYTES + 1024);
+ } catch (err) {
+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
+ }
+
+ const { worldId, doc, ifMatch, owner } = body || {};
+ if (!isValidWorldId(worldId)) return error(res, 400, 'validation_error', 'invalid or missing worldId');
+ if (doc === undefined || doc === null || typeof doc !== 'object') {
+ return error(res, 400, 'validation_error', 'doc must be a JSON object or array');
+ }
+ if (ifMatch != null && ifMatch !== '*' && typeof ifMatch !== 'string') {
+ return error(res, 400, 'validation_error', 'ifMatch must be an etag string, "*", or null');
+ }
+
+ // Permission gate. Service writes are always allowed; user writes depend on the
+ // world's current owner. We need the existing owner to decide, so peek first —
+ // loadWorld returns null for a brand-new world (unowned → first writer allowed).
+ if (!service) {
+ const existing = await loadWorld(worldId);
+ const allowed = canWriteWorld({
+ isService: false,
+ account: account.userId,
+ currentOwner: existing?.ownerId ?? null,
+ });
+ if (!allowed) return error(res, 403, 'forbidden', 'not permitted to build in this world');
+ }
+
+ // On first save by a user, stamp them as the owner so they keep edit rights.
+ const ownerToSet = service ? (typeof owner === 'string' ? owner : null) : account.userId;
+
+ try {
+ const result = await saveWorld({ worldId, doc, ifMatch: ifMatch ?? null, writer, owner: ownerToSet });
+ return json(res, 200, result);
+ } catch (err) {
+ if (err instanceof ConflictError) {
+ return error(res, 409, err.code, err.message, { etagMismatch: true });
+ }
+ if (err instanceof TooLargeError) {
+ return error(res, 413, err.code, err.message);
+ }
+ if (err instanceof PermissionError) {
+ return error(res, 403, err.code, err.message);
+ }
+ throw err;
+ }
+}
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 120e1778a..ef2b09ccf 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -25,6 +25,7 @@
import { controller, remoteServer, config, params, toolSchema, syncServer, brandConfig, ttsEnabled, localAgentId, activeAgent, talkingHeadEnabled, talkingHeadAvatarUrl, route, mode, websiteCategory, loadCurrentUser, currentUser, notify, localProvidersEnabled, generating as generatingStore } from './stores.js';
import { t } from './i18n.js';
import Notifications from './Notifications.svelte';
+ import TxApprovalModal from './TxApprovalModal.svelte';
import AuthPage from './three-ui/pages/AuthPage.svelte';
import Pricing from './three-ui/pages/Pricing.svelte';
import MarketingPage from './three-ui/pages/MarketingPage.svelte';
@@ -65,7 +66,7 @@
feUsers,
feX,
} from './feather.js';
- import { defaultToolSchema, agentToolSchema, pumpToolSchema, agentPaymentsToolSchema, pumpTradingToolSchema, curatedToolPacks } from './tools.js';
+ import { defaultToolSchema, agentToolSchema, pumpToolSchema, agentPaymentsToolSchema, pumpTradingToolSchema, walletToolSchema, curatedToolPacks } from './tools.js';
import { signMessageSolana, signMessageEVM } from './walletAuth.js';
import { debounce, readFileAsDataURL } from './util.js';
import { flash, focusOnMount } from './actions';
@@ -1423,6 +1424,13 @@
let question = '';
let choices = [];
let chose = null; // index
+
+ // Wallet transaction approval gate. Tool bodies call
+ // window.requestWalletApproval(details) which resolves on Approve and rejects
+ // on Reject, pausing the transaction until the user confirms.
+ let txApprovalDetails = null;
+ let txApprovalResolve = null;
+ let txApprovalReject = null;
export async function choose(newQuestion, newChoices) {
chose = null;
question = newQuestion;
@@ -1465,6 +1473,14 @@
syncRouteFromHash();
window.addEventListener('hashchange', syncRouteFromHash);
+ // Expose a transaction-approval gate for eval'd wallet tool bodies.
+ window.requestWalletApproval = (details) =>
+ new Promise((resolve, reject) => {
+ txApprovalDetails = details;
+ txApprovalResolve = resolve;
+ txApprovalReject = reject;
+ });
+
// Populate auth state from session cookie
await loadCurrentUser();
@@ -2758,6 +2774,14 @@
<Notifications />
+{#if txApprovalDetails}
+ <TxApprovalModal
+ details={txApprovalDetails}
+ onApprove={() => { const r = txApprovalResolve; txApprovalDetails = null; txApprovalResolve = null; txApprovalReject = null; r?.(); }}
+ onReject={() => { const r = txApprovalReject; txApprovalDetails = null; txApprovalResolve = null; txApprovalReject = null; r?.(new Error('User rejected transaction')); }}
+ />
+{/if}
+
{#if installToastMsg}
<div transition:fade={{ duration: 200 }} class="fixed bottom-16 left-1/2 z-[200] -translate-x-1/2 rounded-lg border border-green-200 bg-green-50 px-4 py-2 text-sm text-green-800 shadow-md">
{installToastMsg}
diff --git a/chat/src/Toolcall.svelte b/chat/src/Toolcall.svelte
index ffeac0ec3..1283a3d05 100644
--- a/chat/src/Toolcall.svelte
+++ b/chat/src/Toolcall.svelte
@@ -47,6 +47,8 @@
displayType = 'webpage';
} else if (contentType === 'text/markdown') {
displayType = 'markdown';
+ } else if (contentType === 'application/tx-result') {
+ displayType = 'tx_result';
}
// ...
}
@@ -180,6 +182,44 @@
<div class="flex flex-col rounded-b-lg border border-t-0 border-slate-200 px-6 py-5">
<Choice bind:chose {choiceHandler} {question} {choices} />
</div>
+ {:else if toolresponse && displayType === 'tx_result'}
+ <div class="flex flex-col gap-3 rounded-b-lg border border-t-0 border-slate-200 px-5 py-4">
+ <!-- Status badge + amount -->
+ <div class="flex flex-wrap items-center gap-2">
+ {#if displayedContent.status === 'success'}
+ <span class="rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-medium text-emerald-700">Confirmed</span>
+ {:else if displayedContent.status === 'pending'}
+ <span class="rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-700">Pending</span>
+ {:else}
+ <span class="rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-700">Failed</span>
+ {/if}
+ <span class="text-sm font-medium text-slate-700">{displayedContent.amount} {displayedContent.token}</span>
+ <span class="text-xs text-slate-400">on {displayedContent.network}</span>
+ </div>
+
+ <!-- Addresses -->
+ <div class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 font-mono text-xs text-slate-600">
+ <span class="font-sans text-slate-400">From</span>
+ <span class="break-all">{displayedContent.from?.slice(0, 6)}…{displayedContent.from?.slice(-4)}</span>
+ <span class="font-sans text-slate-400">To</span>
+ <span class="break-all">{displayedContent.to?.slice(0, 6)}…{displayedContent.to?.slice(-4)}</span>
+ </div>
+
+ <!-- Tx hash + explorer link -->
+ <div class="flex items-center gap-2 font-mono text-xs text-slate-500">
+ <span class="break-all">{displayedContent.txHash?.slice(0, 12)}…{displayedContent.txHash?.slice(-6)}</span>
+ {#if displayedContent.explorerUrl}
+ <a
+ href={displayedContent.explorerUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="ml-auto whitespace-nowrap rounded border border-slate-200 px-2 py-0.5 font-sans text-[10px] text-slate-600 transition-colors hover:bg-slate-50"
+ >
+ View on Explorer ↗
+ </a>
+ {/if}
+ </div>
+ </div>
{/if}
</div>
{/if}
diff --git a/chat/src/WalletConnect.svelte b/chat/src/WalletConnect.svelte
index a2ee1c69a..8569899b5 100644
--- a/chat/src/WalletConnect.svelte
+++ b/chat/src/WalletConnect.svelte
@@ -1,5 +1,5 @@
<script>
- import { currentUser, loadCurrentUser } from './stores.js';
+ import { currentUser, loadCurrentUser, walletProvider } from './stores.js';
import { signInWithEVM, signInWithSolana, signOut } from './walletAuth.js';
let loading = null; // 'evm' | 'sol' | null
@@ -9,7 +9,8 @@
error = '';
loading = 'evm';
try {
- await signInWithEVM();
+ const { wallet } = await signInWithEVM();
+ walletProvider.set(wallet);
await loadCurrentUser();
} catch (e) {
error = e.message || 'EVM sign-in failed.';
@@ -22,7 +23,8 @@
error = '';
loading = 'sol';
try {
- await signInWithSolana();
+ const { wallet } = await signInWithSolana();
+ walletProvider.set(wallet);
await loadCurrentUser();
} catch (e) {
error = e.message || 'Solana sign-in failed.';
@@ -33,6 +35,7 @@
async function handleSignOut() {
await signOut();
+ walletProvider.set(null);
currentUser.set(null);
}
diff --git a/chat/src/stores.js b/chat/src/stores.js
index fef7a38b4..5d2ba3cc8 100644
--- a/chat/src/stores.js
+++ b/chat/src/stores.js
@@ -110,6 +110,16 @@ export const locale = persisted('locale', 'en');
export const currentUser = writable(null);
+// Which wallet is currently connected, for tool bodies and components that need
+// the live provider without re-parsing `currentUser` or polling window.solana /
+// window.ethereum. Shape: { type: 'solana'|'evm', address: string, chainId?: number } | null
+export const walletProvider = writable(null);
+
+// Read the connected wallet imperatively (e.g. from eval'd tool bodies).
+export function getConnectedWallet() {
+ return get(walletProvider);
+}
+
// Selected agent id whose Solana wallet pays for x402 paid-tool calls.
// Null means "use the shared demo wallet" served by /api/x402-pay.
export const payAgentId = persisted('payAgentId', null);
@@ -131,3 +141,9 @@ export async function loadCurrentUser() {
return null;
}
}
+
+// Mirror the connected wallet onto a window global so eval'd tool bodies (which
+// run without module imports) can read it as `window.__wallet`.
+if (typeof window !== 'undefined') {
+ walletProvider.subscribe((w) => { window.__wallet = w; });
+}
diff --git a/chat/src/tools.js b/chat/src/tools.js
index b131a892b..718c47c3c 100644
--- a/chat/src/tools.js
+++ b/chat/src/tools.js
@@ -42,7 +42,275 @@ function x402PayBody(toolName, argsBuilder) {
.replace('ARGS_BUILDER', argsBuilder);
}
+// ── Wallet Transactions tool pack ─────────────────────────────────────────────
+// Four tools that send / swap tokens on Solana and EVM chains from chat. Each
+// body resolves the live wallet provider (so it works even after a reload, not
+// only right after sign-in), pauses on window.requestWalletApproval() for an
+// explicit user confirmation, broadcasts the real transaction, and returns an
+// `application/tx-result` envelope that Toolcall.svelte renders as a status card.
+//
+// Defined above curatedToolPacks because the pack entry below references it
+// inside the array literal (const TDZ).
+const _solanaTransferBody = `const recipient = String(args.recipient || '').trim();
+const amount = Number(args.amount);
+const token = args.token ? String(args.token).trim() : 'SOL';
+const memo = args.memo ? String(args.memo) : undefined;
+const network = args.network === 'devnet' ? 'devnet' : 'mainnet';
+if (!recipient) throw new Error('recipient is required (base58 address)');
+if (!(amount > 0)) throw new Error('amount must be a positive number');
+const provider = window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;
+if (!provider) throw new Error('No Solana wallet connected. Install Phantom or another Solana wallet, then connect.');
+if (!provider.isConnected || !provider.publicKey) await provider.connect();
+const sender = provider.publicKey.toBase58();
+const buildRes = await fetch('/api/tx/solana/build-transfer', {
+ method: 'POST', headers: { 'content-type': 'application/json' }, credentials: 'include',
+ body: JSON.stringify({ sender, recipient, amount, token, memo, network }),
+});
+if (!buildRes.ok) { const e = await buildRes.json().catch(() => ({})); throw new Error(e.message || ('Failed to build transaction (HTTP ' + buildRes.status + ')')); }
+const built = await buildRes.json();
+const networkLabel = network === 'devnet' ? 'Solana Devnet' : 'Solana';
+await window.requestWalletApproval(Object.assign({ network: networkLabel, from: sender, to: recipient, amount: String(amount), token }, memo ? { memo } : {}));
+const web3 = await import('https://esm.sh/@solana/web3.js@1');
+const txBytes = Uint8Array.from(atob(built.transaction), c => c.charCodeAt(0));
+let tx; try { tx = web3.VersionedTransaction.deserialize(txBytes); } catch { tx = web3.Transaction.from(txBytes); }
+let signature;
+if (provider.signAndSendTransaction) { const r = await provider.signAndSendTransaction(tx); signature = r.signature || r; }
+else {
+ const signed = await provider.signTransaction(tx);
+ const conn = new web3.Connection(network === 'devnet' ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com', 'confirmed');
+ signature = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction({ signature, blockhash: built.blockhash, lastValidBlockHeight: built.lastValidBlockHeight }, 'confirmed');
+}
+const explorerUrl = 'https://solscan.io/tx/' + signature + (network === 'devnet' ? '?cluster=devnet' : '');
+return { contentType: 'application/tx-result', content: { status: 'success', txHash: signature, network: networkLabel, from: sender, to: recipient, amount: String(amount), token, explorerUrl } };`;
+
+const _solanaSwapBody = `const inputMint = String(args.inputMint || '').trim();
+const outputMint = String(args.outputMint || '').trim();
+const amount = Number(args.amount);
+const slippageBps = args.slippageBps != null ? Math.round(Number(args.slippageBps)) : 50;
+if (!inputMint || !outputMint) throw new Error('inputMint and outputMint are required (base58 mint addresses)');
+if (!(amount > 0)) throw new Error('amount must be a positive number');
+const provider = window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare;
+if (!provider) throw new Error('No Solana wallet connected. Install Phantom or another Solana wallet, then connect.');
+if (!provider.isConnected || !provider.publicKey) await provider.connect();
+const sender = provider.publicKey.toBase58();
+const buildRes = await fetch('/api/tx/solana/build-swap', {
+ method: 'POST', headers: { 'content-type': 'application/json' }, credentials: 'include',
+ body: JSON.stringify({ sender, inputMint, outputMint, amount, slippageBps }),
+});
+if (!buildRes.ok) { const e = await buildRes.json().catch(() => ({})); throw new Error(e.message || 'Failed to get swap route'); }
+const built = await buildRes.json();
+await window.requestWalletApproval({ network: 'Solana', from: sender, to: 'Jupiter (DEX aggregator)', amount: String(amount), token: inputMint.slice(0, 6) + '… → ' + outputMint.slice(0, 6) + '…', memo: '~' + built.outputAmount + ' out, ' + built.priceImpactPct + '% price impact' });
+const web3 = await import('https://esm.sh/@solana/web3.js@1');
+const txBytes = Uint8Array.from(atob(built.transaction), c => c.charCodeAt(0));
+let tx; try { tx = web3.VersionedTransaction.deserialize(txBytes); } catch { tx = web3.Transaction.from(txBytes); }
+let signature;
+if (provider.signAndSendTransaction) { const r = await provider.signAndSendTransaction(tx); signature = r.signature || r; }
+else {
+ const signed = await provider.signTransaction(tx);
+ const conn = new web3.Connection('https://api.mainnet-beta.solana.com', 'confirmed');
+ signature = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+}
+return { contentType: 'application/tx-result', content: { status: 'success', txHash: signature, network: 'Solana', from: sender, to: outputMint, amount: String(built.outputAmount), token: outputMint.slice(0, 8) + '…', explorerUrl: 'https://solscan.io/tx/' + signature } };`;
+
+const _evmChainNames = "{ 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' }";
+const _evmExplorerBases = "{ 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' }";
+
+const _evmTransferBody = `const recipient = String(args.recipient || '').trim();
+const amount = String(args.amount || '').trim();
+const token = args.token ? String(args.token).trim() : 'ETH';
+const decimals = args.decimals != null ? Number(args.decimals) : 18;
+if (!recipient) throw new Error('recipient is required (0x address)');
+if (!amount || !(parseFloat(amount) > 0)) throw new Error('amount must be a positive number');
+const eth = window.ethereum;
+if (!eth) throw new Error('No EVM wallet connected. Install MetaMask or a compatible wallet, then connect.');
+const accounts = await eth.request({ method: 'eth_requestAccounts' });
+const from = (window.__wallet && window.__wallet.type === 'evm' && window.__wallet.address) || accounts[0];
+const chainId = parseInt(await eth.request({ method: 'eth_chainId' }), 16);
+const chainNames = ${_evmChainNames};
+const networkName = chainNames[chainId] || ('Chain ' + chainId);
+await window.requestWalletApproval({ network: networkName, from, to: recipient, amount, token: token === 'ETH' ? 'ETH' : (token.slice(0, 8) + '…') });
+let txHash;
+if (token === 'ETH') {
+ const valueHex = '0x' + BigInt(Math.round(parseFloat(amount) * 1e18)).toString(16);
+ txHash = await eth.request({ method: 'eth_sendTransaction', params: [{ from, to: recipient, value: valueHex }] });
+} else {
+ const amt = BigInt(Math.round(parseFloat(amount) * 10 ** decimals));
+ const data = '0xa9059cbb' + recipient.replace(/^0x/, '').padStart(64, '0') + amt.toString(16).padStart(64, '0');
+ txHash = await eth.request({ method: 'eth_sendTransaction', params: [{ from, to: token, data }] });
+}
+const explorerBases = ${_evmExplorerBases};
+const explorerUrl = (explorerBases[chainId] || 'https://etherscan.io/tx/') + txHash;
+return { contentType: 'application/tx-result', content: { status: 'pending', txHash, network: networkName, chainId, from, to: recipient, amount, token: token === 'ETH' ? 'ETH' : (token.slice(0, 10) + '…'), explorerUrl } };`;
+
+const _evmSwapBody = `const fromToken = String(args.fromToken || '').trim();
+const toToken = String(args.toToken || '').trim();
+const amount = String(args.amount || '').trim();
+const decimals = args.decimals != null ? Number(args.decimals) : 18;
+const slippage = args.slippage != null ? Number(args.slippage) : 1;
+if (!fromToken || !toToken) throw new Error('fromToken and toToken are required (contract addresses; use 0xEeee… for native ETH)');
+if (!amount || !(parseFloat(amount) > 0)) throw new Error('amount must be a positive number');
+const eth = window.ethereum;
+if (!eth) throw new Error('No EVM wallet connected. Install MetaMask or a compatible wallet, then connect.');
+const accounts = await eth.request({ method: 'eth_requestAccounts' });
+const from = (window.__wallet && window.__wallet.type === 'evm' && window.__wallet.address) || accounts[0];
+const chainId = parseInt(await eth.request({ method: 'eth_chainId' }), 16);
+const chainNames = ${_evmChainNames};
+const networkName = chainNames[chainId] || ('Chain ' + chainId);
+const amountWei = BigInt(Math.round(parseFloat(amount) * 10 ** decimals)).toString();
+const quoteUrl = 'https://api.1inch.dev/swap/v5.2/' + chainId + '/swap?src=' + fromToken + '&dst=' + toToken + '&amount=' + amountWei + '&from=' + from + '&slippage=' + slippage + '&disableEstimate=true';
+const quoteRes = await fetch(quoteUrl, { headers: { 'Accept': 'application/json' } });
+if (!quoteRes.ok) { const e = await quoteRes.json().catch(() => ({})); throw new Error(e.description || e.message || ('1inch quote failed (HTTP ' + quoteRes.status + ')')); }
+const quote = await quoteRes.json();
+if (!quote.tx || !quote.tx.to) throw new Error('1inch returned no swap transaction for this pair');
+const toAmountHuman = quote.toAmount != null ? (Number(quote.toAmount) / 10 ** 18).toFixed(6) : '?';
+await window.requestWalletApproval({ network: networkName, from, to: '1inch Router', amount, token: fromToken.slice(0, 8) + '… → ' + toToken.slice(0, 8) + '…', memo: '~' + toAmountHuman + ' out' });
+const ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
+if (fromToken.toLowerCase() !== ETH_ADDRESS.toLowerCase()) {
+ const paddedOwner = from.replace(/^0x/, '').padStart(64, '0');
+ const paddedSpender = quote.tx.to.replace(/^0x/, '').padStart(64, '0');
+ const allowanceHex = await eth.request({ method: 'eth_call', params: [{ to: fromToken, data: '0xdd62ed3e' + paddedOwner + paddedSpender }, 'latest'] });
+ if (BigInt(allowanceHex || '0x0') < BigInt(amountWei)) {
+ await eth.request({ method: 'eth_sendTransaction', params: [{ from, to: fromToken, data: '0x095ea7b3' + paddedSpender + 'f'.repeat(64) }] });
+ }
+}
+const txHash = await eth.request({ method: 'eth_sendTransaction', params: [{ from, to: quote.tx.to, data: quote.tx.data, value: quote.tx.value || '0x0' }] });
+const explorerBases = ${_evmExplorerBases};
+const explorerUrl = (explorerBases[chainId] || 'https://etherscan.io/tx/') + txHash;
+return { contentType: 'application/tx-result', content: { status: 'pending', txHash, network: networkName, chainId, from, to: toToken, amount: '~' + toAmountHuman, token: toToken.slice(0, 10) + '…', explorerUrl } };`;
+
+export const walletToolSchema = [
+ {
+ clientDefinition: {
+ id: 'wallet-solana-transfer-001',
+ name: 'solana_transfer',
+ description: 'Send SOL or a Solana SPL token (e.g. USDC) to a recipient address. Requires a connected Solana wallet.',
+ arguments: [
+ { name: 'recipient', type: 'string', description: 'Base58 recipient wallet address' },
+ { name: 'amount', type: 'number', description: 'Amount to send in human-readable units (e.g. 1.5 for 1.5 SOL)' },
+ { name: 'token', type: 'string', description: 'Token to send: "SOL" or an SPL mint address (e.g. USDC mint). Default: "SOL"' },
+ { name: 'memo', type: 'string', description: 'Optional memo string to attach' },
+ { name: 'network', type: 'string', description: '"mainnet" or "devnet". Default: "mainnet"' },
+ ],
+ body: _solanaTransferBody,
+ },
+ type: 'function',
+ function: {
+ name: 'solana_transfer',
+ description: 'Send SOL or SPL tokens on Solana. Requires a connected Solana wallet. Pauses for user approval before broadcasting.',
+ parameters: {
+ type: 'object',
+ properties: {
+ recipient: { type: 'string', description: 'Base58 recipient wallet address' },
+ amount: { type: 'number', description: 'Amount in human-readable units' },
+ token: { type: 'string', description: '"SOL" or SPL mint address. Default: "SOL"' },
+ memo: { type: 'string', description: 'Optional memo' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Default: mainnet' },
+ },
+ required: ['recipient', 'amount'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'wallet-solana-swap-002',
+ name: 'solana_swap',
+ description: 'Swap tokens on Solana via Jupiter aggregator. Finds the best route automatically. Requires a connected Solana wallet.',
+ arguments: [
+ { name: 'inputMint', type: 'string', description: 'Mint address of the token to sell (e.g. USDC: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)' },
+ { name: 'outputMint', type: 'string', description: 'Mint address of the token to buy (e.g. SOL: So11111111111111111111111111111111111111112)' },
+ { name: 'amount', type: 'number', description: 'Amount of input token to sell in human-readable units' },
+ { name: 'slippageBps', type: 'number', description: 'Max slippage in basis points (100 = 1%). Default: 50' },
+ ],
+ body: _solanaSwapBody,
+ },
+ type: 'function',
+ function: {
+ name: 'solana_swap',
+ description: 'Swap tokens on Solana via Jupiter. Best-route aggregation. Pauses for user approval before broadcasting.',
+ parameters: {
+ type: 'object',
+ properties: {
+ inputMint: { type: 'string', description: 'Mint address of token to sell' },
+ outputMint: { type: 'string', description: 'Mint address of token to buy' },
+ amount: { type: 'number', description: 'Amount of input token in human-readable units' },
+ slippageBps: { type: 'integer', description: 'Max slippage in bps. Default: 50' },
+ },
+ required: ['inputMint', 'outputMint', 'amount'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'wallet-evm-transfer-003',
+ name: 'evm_transfer',
+ description: 'Send ETH or an ERC20 token to a recipient address on any EVM chain. Requires a connected EVM wallet (MetaMask or compatible).',
+ arguments: [
+ { name: 'recipient', type: 'string', description: '0x recipient address' },
+ { name: 'amount', type: 'string', description: 'Amount in human-readable units (e.g. "0.01" for 0.01 ETH)' },
+ { name: 'token', type: 'string', description: '"ETH" for native token, or an ERC20 contract address (0x...). Default: "ETH"' },
+ { name: 'decimals', type: 'number', description: 'Token decimals (required for ERC20, ignored for ETH). Default: 18' },
+ ],
+ body: _evmTransferBody,
+ },
+ type: 'function',
+ function: {
+ name: 'evm_transfer',
+ description: 'Send ETH or ERC20 tokens on any EVM chain (Ethereum, Base, Optimism, Arbitrum, Polygon). Pauses for user approval before sending.',
+ parameters: {
+ type: 'object',
+ properties: {
+ recipient: { type: 'string', description: '0x recipient address' },
+ amount: { type: 'string', description: 'Amount in human-readable units' },
+ token: { type: 'string', description: '"ETH" or ERC20 contract address. Default: "ETH"' },
+ decimals: { type: 'number', description: 'ERC20 decimals. Default: 18' },
+ },
+ required: ['recipient', 'amount'],
+ },
+ },
+ },
+ {
+ clientDefinition: {
+ id: 'wallet-evm-swap-004',
+ name: 'evm_swap',
+ description: 'Swap tokens on EVM chains using the 1inch aggregator. Finds the best DEX route. Requires a connected EVM wallet.',
+ arguments: [
+ { name: 'fromToken', type: 'string', description: 'Token contract address to sell (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native ETH)' },
+ { name: 'toToken', type: 'string', description: 'Token contract address to buy' },
+ { name: 'amount', type: 'string', description: 'Amount of fromToken in human-readable units' },
+ { name: 'decimals', type: 'number', description: 'Decimals of fromToken. Default: 18' },
+ { name: 'slippage', type: 'number', description: 'Max slippage percentage (e.g. 1 for 1%). Default: 1' },
+ ],
+ body: _evmSwapBody,
+ },
+ type: 'function',
+ function: {
+ name: 'evm_swap',
+ description: 'Swap ERC20 tokens or ETH on EVM chains via the 1inch DEX aggregator. Pauses for user approval; auto-approves token allowance when needed.',
+ parameters: {
+ type: 'object',
+ properties: {
+ fromToken: { type: 'string', description: 'Token to sell (address or 0xEeee... for ETH)' },
+ toToken: { type: 'string', description: 'Token to buy (address)' },
+ amount: { type: 'string', description: 'Amount of fromToken in human-readable units' },
+ decimals: { type: 'number', description: 'fromToken decimals. Default: 18' },
+ slippage: { type: 'number', description: 'Max slippage %. Default: 1' },
+ },
+ required: ['fromToken', 'toToken', 'amount'],
+ },
+ },
+ },
+];
+
export const curatedToolPacks = [
+ {
+ id: 'wallet-transactions',
+ name: 'Wallet Transactions',
+ description:
+ 'Send and swap tokens on Solana and EVM chains directly from chat. Supports SOL, SPL tokens, ETH, ERC20, and DEX swaps via Jupiter and 1inch. Every transaction pauses for your explicit approval.',
+ schema: walletToolSchema,
+ },
{
id: 'x402-pay',
name: 'three.ws · Pay-per-call (x402)',
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index f54f4819e..71c2eddcf 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -23,6 +23,7 @@ import { WalkRoom } from './rooms/WalkRoom.js';
import { GameRoom } from './rooms/GameRoom.js';
import { REALMS } from './rooms/realms.js';
import { blockStore } from './block-store.js';
+import { worldPersistence } from './persistence.js';
import { flushAllPlayers } from './playerStore.js';
import { marketplaceStore } from './marketplaceStore.js';
import { SERVERS } from './servers.js';
@@ -317,6 +318,13 @@ const shutdown = async (signal) => {
} catch (err) {
console.error('[multiplayer] final block flush error:', err);
}
+ // Generic per-world docs (T3): flush any room whose debounced world save hadn't
+ // fired, so placed builds / gated-world state survive a redeploy.
+ try {
+ await worldPersistence.flushAll();
+ } catch (err) {
+ console.error('[multiplayer] final world flush error:', err);
+ }
// Same guarantee for player progression (Task 16): persist every account whose
// debounced profile save hadn't landed yet, so a redeploy never resets a player.
try {
diff --git a/multiplayer/src/persistence.js b/multiplayer/src/persistence.js
new file mode 100644
index 000000000..68fd58bd0
--- /dev/null
+++ b/multiplayer/src/persistence.js
@@ -0,0 +1,198 @@
+// WorldPersistence — generic per-world JSON persistence for Colyseus rooms (T3).
+//
+// Rooms that need durable, non-voxel world state (placed props, gated-world pass
+// rosters, mutable realm layout) use this instead of the voxel-specific
+// block-store. A room typically:
+//
+// import { worldPersistence } from '../persistence.js';
+// // onCreate:
+// const { doc, etag } = await worldPersistence.load(this.worldKey);
+// if (doc) this.restoreFrom(doc);
+// // on change:
+// worldPersistence.save(this.worldKey, () => this.snapshot()); // debounced
+// // onDispose:
+// await worldPersistence.flush(this.worldKey);
+//
+// Durable storage lives in the Vercel API (api/world/[action] → Postgres index +
+// R2 blob). This process keeps only a memory mirror + the last-seen etag for
+// optimistic concurrency, and signs a short-lived service token per request so
+// the API trusts the write. The token format is mirrored byte-for-byte by the
+// API verifier (api/_lib/world-service-auth.js).
+//
+// Two tiers, like block-store:
+// 1. In-process memory — the latest doc-producer + last doc, so a re-created
+// room rehydrates instantly and a brief API outage doesn't lose the build.
+// 2. The persistence API — survives this process dying / redeploying.
+
+import crypto from 'node:crypto';
+
+const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
+const SAVE_DEBOUNCE_MS = 4000;
+const TOKEN_TTL_SEC = 120;
+
+function secret() {
+ return (
+ process.env.MULTIPLAYER_SHARED_SECRET ||
+ process.env.HOLDER_PASS_SECRET ||
+ 'dev-insecure-multiplayer-secret'
+ );
+}
+
+// base64url(JSON{svc:'world',exp}).base64url(HMAC). Mirrors presence-token.js.
+function signServiceToken() {
+ const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL_SEC;
+ const payload = Buffer.from(JSON.stringify({ svc: 'world', exp }), 'utf8').toString('base64url');
+ const sig = crypto.createHmac('sha256', secret()).update(payload).digest('base64url');
+ return `${payload}.${sig}`;
+}
+
+class WorldPersistence {
+ constructor() {
+ // worldId → { produce: () => doc, lastDoc, etag, version, dirty }
+ this._mem = new Map();
+ this._timers = new Map();
+ // Flips true after a verified API round-trip; a room reads it to honestly
+ // tell builders whether their work survives a restart.
+ this._durable = false;
+ this._warnedUnconfigured = false;
+ }
+
+ get durable() {
+ return this._durable;
+ }
+
+ _entry(worldId) {
+ let e = this._mem.get(worldId);
+ if (!e) {
+ e = { produce: null, lastDoc: null, etag: null, version: 0, dirty: false };
+ this._mem.set(worldId, e);
+ }
+ return e;
+ }
+
+ // Load a world's current doc from the API, falling back to the in-memory
+ // mirror if the network read fails. Returns { doc, etag, version }.
+ async load(worldId) {
+ const e = this._entry(worldId);
+ try {
+ const res = await fetch(`${API_BASE}/api/world/load?worldId=${encodeURIComponent(worldId)}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const body = await res.json();
+ e.etag = body.etag ?? null;
+ e.version = body.version ?? 0;
+ e.lastDoc = body.doc ?? null;
+ this._durable = true;
+ return { doc: e.lastDoc, etag: e.etag, version: e.version };
+ } catch (err) {
+ // Memory tier: a re-created room in the same process still rehydrates.
+ console.warn(`[world-persistence] load failed for ${worldId}: ${err?.message} — using memory mirror`);
+ return { doc: e.lastDoc, etag: e.etag, version: e.version };
+ }
+ }
+
+ // Record the latest doc producer and schedule a debounced durable write.
+ // Synchronous so callers don't await on the hot path of an edit. `produce` is
+ // called at flush time so the most recent state is what lands.
+ save(worldId, produce) {
+ if (typeof produce !== 'function') {
+ throw new TypeError('worldPersistence.save(worldId, produce): produce must be a function returning the doc');
+ }
+ const e = this._entry(worldId);
+ e.produce = produce;
+ e.dirty = true;
+ this._schedule(worldId);
+ }
+
+ _schedule(worldId) {
+ if (this._timers.has(worldId)) return;
+ const handle = setTimeout(() => {
+ this._timers.delete(worldId);
+ this.flush(worldId).catch(() => {});
+ }, SAVE_DEBOUNCE_MS);
+ if (typeof handle.unref === 'function') handle.unref();
+ this._timers.set(worldId, handle);
+ }
+
+ // Write the current world doc to the API now. Called by the debounce timer and
+ // on room dispose so the final state always lands.
+ async flush(worldId) {
+ const pending = this._timers.get(worldId);
+ if (pending) {
+ clearTimeout(pending);
+ this._timers.delete(worldId);
+ }
+ const e = this._mem.get(worldId);
+ if (!e || !e.dirty || !e.produce) return;
+
+ const doc = e.produce();
+ e.lastDoc = doc;
+
+ // One retry: if a concurrent writer moved the etag, re-read it and
+ // overwrite (a single always-on instance owns each world, so last-writer-
+ // wins is the right policy here rather than a merge).
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const outcome = await this._postSave(worldId, doc, e.etag);
+ if (outcome === 'ok') {
+ e.dirty = false;
+ return;
+ }
+ if (outcome === 'conflict' && attempt === 0) {
+ const fresh = await this.load(worldId);
+ e.etag = fresh.etag;
+ continue;
+ }
+ return; // network/other error or repeated conflict — keep dirty, retry next change
+ }
+ }
+
+ async _postSave(worldId, doc, ifMatch) {
+ try {
+ const res = await fetch(`${API_BASE}/api/world/save`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${signServiceToken()}`,
+ },
+ body: JSON.stringify({ worldId, doc, ifMatch: ifMatch ?? null }),
+ });
+ if (res.ok) {
+ const body = await res.json();
+ const e = this._entry(worldId);
+ e.etag = body.etag ?? e.etag;
+ e.version = body.version ?? e.version;
+ this._durable = true;
+ return 'ok';
+ }
+ if (res.status === 409) return 'conflict';
+ if (res.status === 401 || res.status === 403) {
+ if (!this._warnedUnconfigured) {
+ this._warnedUnconfigured = true;
+ console.error(
+ `[world-persistence] save rejected (${res.status}) — set MULTIPLAYER_SHARED_SECRET to match the API, or worlds are MEMORY-ONLY.`,
+ );
+ }
+ this._durable = false;
+ return 'error';
+ }
+ console.warn(`[world-persistence] save for ${worldId} failed: HTTP ${res.status}`);
+ this._durable = false;
+ return 'error';
+ } catch (err) {
+ console.warn(`[world-persistence] save for ${worldId} failed: ${err?.message}`);
+ this._durable = false;
+ return 'error';
+ }
+ }
+
+ // Flush every dirty world. Call on SIGTERM (redeploy) so edits whose debounce
+ // hasn't fired aren't lost.
+ async flushAll() {
+ await Promise.allSettled([...this._mem.keys()].map((id) => this.flush(id)));
+ }
+}
+
+// One store shared by every room in the process — that shared memory is what lets
+// a build outlive its room between disposal and the next join.
+export const worldPersistence = new WorldPersistence();
diff --git a/package-lock.json b/package-lock.json
index 6da92562d..a56104ed4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -92,7 +92,7 @@
"bn.js": "^5.2.3",
"bs58": "^6.0.0",
"colyseus": "^0.17.10",
- "colyseus.js": "^0.16.22",
+ "colyseus.js": "0.16.22",
"dat.gui": "^0.7.9",
"ethers": "^6.16.0",
"express": "^4.22.1",
@@ -107,6 +107,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.4",
"node-fetch": "^3.3.2",
+ "postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
"qrcode": "^1.5.4",
"query-string": "^9.4.0",
@@ -116,6 +117,7 @@
"short-uuid": "6.0.3",
"simple-dropzone": "^0.8.3",
"three": "latest",
+ "three-mesh-bvh": "^0.9.10",
"twitter-api-v2": "^1.29.0",
"vhtml": "^2.2.0",
"viem": "^2.51.3",
@@ -1292,7 +1294,7 @@
"@colyseus/monitor": "^0.16.7",
"@colyseus/redis-driver": "^0.16.0",
"@colyseus/redis-presence": "^0.16.0",
- "@colyseus/schema": "^3.0.0",
+ "@colyseus/schema": "3.0.76",
"@colyseus/ws-transport": "^0.16.5",
"@ethereum-attestation-service/eas-sdk": "0.29.1",
"@metaplex-foundation/js": "^0.20.1",
diff --git a/package.json b/package.json
index b9bef88c4..5ec92c1d1 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
"build:extension": "node scripts/build-extension-icons.mjs && node scripts/build-extension.mjs",
"build:extension:prod": "node scripts/build-extension-icons.mjs && node scripts/build-extension.mjs --prod",
"optimize:glb": "node scripts/optimize-glb.mjs",
+ "compress:glbs": "node scripts/compress-glbs.mjs",
"fetch-animations": "node scripts/download-animations.mjs",
"fetch:mixamo-catalog": "node scripts/fetch-mixamo-catalog.mjs",
"test": "vitest run && playwright test",
@@ -190,6 +191,7 @@
"meshoptimizer": "^1.1.1",
"nipplejs": "^1.0.4",
"node-fetch": "^3.3.2",
+ "postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
"qrcode": "^1.5.4",
"query-string": "^9.4.0",
@@ -199,6 +201,7 @@
"short-uuid": "6.0.3",
"simple-dropzone": "^0.8.3",
"three": "latest",
+ "three-mesh-bvh": "^0.9.10",
"twitter-api-v2": "^1.29.0",
"vhtml": "^2.2.0",
"viem": "^2.51.3",
diff --git a/pages/a-edit.html b/pages/a-edit.html
index e8498c2a8..b57a90c76 100644
--- a/pages/a-edit.html
+++ b/pages/a-edit.html
@@ -287,5 +287,6 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/a-me.html b/pages/a-me.html
index 8eaa7e7ed..6db3a63a5 100644
--- a/pages/a-me.html
+++ b/pages/a-me.html
@@ -11,5 +11,6 @@
<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
<script type="module" src="/src/a-me.js"></script>
</head>
-<body></body>
+<body> <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/agenc/embodied.html b/pages/agenc/embodied.html
index d5f8d0d17..6b60df0bc 100644
--- a/pages/agenc/embodied.html
+++ b/pages/agenc/embodied.html
@@ -369,5 +369,6 @@
if (taskInput.value) startWatching();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/agenc/room.html b/pages/agenc/room.html
index 383906a6a..a1421d050 100644
--- a/pages/agenc/room.html
+++ b/pages/agenc/room.html
@@ -333,5 +333,6 @@
});
if (creatorInput.value) start();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 2e80391dd..e30f451ad 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -352,5 +352,6 @@
</div>
<script type="module" src="/src/agent-detail.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index d6a5a3254..eb253013b 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -1640,5 +1640,6 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/agent-home.html b/pages/agent-home.html
index f6b8a792d..6c2f47e9d 100644
--- a/pages/agent-home.html
+++ b/pages/agent-home.html
@@ -1395,5 +1395,6 @@
<!-- END:AGENT_HOME_ORPHANS_SCRIPT -->
<!-- Launch Token modal boot — owner-only, wired via agent:ready event -->
<script type="module" src="/src/pump/launch-token-boot.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/agent-next.html b/pages/agent-next.html
index 38de085b0..2e540e2e2 100644
--- a/pages/agent-next.html
+++ b/pages/agent-next.html
@@ -1485,5 +1485,6 @@
if (!animPlaying) mixer.update(0);
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/app-demo.html b/pages/app-demo.html
index 3d60ea122..504f5f5e8 100644
--- a/pages/app-demo.html
+++ b/pages/app-demo.html
@@ -326,5 +326,6 @@
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/app-next.html b/pages/app-next.html
index f7842898a..05e383594 100644
--- a/pages/app-next.html
+++ b/pages/app-next.html
@@ -548,5 +548,6 @@
<div class="nxt-more-sep" role="separator"></div>
<a href="/app-classic" role="menuitem">Classic viewer</a>
</div>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/app.html b/pages/app.html
index ab86f0ecd..b1f007dff 100644
--- a/pages/app.html
+++ b/pages/app.html
@@ -540,5 +540,6 @@
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/ar.html b/pages/ar.html
index 46b6c9300..477dc9ae6 100644
--- a/pages/ar.html
+++ b/pages/ar.html
@@ -323,5 +323,6 @@
</button>
</footer>
</div>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/avatar-edit.html b/pages/avatar-edit.html
index f6ecf187c..1a1a8d621 100644
--- a/pages/avatar-edit.html
+++ b/pages/avatar-edit.html
@@ -687,5 +687,6 @@
</aside>
</main>
<script src="/src/avatar-edit.js" type="module"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index 95e745535..22098f556 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -1132,5 +1132,6 @@
</footer>
<script src="/src/avatar-page.js" type="module"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/avatar-sdk.html b/pages/avatar-sdk.html
index eff2329b4..de6bf03bf 100644
--- a/pages/avatar-sdk.html
+++ b/pages/avatar-sdk.html
@@ -732,5 +732,6 @@ creator.<span class="t-fn">open</span>()<span class="t-op">;</span></pre>
<script src="/nav.js" defer></script>
<script type="module" src="/src/avatar-sdk-page.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/avatar-studio-demo.html b/pages/avatar-studio-demo.html
index a1837f111..bd113c634 100644
--- a/pages/avatar-studio-demo.html
+++ b/pages/avatar-studio-demo.html
@@ -70,5 +70,6 @@
</main>
<script type="module" src="/src/avatar-studio-demo.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.html
index dcf897394..05084c1f0 100644
--- a/pages/avatar-studio.html
+++ b/pages/avatar-studio.html
@@ -862,5 +862,6 @@
</aside>
</main>
<script src="/src/avatar-studio.js" type="module"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/aws-marketplace/welcome.html b/pages/aws-marketplace/welcome.html
index d71a0451f..95821d1c8 100644
--- a/pages/aws-marketplace/welcome.html
+++ b/pages/aws-marketplace/welcome.html
@@ -218,5 +218,6 @@
</div>
<script type="module" src="/src/aws-marketplace-welcome.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/aws/index.html b/pages/aws/index.html
index 805f16626..cf7fdcf42 100644
--- a/pages/aws/index.html
+++ b/pages/aws/index.html
@@ -268,5 +268,6 @@
<div class="footer">
<a href="/">three.ws</a> · <a href="/docs">Docs</a> · <a href="/legal/privacy">Privacy</a> · <a href="/legal/tos">Terms</a>
</div>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/brain.html b/pages/brain.html
index b26eaf134..052821c49 100644
--- a/pages/brain.html
+++ b/pages/brain.html
@@ -263,5 +263,6 @@
<script src="/nav.js" defer></script>
<script type="module" src="/src/brain.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/city.html b/pages/city.html
index 30f759b3c..6d8a267ad 100644
--- a/pages/city.html
+++ b/pages/city.html
@@ -45,5 +45,6 @@
</div>
<script type="module" src="/src/city/city-world.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/club.html b/pages/club.html
index f3bcbb591..cec0ec236 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -1258,5 +1258,6 @@
}
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/communities.html b/pages/communities.html
index 31f51cba6..89fb4cd21 100644
--- a/pages/communities.html
+++ b/pages/communities.html
@@ -353,5 +353,6 @@
</main>
<script type="module" src="/src/communities.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/community.html b/pages/community.html
index c00ca833f..d3e0e0359 100644
--- a/pages/community.html
+++ b/pages/community.html
@@ -162,5 +162,6 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/create-review.html b/pages/create-review.html
index 620a9ce8d..00a2e35bf 100644
--- a/pages/create-review.html
+++ b/pages/create-review.html
@@ -1877,5 +1877,6 @@
></div>
<script type="module" src="/src/create-review.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index 6c2a4cde2..e3c0a0fa9 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -1463,5 +1463,6 @@
showStep('capture');
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/create.html b/pages/create.html
index 2b0f8ba5e..f78496c27 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -1131,5 +1131,6 @@
const btn = document.getElementById('btn-wallet-signin');
if (btn) wireSigninButton(btn);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/create/video.html b/pages/create/video.html
index 41415d03f..4116fb5d6 100644
--- a/pages/create/video.html
+++ b/pages/create/video.html
@@ -549,5 +549,6 @@
const btn = document.getElementById('btn-wallet-signin');
if (btn) wireSigninButton(btn);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/creating.html b/pages/creating.html
index 8c1b40bf0..6cd2bf2c1 100644
--- a/pages/creating.html
+++ b/pages/creating.html
@@ -330,5 +330,6 @@
}
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/discover-next.html b/pages/discover-next.html
index d7118712a..57fec02ed 100644
--- a/pages/discover-next.html
+++ b/pages/discover-next.html
@@ -413,5 +413,6 @@
showSkeletons();
fetchPage();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/extension-privacy.html b/pages/extension-privacy.html
index 6df93525b..1b3571c4a 100644
--- a/pages/extension-privacy.html
+++ b/pages/extension-privacy.html
@@ -65,5 +65,6 @@
<p>Questions? Email <a href="mailto:[email protected]">[email protected]</a> or visit <a href="https://three.ws">three.ws</a>.</p>
</div>
<script type="module" src="/public/nav.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/extension-terms.html b/pages/extension-terms.html
index 9b638d652..fe0c60236 100644
--- a/pages/extension-terms.html
+++ b/pages/extension-terms.html
@@ -50,5 +50,6 @@
<p><a href="mailto:[email protected]">[email protected]</a></p>
</div>
<script type="module" src="/public/nav.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/fact-checker.html b/pages/fact-checker.html
index 6e090019a..a1de97499 100644
--- a/pages/fact-checker.html
+++ b/pages/fact-checker.html
@@ -636,5 +636,6 @@
</main>
<script type="module" src="/src/fact-checker-app.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/features.html b/pages/features.html
index d7f68905f..9b7a934c5 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -1504,5 +1504,6 @@
});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/gallery-picker.html b/pages/gallery-picker.html
index 9b6fd88bf..624d899a1 100644
--- a/pages/gallery-picker.html
+++ b/pages/gallery-picker.html
@@ -109,5 +109,6 @@
picker.mountInline(host);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/game.html b/pages/game.html
index b807d8fb9..66cf1b13f 100644
--- a/pages/game.html
+++ b/pages/game.html
@@ -333,5 +333,6 @@
<script type="module" src="/src/game/iso-game.js"></script>
<!-- Controls layer (Task 12): hotbar number keys, panel toggles, rebindable keybindings. -->
<script type="module" src="/src/game/iso-controls.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/handle.html b/pages/handle.html
index 3ea7e92aa..6d5ec430c 100644
--- a/pages/handle.html
+++ b/pages/handle.html
@@ -249,5 +249,6 @@
<main id="main"></main>
<script type="module" src="/src/handle.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/home-classic.html b/pages/home-classic.html
index 4ebf72ce6..d826a0fbc 100644
--- a/pages/home-classic.html
+++ b/pages/home-classic.html
@@ -1573,5 +1573,6 @@
});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/home-v2.html b/pages/home-v2.html
index 67dc7b299..1a26cc040 100644
--- a/pages/home-v2.html
+++ b/pages/home-v2.html
@@ -1467,5 +1467,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/home-v3.html b/pages/home-v3.html
index 97665483f..6e2a71c51 100644
--- a/pages/home-v3.html
+++ b/pages/home-v3.html
@@ -1069,5 +1069,6 @@
})();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/home-v4.html b/pages/home-v4.html
index 9894667d3..9ee8db4dc 100644
--- a/pages/home-v4.html
+++ b/pages/home-v4.html
@@ -509,5 +509,6 @@
</div>
</footer>
</main>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/home.html b/pages/home.html
index dcb123037..f7c8d85c7 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -6404,5 +6404,6 @@ if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {
});
})();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/import-rpm.html b/pages/import-rpm.html
index cc8243c64..ce4e3388f 100644
--- a/pages/import-rpm.html
+++ b/pages/import-rpm.html
@@ -692,5 +692,6 @@
return err.message || 'Import failed. Please try again.';
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/launchpad.html b/pages/launchpad.html
index 18f0df911..9bb90098a 100644
--- a/pages/launchpad.html
+++ b/pages/launchpad.html
@@ -37,5 +37,6 @@
avatarSrc: url.searchParams.get('avatar') || '',
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/marketplace.html b/pages/marketplace.html
index b8294b362..6b31ad66d 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -3122,6 +3122,7 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/mocap-studio.html b/pages/mocap-studio.html
index 724ee3793..57310ed8e 100644
--- a/pages/mocap-studio.html
+++ b/pages/mocap-studio.html
@@ -579,5 +579,6 @@
<script src="/footer.js"></script>
<script type="module" src="/src/mocap-studio.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/play.html b/pages/play.html
index 755726f25..ebdd79fa1 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -50,5 +50,6 @@
<script type="module" src="/src/game/boot-avatar.js"></script>
<script type="module" src="/src/game/coincommunities.js"></script>
<script type="module" src="/src/game/ambient-crowd.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/playground.html b/pages/playground.html
index c3d51867b..15be8d439 100644
--- a/pages/playground.html
+++ b/pages/playground.html
@@ -841,5 +841,6 @@
})();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/pose.html b/pages/pose.html
index 8a7bb618d..e574c370c 100644
--- a/pages/pose.html
+++ b/pages/pose.html
@@ -1053,5 +1053,6 @@
</div>
<script type="module" src="/src/pose-studio.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pricing.html b/pages/pricing.html
index 4071fb010..5fa1aaaca 100644
--- a/pages/pricing.html
+++ b/pages/pricing.html
@@ -696,5 +696,6 @@
} catch (_) {}
})();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/profile.html b/pages/profile.html
index 8cfa6c4b8..dac6079b3 100644
--- a/pages/profile.html
+++ b/pages/profile.html
@@ -1278,5 +1278,6 @@
} catch {}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pump-3d-agent.html b/pages/pump-3d-agent.html
index d16866ecb..c14184ab3 100644
--- a/pages/pump-3d-agent.html
+++ b/pages/pump-3d-agent.html
@@ -11,5 +11,6 @@
</head>
<body>
<p>Moved to <a href="/pump-live">/pump-live</a>.</p>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/pump-coin-page.html b/pages/pump-coin-page.html
index 1072cba2c..c17272196 100644
--- a/pages/pump-coin-page.html
+++ b/pages/pump-coin-page.html
@@ -95,5 +95,6 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index 3853c42d1..24f77deca 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -27,6 +27,19 @@
<link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
+ <style>
+ /* Config connection-test pills (Task 10) */
+ .pd-probe { display:inline-block; margin-left:0.4rem; font-size:0.66rem; font-weight:600; padding:0.05rem 0.45rem; border-radius:999px; vertical-align:middle; }
+ .pd-probe.is-ok { color:var(--pd-success); background:var(--pd-success-soft); border:1px solid var(--pd-success-border); }
+ .pd-probe.is-err { color:var(--pd-danger); background:var(--pd-danger-soft); border:1px solid var(--pd-danger-border); }
+ .pd-probe.is-pending { color:var(--pd-warn); background:var(--pd-warn-soft); border:1px solid var(--pd-warn-border); }
+ /* Stale monitor stat cards (Task 07) */
+ .pd-stat.is-stale { opacity:0.5; }
+ .pd-stale-badge { display:inline-block; font-size:0.58rem; color:var(--pd-warn); margin-left:0.35rem; text-transform:uppercase; letter-spacing:0.05em; vertical-align:middle; }
+ /* Wallet holdings token logos (Task 02) */
+ .pd-token-logo { width:18px; height:18px; border-radius:50%; vertical-align:middle; margin-right:0.4rem; object-fit:cover; background:var(--pd-bg-elev); }
+ #pd-market-chart { cursor:crosshair; }
+ </style>
</head>
<body class="home-page pump-dashboard-page">
<a href="#pd-main" class="h-skip-link">Skip to main content</a>
@@ -143,6 +156,10 @@
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><circle cx="8" cy="5" r="2.5"/><path d="M3 14c0-3 2.2-5 5-5s5 2 5 5"/></svg>
Default Agent
</a>
+ <a href="#" data-page="revenue">
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M2 13l3.5-4 3 2.5L13 5"/><path d="M10 5h3v3"/></svg>
+ Revenue
+ </a>
<div class="pd-nav-section">System</div>
<a href="#" data-page="config">
@@ -179,6 +196,34 @@
<!-- ═══════ Dashboard page ═══════ -->
<section class="pd-page is-active" id="page-dashboard" aria-labelledby="pd-page-title">
+ <!-- Bot/monitor stat cards — bound to GET /api/healthz (monitor + watches + uptime). -->
+ <div class="pd-stat-grid" id="pd-monitor-stats" style="margin-bottom:1rem">
+ <div class="pd-stat">
+ <div class="pd-stat-label">Bot status</div>
+ <div class="pd-stat-value" id="stat-bot-status">—</div>
+ <div class="pd-stat-sub" id="stat-bot-status-sub">Live monitor</div>
+ </div>
+ <div class="pd-stat">
+ <div class="pd-stat-label">Mode</div>
+ <div class="pd-stat-value" id="stat-bot-mode">—</div>
+ <div class="pd-stat-sub">Worker mode</div>
+ </div>
+ <div class="pd-stat">
+ <div class="pd-stat-label">Graduations seen</div>
+ <div class="pd-stat-value" id="stat-claims">—</div>
+ <div class="pd-stat-sub">Detected on-chain</div>
+ </div>
+ <div class="pd-stat">
+ <div class="pd-stat-label">Active alerts</div>
+ <div class="pd-stat-value" id="stat-watches">—</div>
+ <div class="pd-stat-sub">Users watching</div>
+ </div>
+ <div class="pd-stat">
+ <div class="pd-stat-label">Uptime</div>
+ <div class="pd-stat-value" id="stat-uptime">—</div>
+ <div class="pd-stat-sub">API process</div>
+ </div>
+ </div>
<div class="pd-dash-grid">
<div class="pd-panel pd-mod-8">
<div class="pd-panel-head"><h2>Featured agent</h2></div>
@@ -213,15 +258,20 @@
</div>
<div class="pd-panel pd-mod-4">
- <div class="pd-panel-head"><h2>Wallet snapshot</h2></div>
+ <div class="pd-panel-head">
+ <h2>Wallet snapshot</h2>
+ <div class="pd-spacer"></div>
+ <button class="pd-btn pd-btn-sm" id="pd-wallet-disconnect" type="button" hidden>Disconnect</button>
+ </div>
<div class="pd-panel-body" id="pd-wallet-body">
- <div class="pd-empty">
+ <div class="pd-empty" id="pd-wallet-empty">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18M16 14h2"/></svg>
- <div>Sign in to view your Solana balance and token holdings.</div>
+ <div>Connect your Solana wallet to see SOL &amp; token holdings.</div>
<div style="margin-top: 0.85rem">
- <a class="pd-btn is-primary pd-btn-sm" href="/login">Sign in</a>
+ <button class="pd-btn is-primary pd-btn-sm" id="connect-wallet-btn" type="button">Connect Wallet</button>
</div>
</div>
+ <div id="pd-wallet-holdings" hidden></div>
</div>
</div>
@@ -257,6 +307,24 @@
</div>
</div>
+ <div class="pd-panel pd-mod-12">
+ <div class="pd-panel-head">
+ <h2>Market chart</h2>
+ <div class="pd-spacer"></div>
+ <select class="pd-select" id="pd-chart-token" aria-label="Select token for the market chart" style="max-width:280px">
+ <option value="" disabled selected>Loading trending tokens…</option>
+ </select>
+ <button class="pd-btn pd-btn-sm" id="pd-chart-retry" type="button" hidden>Retry</button>
+ </div>
+ <div class="pd-panel-body">
+ <div id="pd-chart-meta" style="display:flex;gap:1rem;flex-wrap:wrap;align-items:baseline;margin-bottom:0.6rem;min-height:1.2rem;font-size:0.82rem;color:var(--pd-text-muted)"></div>
+ <div style="position:relative">
+ <canvas id="pd-market-chart" style="width:100%;height:300px;display:block"></canvas>
+ <div id="pd-chart-tooltip" style="position:absolute;pointer-events:none;display:none;background:var(--pd-bg-elev);border:1px solid var(--pd-border-strong);border-radius:6px;padding:0.35rem 0.55rem;font-family:var(--pd-font-mono);font-size:0.72rem;color:var(--pd-text-bright);white-space:nowrap;z-index:3;transform:translate(-50%,-120%)"></div>
+ </div>
+ </div>
+ </div>
+
<div class="pd-panel pd-mod-6">
<div class="pd-panel-head">
<h2>Live feed</h2>
@@ -408,6 +476,11 @@
<label>Trade alert cooldown (s)</label>
<input class="pd-input" type="number" id="pd-threshold-cooldown" value="30" min="5" step="5" />
</div>
+ <div class="pd-form-group">
+ <label>Webhook URL (optional)</label>
+ <input class="pd-input" type="url" id="pd-alert-webhook" placeholder="https://your-server.com/pump-alerts" />
+ <div style="font-size:0.72rem;color:var(--pd-text-dim);margin-top:0.3rem">Graduation alerts POST here even when no tab is open. Must be https.</div>
+ </div>
<button class="pd-btn is-primary" id="pd-save-alerts" type="button">Save settings</button>
</div>
</div>
@@ -549,7 +622,10 @@
<div class="pd-form-group">
<label>Speech</label>
<input class="pd-input" type="text" id="pd-speech-input" placeholder="Enter text to speak…" />
- <button class="pd-btn is-primary" id="pd-speak-btn" type="button" style="margin-top:0.5rem">Speak</button>
+ <div style="display:flex;gap:0.4rem;margin-top:0.5rem">
+ <button class="pd-btn is-primary" id="pd-speak-btn" type="button">Speak</button>
+ <button class="pd-btn is-danger" id="pd-speak-stop" type="button" hidden>Stop</button>
+ </div>
</div>
<div class="pd-form-group">
<label>Quick actions</label>
@@ -590,6 +666,64 @@
</div>
</section>
+ <!-- ═══════ Revenue page ═══════ -->
+ <section class="pd-page" id="page-revenue" aria-label="Revenue">
+ <div class="pd-form-inline">
+ <div class="pd-form-group" style="flex:2">
+ <label>Agent</label>
+ <select class="pd-select" id="pd-rev-agent">
+ <option value="">All agents</option>
+ </select>
+ </div>
+ <div class="pd-form-group" style="flex:1">
+ <label>Granularity</label>
+ <select class="pd-select" id="pd-rev-granularity">
+ <option value="day" selected>Day</option>
+ <option value="week">Week</option>
+ <option value="month">Month</option>
+ </select>
+ </div>
+ <div class="pd-form-group" style="flex:1">
+ <label>From</label>
+ <input class="pd-input" type="date" id="pd-rev-from" />
+ </div>
+ <div class="pd-form-group" style="flex:1">
+ <label>To</label>
+ <input class="pd-input" type="date" id="pd-rev-to" />
+ </div>
+ <button class="pd-btn is-primary" id="pd-rev-refresh" type="button">Refresh</button>
+ </div>
+
+ <div class="pd-stat-grid" id="pd-rev-summary" style="margin-bottom:1rem">
+ <div class="pd-stat"><div class="pd-stat-label">Gross</div><div class="pd-stat-value" id="pd-rev-gross">—</div><div class="pd-stat-sub" id="pd-rev-currency">—</div></div>
+ <div class="pd-stat"><div class="pd-stat-label">Platform fees</div><div class="pd-stat-value" id="pd-rev-fees">—</div><div class="pd-stat-sub">Deducted</div></div>
+ <div class="pd-stat"><div class="pd-stat-label">Net earnings</div><div class="pd-stat-value is-success" id="pd-rev-net">—</div><div class="pd-stat-sub">After fees</div></div>
+ <div class="pd-stat"><div class="pd-stat-label">Payments</div><div class="pd-stat-value" id="pd-rev-count">—</div><div class="pd-stat-sub" id="pd-rev-chain">—</div></div>
+ </div>
+
+ <div class="pd-panel" style="margin-bottom:1rem">
+ <div class="pd-panel-head"><h2>Net earnings over time</h2></div>
+ <div class="pd-panel-body">
+ <div id="pd-rev-status" style="font-size:0.85rem;color:var(--pd-text-muted);margin-bottom:0.5rem;min-height:1.2rem"></div>
+ <div style="position:relative">
+ <canvas id="pd-rev-chart" style="width:100%;height:260px;display:block"></canvas>
+ </div>
+ </div>
+ </div>
+
+ <div class="pd-panel">
+ <div class="pd-panel-head"><h2>By skill</h2></div>
+ <div class="pd-panel-body no-pad">
+ <table class="pd-table">
+ <thead><tr><th>Skill</th><th style="text-align:right">Payments</th><th style="text-align:right">Net</th></tr></thead>
+ <tbody id="pd-rev-skill-table">
+ <tr><td colspan="3" class="pd-empty">Open the Revenue tab to load.</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </section>
+
<!-- ═══════ Config page ═══════ -->
<section class="pd-page" id="page-config" aria-label="Configuration">
<div class="pd-callout" style="margin-bottom:1rem">
@@ -600,15 +734,15 @@
<div class="pd-panel-head"><h2>Connection</h2></div>
<div class="pd-panel-body">
<div class="pd-form-group">
- <label>API base URL</label>
+ <label>API base URL <span class="pd-probe" id="pd-probe-api"></span></label>
<input class="pd-input" type="text" id="pd-cfg-api-url" placeholder="https://your-pumpkit.example" />
</div>
<div class="pd-form-group">
- <label>WebSocket URL</label>
+ <label>WebSocket URL <span class="pd-probe" id="pd-probe-ws"></span></label>
<input class="pd-input" type="text" id="pd-cfg-ws-url" />
</div>
<div class="pd-form-group">
- <label>API key</label>
+ <label>API key <span class="pd-probe" id="pd-probe-key"></span></label>
<input class="pd-input" type="password" id="pd-cfg-api-key" placeholder="Optional API key…" />
</div>
<button class="pd-btn is-primary" id="pd-save-config" type="button">Save &amp; reconnect</button>
@@ -619,7 +753,7 @@
<div class="pd-panel-head"><h2>Solana RPC</h2></div>
<div class="pd-panel-body">
<div class="pd-form-group">
- <label>RPC endpoint</label>
+ <label>RPC endpoint <span class="pd-probe" id="pd-probe-rpc"></span></label>
<input class="pd-input" type="text" id="pd-cfg-rpc-url" value="https://api.mainnet-beta.solana.com" />
</div>
<div class="pd-form-group">
@@ -637,6 +771,41 @@
<!-- ═══════ API page ═══════ -->
<section class="pd-page" id="page-api" aria-label="API reference">
+ <div class="pd-panel" style="margin-bottom:1rem">
+ <div class="pd-panel-head">
+ <h2>Your keys</h2>
+ <div class="pd-spacer"></div>
+ <span class="pd-badge" id="pd-keys-count">—</span>
+ </div>
+ <div class="pd-panel-body">
+ <form id="pd-key-create-form" style="display:flex;gap:0.75rem;flex-wrap:wrap;align-items:flex-end;margin-bottom:1rem">
+ <div class="pd-form-group" style="flex:2;min-width:200px;margin:0">
+ <label for="pd-key-name">Key name</label>
+ <input class="pd-input" type="text" id="pd-key-name" maxlength="80" placeholder="e.g. CI pipeline" required />
+ </div>
+ <div class="pd-form-group" style="flex:1;min-width:160px;margin:0">
+ <label for="pd-key-expiry">Expires (optional)</label>
+ <input class="pd-input" type="datetime-local" id="pd-key-expiry" />
+ </div>
+ <div class="pd-form-group" style="flex:2;min-width:240px;margin:0">
+ <label>Scopes</label>
+ <div style="display:flex;gap:0.85rem;flex-wrap:wrap;font-size:0.82rem;color:var(--pd-text-muted)">
+ <label style="display:flex;gap:0.3rem;align-items:center"><input type="checkbox" class="pd-key-scope" value="avatars:read" checked /> avatars:read</label>
+ <label style="display:flex;gap:0.3rem;align-items:center"><input type="checkbox" class="pd-key-scope" value="avatars:write" checked /> avatars:write</label>
+ <label style="display:flex;gap:0.3rem;align-items:center"><input type="checkbox" class="pd-key-scope" value="avatars:delete" /> avatars:delete</label>
+ <label style="display:flex;gap:0.3rem;align-items:center"><input type="checkbox" class="pd-key-scope" value="profile" /> profile</label>
+ </div>
+ </div>
+ <button class="pd-btn is-primary" id="pd-key-create" type="submit">Create key</button>
+ </form>
+ <table class="pd-table">
+ <thead><tr><th>Name</th><th>Prefix</th><th>Scopes</th><th>Created</th><th>Last used</th><th>Expires</th><th></th></tr></thead>
+ <tbody id="pd-keys-table">
+ <tr><td colspan="7" class="pd-empty">Open the API tab to load your keys.</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
<div class="pd-panel">
<div class="pd-panel-head"><h2>API endpoints</h2></div>
<div class="pd-panel-body">
@@ -695,6 +864,24 @@
</div>
</div>
+ <!-- ── API key created modal (shows plaintext token once) ────────────── -->
+ <div class="pd-modal-backdrop" id="pd-key-modal" role="dialog" aria-modal="true" aria-labelledby="pd-key-modal-title">
+ <div class="pd-modal">
+ <h3 id="pd-key-modal-title">API key created</h3>
+ <p style="font-size:0.85rem;color:var(--pd-warn);margin:0 0 0.75rem">
+ Copy this token now — you won't be able to see it again.
+ </p>
+ <div class="pd-form-group">
+ <label>Token</label>
+ <input class="pd-input pd-mono" type="text" id="pd-key-token" readonly />
+ </div>
+ <div class="pd-modal-actions">
+ <button class="pd-btn" id="pd-key-copy" type="button">Copy</button>
+ <button class="pd-btn is-primary" id="pd-key-done" type="button">Done</button>
+ </div>
+ </div>
+ </div>
+
<div class="pd-toast-container" id="pd-toasts" role="status" aria-live="polite"></div>
<script type="module">
@@ -708,6 +895,7 @@
import { grindVanity } from '/src/solana/vanity/grinder.js';
import { validatePattern } from '/src/solana/vanity/validation.js';
+ import { initWalletButton, getConnectedWallet, getConnectedWalletAddress } from '/src/wallet.js';
const PAGE_TITLES = {
dashboard: 'Dashboard',
@@ -719,6 +907,7 @@
quoting: 'Quote Engine',
vanity: 'Vanity Generator',
animations: 'Default Agent',
+ revenue: 'Revenue',
config: 'Configuration',
api: 'API Reference',
};
@@ -740,6 +929,9 @@
vanityAbort: null,
healthInterval: null,
networkInterval: null,
+ monitorInterval: null,
+ walletAddress: null,
+ solPrice: null,
startupAt: Date.now(),
};
@@ -800,6 +992,10 @@
if (page === 'animations') loadAgent();
if (page === 'watches') refreshWatches();
if (page === 'claims') refreshClaims();
+ if (page === 'revenue') loadRevenue();
+ if (page === 'api') loadApiKeys();
+ if (page === 'alerts') loadAlertConfig();
+ if (page === 'dashboard') { loadFeaturedAgent(); loadTrendingTokens(); pollMonitorStats(); }
}
// ── API health + network ─────────────────────────────────────
@@ -847,6 +1043,7 @@
const sol = Number(data.sol_price || 0);
if (sol > 0) {
+ state.solPrice = sol;
$('pd-stat-sol').textContent = '$' + sol.toFixed(2);
$('pd-sol-status').textContent = 'SOL: $' + sol.toFixed(2);
$('pd-sol-dot').className = 'pd-dot is-on';
@@ -872,80 +1069,150 @@
// ── Featured agent ───────────────────────────────────────────
+ function initialsOf(name) {
+ const words = String(name || '').trim().split(/\s+/).filter(Boolean);
+ if (!words.length) return '?';
+ if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
+ return (words[0][0] + words[words.length - 1][0]).toUpperCase();
+ }
+
+ function renderFeaturedAvatar(agent) {
+ const slot = $('pd-featured-avatar');
+ if (!slot) return;
+ if (agent.avatar_url) {
+ slot.innerHTML = `<img src="${escapeHtml(agent.avatar_url)}" alt="${escapeHtml(agent.display_name || 'Agent')} avatar" style="width:100%;height:100%;object-fit:cover" loading="lazy" />`;
+ } else {
+ // Never a stock placeholder — render the agent's initials.
+ slot.innerHTML = `<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-family:var(--pd-font-display);font-size:2.2rem;font-weight:700;color:var(--pd-text-bright);background:linear-gradient(135deg,var(--pd-bg-elev),#161616)">${escapeHtml(initialsOf(agent.display_name))}</div>`;
+ }
+ }
+
+ // Task 01: the Featured agent is selected platform-wide from real data
+ // (top 30-day revenue, else newest public agent) by GET /api/agents/featured.
async function loadFeaturedAgent() {
+ const nameEl = $('pd-featured-name');
+ const descEl = $('pd-featured-desc');
+ const linkEl = $('pd-featured-link');
+ const statsEl = $('pd-featured-stats');
+ if (!nameEl) return;
+ nameEl.textContent = 'Loading agent…';
+ descEl.textContent = 'Fetching the featured agent for the platform.';
try {
- const resp = await apiFetch('/api/agents/me');
- if (resp.status === 401 || !resp.ok) {
- $('pd-featured-name').textContent = 'Sign in to see your agents';
- $('pd-featured-desc').textContent = 'Once you create an agent, it shows up here with live stats and a 3D preview.';
- $('pd-featured-link').textContent = 'Sign in';
- $('pd-featured-link').href = '/login';
- return;
- }
- const { agent } = await resp.json();
- if (!agent) {
- $('pd-featured-name').textContent = 'No agent yet';
- $('pd-featured-desc').textContent = 'Create your first 3D agent and it will appear here.';
- $('pd-featured-link').textContent = 'Create agent';
- $('pd-featured-link').href = '/create';
+ const resp = await apiFetch('/api/agents/featured');
+ if (resp.status === 404) {
+ nameEl.textContent = 'No agents available yet';
+ descEl.textContent = 'Be the first — create a 3D agent and it can be featured here.';
+ linkEl.textContent = 'Create agent';
+ linkEl.href = '/create';
+ if (statsEl) statsEl.hidden = true;
+ $('pd-featured-avatar').innerHTML = `<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:var(--pd-text-dim);font-size:0.8rem">No agents yet</div>`;
return;
}
- $('pd-featured-name').textContent = agent.name || 'Untitled agent';
- $('pd-featured-desc').textContent = agent.description || 'Your default agent. Ready to chat, speak, and embed.';
- $('pd-featured-link').textContent = 'View profile';
- $('pd-featured-link').href = '/agent/' + agent.id;
-
- const stats = $('pd-featured-stats');
- stats.hidden = false;
- stats.innerHTML = [
- agent.id ? `<span class="pd-featured-stat"><span class="pd-featured-stat-label">ID</span>${shortAddr(agent.id)}</span>` : '',
- agent.created_at ? `<span class="pd-featured-stat"><span class="pd-featured-stat-label">Created</span>${new Date(agent.created_at).toLocaleDateString()}</span>` : '',
- agent.token_mint ? `<span class="pd-featured-stat"><span class="pd-featured-stat-label">Token</span>${shortAddr(agent.token_mint)}</span>` : '',
- ].filter(Boolean).join('');
-
- // Preview the actual agent in the avatar slot when we have its embed.
- if (agent.id) {
- $('pd-featured-avatar').innerHTML = `<iframe src="/agent-embed.html?id=${encodeURIComponent(agent.id)}" title="Featured agent preview"></iframe>`;
+ if (!resp.ok) throw new Error('featured ' + resp.status);
+ const { data: agent } = await resp.json();
+ nameEl.textContent = agent.display_name || 'Untitled agent';
+ descEl.textContent = agent.bio || 'A featured 3D agent on three.ws.';
+ linkEl.textContent = 'View profile';
+ linkEl.href = agent.detail_url || ('/agent/' + agent.id);
+ if (statsEl) {
+ statsEl.hidden = false;
+ statsEl.innerHTML = [
+ `<span class="pd-featured-stat"><span class="pd-featured-stat-label">ID</span>${shortAddr(agent.id)}</span>`,
+ agent.net_30d > 0 ? `<span class="pd-featured-stat"><span class="pd-featured-stat-label">30d net</span>${(agent.net_30d / 1e6).toLocaleString(undefined, { maximumFractionDigits: 2 })} USDC</span>` : '',
+ ].filter(Boolean).join('');
}
+ renderFeaturedAvatar(agent);
} catch {
- $('pd-featured-name').textContent = 'Couldn’t load agent';
- $('pd-featured-desc').textContent = 'Try refreshing the page, or check your connection in the Configuration tab.';
+ nameEl.textContent = 'Couldn’t load featured agent';
+ descEl.textContent = 'Try refreshing, or check connectivity in the Configuration tab.';
+ if (statsEl) statsEl.hidden = true;
}
}
// ── Wallet snapshot ──────────────────────────────────────────
- async function loadWalletSnapshot() {
+ // Task 02: real Solana wallet connect via src/wallet.js, balances via the
+ // server-side POST /api/wallet/balances (Helius + Jupiter, key stays server-side).
+ async function onWalletChanged(address) {
+ const empty = $('pd-wallet-empty');
+ const holdings = $('pd-wallet-holdings');
+ const disconnectBtn = $('pd-wallet-disconnect');
+ if (!holdings) return;
+ state.walletAddress = address || null;
+
+ if (!address) {
+ holdings.hidden = true;
+ holdings.innerHTML = '';
+ if (empty) empty.hidden = false;
+ if (disconnectBtn) disconnectBtn.hidden = true;
+ return;
+ }
+
+ if (empty) empty.hidden = true;
+ if (disconnectBtn) disconnectBtn.hidden = false;
+ holdings.hidden = false;
+ holdings.innerHTML = '<div style="font-size:0.85rem;color:var(--pd-text-muted)">Loading balances…</div>';
+
try {
- const resp = await apiFetch('/api/pump/balances');
- if (resp.status === 401) return; // already shows the sign-in CTA
- if (!resp.ok) return;
- const data = await resp.json();
- const body = $('pd-wallet-body');
- const sol = Number(data.solBalance || data.sol || 0);
- const tokens = data.tokens || data.tokenBalances || [];
- body.innerHTML = `
- <div class="pd-stat" style="margin-bottom:0.7rem">
- <div class="pd-stat-label">SOL balance</div>
- <div class="pd-stat-value">${sol.toFixed(4)}</div>
- <div class="pd-stat-sub">${data.wallet ? shortAddr(data.wallet) : 'your wallet'}</div>
- </div>
- <div style="font-size:0.78rem;color:var(--pd-text-muted);margin-bottom:0.45rem;font-family:var(--pd-font-display);text-transform:uppercase;letter-spacing:0.08em">Top holdings</div>
- ${tokens.length === 0 ? '<div style="font-size:0.85rem;color:var(--pd-text-dim)">No token balances detected.</div>' : `
- <table class="pd-table">
- <thead><tr><th>Token</th><th style="text-align:right">Amount</th></tr></thead>
- <tbody>
- ${tokens.slice(0, 5).map((t) => `
- <tr>
- <td><span class="pd-mono">${escapeHtml(t.symbol || shortAddr(t.mint || ''))}</span></td>
- <td style="text-align:right" class="pd-mono">${Number(t.uiAmount || t.amount || 0).toLocaleString(undefined, { maximumFractionDigits: 4 })}</td>
- </tr>
- `).join('')}
- </tbody>
- </table>
- `}
- `;
- } catch { /* keep the empty state */ }
+ const resp = await apiFetch('/api/wallet/balances', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ chain: 'solana', address }),
+ });
+ const data = await resp.json().catch(() => ({}));
+ if (!resp.ok) {
+ const msg = data.error_description || data.error || `Balance lookup failed (${resp.status})`;
+ holdings.innerHTML = `<div style="font-size:0.85rem;color:var(--pd-danger)">${escapeHtml(msg)}</div>`;
+ return;
+ }
+ renderWalletHoldings(address, data);
+ } catch (e) {
+ holdings.innerHTML = `<div style="font-size:0.85rem;color:var(--pd-danger)">Network error: ${escapeHtml(e.message || 'failed')}</div>`;
+ }
+ }
+
+ function renderWalletHoldings(address, data) {
+ const holdings = $('pd-wallet-holdings');
+ const native = data.native || {};
+ const solAmount = Number(native.amount || 0);
+ const solUsd = Number(native.usd || 0);
+ const tokens = (data.tokens || [])
+ .map((t) => ({ ...t, usd: Number(t.usd || 0), amount: Number(t.amount || 0) }))
+ .sort((a, b) => b.usd - a.usd)
+ .slice(0, 10);
+
+ holdings.innerHTML = `
+ <div style="margin-bottom:0.6rem">
+ <a class="pd-addr pd-mono" href="https://solscan.io/account/${escapeHtml(address)}" target="_blank" rel="noopener">${shortAddr(address)}</a>
+ </div>
+ <div class="pd-stat" style="margin-bottom:0.7rem">
+ <div class="pd-stat-label">${escapeHtml(native.symbol || 'SOL')} balance</div>
+ <div class="pd-stat-value">${solAmount.toLocaleString(undefined, { maximumFractionDigits: 4 })}</div>
+ <div class="pd-stat-sub">${solUsd > 0 ? '$' + solUsd.toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</div>
+ </div>
+ <div style="font-size:0.78rem;color:var(--pd-text-muted);margin-bottom:0.45rem;font-family:var(--pd-font-display);text-transform:uppercase;letter-spacing:0.08em">Top holdings</div>
+ ${tokens.length === 0 ? '<div style="font-size:0.85rem;color:var(--pd-text-dim)">No SPL tokens</div>' : `
+ <table class="pd-table">
+ <thead><tr><th>Token</th><th style="text-align:right">Amount</th><th style="text-align:right">USD</th></tr></thead>
+ <tbody>
+ ${tokens.map((t) => `
+ <tr>
+ <td>${t.logo ? `<img class="pd-token-logo" src="${escapeHtml(t.logo)}" alt="" />` : ''}<span class="pd-mono">${escapeHtml(t.symbol || shortAddr(t.mint || ''))}</span></td>
+ <td style="text-align:right" class="pd-mono">${t.amount.toLocaleString(undefined, { maximumFractionDigits: 4 })}</td>
+ <td style="text-align:right" class="pd-mono">${t.usd > 0 ? '$' + t.usd.toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</td>
+ </tr>
+ `).join('')}
+ </tbody>
+ </table>
+ `}
+ `;
+ }
+
+ function disconnectWallet() {
+ try {
+ getConnectedWallet()?.disconnect?.();
+ } catch { /* provider may already be disconnected */ }
+ onWalletChanged(null);
}
// ── Custom agents list ───────────────────────────────────────
@@ -953,35 +1220,63 @@
async function loadCustomAgents() {
const tbody = $('pd-custom-agents-table');
if (!tbody) return;
+ tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">Loading agents…</td></tr>';
try {
const resp = await apiFetch('/api/agents');
+ if (resp.status === 401) {
+ tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">Sign in to manage your agents. <a href="/login" style="color:var(--pd-accent)">Sign in</a></td></tr>';
+ return;
+ }
if (!resp.ok) {
- tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">Sign in to see your agents.</td></tr>';
+ tbody.innerHTML = `<tr><td colspan="4" class="pd-empty">Couldn’t load agents (${resp.status}).</td></tr>`;
return;
}
const j = await resp.json();
const agents = j.agents || j.data || [];
if (!agents.length) {
- tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">No agents yet — click <strong>+ New agent</strong>.</td></tr>';
+ tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">No custom agents yet — click <strong>+ New agent</strong>.</td></tr>';
return;
}
tbody.innerHTML = agents.map((a) => {
const created = a.created_at ? new Date(a.created_at).toLocaleDateString() : '—';
- return `<tr>
+ return `<tr data-agent-row="${escapeHtml(a.id)}">
<td>${escapeHtml(a.name || a.id)}</td>
<td>${escapeHtml((a.description || '').slice(0, 80))}</td>
<td class="pd-mono">${created}</td>
<td>
<a class="pd-btn pd-btn-sm" href="/agent/${escapeHtml(a.id)}/edit">Edit</a>
<a class="pd-btn pd-btn-sm" href="/agent/${escapeHtml(a.id)}">Open</a>
+ <button class="pd-btn pd-btn-sm is-danger" type="button" data-delete-agent="${escapeHtml(a.id)}" data-agent-name="${escapeHtml(a.name || a.id)}">Delete</button>
</td>
</tr>`;
}).join('');
+ tbody.querySelectorAll('[data-delete-agent]').forEach((b) => {
+ b.addEventListener('click', () => deleteAgent(b.dataset.deleteAgent, b.dataset.agentName));
+ });
} catch {
tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">Failed to load agents.</td></tr>';
}
}
+ async function deleteAgent(id, name) {
+ if (!confirm(`Delete agent "${name}"? This cannot be undone.`)) return;
+ try {
+ const csrf = await getCsrfToken();
+ const headers = {};
+ if (csrf) headers['x-csrf-token'] = csrf;
+ const resp = await apiFetch('/api/agents/' + encodeURIComponent(id), { method: 'DELETE', headers });
+ if (resp.ok) {
+ toast('Agent deleted', 'success');
+ loadCustomAgents();
+ } else {
+ const err = await resp.json().catch(() => ({}));
+ toast(err.error_description || err.error || `Delete failed (${resp.status})`, 'error');
+ }
+ } catch (e) {
+ toast('Network error: ' + (e.message || 'delete failed'), 'error');
+ }
+ }
+
// ── Agent control (postMessage to embedded iframe) ───────────
async function loadAgent() {
@@ -1000,23 +1295,64 @@
loadCustomAgents();
}
- function agentAction(type) {
+ function postAgentAction(action) {
const iframe = $('pd-agent-iframe');
- if (!iframe || !iframe.contentWindow || !state.agentId) return;
+ if (!iframe || !iframe.contentWindow || !state.agentId) {
+ toast('Agent preview not ready yet', 'error');
+ return false;
+ }
+ iframe.contentWindow.postMessage({ agentId: state.agentId, type: 'agent:action', action }, '*');
+ return true;
+ }
+
+ // Task 11: Speak posts a real TTS action; the embed plays ElevenLabs audio,
+ // drives lip-sync, and replies with agent:action:result so we surface
+ // real upstream errors instead of failing silently.
+ function agentAction(type) {
let action;
switch (type) {
case 'speak': {
- const text = $('pd-speech-input').value;
- if (!text) return;
- action = { type: 'speak', text };
- break;
+ const text = $('pd-speech-input').value.trim();
+ if (!text) { toast('Enter something to speak', 'error'); return; }
+ if (postAgentAction({ type: 'speak', text })) setSpeaking(true);
+ return;
}
case 'emote': action = { type: 'emote', name: 'dance' }; break;
case 'wave': action = { type: 'gesture', name: 'wave' }; break;
case 'verify': action = { type: 'validate-model' }; break;
default: return;
}
- iframe.contentWindow.postMessage({ agentId: state.agentId, type: 'agent:action', action }, '*');
+ postAgentAction(action);
+ }
+
+ function setSpeaking(on) {
+ const speak = $('pd-speak-btn');
+ const stop = $('pd-speak-stop');
+ if (speak) speak.disabled = on;
+ if (stop) stop.hidden = !on;
+ }
+
+ function stopSpeak() {
+ postAgentAction({ type: 'speak:stop' });
+ setSpeaking(false);
+ }
+
+ // Result + lifecycle messages from the agent embed.
+ function handleAgentMessage(ev) {
+ const msg = ev.data;
+ if (!msg || typeof msg !== 'object') return;
+ if (msg.type === 'agent:action:result') {
+ const act = msg.action || {};
+ if (act.type === 'speak' || act.type === 'speak:stop') {
+ setSpeaking(false);
+ if (msg.ok === false) toast(msg.error || 'Speech failed', 'error');
+ }
+ }
+ // The embed echoes every protocol action; reset the Speak button when
+ // playback finishes even if no explicit result arrives.
+ if (msg.type === 'agent:action' && msg.action?.type === 'speak:end') {
+ setSpeaking(false);
+ }
}
function playAnimation() {
@@ -1232,18 +1568,90 @@
while (feed.children.length > 200) feed.lastElementChild.remove();
}
- function saveAlertConfig() {
- state.alertConfig = {
+ // Task 12: alert config is server-persisted (per user, cross-device) and
+ // evaluated server-side by the pumpfun-monitor cron. localStorage is only
+ // a fast render cache.
+ function applyAlertConfigToForm(cfg) {
+ if (cfg.graduation !== undefined) $('pd-alert-graduation').checked = cfg.graduation;
+ if (cfg.whale !== undefined) $('pd-alert-whale').checked = cfg.whale;
+ if (cfg.fees !== undefined) $('pd-alert-fees').checked = cfg.fees;
+ if (cfg.launch !== undefined) $('pd-alert-launch').checked = cfg.launch;
+ if (cfg.whaleThreshold != null) $('pd-threshold-whale').value = cfg.whaleThreshold;
+ if (cfg.claimThreshold != null) $('pd-threshold-claim').value = cfg.claimThreshold;
+ if (cfg.cooldown != null) $('pd-threshold-cooldown').value = cfg.cooldown;
+ if (cfg.webhookUrl != null) $('pd-alert-webhook').value = cfg.webhookUrl || '';
+ }
+
+ let _alertConfigLoaded = false;
+ async function loadAlertConfig() {
+ // Fetch server alert history into the feed regardless of auth state.
+ loadServerAlerts();
+ if (_alertConfigLoaded) return;
+ try {
+ const resp = await apiFetch('/api/alerts/config');
+ if (resp.status === 401) return; // anonymous — keep local cache
+ if (!resp.ok) return;
+ const { data } = await resp.json();
+ state.alertConfig = data;
+ localStorage.setItem('pumpbot-alerts', JSON.stringify(data));
+ applyAlertConfigToForm(data);
+ _alertConfigLoaded = true;
+ } catch { /* keep local cache */ }
+ }
+
+ async function loadServerAlerts() {
+ try {
+ const resp = await apiFetch('/api/notifications?type=pump_alert&limit=50');
+ if (!resp.ok) return;
+ const { notifications } = await resp.json();
+ if (!Array.isArray(notifications) || !notifications.length) return;
+ notifications.slice().reverse().forEach((n) => {
+ const p = n.payload || {};
+ addAlertItem({
+ time: new Date(n.created_at),
+ data: { name: p.name, tokenSymbol: p.symbol, mint: p.mint, solAmount: p.amount_sol },
+ }, `Graduated · ${p.symbol || p.name || 'token'}`);
+ });
+ } catch { /* server history is best-effort */ }
+ }
+
+ async function saveAlertConfig() {
+ const webhookUrl = $('pd-alert-webhook').value.trim();
+ if (webhookUrl && !/^https:\/\//i.test(webhookUrl)) {
+ toast('Webhook URL must start with https://', 'error');
+ return;
+ }
+ const payload = {
graduation: $('pd-alert-graduation').checked,
whale: $('pd-alert-whale').checked,
fees: $('pd-alert-fees').checked,
launch: $('pd-alert-launch').checked,
- whaleThreshold: $('pd-threshold-whale').value,
- claimThreshold: $('pd-threshold-claim').value,
- cooldown: $('pd-threshold-cooldown').value,
+ whaleThreshold: parseFloat($('pd-threshold-whale').value) || 0,
+ claimThreshold: parseFloat($('pd-threshold-claim').value) || 0,
+ cooldown: parseInt($('pd-threshold-cooldown').value, 10) || 30,
+ webhookUrl: webhookUrl || null,
};
- localStorage.setItem('pumpbot-alerts', JSON.stringify(state.alertConfig));
- toast('Alert settings saved', 'success');
+ try {
+ const csrf = await getCsrfToken();
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrf) headers['x-csrf-token'] = csrf;
+ const resp = await apiFetch('/api/alerts/config', { method: 'PUT', headers, body: JSON.stringify(payload) });
+ if (resp.status === 401) {
+ toast('Sign in to save alerts across devices', 'error');
+ return;
+ }
+ if (!resp.ok) {
+ const err = await resp.json().catch(() => ({}));
+ toast(err.error_description || err.error || `Save failed (${resp.status})`, 'error');
+ return;
+ }
+ const { data } = await resp.json();
+ state.alertConfig = data;
+ localStorage.setItem('pumpbot-alerts', JSON.stringify(data));
+ toast('Alert settings saved', 'success');
+ } catch (e) {
+ toast('Network error: ' + (e.message || 'save failed'), 'error');
+ }
}
// ── Watches ──────────────────────────────────────────────────
@@ -1596,20 +2004,46 @@
},
});
const secretJson = JSON.stringify(Array.from(result.secretKey));
+ const secretB58 = b58encode(result.secretKey);
const seconds = (result.durationMs / 1000).toFixed(1);
$('pd-vanity-status').textContent = `Found in ${seconds}s · ${result.attempts.toLocaleString()} attempts · ${result.workers} worker${result.workers > 1 ? 's' : ''}`;
$('pd-vanity-result').innerHTML = `
<div style="padding:0.85rem 1rem;background:var(--pd-bg-elev);border-radius:var(--pd-radius-sm);border:1px solid var(--pd-accent-border)">
<div style="font-family:var(--pd-font-display);font-size:0.66rem;text-transform:uppercase;letter-spacing:0.1em;color:var(--pd-text-dim);margin-bottom:0.25rem">Public key</div>
<div class="pd-mono" style="font-size:0.92rem;color:var(--pd-accent-bright);word-break:break-all;margin-bottom:0.55rem">${escapeHtml(result.publicKey)}</div>
- <button class="pd-btn pd-btn-sm" id="pd-vanity-copy-pub" type="button">Copy address</button>
- <button class="pd-btn pd-btn-sm" id="pd-vanity-download-key" type="button">Download keypair JSON</button>
+ <div style="display:flex;gap:0.4rem;flex-wrap:wrap">
+ <button class="pd-btn pd-btn-sm" id="pd-vanity-copy-pub" type="button">Copy address</button>
+ <button class="pd-btn pd-btn-sm" id="pd-vanity-reveal" type="button">Reveal secret key</button>
+ <button class="pd-btn pd-btn-sm" id="pd-vanity-download-key" type="button">Download keypair JSON</button>
+ </div>
+ <div id="pd-vanity-secret" hidden style="margin-top:0.6rem">
+ <div style="font-family:var(--pd-font-display);font-size:0.66rem;text-transform:uppercase;letter-spacing:0.1em;color:var(--pd-danger);margin-bottom:0.25rem">Secret key (base58)</div>
+ <div class="pd-mono" id="pd-vanity-secret-val" style="font-size:0.8rem;color:var(--pd-text-bright);word-break:break-all;margin-bottom:0.45rem"></div>
+ <button class="pd-btn pd-btn-sm" id="pd-vanity-copy-secret" type="button">Copy secret</button>
+ </div>
<div class="pd-callout" style="margin-top:0.6rem;font-size:0.78rem">Secret key never leaves your browser. Save it securely or import into a wallet.</div>
</div>
`;
$('pd-vanity-copy-pub').addEventListener('click', async () => {
try { await navigator.clipboard.writeText(result.publicKey); toast('Address copied', 'success'); } catch {}
});
+ $('pd-vanity-reveal').addEventListener('click', () => {
+ const box = $('pd-vanity-secret');
+ const btn = $('pd-vanity-reveal');
+ const showing = !box.hidden;
+ if (showing) {
+ box.hidden = true;
+ $('pd-vanity-secret-val').textContent = '';
+ btn.textContent = 'Reveal secret key';
+ } else {
+ $('pd-vanity-secret-val').textContent = secretB58;
+ box.hidden = false;
+ btn.textContent = 'Hide secret key';
+ }
+ });
+ $('pd-vanity-copy-secret').addEventListener('click', async () => {
+ try { await navigator.clipboard.writeText(secretB58); toast('Secret key copied', 'success'); } catch {}
+ });
$('pd-vanity-download-key').addEventListener('click', () => {
const blob = new Blob([secretJson], { type: 'application/json' });
const url = URL.createObjectURL(blob);
@@ -1639,7 +2073,85 @@
// ── Config ───────────────────────────────────────────────────
- function saveConfig() {
+ // Task 10: persist, reconnect, then probe each endpoint for real and
+ // reflect the live result inline next to each field.
+ function setProbe(id, state_, detail) {
+ const el = $(id);
+ if (!el) return;
+ el.className = 'pd-probe is-' + state_;
+ el.textContent = state_ === 'ok' ? 'OK' : state_ === 'pending' ? 'Testing…' : `Failed: ${detail || 'error'}`;
+ el.title = detail || '';
+ }
+
+ async function probeApi() {
+ try {
+ const r = await fetch(state.apiUrl.replace(/\/$/, '') + '/api/healthz', { signal: AbortSignal.timeout(5000) });
+ if (!r.ok) return { ok: false, detail: `HTTP ${r.status}` };
+ const d = await r.json().catch(() => ({}));
+ return d.ok || d.status === 'ok' ? { ok: true, detail: 'healthy' } : { ok: false, detail: 'no ok flag' };
+ } catch (e) { return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message }; }
+ }
+
+ async function probeApiKey() {
+ if (!state.apiKey) return { ok: false, detail: 'no key set' };
+ try {
+ const r = await fetch(state.apiUrl.replace(/\/$/, '') + '/api/v1/status', {
+ headers: { 'X-API-Key': state.apiKey },
+ signal: AbortSignal.timeout(5000),
+ });
+ if (r.ok) return { ok: true, detail: 'authorized' };
+ if (r.status === 401 || r.status === 403) return { ok: false, detail: `${r.status} unauthorized` };
+ return { ok: false, detail: `HTTP ${r.status}` };
+ } catch (e) { return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message }; }
+ }
+
+ function probeWs() {
+ return new Promise((resolve) => {
+ let settled = false;
+ let sock;
+ const done = (ok, detail) => {
+ if (settled) return;
+ settled = true;
+ try { sock?.close(); } catch {}
+ resolve({ ok, detail });
+ };
+ try {
+ sock = new WebSocket(state.wsUrl);
+ sock.onopen = () => done(true, 'connected');
+ sock.onerror = () => done(false, 'connection error');
+ setTimeout(() => done(false, 'timeout'), 3000);
+ } catch (e) { done(false, e.message); }
+ });
+ }
+
+ async function probeRpc() {
+ try {
+ const r = await fetch(state.rpcUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
+ signal: AbortSignal.timeout(5000),
+ });
+ const d = await r.json().catch(() => ({}));
+ if (d.result === 'ok') return { ok: true, detail: 'healthy' };
+ if (d.error) return { ok: false, detail: d.error.message || 'rpc error' };
+ return { ok: false, detail: `HTTP ${r.status}` };
+ } catch (e) { return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message }; }
+ }
+
+ async function runConfigProbes() {
+ setProbe('pd-probe-api', 'pending');
+ setProbe('pd-probe-key', 'pending');
+ setProbe('pd-probe-ws', 'pending');
+ setProbe('pd-probe-rpc', 'pending');
+ const [api, key, ws, rpc] = await Promise.all([probeApi(), probeApiKey(), probeWs(), probeRpc()]);
+ setProbe('pd-probe-api', api.ok ? 'ok' : 'err', api.detail);
+ setProbe('pd-probe-key', key.ok ? 'ok' : 'err', key.detail);
+ setProbe('pd-probe-ws', ws.ok ? 'ok' : 'err', ws.detail);
+ setProbe('pd-probe-rpc', rpc.ok ? 'ok' : 'err', rpc.detail);
+ }
+
+ async function saveConfig() {
state.apiUrl = $('pd-cfg-api-url').value.trim() || location.origin;
state.wsUrl = $('pd-cfg-ws-url').value.trim() || 'wss://pumpportal.fun/api/data';
state.apiKey = $('pd-cfg-api-key').value.trim();
@@ -1651,7 +2163,18 @@
$('pd-api-endpoint-display').textContent = state.apiUrl;
connectApi();
connectWebSocket();
- toast('Configuration saved & reconnecting', 'success');
+ toast('Configuration saved — testing connections', 'success');
+
+ const btn = $('pd-save-config');
+ const original = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = 'Testing…';
+ try {
+ await runConfigProbes();
+ } finally {
+ btn.disabled = false;
+ btn.textContent = original;
+ }
}
// ── Modals ───────────────────────────────────────────────────
@@ -1680,6 +2203,450 @@
});
}
+ // ── CSRF (single-use, fetched fresh per mutation) ────────────
+ async function getCsrfToken() {
+ try {
+ const r = await apiFetch('/api/csrf-token');
+ if (!r.ok) return null;
+ const d = await r.json();
+ return d.token || d.data?.token || null;
+ } catch { return null; }
+ }
+
+ // ── base58 encode (for revealing the vanity secret key) ──────
+ function b58encode(bytes) {
+ const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+ const digits = [0];
+ for (let i = 0; i < bytes.length; i++) {
+ let carry = bytes[i];
+ for (let j = 0; j < digits.length; j++) {
+ carry += digits[j] << 8;
+ digits[j] = carry % 58;
+ carry = (carry / 58) | 0;
+ }
+ while (carry > 0) { digits.push(carry % 58); carry = (carry / 58) | 0; }
+ }
+ let str = '';
+ for (let i = 0; i < bytes.length && bytes[i] === 0; i++) str += '1';
+ for (let i = digits.length - 1; i >= 0; i--) str += ALPHABET[digits[i]];
+ return str;
+ }
+
+ function relTime(iso) {
+ const diff = Date.now() - new Date(iso).getTime();
+ const m = Math.floor(diff / 60000);
+ if (m < 1) return 'just now';
+ if (m < 60) return m + 'm ago';
+ const h = Math.floor(m / 60);
+ if (h < 24) return h + 'h ago';
+ return Math.floor(h / 24) + 'd ago';
+ }
+
+ // ════════════════════════════════════════════════════════════
+ // Monitor stat cards (Task 07) — bound to GET /api/healthz
+ // ════════════════════════════════════════════════════════════
+ function formatUptime(sec) {
+ const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = Math.floor(sec % 60);
+ if (h > 0) return `${h}h ${m}m`;
+ if (m > 0) return `${m}m ${s}s`;
+ return `${s}s`;
+ }
+ function setMonitorStale(stale) {
+ const grid = $('pd-monitor-stats');
+ if (grid) grid.querySelectorAll('.pd-stat').forEach((c) => c.classList.toggle('is-stale', stale));
+ const sub = $('stat-bot-status-sub');
+ if (sub) sub.innerHTML = stale ? 'Live monitor <span class="pd-stale-badge">stale</span>' : 'Live monitor';
+ }
+ async function pollMonitorStats() {
+ try {
+ const r = await apiFetch('/api/healthz');
+ if (!r.ok) throw new Error('health ' + r.status);
+ const d = await r.json();
+ const m = d.monitor || {};
+ setMonitorStale(false);
+ $('stat-bot-status').textContent = m.running ? 'Running' : 'Stopped';
+ $('stat-bot-status').className = 'pd-stat-value ' + (m.running ? 'is-success' : 'is-danger');
+ $('stat-bot-mode').textContent = m.mode || '—';
+ $('stat-claims').textContent = Number(m.claimsDetected ?? 0).toLocaleString();
+ $('stat-watches').textContent = Number((d.watches || {}).total ?? 0).toLocaleString();
+ $('stat-uptime').textContent = formatUptime(d.uptime || 0);
+ } catch {
+ // Keep last real values, flag stale.
+ setMonitorStale(true);
+ }
+ }
+
+ // ════════════════════════════════════════════════════════════
+ // Canvas helpers shared by the market + revenue charts
+ // ════════════════════════════════════════════════════════════
+ function setupCanvas(canvas) {
+ const dpr = window.devicePixelRatio || 1;
+ const w = canvas.clientWidth || canvas.parentElement.clientWidth || 600;
+ const h = canvas.clientHeight || 280;
+ canvas.width = Math.round(w * dpr);
+ canvas.height = Math.round(h * dpr);
+ const ctx = canvas.getContext('2d');
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ return { ctx, w, h };
+ }
+ function cssVar(name) {
+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '#fff';
+ }
+ function fmtPrice(v) {
+ const n = Number(v);
+ if (!isFinite(n)) return '—';
+ if (n >= 1) return n.toLocaleString(undefined, { maximumFractionDigits: 2 });
+ if (n >= 0.01) return n.toFixed(4);
+ if (n > 0) return n.toPrecision(3);
+ return '0';
+ }
+ function drawChartMessage(canvas, msg) {
+ const { ctx, w, h } = setupCanvas(canvas);
+ ctx.clearRect(0, 0, w, h);
+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';
+ ctx.lineWidth = 1;
+ for (let i = 1; i < 5; i++) { const y = (h * i) / 5; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
+ ctx.fillStyle = 'rgba(255,255,255,0.42)';
+ ctx.font = '12px system-ui';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(msg === 'skeleton' ? 'Loading…' : msg, w / 2, h / 2);
+ }
+
+ // ════════════════════════════════════════════════════════════
+ // Market chart (Tasks 03 + 04)
+ // ════════════════════════════════════════════════════════════
+ const chart = { candles: [], mint: '', symbol: '', spotUsd: null, geom: null };
+
+ async function loadTrendingTokens() {
+ const sel = $('pd-chart-token');
+ if (!sel) return;
+ sel.innerHTML = '<option value="" disabled selected>Loading trending tokens…</option>';
+ $('pd-chart-retry').hidden = true;
+ try {
+ const r = await fetch('/api/pump/trending?limit=25');
+ const d = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ sel.innerHTML = `<option value="" disabled selected>${escapeHtml(d.error_description || d.error || 'Trending unavailable')}</option>`;
+ $('pd-chart-retry').hidden = false;
+ drawChartMessage($('pd-market-chart'), d.error_description || 'Trending tokens unavailable');
+ return;
+ }
+ const tokens = d.data || [];
+ if (!tokens.length) {
+ sel.innerHTML = '<option value="" disabled selected>No trending tokens right now</option>';
+ drawChartMessage($('pd-market-chart'), 'No trending tokens right now');
+ return;
+ }
+ sel.innerHTML = tokens.map((t) =>
+ `<option value="${escapeHtml(t.mint)}" data-symbol="${escapeHtml(t.symbol)}">#${t.rank ?? '?'} ${escapeHtml(t.symbol)} (${escapeHtml(shortAddr(t.mint))})</option>`
+ ).join('');
+ sel.selectedIndex = 0;
+ const first = tokens[0];
+ document.dispatchEvent(new CustomEvent('chart:tokenChange', { detail: { mint: first.mint, symbol: first.symbol } }));
+ } catch (e) {
+ sel.innerHTML = `<option value="" disabled selected>Error loading tokens</option>`;
+ $('pd-chart-retry').hidden = false;
+ drawChartMessage($('pd-market-chart'), e.message || 'load failed');
+ }
+ }
+
+ async function fetchChartData(mint, symbol) {
+ chart.mint = mint;
+ chart.symbol = symbol;
+ chart.spotUsd = null;
+ const canvas = $('pd-market-chart');
+ drawChartMessage(canvas, 'skeleton');
+ $('pd-chart-meta').innerHTML = `<span class="pd-mono" style="color:var(--pd-text-bright)">${escapeHtml(symbol || '')}</span> <span style="color:var(--pd-text-dim)">${escapeHtml(shortAddr(mint))}</span>`;
+ const now = Math.floor(Date.now() / 1000);
+ const from = now - 24 * 3600;
+ try {
+ const r = await fetch(`/api/pump/price-history?mint=${encodeURIComponent(mint)}&interval=15m&from=${from}&to=${now}`);
+ const d = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ drawChartMessage(canvas, d.error_description || d.error || `Error ${r.status}`);
+ $('pd-chart-retry').hidden = false;
+ return;
+ }
+ $('pd-chart-retry').hidden = true;
+ chart.candles = d.data || [];
+ if (!chart.candles.length) {
+ drawChartMessage(canvas, 'No trades in the selected window');
+ } else {
+ drawMarketChart(canvas);
+ const last = chart.candles[chart.candles.length - 1].c;
+ $('pd-chart-meta').innerHTML += ` · <span style="color:var(--pd-text-bright)">$${fmtPrice(last)}</span>`;
+ }
+ fetchSpotOverlay(mint);
+ } catch (e) {
+ drawChartMessage(canvas, e.message || 'load failed');
+ $('pd-chart-retry').hidden = false;
+ }
+ }
+
+ // Live PumpFun bonding-curve spot price, converted to USD via the cached
+ // SOL price and overlaid as a dashed line. Silent no-op for non-PumpFun mints.
+ async function fetchSpotOverlay(mint) {
+ try {
+ const r = await fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}`);
+ if (!r.ok) return;
+ const d = await r.json();
+ const priceSol = Number(d.price?.priceSol);
+ if (!isFinite(priceSol) || priceSol <= 0 || !state.solPrice) return;
+ chart.spotUsd = priceSol * state.solPrice;
+ if (chart.candles.length) drawMarketChart($('pd-market-chart'));
+ $('pd-chart-meta').innerHTML += ` · <span style="color:var(--pd-warn)">live ${priceSol.toFixed(9)} SOL</span>`;
+ } catch { /* overlay optional */ }
+ }
+
+ function drawMarketChart(canvas) {
+ const candles = chart.candles;
+ if (!candles.length) { drawChartMessage(canvas, 'No trades in the selected window'); return; }
+ const { ctx, w, h } = setupCanvas(canvas);
+ ctx.clearRect(0, 0, w, h);
+ const x0 = 56, x1 = w - 12, y0 = 10, y1 = h - 22;
+ const tMin = candles[0].t, tMax = candles[candles.length - 1].t;
+ let pMin = Infinity, pMax = -Infinity;
+ for (const c of candles) { pMin = Math.min(pMin, c.l ?? c.c); pMax = Math.max(pMax, c.h ?? c.c); }
+ if (chart.spotUsd != null) { pMin = Math.min(pMin, chart.spotUsd); pMax = Math.max(pMax, chart.spotUsd); }
+ if (pMin === pMax) { pMin *= 0.99; pMax *= 1.01; }
+ const padP = (pMax - pMin) * 0.08; pMin -= padP; pMax += padP;
+ const xFor = (t) => x0 + (tMax === tMin ? 0 : (t - tMin) / (tMax - tMin)) * (x1 - x0);
+ const yFor = (p) => y1 - (p - pMin) / (pMax - pMin) * (y1 - y0);
+ // Y grid + price ticks
+ ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.fillStyle = 'rgba(255,255,255,0.42)';
+ ctx.font = '10px system-ui'; ctx.lineWidth = 1; ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
+ for (let i = 0; i <= 5; i++) { const p = pMin + (pMax - pMin) * i / 5; const y = yFor(p); ctx.beginPath(); ctx.moveTo(x0, y); ctx.lineTo(x1, y); ctx.stroke(); ctx.fillText('$' + fmtPrice(p), x0 - 6, y); }
+ // X time ticks
+ ctx.textAlign = 'center'; ctx.textBaseline = 'top';
+ const spanHours = (tMax - tMin) / 3600;
+ for (let i = 0; i <= 6; i++) {
+ const t = tMin + (tMax - tMin) * i / 6; const x = xFor(t); const dt = new Date(t * 1000);
+ const label = spanHours <= 24
+ ? dt.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })
+ : `${dt.getMonth() + 1}/${dt.getDate()}`;
+ ctx.fillText(label, Math.max(x0 + 14, Math.min(x1 - 14, x)), y1 + 5);
+ }
+ // Price line + area
+ ctx.strokeStyle = cssVar('--pd-accent'); ctx.lineWidth = 1.5; ctx.beginPath();
+ candles.forEach((c, i) => { const x = xFor(c.t), y = yFor(c.c); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
+ ctx.stroke();
+ ctx.lineTo(xFor(tMax), y1); ctx.lineTo(xFor(tMin), y1); ctx.closePath();
+ ctx.fillStyle = 'rgba(255,255,255,0.05)'; ctx.fill();
+ // Spot overlay
+ if (chart.spotUsd != null) {
+ const y = yFor(chart.spotUsd);
+ ctx.strokeStyle = cssVar('--pd-warn'); ctx.setLineDash([4, 3]); ctx.beginPath(); ctx.moveTo(x0, y); ctx.lineTo(x1, y); ctx.stroke(); ctx.setLineDash([]);
+ }
+ chart.geom = { x0, x1, y0, y1, tMin, tMax, pMin, pMax };
+ }
+
+ function onChartMove(e) {
+ const canvas = $('pd-market-chart');
+ const tip = $('pd-chart-tooltip');
+ const g = chart.geom;
+ if (!g || !chart.candles.length) { tip.style.display = 'none'; return; }
+ const rect = canvas.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ if (x < g.x0 || x > g.x1) { tip.style.display = 'none'; return; }
+ const frac = (x - g.x0) / (g.x1 - g.x0);
+ const t = g.tMin + frac * (g.tMax - g.tMin);
+ let nearest = chart.candles[0], best = Infinity;
+ for (const c of chart.candles) { const dd = Math.abs(c.t - t); if (dd < best) { best = dd; nearest = c; } }
+ const cx = g.x0 + (g.tMax === g.tMin ? 0 : (nearest.t - g.tMin) / (g.tMax - g.tMin)) * (g.x1 - g.x0);
+ const cy = g.y1 - (nearest.c - g.pMin) / (g.pMax - g.pMin) * (g.y1 - g.y0);
+ drawMarketChart(canvas);
+ const ctx = canvas.getContext('2d');
+ ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.lineWidth = 1; ctx.setLineDash([3, 3]);
+ ctx.beginPath(); ctx.moveTo(cx, g.y0); ctx.lineTo(cx, g.y1); ctx.stroke(); ctx.setLineDash([]);
+ ctx.fillStyle = cssVar('--pd-accent'); ctx.beginPath(); ctx.arc(cx, cy, 3, 0, Math.PI * 2); ctx.fill();
+ const dt = new Date(nearest.t * 1000);
+ tip.textContent = `${dt.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })} · $${fmtPrice(nearest.c)}`;
+ tip.style.left = cx + 'px';
+ tip.style.top = cy + 'px';
+ tip.style.display = 'block';
+ }
+
+ // ════════════════════════════════════════════════════════════
+ // Revenue (Task 08)
+ // ════════════════════════════════════════════════════════════
+ const KNOWN_DECIMALS = {
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: 6, // USDC mainnet
+ Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: 6, // USDT mainnet
+ So11111111111111111111111111111111111111112: 9, // wSOL
+ };
+ const _decimalsCache = { ...KNOWN_DECIMALS };
+ async function getMintDecimals(mint) {
+ if (mint in _decimalsCache) return _decimalsCache[mint];
+ try {
+ const r = await fetch(state.rpcUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAccountInfo', params: [mint, { encoding: 'jsonParsed' }] }),
+ });
+ const d = await r.json();
+ const dec = d.result?.value?.data?.parsed?.info?.decimals;
+ if (typeof dec === 'number') { _decimalsCache[mint] = dec; return dec; }
+ } catch { /* fall through */ }
+ return 6;
+ }
+
+ let _revAgentsLoaded = false;
+ async function loadRevenue() {
+ if (!_revAgentsLoaded) { await loadRevenueAgents(); _revAgentsLoaded = true; }
+ await fetchRevenue();
+ }
+ async function loadRevenueAgents() {
+ try {
+ const r = await apiFetch('/api/agents');
+ if (!r.ok) return;
+ const j = await r.json();
+ const agents = j.agents || j.data || [];
+ $('pd-rev-agent').innerHTML = '<option value="">All agents</option>' +
+ agents.map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name || a.id)}</option>`).join('');
+ } catch { /* keep "All agents" */ }
+ }
+ async function fetchRevenue() {
+ const status = $('pd-rev-status');
+ const skillTbody = $('pd-rev-skill-table');
+ status.textContent = 'Loading…';
+ skillTbody.innerHTML = '<tr><td colspan="3" class="pd-empty">Loading…</td></tr>';
+ const params = new URLSearchParams();
+ const agent = $('pd-rev-agent').value; if (agent) params.set('agent_id', agent);
+ params.set('granularity', $('pd-rev-granularity').value || 'day');
+ const from = $('pd-rev-from').value; if (from) params.set('from', new Date(from).toISOString());
+ const to = $('pd-rev-to').value; if (to) params.set('to', new Date(to + 'T23:59:59').toISOString());
+ try {
+ const r = await apiFetch('/api/billing/revenue?' + params.toString());
+ if (r.status === 401) {
+ status.innerHTML = 'Sign in to view revenue. <a href="/login" style="color:var(--pd-accent)">Sign in</a>';
+ skillTbody.innerHTML = '<tr><td colspan="3" class="pd-empty">Sign in required.</td></tr>';
+ ['pd-rev-gross', 'pd-rev-fees', 'pd-rev-net', 'pd-rev-count'].forEach((id) => { $(id).textContent = '—'; });
+ drawChartMessage($('pd-rev-chart'), 'Sign in to view revenue');
+ return;
+ }
+ if (!r.ok) {
+ const err = await r.json().catch(() => ({}));
+ status.textContent = err.error_description || err.error || `Error ${r.status}`;
+ return;
+ }
+ await renderRevenue(await r.json());
+ } catch (e) {
+ status.textContent = 'Error: ' + (e.message || 'failed');
+ }
+ }
+ async function renderRevenue(d) {
+ const s = d.summary || {};
+ const mint = s.currency_mint;
+ const decimals = mint ? await getMintDecimals(mint) : 6;
+ const fmt = (v) => (Number(v || 0) / Math.pow(10, decimals)).toLocaleString(undefined, { maximumFractionDigits: Math.min(decimals, 6) });
+ $('pd-rev-gross').textContent = fmt(s.gross_total);
+ $('pd-rev-fees').textContent = fmt(s.fee_total);
+ $('pd-rev-net').textContent = fmt(s.net_total);
+ $('pd-rev-count').textContent = Number(s.payment_count || 0).toLocaleString();
+ $('pd-rev-currency').textContent = mint ? shortAddr(mint) : '—';
+ $('pd-rev-chain').textContent = s.chain || '—';
+ const skills = d.by_skill || [];
+ $('pd-rev-skill-table').innerHTML = skills.length
+ ? skills.map((r) => `<tr><td>${escapeHtml(r.skill)}</td><td style="text-align:right" class="pd-mono">${Number(r.count || 0).toLocaleString()}</td><td style="text-align:right" class="pd-mono">${fmt(r.net_total)}</td></tr>`).join('')
+ : '<tr><td colspan="3" class="pd-empty">No revenue events in this window.</td></tr>';
+ drawRevenueChart(d.timeseries || [], decimals);
+ $('pd-rev-status').textContent = (s.payment_count || 0) === 0 ? 'No revenue events in this window.' : '';
+ }
+ function drawRevenueChart(series, decimals) {
+ const canvas = $('pd-rev-chart');
+ if (!series.length) { drawChartMessage(canvas, 'No revenue events in this window'); return; }
+ const { ctx, w, h } = setupCanvas(canvas);
+ ctx.clearRect(0, 0, w, h);
+ const x0 = 56, x1 = w - 12, y0 = 10, y1 = h - 22;
+ const vals = series.map((s) => Number(s.net_total || 0) / Math.pow(10, decimals));
+ let vMax = Math.max(...vals, 0); if (vMax === 0) vMax = 1;
+ const n = series.length;
+ const xFor = (i) => x0 + (n === 1 ? 0.5 : i / (n - 1)) * (x1 - x0);
+ const yFor = (v) => y1 - (v / vMax) * (y1 - y0);
+ ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.fillStyle = 'rgba(255,255,255,0.42)';
+ ctx.font = '10px system-ui'; ctx.lineWidth = 1; ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
+ for (let i = 0; i <= 4; i++) { const v = vMax * i / 4; const y = yFor(v); ctx.beginPath(); ctx.moveTo(x0, y); ctx.lineTo(x1, y); ctx.stroke(); ctx.fillText(v.toLocaleString(undefined, { maximumFractionDigits: 2 }), x0 - 6, y); }
+ ctx.textAlign = 'center'; ctx.textBaseline = 'top';
+ const step = Math.max(1, Math.floor(n / 6));
+ for (let i = 0; i < n; i += step) { const x = xFor(i); ctx.fillText(String(series[i].period).slice(5), Math.max(x0 + 12, Math.min(x1 - 12, x)), y1 + 5); }
+ ctx.strokeStyle = cssVar('--pd-success'); ctx.lineWidth = 1.5; ctx.beginPath();
+ vals.forEach((v, i) => { const x = xFor(i), y = yFor(v); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
+ ctx.stroke();
+ ctx.lineTo(xFor(n - 1), y1); ctx.lineTo(xFor(0), y1); ctx.closePath();
+ ctx.fillStyle = 'rgba(74,222,128,0.08)'; ctx.fill();
+ }
+
+ // ════════════════════════════════════════════════════════════
+ // API keys (Task 09)
+ // ════════════════════════════════════════════════════════════
+ async function loadApiKeys() {
+ const tbody = $('pd-keys-table');
+ tbody.innerHTML = '<tr><td colspan="7" class="pd-empty">Loading…</td></tr>';
+ try {
+ const r = await apiFetch('/api/api-keys');
+ if (r.status === 401) { tbody.innerHTML = '<tr><td colspan="7" class="pd-empty">Sign in to manage keys. <a href="/login" style="color:var(--pd-accent)">Sign in</a></td></tr>'; $('pd-keys-count').textContent = '—'; return; }
+ if (r.status === 429) { tbody.innerHTML = '<tr><td colspan="7" class="pd-empty">Too many requests, try again shortly.</td></tr>'; return; }
+ if (!r.ok) { tbody.innerHTML = `<tr><td colspan="7" class="pd-empty">Error ${r.status}.</td></tr>`; return; }
+ const { data } = await r.json();
+ $('pd-keys-count').textContent = String(data.length);
+ if (!data.length) { tbody.innerHTML = '<tr><td colspan="7" class="pd-empty">You haven\'t created any API keys yet.</td></tr>'; return; }
+ tbody.innerHTML = data.map((k) => `<tr>
+ <td>${escapeHtml(k.name)}</td>
+ <td class="pd-mono">${escapeHtml(k.prefix)}…</td>
+ <td class="pd-mono" style="font-size:0.74rem">${escapeHtml((k.scope || '').split(/\s+/).filter(Boolean).join(', '))}</td>
+ <td class="pd-mono">${k.created_at ? new Date(k.created_at).toLocaleDateString() : '—'}</td>
+ <td class="pd-mono">${k.last_used_at ? relTime(k.last_used_at) : 'never'}</td>
+ <td class="pd-mono">${k.expires_at ? new Date(k.expires_at).toLocaleDateString() : '—'}</td>
+ <td><button class="pd-btn pd-btn-sm is-danger" type="button" data-revoke-key="${escapeHtml(k.id)}">Revoke</button></td>
+ </tr>`).join('');
+ tbody.querySelectorAll('[data-revoke-key]').forEach((b) => b.addEventListener('click', () => revokeApiKey(b.dataset.revokeKey)));
+ } catch (e) {
+ tbody.innerHTML = `<tr><td colspan="7" class="pd-empty">Failed: ${escapeHtml(e.message || 'load failed')}</td></tr>`;
+ }
+ }
+ async function createApiKey(e) {
+ e.preventDefault();
+ const name = $('pd-key-name').value.trim();
+ if (!name) { toast('Key name is required', 'error'); return; }
+ const scopes = Array.from(document.querySelectorAll('.pd-key-scope:checked')).map((c) => c.value);
+ if (!scopes.length) { toast('Select at least one scope', 'error'); return; }
+ const body = { name, scope: scopes.join(' ') };
+ const expiryRaw = $('pd-key-expiry').value;
+ if (expiryRaw) body.expires_at = new Date(expiryRaw).toISOString();
+ const btn = $('pd-key-create');
+ btn.disabled = true;
+ try {
+ const csrf = await getCsrfToken();
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrf) headers['x-csrf-token'] = csrf;
+ const r = await apiFetch('/api/api-keys', { method: 'POST', headers, body: JSON.stringify(body) });
+ if (r.status === 429) { toast('Too many requests, try again shortly', 'error'); return; }
+ if (!r.ok) { const err = await r.json().catch(() => ({})); toast(err.error_description || err.error || `Create failed (${r.status})`, 'error'); return; }
+ const { data } = await r.json();
+ $('pd-key-token').value = data.token;
+ openModal('pd-key-modal');
+ } catch (e2) {
+ toast('Network error: ' + (e2.message || 'create failed'), 'error');
+ } finally {
+ btn.disabled = false;
+ }
+ }
+ async function revokeApiKey(id) {
+ if (!confirm('Revoke this API key? Apps using it will stop working immediately.')) return;
+ try {
+ const csrf = await getCsrfToken();
+ const headers = {};
+ if (csrf) headers['x-csrf-token'] = csrf;
+ const r = await apiFetch('/api/api-keys/' + encodeURIComponent(id), { method: 'DELETE', headers });
+ if (!r.ok) { const err = await r.json().catch(() => ({})); toast(err.error_description || err.error || `Revoke failed (${r.status})`, 'error'); return; }
+ toast('Key revoked', 'success');
+ loadApiKeys();
+ } catch (e) {
+ toast('Network error revoking key', 'error');
+ }
+ }
+
// ── Boot ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
@@ -1744,24 +2711,77 @@
$('pd-vanity-start').addEventListener('click', startVanity);
$('pd-vanity-stop').addEventListener('click', stopVanity);
- // Animations
+ if (state.alertConfig.webhookUrl) $('pd-alert-webhook').value = state.alertConfig.webhookUrl;
+
+ // Animations + TTS (Task 11)
$('pd-speak-btn').addEventListener('click', () => agentAction('speak'));
+ $('pd-speak-stop').addEventListener('click', stopSpeak);
$('pd-play-anim').addEventListener('click', playAnimation);
document.querySelectorAll('[data-agent-action]').forEach((b) => {
b.addEventListener('click', () => agentAction(b.dataset.agentAction));
});
+ window.addEventListener('message', handleAgentMessage);
- // Config
+ // Config (Task 10)
$('pd-save-config').addEventListener('click', saveConfig);
+ // Wallet snapshot (Task 02) — connect via src/wallet.js, react to events.
+ initWalletButton();
+ window.addEventListener('wallet:changed', (e) => onWalletChanged(e.detail?.address || null));
+ $('connect-wallet-btn')?.addEventListener('click', () => {
+ const holdings = $('pd-wallet-holdings');
+ if (holdings && !getConnectedWalletAddress()) {
+ $('pd-wallet-empty').hidden = true;
+ holdings.hidden = false;
+ holdings.innerHTML = '<div style="font-size:0.85rem;color:var(--pd-text-muted)">Connecting…</div>';
+ }
+ });
+ $('pd-wallet-disconnect').addEventListener('click', disconnectWallet);
+
+ // Market chart (Tasks 03 + 04)
+ $('pd-chart-token').addEventListener('change', (e) => {
+ const opt = e.target.selectedOptions[0];
+ if (!opt || !opt.value) return;
+ document.dispatchEvent(new CustomEvent('chart:tokenChange', { detail: { mint: opt.value, symbol: opt.dataset.symbol || '' } }));
+ });
+ $('pd-chart-retry').addEventListener('click', () => {
+ if (chart.mint) fetchChartData(chart.mint, chart.symbol);
+ else loadTrendingTokens();
+ });
+ document.addEventListener('chart:tokenChange', (e) => fetchChartData(e.detail.mint, e.detail.symbol));
+ const marketCanvas = $('pd-market-chart');
+ marketCanvas.addEventListener('mousemove', onChartMove);
+ marketCanvas.addEventListener('mouseleave', () => { $('pd-chart-tooltip').style.display = 'none'; });
+ let _chartResizeRaf = 0;
+ new ResizeObserver(() => {
+ cancelAnimationFrame(_chartResizeRaf);
+ _chartResizeRaf = requestAnimationFrame(() => { if (chart.candles.length) drawMarketChart(marketCanvas); });
+ }).observe(marketCanvas);
+
+ // Revenue (Task 08)
+ $('pd-rev-refresh').addEventListener('click', fetchRevenue);
+ ['pd-rev-agent', 'pd-rev-granularity', 'pd-rev-from', 'pd-rev-to'].forEach((id) => {
+ $(id).addEventListener('change', fetchRevenue);
+ });
+
+ // API keys (Task 09)
+ $('pd-key-create-form').addEventListener('submit', createApiKey);
+ $('pd-key-copy').addEventListener('click', async () => {
+ try { await navigator.clipboard.writeText($('pd-key-token').value); toast('Token copied', 'success'); } catch {}
+ });
+ $('pd-key-done').addEventListener('click', () => { closeModal('pd-key-modal'); $('pd-key-token').value = ''; loadApiKeys(); });
+
// Boot the data flows
connectApi();
connectWebSocket();
preloadChannelFeed();
refreshNetworkStats();
loadFeaturedAgent();
- loadWalletSnapshot();
+ loadTrendingTokens();
+ pollMonitorStats();
+ runConfigProbes();
state.networkInterval = setInterval(refreshNetworkStats, 30000);
+ state.monitorInterval = setInterval(pollMonitorStats, 10000);
setInterval(updateUptime, 1000);
});
@@ -1803,5 +2823,6 @@
</script>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pump-live.html b/pages/pump-live.html
index bd5ca2947..dc62a07a2 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -283,6 +283,7 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index f3bcf3c25..1955895a4 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -2125,5 +2125,6 @@
enterFeedMode();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/pumpfun-buy.html b/pages/pumpfun-buy.html
index b8e97b91c..823ee8de8 100644
--- a/pages/pumpfun-buy.html
+++ b/pages/pumpfun-buy.html
@@ -62,5 +62,6 @@
};
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pumpfun-counter.html b/pages/pumpfun-counter.html
index 83cb52594..a57934bd9 100644
--- a/pages/pumpfun-counter.html
+++ b/pages/pumpfun-counter.html
@@ -37,5 +37,6 @@
counterElement.innerText = count;
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pumpfun-search.html b/pages/pumpfun-search.html
index 700ad7637..4f0870755 100644
--- a/pages/pumpfun-search.html
+++ b/pages/pumpfun-search.html
@@ -119,5 +119,6 @@
return d.innerHTML;
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/pumpfun-trending.html b/pages/pumpfun-trending.html
index 1266bd356..c29d7a38d 100644
--- a/pages/pumpfun-trending.html
+++ b/pages/pumpfun-trending.html
@@ -103,5 +103,6 @@
fetchTrending();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/scan.html b/pages/scan.html
index 58d4feb07..b61b89332 100644
--- a/pages/scan.html
+++ b/pages/scan.html
@@ -850,5 +850,6 @@
showStep('capture');
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/shopper.html b/pages/shopper.html
index 84bcd2990..b8f3721d7 100644
--- a/pages/shopper.html
+++ b/pages/shopper.html
@@ -463,5 +463,6 @@
</div>
<script type="module" src="/src/shopper-app.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/skills.html b/pages/skills.html
index e2a026847..73461f305 100644
--- a/pages/skills.html
+++ b/pages/skills.html
@@ -20,5 +20,6 @@
})();
</script>
</head>
- <body></body>
+ <body> <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/start.html b/pages/start.html
index fdc74294b..5b17d721f 100644
--- a/pages/start.html
+++ b/pages/start.html
@@ -940,5 +940,6 @@
<div class="wz-toast" id="wz-toast" role="alert" aria-live="assertive"></div>
<script type="module" src="/src/start.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/three-live.html b/pages/three-live.html
index c433fd13b..2a47baf51 100644
--- a/pages/three-live.html
+++ b/pages/three-live.html
@@ -657,5 +657,6 @@
connectTrades();
raf = requestAnimationFrame(tick);
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/three-ws-launch-week.html b/pages/three-ws-launch-week.html
index bd90bc0c7..648f281da 100644
--- a/pages/three-ws-launch-week.html
+++ b/pages/three-ws-launch-week.html
@@ -1391,5 +1391,6 @@
document.querySelectorAll('.reveal').forEach(el => observer.observe(el));
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/threews-claim.html b/pages/threews-claim.html
index e35b4e87e..fc075b2e6 100644
--- a/pages/threews-claim.html
+++ b/pages/threews-claim.html
@@ -307,5 +307,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/tutorial.html b/pages/tutorial.html
index b67eca316..a0ae40d5d 100644
--- a/pages/tutorial.html
+++ b/pages/tutorial.html
@@ -1023,5 +1023,6 @@
window.addEventListener('DOMContentLoaded', loadTutorial);
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/tutorials.html b/pages/tutorials.html
index c24dc77e9..6ec55785a 100644
--- a/pages/tutorials.html
+++ b/pages/tutorials.html
@@ -732,5 +732,6 @@
window.addEventListener('DOMContentLoaded', renderTutorials);
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/unstoppable.html b/pages/unstoppable.html
index 34184f70c..a7ea68622 100644
--- a/pages/unstoppable.html
+++ b/pages/unstoppable.html
@@ -587,5 +587,6 @@
<script type="module" src="/x402.js"></script>
<!-- DASHBOARD JS -->
<script type="module" src="/src/unstoppable-dashboard.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/voice.html b/pages/voice.html
index 505d4cfb6..26e3ed167 100644
--- a/pages/voice.html
+++ b/pages/voice.html
@@ -770,5 +770,6 @@
<script src="/nav.js" defer></script>
<script type="module" src="/src/voice-lab.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/walk-app.html b/pages/walk-app.html
index 5a0c27803..44a1c76d0 100644
--- a/pages/walk-app.html
+++ b/pages/walk-app.html
@@ -519,5 +519,6 @@
</div>
<script type="module" src="/src/walk.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/walk.html b/pages/walk.html
index cbbb805e0..c968c4969 100644
--- a/pages/walk.html
+++ b/pages/walk.html
@@ -1180,5 +1180,6 @@
feed + realtime bubbles) bound to the current coin. Self-contained;
the 3D scene above is walk.js's, the multiplayer join is walk-net's. -->
<script type="module" src="/src/community/coin-world-boot.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/widgets.html b/pages/widgets.html
index 082e1a9da..13157ce58 100644
--- a/pages/widgets.html
+++ b/pages/widgets.html
@@ -613,5 +613,6 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/worlds.html b/pages/worlds.html
index c23bbefea..372d89451 100644
--- a/pages/worlds.html
+++ b/pages/worlds.html
@@ -457,5 +457,6 @@
<div class="wl-toast" id="wl-toast" role="status" aria-live="polite"></div>
<script type="module" src="/src/worlds-lobby.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/pages/x-pricing.html b/pages/x-pricing.html
index 21085e2ba..f02458aaa 100644
--- a/pages/x-pricing.html
+++ b/pages/x-pricing.html
@@ -155,5 +155,6 @@
}
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/pages/xr.html b/pages/xr.html
index 574d7913f..308d41126 100644
--- a/pages/xr.html
+++ b/pages/xr.html
@@ -397,5 +397,6 @@
});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/404.html b/public/404.html
index 935c6363e..a60706926 100644
--- a/public/404.html
+++ b/public/404.html
@@ -152,5 +152,6 @@
agent.interceptNavigation(homeBtn, { direction: 'right', delay: 1100 });
agent.interceptNavigation(labBtn, { direction: 'left', delay: 1100 });
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/admin/index.html b/public/admin/index.html
index af35807d2..4bb96843c 100644
--- a/public/admin/index.html
+++ b/public/admin/index.html
@@ -396,5 +396,6 @@ function shortAddr(a, n=6) { return a ? `${a.slice(0,n)}…${a.slice(-4)}` : '
boot();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/admin/news.html b/public/admin/news.html
index dc9de53e3..236d28e6f 100644
--- a/public/admin/news.html
+++ b/public/admin/news.html
@@ -538,5 +538,6 @@ window.addEventListener('beforeunload', (e) => {
refresh();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/agent-badge.html b/public/agent-badge.html
index b22a7fbdf..a19987f2e 100644
--- a/public/agent-badge.html
+++ b/public/agent-badge.html
@@ -108,5 +108,6 @@
}
load();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/agent-edit/index.html b/public/agent-edit/index.html
index 1366a1d2d..c9024370c 100644
--- a/public/agent-edit/index.html
+++ b/public/agent-edit/index.html
@@ -694,5 +694,6 @@
<div class="toast" id="toast"></div>
<script type="module" src="./edit.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/agent-passport.html b/public/agent-passport.html
index f8a11949a..91c4f46d1 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -1115,5 +1115,6 @@
if ($('asset').value) load();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/agent/index.html b/public/agent/index.html
index 8367999ec..0ce37b94d 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -1005,5 +1005,6 @@
`<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/agents/index.html b/public/agents/index.html
index d62342eda..676c41cbc 100644
--- a/public/agents/index.html
+++ b/public/agents/index.html
@@ -408,5 +408,6 @@
<script src="/footer.js" defer></script>
<script type="module" src="/agents/boot.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/ai-stream.html b/public/ai-stream.html
index 7de0ad192..3bdb6a0e0 100644
--- a/public/ai-stream.html
+++ b/public/ai-stream.html
@@ -195,5 +195,6 @@
init();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/arbitrage.html b/public/arbitrage.html
index 4d83c7bfa..400237f94 100644
--- a/public/arbitrage.html
+++ b/public/arbitrage.html
@@ -355,5 +355,6 @@
</div>
<script type="module" src="/arbitrage.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/artifact-example.html b/public/artifact-example.html
index 4e3f503d7..42bc6d659 100644
--- a/public/artifact-example.html
+++ b/public/artifact-example.html
@@ -20,5 +20,6 @@
-->
<div data-agent-id="demo" style="width: 100%; height: 100vh"></div>
<script type="module" src="https://three.ws/artifact.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/avatars/cz.glb b/public/avatars/cz.glb
index 79648be49..7b5ec3471 100644
Binary files a/public/avatars/cz.glb and b/public/avatars/cz.glb differ
diff --git a/public/avatars/default.glb b/public/avatars/default.glb
index 23dd38e7f..9ebc33b10 100644
Binary files a/public/avatars/default.glb and b/public/avatars/default.glb differ
diff --git a/public/bazaar.html b/public/bazaar.html
index 28668fdaf..927e06241 100644
--- a/public/bazaar.html
+++ b/public/bazaar.html
@@ -496,5 +496,6 @@
<!-- The drop-in x402 modal, which we use for the "Try it" pay flow. -->
<script type="module" src="/x402.js"></script>
<script type="module" src="/bazaar.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/brand.js b/public/brand.js
new file mode 100644
index 000000000..6bf06cdf9
--- /dev/null
+++ b/public/brand.js
@@ -0,0 +1,153 @@
+/**
+ * three.ws — universal top-left brand mark.
+ *
+ * Guarantees a single, consistent top-left logo on every standalone page.
+ * The site grew a dozen different header treatments (wordmark lockups, dashboard
+ * rails, `header-logo`, bare `<img>`s, page-specific classes, and pages with no
+ * logo at all). Rather than rewrite every header, this fills the gap: if a page
+ * already shows a top-left brand it is left untouched; if it shows none, a
+ * tasteful fixed brand chip is injected linking back home.
+ *
+ * Chromeless surfaces (embeds, widgets, iframes) opt out with either:
+ * <html data-no-brand-mark>
+ * <meta name="brand-mark" content="off" />
+ */
+(function () {
+ if (window.__threeBrandMark) return;
+ window.__threeBrandMark = true;
+
+ if (document.documentElement.hasAttribute('data-no-brand-mark')) return;
+ if (document.querySelector('meta[name="brand-mark"][content="off"]')) return;
+ // Inside an iframe the host already frames us — never overlay a logo.
+ try {
+ if (window.self !== window.top) return;
+ } catch (_) {
+ return;
+ }
+
+ // Known brand classes used across the site's many headers/shells.
+ var BRAND_SELECTORS = [
+ '.brand-mark',
+ '.wordmark-logo',
+ '.header-logo',
+ '.dn-rail-full',
+ '.nxt-brand-mark',
+ '.agent-header-logo',
+ '.pg-header-logo',
+ '[data-brand-mark]',
+ ].join(',');
+
+ // Things that, when they sit in the top-left corner, mean the corner is
+ // already taken — either by an existing brand or by a control (hamburger,
+ // back/close button, home link) the chip must not cover.
+ var CORNER_OCCUPANTS =
+ 'a[href="/"],a[href="/home"],button,summary,[class*="burger" i],[class*="hamburger" i],[class*="menu-toggle" i],[aria-label*="menu" i],[aria-label*="back" i],[aria-label*="home" i]';
+
+ function inOwnChip(el) {
+ return !!(el.closest && el.closest('.brand-mark-chip'));
+ }
+
+ // True when the element is rendered in the top-left corner. `maxWidth` lets
+ // us treat only logo/icon-sized images as brands (a full-bleed hero that
+ // happens to start at 0,0 should not block the mark).
+ function inCorner(el, maxWidth) {
+ if (inOwnChip(el)) return false;
+ var r = el.getBoundingClientRect();
+ if (!(r.width > 0 && r.height > 0)) return false;
+ if (maxWidth && r.width > maxWidth) return false;
+ return r.top < 104 && r.left < 232;
+ }
+
+ function anyInCorner(selector, maxWidth) {
+ var nodes = document.querySelectorAll(selector);
+ for (var i = 0; i < nodes.length; i++) {
+ if (inCorner(nodes[i], maxWidth)) return true;
+ }
+ return false;
+ }
+
+ function hasExistingBrand() {
+ // 1. A known brand element exists anywhere — the page is already branded.
+ var named = document.querySelectorAll(BRAND_SELECTORS);
+ for (var i = 0; i < named.length; i++) {
+ if (!inOwnChip(named[i])) return true;
+ }
+ // 2. A logo/icon image or inline SVG occupies the top-left corner.
+ if (anyInCorner('img,svg', 360)) return true;
+ // 3. A brand wordmark or nav control occupies the top-left corner.
+ if (anyInCorner(CORNER_OCCUPANTS)) return true;
+ return false;
+ }
+
+ function ensureStyles() {
+ if (document.getElementById('three-brand-mark-style')) return;
+ var style = document.createElement('style');
+ style.id = 'three-brand-mark-style';
+ style.textContent = [
+ '.brand-mark-chip{',
+ 'position:fixed;top:14px;left:16px;z-index:60;',
+ 'display:inline-flex;align-items:center;justify-content:center;',
+ 'width:36px;height:36px;border-radius:9px;',
+ 'background:rgba(12,12,16,.55);',
+ '-webkit-backdrop-filter:blur(10px) saturate(140%);',
+ 'backdrop-filter:blur(10px) saturate(140%);',
+ 'box-shadow:0 1px 2px rgba(0,0,0,.28),inset 0 0 0 1px rgba(255,255,255,.07);',
+ 'opacity:0;transform:translateY(-4px);',
+ 'transition:opacity .22s ease,transform .22s ease,box-shadow .18s ease,background .18s ease;',
+ '-webkit-tap-highlight-color:transparent;',
+ '}',
+ '.brand-mark-chip.is-in{opacity:1;transform:none;}',
+ '.brand-mark-chip:hover{background:rgba(12,12,16,.72);box-shadow:0 6px 18px rgba(0,0,0,.32),inset 0 0 0 1px rgba(255,255,255,.12);}',
+ '.brand-mark-chip:focus-visible{outline:2px solid #6e8bff;outline-offset:2px;}',
+ '.brand-mark-chip .brand-mark{display:block;width:24px;height:24px;border-radius:5px;}',
+ '@media (max-width:560px){.brand-mark-chip{top:10px;left:10px;width:34px;height:34px;}}',
+ '@media (prefers-reduced-motion:reduce){.brand-mark-chip{transition:none;transform:none;}}',
+ '@media print{.brand-mark-chip{display:none;}}',
+ ].join('');
+ document.head.appendChild(style);
+ }
+
+ function injectChip() {
+ if (document.querySelector('.brand-mark-chip')) return;
+ var a = document.createElement('a');
+ a.className = 'brand-mark-chip';
+ a.href = '/';
+ a.setAttribute('aria-label', 'three.ws — home');
+ a.innerHTML =
+ '<img class="brand-mark" src="/three.svg" alt="three.ws" width="24" height="24" />';
+ document.body.appendChild(a);
+ requestAnimationFrame(function () {
+ a.classList.add('is-in');
+ });
+ }
+
+ function removeChip() {
+ var chip = document.querySelector('.brand-mark-chip');
+ if (chip) chip.remove();
+ }
+
+ function run() {
+ ensureStyles();
+ if (hasExistingBrand()) return;
+ injectChip();
+ // Some pages render their chrome asynchronously (JS-mounted dashboard
+ // rails, hydrated headers). Re-check briefly and retract the chip if a
+ // real brand appears, so the page never shows two logos.
+ var checks = 0;
+ var timer = setInterval(function () {
+ checks++;
+ if (hasExistingBrand()) {
+ removeChip();
+ clearInterval(timer);
+ } else if (checks >= 8) {
+ clearInterval(timer);
+ }
+ }, 250);
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', run);
+ } else {
+ run();
+ }
+})();
diff --git a/public/changelog/index.html b/public/changelog/index.html
index 38f952245..d986734bb 100644
--- a/public/changelog/index.html
+++ b/public/changelog/index.html
@@ -93,5 +93,6 @@
console.error('[changelog]', err);
}
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/character.html b/public/character.html
index 2a8587e28..06284998e 100644
--- a/public/character.html
+++ b/public/character.html
@@ -71,5 +71,6 @@
</div>
<script type="module" src="/src/character.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/characters.html b/public/characters.html
index 1f42ab587..8c79855a1 100644
--- a/public/characters.html
+++ b/public/characters.html
@@ -45,5 +45,6 @@
<div class="chs-bottom-pad"></div>
<script type="module" src="/src/characters.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/crypto-demo.html b/public/crypto-demo.html
index 46bc97ee6..3853e05a6 100644
--- a/public/crypto-demo.html
+++ b/public/crypto-demo.html
@@ -19,5 +19,6 @@
manifest="/crypto-agent-manifest.json"
></agent-3d>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/cz/index.html b/public/cz/index.html
index 85752074f..d22382850 100644
--- a/public/cz/index.html
+++ b/public/cz/index.html
@@ -75,5 +75,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/cz/offline/index.html b/public/cz/offline/index.html
index 33c3f7571..f7ecae8a9 100644
--- a/public/cz/offline/index.html
+++ b/public/cz/offline/index.html
@@ -451,5 +451,6 @@
console.log('CZ Offline Demo initialized');
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/actions.html b/public/dashboard-classic/actions.html
index 4fcb1718d..492cf07e2 100644
--- a/public/dashboard-classic/actions.html
+++ b/public/dashboard-classic/actions.html
@@ -629,5 +629,6 @@
return String(text).replace(/[&<>"']/g, (c) => map[c]);
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/agent-pumpfun.html b/public/dashboard-classic/agent-pumpfun.html
index 789e44561..08f75c048 100644
--- a/public/dashboard-classic/agent-pumpfun.html
+++ b/public/dashboard-classic/agent-pumpfun.html
@@ -1836,5 +1836,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/delegation.html b/public/dashboard-classic/delegation.html
index 1a417b752..369b6de5b 100644
--- a/public/dashboard-classic/delegation.html
+++ b/public/dashboard-classic/delegation.html
@@ -137,5 +137,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/embed-policy.html b/public/dashboard-classic/embed-policy.html
index 463cb3f06..e24e3d334 100644
--- a/public/dashboard-classic/embed-policy.html
+++ b/public/dashboard-classic/embed-policy.html
@@ -719,5 +719,6 @@
await loadPolicy();
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/index.html b/public/dashboard-classic/index.html
index 3146b8b44..6d5ef48c7 100644
--- a/public/dashboard-classic/index.html
+++ b/public/dashboard-classic/index.html
@@ -1434,5 +1434,6 @@
.catch(() => {});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/memory.html b/public/dashboard-classic/memory.html
index e7efc1273..b6bcfe961 100644
--- a/public/dashboard-classic/memory.html
+++ b/public/dashboard-classic/memory.html
@@ -836,5 +836,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/portfolio-asset.html b/public/dashboard-classic/portfolio-asset.html
index 5fe119aab..9dcd86c33 100644
--- a/public/dashboard-classic/portfolio-asset.html
+++ b/public/dashboard-classic/portfolio-asset.html
@@ -787,5 +787,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/portfolio.html b/public/dashboard-classic/portfolio.html
index 188054c96..c707d4ecd 100644
--- a/public/dashboard-classic/portfolio.html
+++ b/public/dashboard-classic/portfolio.html
@@ -1393,5 +1393,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/sessions.html b/public/dashboard-classic/sessions.html
index 8d34a04ca..9a68ca19d 100644
--- a/public/dashboard-classic/sessions.html
+++ b/public/dashboard-classic/sessions.html
@@ -465,5 +465,6 @@
`;
document.head.appendChild(style);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/sns.html b/public/dashboard-classic/sns.html
index 1d6fc03bd..8ebc411c6 100644
--- a/public/dashboard-classic/sns.html
+++ b/public/dashboard-classic/sns.html
@@ -437,5 +437,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/storage.html b/public/dashboard-classic/storage.html
index e4ca74833..08c16ee70 100644
--- a/public/dashboard-classic/storage.html
+++ b/public/dashboard-classic/storage.html
@@ -499,5 +499,6 @@
});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/strategy.html b/public/dashboard-classic/strategy.html
index db93ea495..5d6fa839f 100644
--- a/public/dashboard-classic/strategy.html
+++ b/public/dashboard-classic/strategy.html
@@ -132,5 +132,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/tokens.html b/public/dashboard-classic/tokens.html
index ae9c08463..84eb441be 100644
--- a/public/dashboard-classic/tokens.html
+++ b/public/dashboard-classic/tokens.html
@@ -157,5 +157,6 @@
onPick: (agentId) => render(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/usage.html b/public/dashboard-classic/usage.html
index 365c77aca..37fb37079 100644
--- a/public/dashboard-classic/usage.html
+++ b/public/dashboard-classic/usage.html
@@ -207,5 +207,6 @@
el.style.display = '';
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/voice.html b/public/dashboard-classic/voice.html
index b260d4c94..0d5dd5dd2 100644
--- a/public/dashboard-classic/voice.html
+++ b/public/dashboard-classic/voice.html
@@ -217,5 +217,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/wallets.html b/public/dashboard-classic/wallets.html
index b1f883899..43ce20836 100644
--- a/public/dashboard-classic/wallets.html
+++ b/public/dashboard-classic/wallets.html
@@ -553,5 +553,6 @@
document.getElementById('link-solana-btn').addEventListener('click', linkSolanaWallet);
refreshLinkButtons();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard-classic/x402.html b/public/dashboard-classic/x402.html
index c7c9674e9..b7825ad0a 100644
--- a/public/dashboard-classic/x402.html
+++ b/public/dashboard-classic/x402.html
@@ -624,5 +624,6 @@
loadList();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/dashboard/actions.html b/public/dashboard/actions.html
index 66e9b6e6f..0a8eb3b2e 100644
--- a/public/dashboard/actions.html
+++ b/public/dashboard/actions.html
@@ -629,5 +629,6 @@
return String(text).replace(/[&<>"']/g, (c) => map[c]);
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.html
index 3e4c65c58..1710aed9f 100644
--- a/public/dashboard/agent-pumpfun.html
+++ b/public/dashboard/agent-pumpfun.html
@@ -1836,5 +1836,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/delegation.html b/public/dashboard/delegation.html
index 1a417b752..369b6de5b 100644
--- a/public/dashboard/delegation.html
+++ b/public/dashboard/delegation.html
@@ -137,5 +137,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.html
index 18be57a4f..c7362b1ee 100644
--- a/public/dashboard/embed-policy.html
+++ b/public/dashboard/embed-policy.html
@@ -719,5 +719,6 @@
await loadPolicy();
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index dd6f215c1..52e91258b 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1440,5 +1440,6 @@
.catch(() => {});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/memory.html b/public/dashboard/memory.html
index 533e2bc9d..b5def8a81 100644
--- a/public/dashboard/memory.html
+++ b/public/dashboard/memory.html
@@ -836,5 +836,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/portfolio-asset.html b/public/dashboard/portfolio-asset.html
index 3470b50a6..4147becdb 100644
--- a/public/dashboard/portfolio-asset.html
+++ b/public/dashboard/portfolio-asset.html
@@ -787,5 +787,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/portfolio.html b/public/dashboard/portfolio.html
index 4fbb055fa..8f724cd0a 100644
--- a/public/dashboard/portfolio.html
+++ b/public/dashboard/portfolio.html
@@ -1393,5 +1393,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/sessions.html b/public/dashboard/sessions.html
index 39a412314..6d4ef8385 100644
--- a/public/dashboard/sessions.html
+++ b/public/dashboard/sessions.html
@@ -465,5 +465,6 @@
`;
document.head.appendChild(style);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/sns.html b/public/dashboard/sns.html
index 1d6fc03bd..8ebc411c6 100644
--- a/public/dashboard/sns.html
+++ b/public/dashboard/sns.html
@@ -437,5 +437,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/storage.html b/public/dashboard/storage.html
index ebd358450..2f8c0f5c5 100644
--- a/public/dashboard/storage.html
+++ b/public/dashboard/storage.html
@@ -499,5 +499,6 @@
});
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/strategy.html b/public/dashboard/strategy.html
index db93ea495..5d6fa839f 100644
--- a/public/dashboard/strategy.html
+++ b/public/dashboard/strategy.html
@@ -132,5 +132,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/tokens.html b/public/dashboard/tokens.html
index ae9c08463..84eb441be 100644
--- a/public/dashboard/tokens.html
+++ b/public/dashboard/tokens.html
@@ -157,5 +157,6 @@
onPick: (agentId) => render(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/usage.html b/public/dashboard/usage.html
index 365c77aca..37fb37079 100644
--- a/public/dashboard/usage.html
+++ b/public/dashboard/usage.html
@@ -207,5 +207,6 @@
el.style.display = '';
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/voice.html b/public/dashboard/voice.html
index b260d4c94..0d5dd5dd2 100644
--- a/public/dashboard/voice.html
+++ b/public/dashboard/voice.html
@@ -217,5 +217,6 @@
onPick: (agentId) => refresh(agentId),
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.html
index 5c41a6b58..14682dc4c 100644
--- a/public/dashboard/wallets.html
+++ b/public/dashboard/wallets.html
@@ -553,5 +553,6 @@
document.getElementById('link-solana-btn').addEventListener('click', linkSolanaWallet);
refreshLinkButtons();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/dashboard/x402.html b/public/dashboard/x402.html
index c7c9674e9..b7825ad0a 100644
--- a/public/dashboard/x402.html
+++ b/public/dashboard/x402.html
@@ -624,5 +624,6 @@
loadList();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/demo/avatar-os/combined.html b/public/demo/avatar-os/combined.html
index cba62f9fd..45c99cb4e 100644
--- a/public/demo/avatar-os/combined.html
+++ b/public/demo/avatar-os/combined.html
@@ -99,5 +99,6 @@
</div>
</main>
<script type="module" src="/src/demo/os-combined.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demo/avatar-os/index.html b/public/demo/avatar-os/index.html
index f97853e3e..26b1816d6 100644
--- a/public/demo/avatar-os/index.html
+++ b/public/demo/avatar-os/index.html
@@ -122,5 +122,6 @@
</section>
</main>
<script type="module" src="/src/demo/os-hub.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demo/avatar-os/live.html b/public/demo/avatar-os/live.html
index 1a467ee35..a5928da95 100644
--- a/public/demo/avatar-os/live.html
+++ b/public/demo/avatar-os/live.html
@@ -132,5 +132,6 @@
</div>
</main>
<script type="module" src="/src/demo/os-live.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demo/avatar-os/selfie.html b/public/demo/avatar-os/selfie.html
index 0df74e739..d671ba37e 100644
--- a/public/demo/avatar-os/selfie.html
+++ b/public/demo/avatar-os/selfie.html
@@ -118,5 +118,6 @@
</div>
</main>
<script type="module" src="/src/demo/os-selfie.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demo/avatar-os/studio.html b/public/demo/avatar-os/studio.html
index 881f8cb63..c8ead1d2b 100644
--- a/public/demo/avatar-os/studio.html
+++ b/public/demo/avatar-os/studio.html
@@ -100,5 +100,6 @@
</div>
</main>
<script type="module" src="/src/demo/os-studio.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demo/coin/index.html b/public/demo/coin/index.html
index d28624902..ccba2829e 100644
--- a/public/demo/coin/index.html
+++ b/public/demo/coin/index.html
@@ -261,5 +261,6 @@
</main>
<footer id="site-footer"></footer>
<script type="module" src="/demo/coin/dashboard.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/demos/3d-home.html b/public/demos/3d-home.html
index 67e0544ed..8f84307a4 100644
--- a/public/demos/3d-home.html
+++ b/public/demos/3d-home.html
@@ -823,5 +823,6 @@
} catch (_) {}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/404.html b/public/demos/404.html
index 3829fdd59..bd06a1929 100644
--- a/public/demos/404.html
+++ b/public/demos/404.html
@@ -166,5 +166,6 @@
agent.interceptNavigation(homeBtn, { direction: 'right', delay: 1100 });
agent.interceptNavigation(labBtn, { direction: 'left', delay: 1100 });
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/auto-rig.html b/public/demos/agents/auto-rig.html
index 3732af64d..a5b3ca438 100644
--- a/public/demos/agents/auto-rig.html
+++ b/public/demos/agents/auto-rig.html
@@ -462,5 +462,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/builds-button.html b/public/demos/agents/builds-button.html
index c33015dd8..3b2f23f7d 100644
--- a/public/demos/agents/builds-button.html
+++ b/public/demos/agents/builds-button.html
@@ -174,5 +174,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/climb-title.html b/public/demos/agents/climb-title.html
index 86a9639db..ef390ce06 100644
--- a/public/demos/agents/climb-title.html
+++ b/public/demos/agents/climb-title.html
@@ -107,5 +107,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/cursor-follower.html b/public/demos/agents/cursor-follower.html
index 09d4459e0..9ec3d1d97 100644
--- a/public/demos/agents/cursor-follower.html
+++ b/public/demos/agents/cursor-follower.html
@@ -140,5 +140,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/face-mocap.html b/public/demos/agents/face-mocap.html
index 3306ae4c8..0917d60de 100644
--- a/public/demos/agents/face-mocap.html
+++ b/public/demos/agents/face-mocap.html
@@ -714,5 +714,6 @@
stage.renderer.render(stage.scene, stage.camera);
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/fall-from-top.html b/public/demos/agents/fall-from-top.html
index 6e1dc0b86..ac6554297 100644
--- a/public/demos/agents/fall-from-top.html
+++ b/public/demos/agents/fall-from-top.html
@@ -105,5 +105,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/falls-asleep.html b/public/demos/agents/falls-asleep.html
index 3cdd8d53b..13ab000fc 100644
--- a/public/demos/agents/falls-asleep.html
+++ b/public/demos/agents/falls-asleep.html
@@ -126,5 +126,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/gemini-live.html b/public/demos/agents/gemini-live.html
index d5f1f0b75..dd0007660 100644
--- a/public/demos/agents/gemini-live.html
+++ b/public/demos/agents/gemini-live.html
@@ -632,5 +632,6 @@
if (mocapActive) mocap.update();
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/high-five.html b/public/demos/agents/high-five.html
index a08b26168..3c9422d26 100644
--- a/public/demos/agents/high-five.html
+++ b/public/demos/agents/high-five.html
@@ -104,5 +104,6 @@
else if (prox < 0.35 && current === A.wave) switchTo(A.idle, 0.3);
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/holds-cta.html b/public/demos/agents/holds-cta.html
index 752b0479f..22809ed88 100644
--- a/public/demos/agents/holds-cta.html
+++ b/public/demos/agents/holds-cta.html
@@ -108,5 +108,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/index.html b/public/demos/agents/index.html
index cbcfab953..e40c51e38 100644
--- a/public/demos/agents/index.html
+++ b/public/demos/agents/index.html
@@ -206,5 +206,6 @@
</div>
</section>
</main>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/pickup-drop.html b/public/demos/agents/pickup-drop.html
index 465caf897..99daae714 100644
--- a/public/demos/agents/pickup-drop.html
+++ b/public/demos/agents/pickup-drop.html
@@ -128,5 +128,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/scroll-inertia.html b/public/demos/agents/scroll-inertia.html
index ff8069b83..d0c6ffd2a 100644
--- a/public/demos/agents/scroll-inertia.html
+++ b/public/demos/agents/scroll-inertia.html
@@ -114,5 +114,6 @@
else if (speed < 0.4 && current === A.falling) switchTo(A.idle, 0.4);
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/sit-in-body.html b/public/demos/agents/sit-in-body.html
index 91ec4c442..2b985562b 100644
--- a/public/demos/agents/sit-in-body.html
+++ b/public/demos/agents/sit-in-body.html
@@ -86,5 +86,6 @@
avatar.position.y += (targetY - avatar.position.y) * lerp;
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/skateboard.html b/public/demos/agents/skateboard.html
index 2f1b7258f..d5d085687 100644
--- a/public/demos/agents/skateboard.html
+++ b/public/demos/agents/skateboard.html
@@ -155,5 +155,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/trampoline.html b/public/demos/agents/trampoline.html
index 498b7c9f4..c747436d3 100644
--- a/public/demos/agents/trampoline.html
+++ b/public/demos/agents/trampoline.html
@@ -117,5 +117,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/walks-gutter.html b/public/demos/agents/walks-gutter.html
index fd910093e..1feaa00fc 100644
--- a/public/demos/agents/walks-gutter.html
+++ b/public/demos/agents/walks-gutter.html
@@ -106,5 +106,6 @@
avatar.rotation.y = dirX < 0 ? Math.PI * 0.18 : -Math.PI * 0.18;
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/agents/wrecking-ball.html b/public/demos/agents/wrecking-ball.html
index 1a3807cb0..20ee20452 100644
--- a/public/demos/agents/wrecking-ball.html
+++ b/public/demos/agents/wrecking-ball.html
@@ -154,5 +154,6 @@
}
}, rootBone, baseRootPos);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/avatar-sdk.html b/public/demos/avatar-sdk.html
index a4b41c566..8c6ee2719 100644
--- a/public/demos/avatar-sdk.html
+++ b/public/demos/avatar-sdk.html
@@ -176,5 +176,6 @@ creator.open();</pre>
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/bonding-curve.html b/public/demos/bonding-curve.html
index 3444b6df0..50f3857a0 100644
--- a/public/demos/bonding-curve.html
+++ b/public/demos/bonding-curve.html
@@ -694,5 +694,6 @@
showBuyPreview();
showSellPreview();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/brain.html b/public/demos/brain.html
index e6d3d5da9..43634edd1 100644
--- a/public/demos/brain.html
+++ b/public/demos/brain.html
@@ -296,5 +296,6 @@ const s=getSession();if(s?.system)systemTa.value=s.system;
checkAvailability();loadAgentContext();
if(window.innerWidth<=860)sidebar.classList.add('collapsed');
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/demos/button-jump.html b/public/demos/button-jump.html
index b660af8f8..2b6c8d310 100644
--- a/public/demos/button-jump.html
+++ b/public/demos/button-jump.html
@@ -448,5 +448,6 @@
boot().catch(console.error);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/button.html b/public/demos/button.html
index b660af8f8..2b6c8d310 100644
--- a/public/demos/button.html
+++ b/public/demos/button.html
@@ -448,5 +448,6 @@
boot().catch(console.error);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/checkout.html b/public/demos/checkout.html
index eb7d99a35..cf46fc09a 100644
--- a/public/demos/checkout.html
+++ b/public/demos/checkout.html
@@ -484,5 +484,6 @@
} catch (_) {}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/create-v2.html b/public/demos/create-v2.html
index 4ebd2d5b1..362b67eaa 100644
--- a/public/demos/create-v2.html
+++ b/public/demos/create-v2.html
@@ -482,5 +482,6 @@
});
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/demos/eas-reputation.html b/public/demos/eas-reputation.html
index b60a497d8..c5e88b542 100644
--- a/public/demos/eas-reputation.html
+++ b/public/demos/eas-reputation.html
@@ -503,5 +503,6 @@ string above, then paste the new UID here.</pre>
updateWalletUI();
logLine(`EAS contract: ${EAS_ADDRESS} on Base Sepolia (84532). Read works without a wallet; write requires testnet ETH.`, 'info');
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/erc8004.html b/public/demos/erc8004.html
index 033ef66bc..81e65fc2c 100644
--- a/public/demos/erc8004.html
+++ b/public/demos/erc8004.html
@@ -249,5 +249,6 @@
form.addEventListener('submit', search);
search();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/gallery-picker.html b/public/demos/gallery-picker.html
index d15842046..1f8e3c101 100644
--- a/public/demos/gallery-picker.html
+++ b/public/demos/gallery-picker.html
@@ -612,5 +612,6 @@
resetAndLoad();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/halfbody-xr.html b/public/demos/halfbody-xr.html
index 9fe202616..c68cf5f05 100644
--- a/public/demos/halfbody-xr.html
+++ b/public/demos/halfbody-xr.html
@@ -315,5 +315,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/index.html b/public/demos/index.html
index 1cf7fc371..59d37f4dd 100644
--- a/public/demos/index.html
+++ b/public/demos/index.html
@@ -260,5 +260,6 @@
</main>
<script src="/nav.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/lipsync-mic.html b/public/demos/lipsync-mic.html
index 98ff508a6..bc829090e 100644
--- a/public/demos/lipsync-mic.html
+++ b/public/demos/lipsync-mic.html
@@ -221,5 +221,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/lipsync-tts.html b/public/demos/lipsync-tts.html
index e560e6f32..7ba039a70 100644
--- a/public/demos/lipsync-tts.html
+++ b/public/demos/lipsync-tts.html
@@ -331,5 +331,6 @@
speakBtn.addEventListener('click', speak);
stopBtn.addEventListener('click', stop);
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/livepeer-inference.html b/public/demos/livepeer-inference.html
index 123e033a5..0e61336c9 100644
--- a/public/demos/livepeer-inference.html
+++ b/public/demos/livepeer-inference.html
@@ -390,5 +390,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/login-2.html b/public/demos/login-2.html
index fda469b58..3b5e32009 100644
--- a/public/demos/login-2.html
+++ b/public/demos/login-2.html
@@ -534,5 +534,6 @@
} catch (_) {}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/login.html b/public/demos/login.html
index cf3ba1974..d296cc9ed 100644
--- a/public/demos/login.html
+++ b/public/demos/login.html
@@ -246,5 +246,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/memory-seed.html b/public/demos/memory-seed.html
index d51a1ebbb..33e77b920 100644
--- a/public/demos/memory-seed.html
+++ b/public/demos/memory-seed.html
@@ -419,5 +419,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/persona-extract.html b/public/demos/persona-extract.html
index 568a7fc65..c274b2b4e 100644
--- a/public/demos/persona-extract.html
+++ b/public/demos/persona-extract.html
@@ -487,5 +487,6 @@
stream.scrollTop = stream.scrollHeight;
}
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/pricing.html b/public/demos/pricing.html
index d294ad533..2444a0404 100644
--- a/public/demos/pricing.html
+++ b/public/demos/pricing.html
@@ -645,5 +645,6 @@
} catch (_) {}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/react-sdk.html b/public/demos/react-sdk.html
index ef0373adc..ae6fd403e 100644
--- a/public/demos/react-sdk.html
+++ b/public/demos/react-sdk.html
@@ -264,5 +264,6 @@ const { avatar, loading, error } = useAvatar(id);</pre>
root.render(h(HookDemo));
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/selfie-fit.html b/public/demos/selfie-fit.html
index cefba9f30..5e2046e70 100644
--- a/public/demos/selfie-fit.html
+++ b/public/demos/selfie-fit.html
@@ -1073,5 +1073,6 @@
log('demo ready. click a slot to begin.', 'ok');
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/skill-royalty.html b/public/demos/skill-royalty.html
index cc8d142fe..987519bfe 100644
--- a/public/demos/skill-royalty.html
+++ b/public/demos/skill-royalty.html
@@ -1754,5 +1754,6 @@
}
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/usdz-ar.html b/public/demos/usdz-ar.html
index 858f45a3b..da4b81a97 100644
--- a/public/demos/usdz-ar.html
+++ b/public/demos/usdz-ar.html
@@ -207,5 +207,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/demos/voice-clone.html b/public/demos/voice-clone.html
index 2948512f1..cd3c1de64 100644
--- a/public/demos/voice-clone.html
+++ b/public/demos/voice-clone.html
@@ -439,5 +439,6 @@
});
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/discover/detail.html b/public/discover/detail.html
index 7cba3f917..5dd1accd9 100644
--- a/public/discover/detail.html
+++ b/public/discover/detail.html
@@ -109,5 +109,6 @@
</main>
<script type="module" src="/discover/detail.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/discover/index.html b/public/discover/index.html
index 94d6ae4b9..984782420 100644
--- a/public/discover/index.html
+++ b/public/discover/index.html
@@ -140,5 +140,6 @@
<script src="/footer.js" defer></script>
<script type="module" src="/discover/discover.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/docs-widgets.html b/public/docs-widgets.html
index e74b26c47..70ff8e0e5 100644
--- a/public/docs-widgets.html
+++ b/public/docs-widgets.html
@@ -493,5 +493,6 @@ img-src https://three.ws/ data:;</code></pre>
</div>
</div>
</footer>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/eth-vanity.html b/public/eth-vanity.html
index b75e9c7a2..2177f10a6 100644
--- a/public/eth-vanity.html
+++ b/public/eth-vanity.html
@@ -610,5 +610,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/features.json b/public/features.json
index 1bdc147a0..6222045da 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-01T07:06:33.691Z",
+ "generated_at": "2026-06-01T17:05:02.016Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/first-meet/index.html b/public/first-meet/index.html
index 5278886bf..4980dcb5c 100644
--- a/public/first-meet/index.html
+++ b/public/first-meet/index.html
@@ -314,5 +314,6 @@
<script src="/dist-lib/agent-3d.js" type="module"></script>
<script type="module" src="./first-meet.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/forever.html b/public/forever.html
index 74fe851af..4a6cb9abe 100644
--- a/public/forever.html
+++ b/public/forever.html
@@ -732,5 +732,6 @@
</div>
<script type="module" src="/forever.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/forgot-password.html b/public/forgot-password.html
index 2a089a156..47e5d4c8c 100644
--- a/public/forgot-password.html
+++ b/public/forgot-password.html
@@ -282,5 +282,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/gallery/index.html b/public/gallery/index.html
index a9ccda3d8..e59c70c6b 100644
--- a/public/gallery/index.html
+++ b/public/gallery/index.html
@@ -144,5 +144,6 @@
<script src="/footer.js"></script>
<script type="module" src="/gallery/gallery.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/gmgn.html b/public/gmgn.html
index 4fb16650f..70a7a460d 100644
--- a/public/gmgn.html
+++ b/public/gmgn.html
@@ -845,5 +845,6 @@
// ── Go ───────────────────────────────────────────────────────────────────
connect();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/hydrate/index.html b/public/hydrate/index.html
index 03b2e52ee..9eac49cd5 100644
--- a/public/hydrate/index.html
+++ b/public/hydrate/index.html
@@ -489,5 +489,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/launch-week.html b/public/launch-week.html
index 7f7d958b8..7693ac8e2 100644
--- a/public/launch-week.html
+++ b/public/launch-week.html
@@ -2788,5 +2788,6 @@
}
</style>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/legal/aws-marketplace-eula.html b/public/legal/aws-marketplace-eula.html
index d4948a380..1d8e8b9d5 100644
--- a/public/legal/aws-marketplace-eula.html
+++ b/public/legal/aws-marketplace-eula.html
@@ -99,5 +99,6 @@
<hr>
<p class="foot">three.ws &nbsp;·&nbsp; <a href="/legal/tos.html">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/privacy.html">Privacy Policy</a> &nbsp;·&nbsp; <a href="/">Home</a></p>
</div>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/legal/eula.html b/public/legal/eula.html
index d02459f43..455f9b62c 100644
--- a/public/legal/eula.html
+++ b/public/legal/eula.html
@@ -103,5 +103,6 @@
<hr>
<p class="foot">three.ws &nbsp;·&nbsp; <a href="/legal/tos.html">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/privacy.html">Privacy Policy</a> &nbsp;·&nbsp; <a href="/">Home</a></p>
</div>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/legal/privacy.html b/public/legal/privacy.html
index 758b9524c..c577d559e 100644
--- a/public/legal/privacy.html
+++ b/public/legal/privacy.html
@@ -106,5 +106,6 @@
<hr>
<p class="foot">three.ws &nbsp;·&nbsp; <a href="/legal/tos.html">Terms of Service</a> &nbsp;·&nbsp; <a href="/marketplace?tab=mine">Home</a></p>
</div>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/legal/tos.html b/public/legal/tos.html
index 656c730c5..246e8cef2 100644
--- a/public/legal/tos.html
+++ b/public/legal/tos.html
@@ -89,5 +89,6 @@
<hr>
<p class="foot">three.ws &nbsp;·&nbsp; <a href="/legal/privacy.html">Privacy Policy</a> &nbsp;·&nbsp; <a href="/">Home</a></p>
</div>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/login.html b/public/login.html
index e82fb4e15..4595cb16b 100644
--- a/public/login.html
+++ b/public/login.html
@@ -911,5 +911,6 @@
agent.play('silly', { loop: true });
};
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/my-agents/index.html b/public/my-agents/index.html
index 0fd2e9d69..8ecfd31be 100644
--- a/public/my-agents/index.html
+++ b/public/my-agents/index.html
@@ -89,5 +89,6 @@
</main>
<script type="module" src="/my-agents/my-agents.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/nav.css b/public/nav.css
index a76b4b745..b64fe7634 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -723,3 +723,61 @@ body.nav-open {
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
}
+
+/* ── Walk Companion toggle ─────────────────────────────────────────────── */
+.home-nav .nav-walk-toggle {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: none;
+ border: 0;
+ padding: 0.45rem 0.7rem;
+ border-radius: 999px;
+ color: var(--nav-fg, rgba(255, 255, 255, 0.72));
+ font-family: inherit;
+ font-weight: 600;
+ font-size: 0.86rem;
+ line-height: 1.2;
+ cursor: pointer;
+ transition:
+ color 0.18s ease,
+ background 0.18s ease,
+ box-shadow 0.18s ease;
+}
+
+.home-nav .nav-walk-toggle .nav-walk-ico {
+ font-size: 1rem;
+ transform: translateY(0);
+ transition: transform 0.18s ease;
+}
+
+.home-nav .nav-walk-toggle:hover {
+ color: #fff;
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.home-nav .nav-walk-toggle:hover .nav-walk-ico {
+ transform: translateX(2px);
+}
+
+.home-nav .nav-walk-toggle:focus-visible {
+ outline: 2px solid #7aa2ff;
+ outline-offset: 2px;
+}
+
+/* Active / pressed state — companion is live */
+.home-nav .nav-walk-toggle.is-on,
+.home-nav .nav-walk-toggle[aria-pressed='true'] {
+ color: #0a0c12;
+ background: linear-gradient(120deg, #9fe6c8, #7aa2ff);
+ box-shadow: 0 6px 16px -8px rgba(122, 162, 255, 0.8);
+}
+
+@media (max-width: 980px) {
+ .home-nav .nav-walk-toggle {
+ width: 100%;
+ justify-content: center;
+ min-height: 44px;
+ }
+}
diff --git a/public/nav.html b/public/nav.html
index 7bdfe65ce..6d4bdaca1 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -433,6 +433,20 @@
<li class="nav-item" id="home-nav-user-li" role="none" hidden>
<a href="/dashboard" id="home-nav-user" class="nav-user" role="menuitem"></a>
</li>
+ <li class="nav-item" role="none">
+ <button
+ type="button"
+ class="nav-walk-toggle"
+ id="home-nav-walk"
+ role="menuitem"
+ aria-pressed="false"
+ aria-label="Walk with me — toggle the avatar companion"
+ title="Walk with me"
+ >
+ <span class="nav-walk-ico" aria-hidden="true">🚶</span>
+ <span class="nav-walk-label">Walk</span>
+ </button>
+ </li>
<li class="nav-item" role="none">
<a href="/login" class="nav-cta" id="home-nav-cta" role="menuitem"
>Get started</a
diff --git a/public/nav.js b/public/nav.js
index 712e186d3..57ada1907 100644
--- a/public/nav.js
+++ b/public/nav.js
@@ -20,6 +20,71 @@ function initNav(root) {
initBurger(root);
initAuthHint(root);
initActivePage(root);
+ initWalkToggle(root);
+}
+
+// Walk Companion toggle. Loads the stable, unhashed /walk-companion.js module
+// (built from src/walk-companion.js — see vite.config.js) only when enabled, so
+// pages pay no Three.js cost when it's off. State lives in localStorage and the
+// ?walk=1 / ?walk=0 query param, both also honored by the module itself.
+const WALK_ENABLED_KEY = 'walk:companion:enabled';
+
+function walkIsEnabled() {
+ try {
+ return localStorage.getItem(WALK_ENABLED_KEY) === '1';
+ } catch (_) {
+ return false;
+ }
+}
+
+function ensureWalkCompanion() {
+ if (document.querySelector('script[src="/walk-companion.js"]')) return;
+ const s = document.createElement('script');
+ s.type = 'module';
+ s.src = '/walk-companion.js';
+ document.head.appendChild(s);
+}
+
+function initWalkToggle(root) {
+ const btn = root.querySelector('#home-nav-walk');
+ if (!btn) return;
+
+ const params = new URLSearchParams(location.search);
+ const override = params.get('walk');
+
+ function sync() {
+ const on = walkIsEnabled();
+ btn.setAttribute('aria-pressed', on ? 'true' : 'false');
+ btn.classList.toggle('is-on', on);
+ }
+
+ // An explicit ?walk= override decides the initial state; otherwise restore.
+ if (override === '1' || override === '0') {
+ try {
+ localStorage.setItem(WALK_ENABLED_KEY, override);
+ } catch (_) {}
+ }
+ sync();
+
+ // Load the module if the companion should be active on this page. The module
+ // is self-mounting; ensureWalkCompanion is idempotent.
+ if (override === '1' || (override !== '0' && walkIsEnabled())) {
+ ensureWalkCompanion();
+ }
+
+ btn.addEventListener('click', () => {
+ if (window.__walkCompanion) {
+ window.__walkCompanion.toggle();
+ } else {
+ try {
+ localStorage.setItem(WALK_ENABLED_KEY, '1');
+ } catch (_) {}
+ ensureWalkCompanion();
+ }
+ sync();
+ });
+
+ window.addEventListener('walk-companion:change', sync);
}
function initActivePage(root) {
diff --git a/public/next/index.html b/public/next/index.html
index 101794894..1bb57e9ce 100644
--- a/public/next/index.html
+++ b/public/next/index.html
@@ -449,5 +449,6 @@
}, { passive: true });
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/p/index.html b/public/p/index.html
index a4f9d03d6..c7e6ec163 100644
--- a/public/p/index.html
+++ b/public/p/index.html
@@ -179,5 +179,6 @@
<div class="skeleton">Loading launchpad…</div>
</div>
<script type="module" src="/p/render.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/pay/c/index.html b/public/pay/c/index.html
index 4438e5cce..efe7c83cf 100644
--- a/public/pay/c/index.html
+++ b/public/pay/c/index.html
@@ -347,5 +347,6 @@
loadSku();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/pay/calls/index.html b/public/pay/calls/index.html
index fd00fe371..2ed25a9ab 100644
--- a/public/pay/calls/index.html
+++ b/public/pay/calls/index.html
@@ -333,5 +333,6 @@ if (!tx) {
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/pay/index.html b/public/pay/index.html
index beb72620a..fc54de8d9 100644
--- a/public/pay/index.html
+++ b/public/pay/index.html
@@ -1694,5 +1694,6 @@ const bscParams = new URLSearchParams(location.search);
if (bscParams.get('chain') === 'bsc') activateChain('bsc');
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/paywall.html b/public/paywall.html
index 2f1952066..61577a374 100644
--- a/public/paywall.html
+++ b/public/paywall.html
@@ -380,5 +380,6 @@
<footer class="page-footer">Secured by the x402 micropayment protocol</footer>
<script src="/paywall.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/persona/authorize.html b/public/persona/authorize.html
index 3131d913c..7f0c4d05b 100644
--- a/public/persona/authorize.html
+++ b/public/persona/authorize.html
@@ -296,5 +296,6 @@
start();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/persona/demo.html b/public/persona/demo.html
index c6c254323..a7af78d09 100644
--- a/public/persona/demo.html
+++ b/public/persona/demo.html
@@ -321,5 +321,6 @@ if (!res.ok) throw new Error(claims.error_description);
log('err', `Error: ${e.detail?.message || 'unknown'}`);
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/providers.html b/public/providers.html
index 4644518ae..f80663234 100644
--- a/public/providers.html
+++ b/public/providers.html
@@ -324,5 +324,6 @@
</div>
<script type="module" src="/providers.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/pump-grid-poc.html b/public/pump-grid-poc.html
index 03ae0640b..5849d4ca9 100644
--- a/public/pump-grid-poc.html
+++ b/public/pump-grid-poc.html
@@ -45,5 +45,6 @@
grid.load(widgets);
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/pumpfun.html b/public/pumpfun.html
index aa95a685f..0cc8cef1c 100644
--- a/public/pumpfun.html
+++ b/public/pumpfun.html
@@ -1734,5 +1734,6 @@
connect();
fetchFirstClaims();
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
\ No newline at end of file
diff --git a/public/register.html b/public/register.html
index eb1876ec3..271c66882 100644
--- a/public/register.html
+++ b/public/register.html
@@ -644,5 +644,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/reputation/index.html b/public/reputation/index.html
index a64cbd038..423e0d9a3 100644
--- a/public/reputation/index.html
+++ b/public/reputation/index.html
@@ -451,5 +451,6 @@
</footer>
<script type="module" src="/reputation/reputation.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/reset-password.html b/public/reset-password.html
index 5d02e3409..37bb6dc88 100644
--- a/public/reset-password.html
+++ b/public/reset-password.html
@@ -218,5 +218,6 @@
}
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/settings/index.html b/public/settings/index.html
index 5bd283d2d..227d4b0a1 100644
--- a/public/settings/index.html
+++ b/public/settings/index.html
@@ -935,5 +935,6 @@
navigate(tabFromQuery || location.hash.slice(1) || 'profile');
})();
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/siwx-test.html b/public/siwx-test.html
index b5471e59e..7ae53a124 100644
--- a/public/siwx-test.html
+++ b/public/siwx-test.html
@@ -123,5 +123,6 @@
first = true;
});
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/strategy-lab.html b/public/strategy-lab.html
index 04df43542..54459dda6 100644
--- a/public/strategy-lab.html
+++ b/public/strategy-lab.html
@@ -528,5 +528,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/studio-deposit-harness.html b/public/studio-deposit-harness.html
index da45580e2..425fd7108 100644
--- a/public/studio-deposit-harness.html
+++ b/public/studio-deposit-harness.html
@@ -6,5 +6,6 @@
<body>
<div id="root"></div>
<script type="module" src="/studio-deposit-harness.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/studio/index.html b/public/studio/index.html
index a54a259a0..c71b4c78c 100644
--- a/public/studio/index.html
+++ b/public/studio/index.html
@@ -400,5 +400,6 @@
<div class="toast" id="toast" hidden></div>
<script type="module" src="/studio/studio.js?v=4"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/studio/studio.js b/public/studio/studio.js
index a603c9dec..a748cd6d0 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -57,6 +57,12 @@ const WIDGET_TYPES = {
status: 'ready',
icon: '⬡',
},
+ 'bonding-curve': {
+ label: 'Bonding Curve',
+ desc: 'Live graduation progress and bonding-curve climb for a pump.fun token.',
+ status: 'ready',
+ icon: '◭',
+ },
};
const DEMO_AVATAR = Object.freeze({
@@ -79,6 +85,7 @@ const DEMO_WIDGET_IDS = Object.freeze({
'pumpfun-feed': 'wdgt_demo_pumpfun',
'kol-trades': 'wdgt_demo_koltrad',
'live-trades-canvas': 'wdgt_demo_ltcnvs',
+ 'bonding-curve': 'wdgt_demo_bondcrv',
});
const BRAND_DEFAULTS = Object.freeze({
@@ -131,6 +138,7 @@ const TYPE_DEFAULTS = {
'pumpfun-feed': { kind: 'all', minTier: '', autoNarrate: true, maxCards: 8 },
'kol-trades': { mint: '', limit: 20, refreshMs: 30000 },
'live-trades-canvas': { mint: '', chain: 'solana', bg: '#0a0a0a', minUsd: 0 },
+ 'bonding-curve': { mint: '', network: 'mainnet', refreshMs: 15000, showUsd: true },
};
function defaultConfig(type) {
@@ -630,6 +638,31 @@ function renderTypeFields() {
numberField('minUsd', 'Min trade size (USD)', state.config.minUsd ?? 0, { min: 0, max: 1000000, step: 1 }),
);
}
+ if (state.type === 'bonding-curve') {
+ wrap.appendChild(
+ textField('mint', 'Token mint address', state.config.mint || '', {
+ max: 64,
+ placeholder: 'Pump.fun mint address (base58)',
+ }),
+ );
+ wrap.appendChild(
+ selectField('network', 'Network', state.config.network ?? 'mainnet', [
+ ['mainnet', 'Mainnet'],
+ ['devnet', 'Devnet'],
+ ]),
+ );
+ wrap.appendChild(
+ selectField('refreshMs', 'Refresh interval', String(state.config.refreshMs ?? 15000), [
+ ['10000', '10 seconds'],
+ ['15000', '15 seconds'],
+ ['30000', '30 seconds'],
+ ['60000', '1 minute'],
+ ]),
+ );
+ wrap.appendChild(
+ boolField('showUsd', 'Show USD values (Jupiter price)', state.config.showUsd !== false),
+ );
+ }
}
function mountTalkingAgentExtras(wrap) {
diff --git a/public/tutor.html b/public/tutor.html
index be5c36966..5c1ccaa4a 100644
--- a/public/tutor.html
+++ b/public/tutor.html
@@ -221,5 +221,6 @@
<script src="/x402.js"></script>
<script type="module" src="/tutor.js"></script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/validation/index.html b/public/validation/index.html
index 55e5a0afe..2ec63e7bb 100644
--- a/public/validation/index.html
+++ b/public/validation/index.html
@@ -1069,5 +1069,6 @@
<div id="footer-container"></div>
<script src="/footer.js" defer></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/vanity-wallet.html b/public/vanity-wallet.html
index fc2edaf5f..21b220e65 100644
--- a/public/vanity-wallet.html
+++ b/public/vanity-wallet.html
@@ -682,5 +682,6 @@
});
}
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/public/wallet-connect-demo.html b/public/wallet-connect-demo.html
index a65898bf4..0eb8749cc 100644
--- a/public/wallet-connect-demo.html
+++ b/public/wallet-connect-demo.html
@@ -131,5 +131,6 @@
},
});
</script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.html
index 26e016f22..c56ac53dc 100644
--- a/public/widgets-gallery/index.html
+++ b/public/widgets-gallery/index.html
@@ -139,5 +139,6 @@
</footer>
<script type="module" src="/widgets-gallery/gallery.js"></script>
- </body>
+ <script src="/brand.js" defer></script>
+</body>
</html>
diff --git a/public/x402-stripe.html b/public/x402-stripe.html
index 886d97c33..452e4f1b6 100644
--- a/public/x402-stripe.html
+++ b/public/x402-stripe.html
@@ -509,5 +509,6 @@
}
</script>
+ <script src="/brand.js" defer></script>
</body>
</html>
diff --git a/scripts/_verify-walk-companion.mjs b/scripts/_verify-walk-companion.mjs
new file mode 100644
index 000000000..36c296d63
--- /dev/null
+++ b/scripts/_verify-walk-companion.mjs
@@ -0,0 +1,94 @@
+// Temporary verification harness for the Walk Companion (src/walk-companion.js).
+// Drives the real dev server with headless Chromium (puppeteer) and asserts the
+// companion mounts on a standard nav page with ?walk=1, the nav toggle reflects
+// state, the avatar canvas renders, persistence survives a navigation, and the
+// disable button removes it — all with zero real console/page errors.
+import puppeteer from 'puppeteer';
+
+const BASE = process.env.BASE || 'http://localhost:3000';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const fails = [];
+const ok = (cond, msg) => {
+ console.log(`${cond ? '✓' : '✗'} ${msg}`);
+ if (!cond) fails.push(msg);
+};
+
+// Dev-only noise absent in production: Vite's HMR client cannot open its
+// websocket through the Codespace forwarded domain over localhost.
+const isDevNoise = (t) =>
+ /\[vite\]/i.test(t) ||
+ /failed to connect to websocket/i.test(t) ||
+ /WebSocket (closed without opened|connection to)/i.test(t) ||
+ /app\.github\.dev/i.test(t) ||
+ /Failed to load resource/i.test(t); // favicon etc.
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--no-sandbox'],
+});
+const page = await browser.newPage();
+
+const consoleErrors = [];
+page.on('console', (m) => {
+ if (m.type() === 'error' && !isDevNoise(m.text())) consoleErrors.push(m.text());
+});
+page.on('pageerror', (e) => {
+ if (!isDevNoise(e.message)) consoleErrors.push(`pageerror: ${e.message}`);
+});
+
+const attr = (sel, name) =>
+ page.$eval(sel, (el, n) => el.getAttribute(n), name).catch(() => null);
+
+// 1) Enabled via ?walk=1 → mounts on a standard nav page.
+await page.goto(`${BASE}/features?walk=1`, { waitUntil: 'domcontentloaded' });
+const canvas = await page.waitForSelector('.walk-companion-canvas', { timeout: 20000 }).catch(() => null);
+ok(!!canvas, 'companion canvas mounts with ?walk=1 on /features');
+
+ok(!!(await page.$('#home-nav-walk')), 'nav Walk toggle button present');
+ok((await attr('#home-nav-walk', 'aria-pressed')) === 'true', 'toggle aria-pressed=true when enabled');
+
+const dims = canvas ? await canvas.evaluate((c) => ({ w: c.width, h: c.height })) : { w: 0, h: 0 };
+ok(dims.w > 0 && dims.h > 0, `canvas has render dimensions (${dims.w}x${dims.h})`);
+
+// Avatar actually loaded into the scene (robot mesh present) — wait for it.
+await sleep(2500);
+const bubbleText = await page.$eval('.walk-companion-bubble', (b) => b.textContent?.trim() || '').catch(() => '');
+ok(bubbleText.length > 0, `context greeting shown ("${bubbleText.slice(0, 42)}")`);
+
+ok(
+ await page.evaluate(() => !!(window.__walkCompanion && typeof window.__walkCompanion.toggle === 'function')),
+ 'window.__walkCompanion API exposed',
+);
+
+// 2) Persistence: enabled flag saved → survives navigation to a different page.
+ok(
+ (await page.evaluate(() => localStorage.getItem('walk:companion:enabled'))) === '1',
+ 'enabled flag persisted to localStorage',
+);
+await page.goto(`${BASE}/pricing`, { waitUntil: 'domcontentloaded' });
+ok(
+ !!(await page.waitForSelector('.walk-companion-canvas', { timeout: 20000 }).catch(() => null)),
+ 'companion re-mounts on /pricing without ?walk param — persistence works',
+);
+
+// 3) Disable button removes the companion and flips the flag off.
+const closeBtn = await page.$('.walk-companion-close');
+ok(!!closeBtn, 'disable (×) button present');
+if (closeBtn) {
+ await closeBtn.click();
+ await sleep(500);
+ ok((await page.$('.walk-companion-canvas')) === null, 'disable button removes the companion');
+ ok(
+ (await page.evaluate(() => localStorage.getItem('walk:companion:enabled'))) === '0',
+ 'disable sets enabled flag to 0',
+ );
+ ok((await attr('#home-nav-walk', 'aria-pressed')) === 'false', 'nav toggle reflects disabled state');
+}
+
+// 4) No real console / page errors throughout.
+ok(consoleErrors.length === 0, `no console errors (${consoleErrors.length})`);
+consoleErrors.slice(0, 10).forEach((e) => console.log(' →', e));
+
+await browser.close();
+console.log(fails.length ? `\nFAILED (${fails.length})` : '\nALL PASS');
+process.exit(fails.length ? 1 : 0);
diff --git a/scripts/add-brand-mark.mjs b/scripts/add-brand-mark.mjs
new file mode 100644
index 000000000..90dbac7ee
--- /dev/null
+++ b/scripts/add-brand-mark.mjs
@@ -0,0 +1,103 @@
+/**
+ * Wire the universal top-left brand mark (/brand.js) into every standalone
+ * site page under pages/ and public/.
+ *
+ * /brand.js is idempotent and self-guarding: it injects a top-left brand chip
+ * only when a page has no existing top-left logo, so it is safe to include on
+ * every page. This codemod just guarantees the <script> tag is present.
+ *
+ * Excluded:
+ * - HTML fragments / partials (no </body>) — e.g. nav.html, footer.html
+ * - Embeddable surfaces meant to render inside host pages: anything whose
+ * path matches embed / widget / iframe / artifact / snippet / overlay-control
+ * - The JS-shell dashboards under pages/dashboard that mount their own
+ * branded rail asynchronously (avoids a first-paint double-logo flash)
+ *
+ * Usage:
+ * node scripts/add-brand-mark.mjs --dry # report only
+ * node scripts/add-brand-mark.mjs # apply
+ */
+import { readdirSync, readFileSync, writeFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = fileURLToPath(new URL('..', import.meta.url));
+const DRY = process.argv.includes('--dry');
+const SCRIPT_TAG = '\t<script src="/brand.js" defer></script>\n';
+
+// Genuine embeddable runtimes only — destination pages that merely mention
+// "widget"/"embed" in their name (the widgets gallery, widget docs, embed-policy
+// settings) are intentionally NOT matched and DO get the brand mark.
+const EXCLUDE_PATH = new RegExp(
+ [
+ '(^|/)a-embed\\.html$',
+ '(^|/)agent-embed\\.html$',
+ '(^|/)avatar-embed\\.html$',
+ '(^|/)embed\\.html$',
+ '(^|/)embed-(demo|test|walk|example)\\.html$',
+ '(^|/)walk-embed(-sdk)?\\.html$',
+ 'embed/v1/preview\\.html$',
+ '(^|/)overlay-control\\.html$',
+ '(^|/)avatar-artifact\\.html$',
+ '(^|/)artifact/',
+ '(^|/)widget\\.html$',
+ '(^|/)widget-demo\\.html$',
+ '-widget\\.html$',
+ '/iframe/',
+ ].join('|'),
+ 'i'
+);
+const EXCLUDE_SHELL_DASHBOARD = /^pages\/dashboard(-next)?\//;
+
+function walk(dir, out = []) {
+ for (const entry of readdirSync(dir)) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) walk(full, out);
+ else if (entry.endsWith('.html')) out.push(full);
+ }
+ return out;
+}
+
+const files = [...walk(join(ROOT, 'pages')), ...walk(join(ROOT, 'public'))];
+
+const added = [];
+const already = [];
+const skipped = [];
+
+for (const file of files) {
+ const rel = relative(ROOT, file).split('\\').join('/');
+ const html = readFileSync(file, 'utf8');
+
+ if (!html.includes('</body>')) {
+ skipped.push([rel, 'fragment (no </body>)']);
+ continue;
+ }
+ if (EXCLUDE_PATH.test(rel)) {
+ skipped.push([rel, 'embeddable surface']);
+ continue;
+ }
+ if (EXCLUDE_SHELL_DASHBOARD.test(rel)) {
+ skipped.push([rel, 'JS-shell dashboard (own rail)']);
+ continue;
+ }
+ if (html.includes('/brand.js')) {
+ already.push(rel);
+ continue;
+ }
+
+ const idx = html.lastIndexOf('</body>');
+ const next = html.slice(0, idx) + SCRIPT_TAG + html.slice(idx);
+ if (!DRY) writeFileSync(file, next);
+ added.push(rel);
+}
+
+const log = (title, list) => {
+ console.log(`\n${title} (${list.length})`);
+ for (const item of list) console.log(' ' + (Array.isArray(item) ? `${item[0]} — ${item[1]}` : item));
+};
+
+console.log(DRY ? '── DRY RUN ──' : '── APPLIED ──');
+log(DRY ? 'WOULD ADD' : 'ADDED', added);
+log('ALREADY PRESENT', already);
+log('SKIPPED', skipped);
+console.log(`\nTotal: ${files.length} html · +${added.length} · =${already.length} · −${skipped.length}`);
diff --git a/scripts/apply-paid-assets-migration.mjs b/scripts/apply-paid-assets-migration.mjs
new file mode 100644
index 000000000..0fe9a98c9
--- /dev/null
+++ b/scripts/apply-paid-assets-migration.mjs
@@ -0,0 +1,66 @@
+#!/usr/bin/env node
+// Apply the paid_assets migration against $DATABASE_URL.
+// Usage: DATABASE_URL=... node scripts/apply-paid-assets-migration.mjs
+//
+// Idempotent — re-runnable. The migration uses IF NOT EXISTS on every CREATE.
+// Pairs with scripts/seed-paid-assets.mjs (which assumes the table exists) so a
+// fresh DB can stand up the SIWX-gated /api/x402/asset-download bazaar.
+
+import { readFileSync } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+import { neon } from '@neondatabase/serverless';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '..');
+
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ break;
+ } catch {
+ /* file not present */
+ }
+}
+
+const url = process.env.DATABASE_URL;
+if (!url) {
+ console.error('DATABASE_URL not set');
+ process.exit(1);
+}
+const sql = neon(url);
+const text = await readFile(
+ new URL('../api/_lib/migrations/2026-05-21-paid-assets.sql', import.meta.url),
+ 'utf8',
+);
+
+// Neon HTTP API runs one statement per call. Split on top-level semicolons —
+// the paid-assets migration uses no DO blocks / dollar-quoted strings. Strip
+// leading `--` comment lines per chunk so the migration's header block doesn't
+// cause the first CREATE statement to be filtered out as a comment-only chunk.
+const statements = text
+ .split(/;\s*$/m)
+ .map((s) =>
+ s
+ .split('\n')
+ .filter((line) => !/^\s*--/.test(line))
+ .join('\n')
+ .trim(),
+ )
+ .filter((s) => s.length > 0);
+
+for (const s of statements) {
+ await sql(s, [], {});
+ console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));
+}
+console.log('paid_assets table ready');
diff --git a/scripts/compress-glbs.mjs b/scripts/compress-glbs.mjs
new file mode 100644
index 000000000..5543e9786
--- /dev/null
+++ b/scripts/compress-glbs.mjs
@@ -0,0 +1,161 @@
+#!/usr/bin/env node
+/**
+ * GLB compression pipeline.
+ *
+ * Reads GLB files with @gltf-transform, applies a lossless-perceptual transform
+ * chain (dedup → prune → resample → quantize → EXT_meshopt_compression) and
+ * writes the result back in place — but only if the output is actually smaller.
+ *
+ * node scripts/compress-glbs.mjs # scan public/ + rider/assets/
+ * node scripts/compress-glbs.mjs public/avatars/x.glb # explicit file list
+ *
+ * The output uses EXT_meshopt_compression because the main viewer and the
+ * marketplace lobby both wire the meshopt decoder (src/viewer/internal.js).
+ * Three.js' GLTFLoader decodes KHR_mesh_quantization natively.
+ *
+ * Idempotent: reading an already-compressed GLB requires the meshopt *decoder*,
+ * which is why both encoder and decoder are registered below. Re-running yields
+ * files of similar or smaller size, never growth (growth is detected and the
+ * write is skipped).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { dedup, prune, resample, quantize, meshopt } from '@gltf-transform/functions';
+import { MeshoptEncoder, MeshoptDecoder } from 'meshoptimizer';
+
+const ROOT = path.resolve(fileURLToPath(import.meta.url), '../..');
+const DEFAULT_SCAN_DIRS = ['public', 'rider/assets'];
+
+/** Recursively collect every `.glb` under `dir`, excluding any `dist/` segment. */
+function collectGlbs(dir) {
+ const out = [];
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return out; // directory does not exist — skip silently
+ }
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'dist' || entry.name === 'node_modules') continue;
+ out.push(...collectGlbs(full));
+ } else if (entry.isFile() && entry.name.toLowerCase().endsWith('.glb')) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+function resolveTargets(argv) {
+ if (argv.length) {
+ return argv.map((p) => path.resolve(ROOT, p)).filter((p) => {
+ if (!fs.existsSync(p)) {
+ console.warn(`[compress] skip (not found): ${p}`);
+ return false;
+ }
+ return true;
+ });
+ }
+ const found = [];
+ for (const rel of DEFAULT_SCAN_DIRS) found.push(...collectGlbs(path.join(ROOT, rel)));
+ return found;
+}
+
+function fmtBytes(n) {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;
+}
+
+async function main() {
+ await MeshoptEncoder.ready;
+ await MeshoptDecoder.ready;
+
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
+ 'meshopt.encoder': MeshoptEncoder,
+ 'meshopt.decoder': MeshoptDecoder,
+ });
+
+ const targets = resolveTargets(process.argv.slice(2));
+ if (!targets.length) {
+ console.log('[compress] no GLB files found.');
+ return;
+ }
+
+ console.log(`[compress] processing ${targets.length} file(s)…\n`);
+ const summary = [];
+
+ for (const file of targets) {
+ const rel = path.relative(ROOT, file);
+ let before;
+ try {
+ before = fs.statSync(file).size;
+ } catch (err) {
+ console.warn(`[compress] skip ${rel}: ${err.message}`);
+ continue;
+ }
+
+ try {
+ const document = await io.read(file);
+ await document.transform(
+ dedup(),
+ prune(),
+ resample(),
+ quantize(),
+ meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
+ // TODO: add textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 })
+ // once sharp is wired into the asset pipeline (it needs a native binary).
+ );
+
+ const bytes = await io.writeBinary(document);
+ const after = bytes.byteLength;
+
+ if (after >= before) {
+ console.warn(
+ ` ⚠ ${rel}: ${fmtBytes(before)} → ${fmtBytes(after)} (would grow) — keeping original.`,
+ );
+ summary.push({ rel, before, after: before, pct: 0, status: 'kept (no gain)' });
+ continue;
+ }
+
+ fs.writeFileSync(file, bytes);
+ const pct = ((1 - after / before) * 100).toFixed(1);
+ console.log(` ✓ ${rel}: ${fmtBytes(before)} → ${fmtBytes(after)} (−${pct}%)`);
+ summary.push({ rel, before, after, pct: Number(pct), status: 'compressed' });
+ } catch (err) {
+ console.error(` ✗ ${rel}: ${err.message}`);
+ summary.push({ rel, before, after: before, pct: 0, status: `error: ${err.message}` });
+ }
+ }
+
+ // Summary table.
+ console.log('\n── Summary ─────────────────────────────────────────────');
+ const nameW = Math.max(4, ...summary.map((s) => s.rel.length));
+ console.log(
+ `${'file'.padEnd(nameW)} ${'before'.padStart(10)} ${'after'.padStart(10)} ${'saved'.padStart(7)} status`,
+ );
+ let totalBefore = 0;
+ let totalAfter = 0;
+ for (const s of summary) {
+ totalBefore += s.before;
+ totalAfter += s.after;
+ console.log(
+ `${s.rel.padEnd(nameW)} ${fmtBytes(s.before).padStart(10)} ${fmtBytes(s.after).padStart(10)} ${(s.pct ? `−${s.pct}%` : '—').padStart(7)} ${s.status}`,
+ );
+ }
+ const totalPct = totalBefore ? ((1 - totalAfter / totalBefore) * 100).toFixed(1) : '0';
+ console.log('─'.repeat(56));
+ console.log(
+ `${'TOTAL'.padEnd(nameW)} ${fmtBytes(totalBefore).padStart(10)} ${fmtBytes(totalAfter).padStart(10)} ${`−${totalPct}%`.padStart(7)}`,
+ );
+}
+
+main().catch((err) => {
+ console.error('[compress] fatal:', err);
+ process.exit(1);
+});
diff --git a/scripts/verify-bonding-curve.mjs b/scripts/verify-bonding-curve.mjs
new file mode 100644
index 000000000..c082384bf
--- /dev/null
+++ b/scripts/verify-bonding-curve.mjs
@@ -0,0 +1,121 @@
+import { chromium } from 'playwright';
+
+const BASE = process.env.BASE || 'http://localhost:3001';
+const REAL_MINT = process.env.MINT || '2xmwo8kN1MNMttfBENLkTLo2sFXiDYuReEa3y1eopump';
+
+const cfg = {
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ showControls: false,
+ autoRotate: true,
+ rotationSpeed: 0.4,
+ envPreset: 'neutral',
+ mint: REAL_MINT,
+ network: 'mainnet',
+ refreshMs: 15000,
+ showUsd: true,
+};
+
+// A realistic mid-bonding payload (~34.5%) shaped exactly like /api/pump/curve.
+const FIXTURE_34 = {
+ mint: REAL_MINT,
+ network: 'mainnet',
+ curve: {
+ virtualTokenReserves: '900000000000000',
+ virtualSolReserves: '48000000000',
+ realTokenReserves: '519000000000000',
+ realSolReserves: '18400000000',
+ tokenTotalSupply: '1000000000000000',
+ complete: false,
+ creator: '2n5AxmKaqKTWMyuBh7nedaj3SwxYSWB9wE3CQa1o92YY',
+ isMayhemMode: false,
+ },
+ price: { buyPricePerToken: '92', sellPricePerToken: '88', marketCap: '92000000000', isGraduated: false },
+ graduation: { progressBps: 3450, isGraduated: false, tokensRemaining: '519000000000000', tokensTotal: '793100000000000', solAccumulated: '18400000000' },
+};
+
+async function boot(page, { intercept } = {}) {
+ if (intercept) {
+ await page.route('**/api/pump/curve**', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(intercept) }),
+ );
+ }
+ const errors = [];
+ page.on('console', (m) => {
+ if (m.type() === 'error') errors.push(m.text());
+ });
+ page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
+
+ const hash = `model=${encodeURIComponent('/avatars/cz.glb')}&kiosk=true&type=bonding-curve`;
+ await page.goto(`${BASE}/widget#${hash}`, { waitUntil: 'domcontentloaded', timeout: 20000 });
+ // Studio-style: the widget runtime mounts on the first config message.
+ await page.waitForTimeout(1200);
+ await page.evaluate((c) => window.postMessage({ type: 'widget:config', config: c }, location.origin), cfg);
+ return errors;
+}
+
+(async () => {
+ const browser = await chromium.launch();
+ let failed = false;
+
+ // ── Scenario A: real endpoint (proxied to prod) ─────────────────────────
+ {
+ const page = await browser.newPage({ viewport: { width: 900, height: 700 } });
+ const errors = await boot(page);
+ await page.waitForSelector('.bcw-card', { timeout: 8000 }).catch(() => {});
+ const present = await page.locator('.bcw-card').count();
+ const hasCurve = await page.locator('.bcw-curve [data-marker]').count();
+ const hasCta = await page.locator('.bcw-cta').count();
+ // Give the live fetch a moment to resolve into a real state class.
+ await page.waitForTimeout(4000);
+ const cls = await page.locator('.bcw-card').getAttribute('class').catch(() => '');
+ console.log(`A/real → card=${present} marker=${hasCurve} cta=${hasCta} state="${cls}"`);
+ if (!present || !hasCurve || !hasCta) failed = true;
+ const appErrors = errors.filter((e) => /bonding|bcw|curve/i.test(e));
+ if (appErrors.length) { console.log(' widget console errors:', appErrors); failed = true; }
+ await page.screenshot({ path: 'scripts/.bcw-real.png' });
+ await page.close();
+ }
+
+ // ── Scenario B: intercepted 34.5% populated render ──────────────────────
+ {
+ const page = await browser.newPage({ viewport: { width: 900, height: 700 } });
+ await boot(page, { intercept: FIXTURE_34 });
+ await page.waitForSelector('.bcw-card.is-bonding', { timeout: 9000 });
+ await page.waitForTimeout(1400); // let the count-up + marker glide settle
+ const pct = (await page.locator('.bcw-pct-num').textContent())?.trim();
+ const mc = (await page.locator('[data-mc]').textContent())?.trim();
+ const raised = (await page.locator('[data-raised]').textContent())?.trim();
+ const price = (await page.locator('[data-price]').textContent())?.trim();
+ const marker = await page.locator('[data-marker]').getAttribute('transform');
+ const area = await page.locator('[data-area]').getAttribute('d');
+ console.log(`B/34.5% → pct=${pct} mc=${mc} raised=${raised} price=${price}`);
+ console.log(` marker=${marker} area.len=${(area || '').length}`);
+ const okPct = pct === '34' || pct === '35';
+ const okMarker = marker && marker.includes('translate(');
+ const okArea = (area || '').endsWith('Z') && (area || '').length > 30;
+ if (!okPct || !okMarker || !okArea) { console.log(' ✗ populated assertions failed'); failed = true; }
+ await page.screenshot({ path: 'scripts/.bcw-34.png' });
+ await page.close();
+ }
+
+ // ── Scenario C: graceful empty on 404 ───────────────────────────────────
+ {
+ const page = await browser.newPage({ viewport: { width: 900, height: 700 } });
+ await boot(page, { intercept: undefined });
+ await page.route('**/api/pump/curve**', (route) =>
+ route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ error: 'no_curve' }) }),
+ );
+ await page.evaluate((c) => window.postMessage({ type: 'widget:config', config: c }, location.origin), cfg);
+ await page.waitForSelector('.bcw-card.is-empty', { timeout: 9000 }).catch(() => {});
+ const isEmpty = await page.locator('.bcw-card.is-empty').count();
+ const msg = await page.locator('.bcw-empty-msg').textContent().catch(() => '');
+ console.log(`C/404 → is-empty=${isEmpty} msg="${(msg || '').slice(0, 48)}…"`);
+ if (!isEmpty) failed = true;
+ await page.close();
+ }
+
+ await browser.close();
+ console.log(failed ? '\n❌ FAIL' : '\n✅ PASS — bonding-curve widget verified end-to-end');
+ process.exit(failed ? 1 : 0);
+})();
diff --git a/src/app.js b/src/app.js
index 148dd9fb2..eba4393b9 100644
--- a/src/app.js
+++ b/src/app.js
@@ -21,6 +21,7 @@ import { mountHotspotTour } from './widgets/hotspot-tour.js';
import { mountPumpfunFeed } from './widgets/pumpfun-feed.js';
import { mountKolTradesWidget } from './widgets/kol-trades.js';
import { mountLiveTradesCanvas } from './widgets/live-trades-canvas.js';
+import { mountBondingCurve } from './widgets/bonding-curve.js';
import { mountPassport } from './widgets/passport.js';
import queryString from 'query-string';
import { ScreenshotModal } from './components/screenshot-modal.js';
@@ -1347,6 +1348,26 @@ class App {
minUsd: cfg.minUsd,
});
this._widgetController = ctl;
+ } else if (type === 'bonding-curve') {
+ const host = document.createElement('div');
+ host.className = 'bonding-curve-host';
+ host.style.cssText =
+ 'position:absolute;inset:0;display:grid;place-items:center;padding:24px;z-index:5;pointer-events:none;box-sizing:border-box';
+ document.body.appendChild(host);
+ const inner = mountBondingCurve(host, {
+ mint: cfg.mint,
+ network: cfg.network,
+ refreshMs: cfg.refreshMs,
+ showUsd: cfg.showUsd,
+ accent: cfg.accent,
+ showPoweredBy: cfg.showPoweredBy,
+ });
+ this._widgetController = {
+ destroy() {
+ inner?.destroy?.();
+ host.remove();
+ },
+ };
} else if (type === 'passport') {
const ctl = await mountPassport(this.viewer, cfg, document.body, widgetId);
this._widgetController = ctl;
diff --git a/src/community/town-auth.js b/src/community/town-auth.js
index b92c38771..190b62b4c 100644
--- a/src/community/town-auth.js
+++ b/src/community/town-auth.js
@@ -80,12 +80,18 @@ export async function signInWithX() {
});
}
-/** Connect Phantom (or any window.solana provider) and return its address. */
-async function connectSolana() {
+/** Connect Phantom (or any window.solana provider) and return its address. When
+ * `forceReconnect` is set, drop any existing connection first — injected wallets
+ * silently re-hand back the already-trusted account, so without this the user
+ * can never pick a different wallet to link. */
+async function connectSolana({ forceReconnect = false } = {}) {
const provider = window.phantom?.solana || window.solana;
if (!provider?.connect) {
throw new Error('No Solana wallet found — install Phantom to post.');
}
+ if (forceReconnect) {
+ try { await provider.disconnect?.(); } catch { /* nothing connected — fine */ }
+ }
const resp = await provider.connect();
const address = (resp?.publicKey || provider.publicKey)?.toString();
if (!address) throw new Error('Could not read wallet address.');
@@ -95,11 +101,15 @@ async function connectSolana() {
/**
* Ensure the signed-in user has a linked Solana wallet, linking one via a
* signed challenge if needed. Returns the wallet address to post from.
+ *
+ * @param {object} [opts]
+ * @param {boolean} [opts.forceReconnect] link a freshly-chosen wallet even if one
+ * is already linked — used when switching wallets (see relinkSolanaWallet).
*/
-export async function ensureSolanaWallet(session) {
- if (session?.solWallet) return session.solWallet;
+export async function ensureSolanaWallet(session, { forceReconnect = false } = {}) {
+ if (!forceReconnect && session?.solWallet) return session.solWallet;
- const { provider, address } = await connectSolana();
+ const { provider, address } = await connectSolana({ forceReconnect });
const { message } = await json('/wallet/challenge', {
method: 'POST',
headers: { 'content-type': 'application/json' },
@@ -120,6 +130,23 @@ export async function ensureSolanaWallet(session) {
return linked?.address || address;
}
+/** Unlink the Solana wallet currently bound to the session. Idempotent — safe to
+ * call when none is linked. */
+export function unlinkSolanaWallet() {
+ return json('/wallet/unlink', { method: 'POST' });
+}
+
+/**
+ * Switch the linked Solana wallet: unlink the current one, then connect and link
+ * a freshly-chosen wallet. Lets a holder enter from the wallet that actually
+ * holds the coin when the first one they linked falls short. Returns the new
+ * linked address.
+ */
+export async function relinkSolanaWallet() {
+ await unlinkSolanaWallet();
+ return ensureSolanaWallet(null, { forceReconnect: true });
+}
+
/**
* Ask the server whether the signed-in user holds enough of `mint` to enter its
* Holders world, and if so mint a holder pass for the game server.
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index e29eae230..e123a891f 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -795,7 +795,7 @@ export class CommunityUI {
// (default $8) of the coin. This overlay is a thin view over the scene's gate
// state machine (coincommunities.js _passHolderGate) — the scene drives us
// through setHolderGate(state, data) and we report the player's choice back via
- // onHolderAction(action): 'signin' | 'wallet' | 'buy' | 'recheck' | 'cancel'.
+ // onHolderAction(action): 'signin' | 'wallet' | 'switch' | 'buy' | 'recheck' | 'cancel'.
openHolderGate(coin) {
if (this._gate) return; // already open — the scene re-uses it across states
this._gateBody = el('div', { class: 'cc-gate-body' });
@@ -882,6 +882,7 @@ export class CommunityUI {
actions(
btn(`Buy ${sym}`, 'buy', 'cc-gate-primary'),
btn('I bought — re-check', 'recheck'),
+ btn('Use a different wallet', 'switch'),
btn('Enter the open world instead', 'cancel', 'cc-gate-ghost'),
),
];
@@ -910,7 +911,11 @@ export class CommunityUI {
el('div', { class: 'cc-gate-lock', text: '!' }),
title('Couldn’t verify'),
msg(data.error || 'Something went wrong checking your holdings.'),
- actions(btn('Try again', 'recheck', 'cc-gate-primary'), btn('Cancel', 'cancel', 'cc-gate-ghost')),
+ actions(
+ btn('Try again', 'recheck', 'cc-gate-primary'),
+ btn('Use a different wallet', 'switch'),
+ btn('Cancel', 'cancel', 'cc-gate-ghost'),
+ ),
];
break;
}
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 91c0c9ebe..6a10a7b0d 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1470,6 +1470,18 @@ html, body {
.pg-btn-ghost { color: var(--cc-dim); }
.pg-btn-ghost:hover { color: var(--cc-text); }
+/* quiet text action — "use a different wallet" */
+.pg-link {
+ -webkit-appearance: none; appearance: none; cursor: pointer;
+ margin: 12px 0 0; padding: 4px 6px;
+ font-family: inherit; font-size: 12px; font-weight: 500; letter-spacing: 0.02em;
+ background: none; border: none; border-radius: var(--cc-radius-sm);
+ color: var(--cc-dim); text-decoration: underline; text-underline-offset: 3px;
+ transition: color 0.18s ease;
+}
+.pg-link:hover { color: var(--cc-text); }
+.pg-link:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-edge-hi); }
+
/* balance comparison (too-low state) */
.pg-balance {
display: flex; align-items: center; justify-content: center; gap: 14px;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index be876b882..c48ba2341 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -34,7 +34,7 @@ import {
import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
-import { requestHolderPass, signInWithX, ensureSolanaWallet, getSession } from '../community/town-auth.js';
+import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession } from '../community/town-auth.js';
import { ensurePlayAccess } from './play-gate.js';
import { clearStoredPass, fetchPlayConfig, signInToPlay, loadStoredPass, storePass } from './play-auth.js';
@@ -889,6 +889,15 @@ export class CoinCommunities {
} catch (e) { carryError = e?.message || 'Could not link a wallet.'; }
continue;
}
+ if (action === 'switch') {
+ // Drop the linked wallet and connect a different one, then re-check —
+ // the way out of a short balance when the coin lives in another wallet.
+ this.ui.setHolderGate('working', { symbol, msg: 'Switching wallet…' });
+ try {
+ await relinkSolanaWallet();
+ } catch (e) { carryError = e?.message || 'Could not switch wallet.'; }
+ continue;
+ }
if (action === 'buy') { this._openBuy(coin); skipCheck = true; continue; }
// 'recheck' (or any other) → loop and re-run the on-chain check.
}
diff --git a/src/game/play-auth.js b/src/game/play-auth.js
index c27c64c96..a26966fff 100644
--- a/src/game/play-auth.js
+++ b/src/game/play-auth.js
@@ -86,6 +86,8 @@ function buildPlayMessage(address, nonce) {
*
* @param {object} opts
* @param {string} opts.nonce nonce from fetchPlayConfig()
+ * @param {boolean} [opts.forceReconnect] drop the current wallet link before
+ * connecting, so the wallet re-prompts and a different account can be chosen.
* @param {(stage: string) => void} [opts.onStage] 'connecting' | 'signing' | 'verifying'
* @returns {Promise<object>} the /verify result — { ok: true, wallet, balance,
* playPass, … } when the wallet clears the floor, or { ok: false,
@@ -93,12 +95,21 @@ function buildPlayMessage(address, nonce) {
* @throws {PlayAuthError} no_wallet | rejected | nonce_invalid | bad_signature |
* balance_unavailable | verify_failed
*/
-export async function signInToPlay({ nonce, onStage = () => {} } = {}) {
+export async function signInToPlay({ nonce, forceReconnect = false, onStage = () => {} } = {}) {
const provider = detectProvider();
if (!provider?.connect) {
throw new PlayAuthError('no_wallet', 'No Solana wallet found. Install Phantom to play.');
}
+ // Switching wallets: injected providers silently re-hand back the already-
+ // trusted account on connect(), so without disconnecting first the player is
+ // stuck on whichever wallet they picked the first time. Dropping the link makes
+ // the wallet show its account picker again. Best-effort — a no-op when nothing
+ // is connected yet.
+ if (forceReconnect) {
+ try { await provider.disconnect?.(); } catch { /* not connected — fine */ }
+ }
+
onStage('connecting');
let address;
try {
diff --git a/src/game/play-gate.js b/src/game/play-gate.js
index 13bced113..37beed45b 100644
--- a/src/game/play-gate.js
+++ b/src/game/play-gate.js
@@ -12,7 +12,7 @@
// (no token pinned) or a fresh pass is already cached, it resolves instantly with
// no visible interruption.
-import { fetchPlayConfig, signInToPlay, loadStoredPass, hasWallet, PlayAuthError } from './play-auth.js';
+import { fetchPlayConfig, signInToPlay, loadStoredPass, clearStoredPass, hasWallet, PlayAuthError } from './play-auth.js';
const PHANTOM_INSTALL = 'https://phantom.app/download';
@@ -77,7 +77,7 @@ class Gate {
if (!hasWallet()) {
this._render({ state: 'no_wallet', onRetry: () => this._checkWalletThenConnect() });
} else {
- this._render({ state: 'connect', onConnect: () => this._attempt() });
+ this._render({ state: 'connect', onConnect: () => this._attempt(), onSwitch: () => this._switchWallet() });
}
}
@@ -91,7 +91,15 @@ class Gate {
}
}
- async _attempt() {
+ // Drop the current wallet link and start a fresh sign-in so the player can pick
+ // a different account. Clears any cached pass for the old wallet too, so the
+ // new wallet is the one that gets verified and remembered.
+ _switchWallet() {
+ clearStoredPass();
+ this._attempt({ forceReconnect: true });
+ }
+
+ async _attempt({ forceReconnect = false } = {}) {
// Fetch a fresh nonce on each attempt (they're short-lived + single-use).
this._render({ state: 'working', stage: 'connecting' });
let nonce = this.cfg?.nonce;
@@ -104,14 +112,21 @@ class Gate {
}
try {
- const res = await signInToPlay({ nonce, onStage: (stage) => this._render({ state: 'working', stage }) });
+ const res = await signInToPlay({ nonce, forceReconnect, onStage: (stage) => this._render({ state: 'working', stage }) });
if (res.ok && res.playPass) {
this._render({ state: 'granted', symbol: res.symbol, balance: res.balance });
setTimeout(() => this._finish({ required: true, wallet: res.wallet, playPass: res.playPass, balance: res.balance, symbol: res.symbol }), 700);
return;
}
- // Signature verified but balance is short.
- this._render({ state: 'low', data: res, onRecheck: () => this._attempt(), onAcquire: res.acquireUrl ? () => window.open(res.acquireUrl, '_blank', 'noopener noreferrer') : null });
+ // Signature verified but balance is short. Offer a recheck (same wallet,
+ // after a top-up) and a switch (try a different wallet entirely).
+ this._render({
+ state: 'low',
+ data: res,
+ onRecheck: () => this._attempt(),
+ onSwitch: () => this._switchWallet(),
+ onAcquire: res.acquireUrl ? () => window.open(res.acquireUrl, '_blank', 'noopener noreferrer') : null,
+ });
} catch (err) {
const code = err instanceof PlayAuthError ? err.code : 'error';
if (code === 'no_wallet') {
@@ -120,10 +135,10 @@ class Gate {
}
if (code === 'rejected') {
// Wallet cancelled — drop back to the connect screen with the reason.
- this._render({ state: 'connect', error: err.message, onConnect: () => this._attempt() });
+ this._render({ state: 'connect', error: err.message, onConnect: () => this._attempt(), onSwitch: () => this._switchWallet() });
return;
}
- this._render({ state: 'error', error: err?.message || 'Sign-in failed. Please try again.', onRetry: () => this._attempt() });
+ this._render({ state: 'error', error: err?.message || 'Sign-in failed. Please try again.', onRetry: () => this._attempt(), onSwitch: () => this._switchWallet() });
}
}
@@ -184,6 +199,7 @@ class Gate {
q('[data-act="retry"]')?.addEventListener('click', () => view.onRetry?.());
q('[data-act="recheck"]')?.addEventListener('click', () => view.onRecheck?.());
q('[data-act="acquire"]')?.addEventListener('click', () => view.onAcquire?.());
+ q('[data-act="switch"]')?.addEventListener('click', () => view.onSwitch?.());
// Move keyboard focus onto the primary CTA.
setTimeout(() => (q('.pg-btn-primary') || q('.pg-btn'))?.focus(), 50);
}
@@ -216,6 +232,7 @@ class Gate {
<p class="pg-sub">Connect your Solana wallet and approve a signature to prove it's yours. You'll need at least <strong>${esc(String(min))} ${tokenLabel}</strong> to enter. This never moves any funds.</p>
${view.error ? `<p class="pg-error" role="alert">${esc(view.error)}</p>` : ''}
<button class="pg-btn pg-btn-primary" data-act="connect">Connect wallet</button>
+ ${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}
<p class="pg-fine">We will never ask for your seed phrase.</p>`);
case 'working': {
@@ -242,7 +259,8 @@ class Gate {
<div><span class="pg-balance-k">Required</span><span class="pg-balance-v pg-balance-need">${need}</span></div>
</div>
${view.onAcquire ? `<button class="pg-btn pg-btn-primary" data-act="acquire">Get ${displaySym}</button>` : ''}
- <button class="pg-btn ${view.onAcquire ? 'pg-btn-ghost' : 'pg-btn-primary'}" data-act="recheck">Recheck balance</button>`);
+ <button class="pg-btn ${view.onAcquire ? 'pg-btn-ghost' : 'pg-btn-primary'}" data-act="recheck">Recheck balance</button>
+ ${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}`);
}
case 'granted':
@@ -257,7 +275,8 @@ class Gate {
<div class="pg-icon">${SVG.warn}</div>
<h1 class="pg-title">Something went wrong</h1>
<p class="pg-sub" role="alert">${esc(view.error || 'Please try again.')}</p>
- <button class="pg-btn pg-btn-primary" data-act="retry">Try again</button>`);
+ <button class="pg-btn pg-btn-primary" data-act="retry">Try again</button>
+ ${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}`);
}
}
}
diff --git a/src/marketplace-lobby.js b/src/marketplace-lobby.js
index ca01639ed..59949b248 100644
--- a/src/marketplace-lobby.js
+++ b/src/marketplace-lobby.js
@@ -13,6 +13,7 @@
import {
AmbientLight,
Box3,
+ BufferGeometry,
CircleGeometry,
Color,
DirectionalLight,
@@ -34,8 +35,16 @@ import {
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
+import { EffectComposer, RenderPass, SelectiveBloomEffect, EffectPass } from 'postprocessing';
import { getMeshoptDecoder } from './viewer/internal.js';
+// Accelerate click-to-select raycasting with a BVH. Patches the Three.js
+// prototypes once at module load — idempotent if the main viewer already did so.
+BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
+BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
+Mesh.prototype.raycast = acceleratedRaycast;
+
const SLOT_SPACING = 1.6; // metres between avatar centres
const PODIUM_RADIUS = 0.55;
const PODIUM_HEIGHT = 0.05;
@@ -85,6 +94,7 @@ export async function mountLobby(canvas, avatars, options = {}) {
const pmrem = new PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ pmrem.dispose(); // environment baked — the generator's GPU targets are no longer needed
// Podiums under each avatar slot.
const podiumGroup = new Group();
@@ -92,17 +102,34 @@ export async function mountLobby(canvas, avatars, options = {}) {
const slotsRoot = new Group();
scene.add(slotsRoot);
const startX = -((slots.length - 1) * SLOT_SPACING) / 2;
+ const bloomSelection = [];
const slotMeta = slots.map((_, i) => {
const x = startX + i * SLOT_SPACING;
- const podium = makePodium();
+ const { group: podium, ring } = makePodium();
podium.position.set(x, 0, 0);
podiumGroup.add(podium);
+ bloomSelection.push(ring);
const slotGroup = new Group();
slotGroup.position.set(x, PODIUM_HEIGHT, 0);
slotsRoot.add(slotGroup);
return { x, group: slotGroup, model: null };
});
+ // Post-processing: merge a single fullscreen pass with selective bloom so the
+ // emissive podium rings glow without blooming the avatars sitting on them.
+ const composer = new EffectComposer(renderer);
+ composer.addPass(new RenderPass(scene, camera));
+ const bloomEffect = new SelectiveBloomEffect(scene, camera, {
+ intensity: 1.8,
+ luminanceThreshold: 0.05,
+ luminanceSmoothing: 0.3,
+ mipmapBlur: true,
+ });
+ bloomEffect.selection.set(bloomSelection);
+ const effectPass = new EffectPass(camera, bloomEffect);
+ effectPass.renderToScreen = true;
+ composer.addPass(effectPass);
+
// Lazy-load GLBs in parallel; if one fails, the other slots still render.
// Baked avatars use EXT_meshopt_compression, so the loader needs the
// matching decoder before it can parse them.
@@ -118,6 +145,12 @@ export async function mountLobby(canvas, avatars, options = {}) {
const root = gltf.scene || gltf.scenes?.[0];
if (!root) return;
fitToHeight(root, TARGET_HEIGHT);
+ // Build a BVH per mesh so click raycasts are O(log n), not per-triangle.
+ root.traverse((node) => {
+ if (node.isMesh && node.geometry?.attributes?.position?.count) {
+ node.geometry.computeBoundsTree();
+ }
+ });
slotMeta[i].group.add(root);
slotMeta[i].model = root;
slotMeta[i].avatar = avatar;
@@ -169,19 +202,32 @@ export async function mountLobby(canvas, avatars, options = {}) {
width = Math.max(1, Math.floor(rect.width));
height = Math.max(1, Math.floor(rect.height));
renderer.setSize(width, height, false);
+ composer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
resize();
+ // Pause rendering while the canvas is scrolled out of view — saves GPU.
+ let visible = true;
+ const io = new IntersectionObserver(
+ ([entry]) => {
+ visible = entry.isIntersecting;
+ },
+ { threshold: 0.01 },
+ );
+ io.observe(canvas);
+
// Render loop with subtle scene rotation + camera parallax + per-slot spin.
let alive = true;
let lastT = performance.now();
function tick() {
if (!alive) return;
+ rafId = requestAnimationFrame(tick);
const now = performance.now();
const dt = (now - lastT) / 1000;
lastT = now;
+ if (!visible) return; // off-screen: skip render, keep the RAF alive for return
// Slow constant rotation of each loaded avatar (idle showcase).
for (const slot of slotMeta) {
@@ -195,8 +241,7 @@ export async function mountLobby(canvas, avatars, options = {}) {
camera.position.lerp(baseCamPos.clone().add(targetCamOffset), 0.06);
camera.lookAt(0, 1.05, 0);
- renderer.render(scene, camera);
- rafId = requestAnimationFrame(tick);
+ composer.render();
}
let rafId = requestAnimationFrame(tick);
@@ -204,11 +249,15 @@ export async function mountLobby(canvas, avatars, options = {}) {
alive = false;
cancelAnimationFrame(rafId);
ro.disconnect();
+ io.disconnect();
canvas.removeEventListener('pointermove', onPointerMove);
canvas.removeEventListener('click', onClick);
// Free GPU resources.
scene.traverse((obj) => {
- if (obj.geometry) obj.geometry.dispose?.();
+ if (obj.geometry) {
+ obj.geometry.disposeBoundsTree?.();
+ obj.geometry.dispose?.();
+ }
if (obj.material) {
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
for (const m of mats) {
@@ -220,7 +269,7 @@ export async function mountLobby(canvas, avatars, options = {}) {
}
}
});
- pmrem.dispose();
+ composer.dispose();
renderer.dispose();
}
@@ -260,7 +309,7 @@ function makePodium() {
ring.position.y = 0.001;
g.add(ring);
- return g;
+ return { group: g, ring };
}
function fitToHeight(object, targetHeight) {
diff --git a/src/viewer.js b/src/viewer.js
index b26a68dcc..95f0af818 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -48,6 +48,7 @@ import { setClips, playAllClips } from './viewer/animation.js';
import { LightProbeGrid } from './light-probe-grid.js';
import { AnimationManager } from './animation-manager.js';
import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
+import { EffectComposer, RenderPass, BloomEffect, VignetteEffect, EffectPass } from 'postprocessing';
// Install BVH-accelerated raycasting on Three.js prototypes. This must happen
// before any geometry is created so every Mesh benefits transparently.
@@ -176,6 +177,25 @@ export class Viewer {
this.el.appendChild(this.renderer.domElement);
+ // Post-processing: a single merged fullscreen pass (postprocessing lib)
+ // gives a subtle vignette that focuses attention on the avatar, plus mild
+ // bloom on bright specular highlights. The luminance threshold keeps normal
+ // surfaces from blooming. Screenshot capture bypasses this — see screenshot.js.
+ this._composer = new EffectComposer(this.renderer);
+ this._renderPass = new RenderPass(this.scene, this.activeCamera);
+ this._composer.addPass(this._renderPass);
+ const vignetteEffect = new VignetteEffect({ offset: 0.35, darkness: 0.4 });
+ const bloomEffect = new BloomEffect({
+ intensity: 0.6,
+ luminanceThreshold: 0.8,
+ luminanceSmoothing: 0.05,
+ mipmapBlur: true,
+ });
+ this._effectPass = new EffectPass(this.activeCamera, bloomEffect, vignetteEffect);
+ this._effectPass.renderToScreen = true;
+ this._composer.addPass(this._effectPass);
+ this._composer.setSize(el.clientWidth, el.clientHeight);
+
this.cameraCtrl = null;
this.cameraFolder = null;
this.animFolder = null;
@@ -572,7 +592,7 @@ export class Viewer {
}
render() {
- this.renderer.render(this.scene, this.activeCamera);
+ this._composer.render();
if (this.state.grid) {
this._ensureAxesRenderer();
this.axesCamera.position.copy(this.defaultCamera.position);
@@ -784,6 +804,7 @@ export class Viewer {
this.defaultCamera.aspect = nextAspect;
this.defaultCamera.updateProjectionMatrix();
this.renderer.setSize(clientWidth, clientHeight);
+ this._composer?.setSize(clientWidth, clientHeight);
this.axesCamera.aspect = this.axesDiv.clientWidth / this.axesDiv.clientHeight;
this.axesCamera.updateProjectionMatrix();
@@ -1058,6 +1079,9 @@ export class Viewer {
}
});
}
+ // Keep the post-processing passes pointed at the live camera.
+ if (this._renderPass) this._renderPass.mainCamera = this.activeCamera;
+ if (this._effectPass) this._effectPass.mainCamera = this.activeCamera;
this.invalidate();
}
@@ -1932,6 +1956,13 @@ export class Viewer {
this.axesScene = null;
this.axesCamera = null;
+ if (this._composer) {
+ this._composer.dispose();
+ this._composer = null;
+ this._renderPass = null;
+ this._effectPass = null;
+ }
+
if (this.renderer) {
this.renderer.dispose();
this.renderer.forceContextLoss?.();
diff --git a/src/walk-companion.js b/src/walk-companion.js
new file mode 100644
index 000000000..f3d56c404
--- /dev/null
+++ b/src/walk-companion.js
@@ -0,0 +1,740 @@
+// Site-wide Walk Companion
+// =========================
+// A persistent 3D avatar mascot that idles in the corner of every standard
+// three.ws page, turns to follow your cursor, waves when you navigate between
+// pages, and greets you with a page-aware tip. Opt-in: toggled from the nav
+// "Walk" button or with ?walk=1, and remembered across page loads via
+// localStorage (`walk:companion:enabled`).
+//
+// Delivery mirrors /footer-bot.js: this file is a Vite-bundled ES module
+// emitted to the stable, unhashed path /walk-companion.js (see
+// vite.config.js → rollupOptions.output.entryFileNames), and public/nav.js
+// injects it with <script type="module" src="/walk-companion.js"> only when the
+// companion is enabled — so there is zero footprint (no Three.js fetch) when
+// it's off.
+//
+// Motion reuses the same building blocks as the rest of the platform: the
+// default mascot is the shared RobotExpressive rig (also used by the footer
+// bot) with its embedded Idle / Walking / Wave clips, and a ?avatar=<id>
+// override loads that avatar's GLB and drives it with the retargeted shared
+// clip library via AnimationManager — the exact flow src/walk-embed.js uses.
+
+import {
+ AmbientLight,
+ AnimationMixer,
+ Box3,
+ Clock,
+ DirectionalLight,
+ Group,
+ HemisphereLight,
+ LoopOnce,
+ LoopRepeat,
+ PerspectiveCamera,
+ Scene,
+ Vector3,
+ WebGLRenderer,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { AnimationManager } from './animation-manager.js';
+import { getMeshoptDecoder } from './viewer/internal.js';
+import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
+
+// ── Config ──────────────────────────────────────────────────────────────────
+const ENABLED_KEY = 'walk:companion:enabled';
+const STATE_KEY = 'walk:companion:state';
+const AVATAR_KEY = 'walk:companion:avatar';
+const GREET_KEY = 'walk:companion:greet'; // sessionStorage flag set on internal nav
+const ROBOT_URL = '/animations/robotexpressive.glb';
+const MANIFEST_URL = '/animations/manifest.json';
+
+// Retargeted shared-library clip names for the ?avatar= path (verified present
+// in /animations/manifest.json + /animations/clips/*.json).
+const AVATAR_CLIPS = { idle: 'idle', walk: 'av-walk-feminine', wave: 'wave' };
+
+const CANVAS_W = 200;
+const CANVAS_H = 280;
+const WAVE_MS = 1500;
+const CURSOR_IDLE_MS = 450; // cursor still longer than this → stop walking
+
+// Routes that already own the viewport with their own 3D / full-screen
+// experience, where a corner mascot would be redundant or intrusive.
+const EXCLUDED_PREFIXES = [
+ '/walk',
+ '/walk-embed',
+ '/embed',
+ '/game',
+ '/play',
+ '/club',
+ '/city',
+ '/xr',
+ '/ar',
+ '/pose',
+ '/mocap-studio',
+ '/avatar-studio',
+];
+
+// ── Small storage helpers (private-mode safe) ───────────────────────────────
+function lsGet(key) {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+function lsSet(key, val) {
+ try {
+ localStorage.setItem(key, val);
+ } catch {
+ /* private mode / disabled storage — non-fatal */
+ }
+}
+function ssGet(key) {
+ try {
+ return sessionStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+function ssSet(key, val) {
+ try {
+ sessionStorage.setItem(key, val);
+ } catch {
+ /* non-fatal */
+ }
+}
+function ssDel(key) {
+ try {
+ sessionStorage.removeItem(key);
+ } catch {
+ /* non-fatal */
+ }
+}
+
+function prefersReducedMotion() {
+ try {
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ } catch {
+ return false;
+ }
+}
+
+function isExcludedRoute() {
+ if (window.top !== window.self) return true; // never inside an iframe/embed
+ const path = location.pathname.replace(/\/$/, '') || '/';
+ return EXCLUDED_PREFIXES.some((p) => path === p || path.startsWith(p + '/'));
+}
+
+// ── Page-context greeting ───────────────────────────────────────────────────
+// Real DOM reads, not canned data: the agent/avatar name comes from the page's
+// own heading; the pricing/features tips reference what's actually on screen.
+function contextGreeting() {
+ const path = location.pathname.replace(/\/$/, '') || '/';
+ if (path === '/pricing' || path === '/x-pricing') {
+ return 'Picking a plan? I can point you to the popular one.';
+ }
+ if (path === '/features') {
+ return 'Tap any feature card to see it in action.';
+ }
+ if (path.startsWith('/agent') || path.startsWith('/a/') || path.startsWith('/marketplace')) {
+ const name = pageSubjectName();
+ return name ? `Say hi to ${name}!` : 'Browse agents — I’ll tag along.';
+ }
+ if (path === '/' || path.startsWith('/home')) {
+ return 'Hey! I’m your guide. I’ll walk with you.';
+ }
+ return 'I’ll walk along while you explore.';
+}
+
+function pageSubjectName() {
+ const el = document.querySelector('[data-agent-name], .agent-name, h1');
+ const txt = el?.textContent?.trim();
+ if (!txt || txt.length > 40) return null;
+ return txt;
+}
+
+// Element the avatar should orient toward for the current route, if present.
+function contextTargetEl() {
+ const path = location.pathname.replace(/\/$/, '') || '/';
+ if (path === '/pricing' || path === '/x-pricing') {
+ return document.querySelector(
+ '[data-recommended], .pricing-card.is-featured, .plan.is-popular, .pricing-card--popular',
+ );
+ }
+ if (path === '/features') {
+ return document.querySelector('.feature-card, [data-feature]');
+ }
+ return null;
+}
+
+// ── Motion controllers ──────────────────────────────────────────────────────
+// Both controllers expose the same interface: setBase('idle'|'walk'),
+// playWave(), update(dt), dispose(). The companion logic never branches on
+// which rig is loaded.
+
+function makeMixerController(root, clips) {
+ const mixer = new AnimationMixer(root);
+ const byName = (name) =>
+ clips.find((c) => c.name.toLowerCase() === name.toLowerCase());
+ const pick = (candidates) => {
+ for (const n of candidates) {
+ const c = byName(n);
+ if (c) return c;
+ }
+ return clips[0] || null;
+ };
+
+ const map = {
+ idle: pick(['Idle', 'idle']),
+ walk: pick(['Walking', 'Walk', 'walk']),
+ wave: pick(['Wave', 'wave']),
+ };
+ const action = {};
+ for (const [state, clip] of Object.entries(map)) {
+ if (!clip) continue;
+ const a = mixer.clipAction(clip);
+ a.enabled = true;
+ action[state] = a;
+ }
+
+ let base = 'idle';
+ let current = null;
+ let waving = false;
+
+ function crossfade(next, { once = false } = {}) {
+ const a = action[next] || action.idle;
+ if (!a) return;
+ a.reset();
+ a.setLoop(once ? LoopOnce : LoopRepeat, once ? 1 : Infinity);
+ a.clampWhenFinished = once;
+ a.fadeIn(0.3).play();
+ if (current && current !== a) current.fadeOut(0.3);
+ current = a;
+ }
+
+ mixer.addEventListener('finished', () => {
+ if (waving) {
+ waving = false;
+ crossfade(base);
+ }
+ });
+
+ crossfade('idle');
+
+ return {
+ setBase(next) {
+ if (next === base) return;
+ base = next;
+ if (!waving) crossfade(base);
+ },
+ playWave() {
+ if (!action.wave || waving) return;
+ waving = true;
+ crossfade('wave', { once: true });
+ },
+ update(dt) {
+ mixer.update(dt);
+ },
+ dispose() {
+ mixer.stopAllAction();
+ mixer.uncacheRoot(root);
+ },
+ };
+}
+
+function makeManagerController(manager, baseClipName) {
+ let base = 'idle';
+ let waveTimer = null;
+ // crossfadeTo is async (it lazy-loads the clip); the clips are preloaded via
+ // loadAll() so these won't reject in practice, but swallow to be safe.
+ const fade = (name, dur) => Promise.resolve(manager.crossfadeTo(name, dur)).catch(() => {});
+
+ fade(AVATAR_CLIPS.idle, 0.0);
+
+ function targetClip(state) {
+ return state === 'walk' ? baseClipName : AVATAR_CLIPS.idle;
+ }
+
+ return {
+ setBase(next) {
+ if (next === base) return;
+ base = next;
+ if (!waveTimer) fade(targetClip(base), 0.3);
+ },
+ playWave() {
+ if (waveTimer) return;
+ fade(AVATAR_CLIPS.wave, 0.25);
+ waveTimer = setTimeout(() => {
+ waveTimer = null;
+ fade(targetClip(base), 0.3);
+ }, WAVE_MS);
+ },
+ update(dt) {
+ manager.update(dt);
+ },
+ dispose() {
+ clearTimeout(waveTimer);
+ manager.dispose();
+ },
+ };
+}
+
+// ── The companion instance ──────────────────────────────────────────────────
+class WalkCompanion {
+ constructor() {
+ this.mounted = false;
+ this.host = null;
+ this.renderer = null;
+ this.scene = null;
+ this.camera = null;
+ this.rig = null;
+ this.controller = null;
+ this.clock = null;
+ this._raf = 0;
+ this._reduced = prefersReducedMotion();
+
+ // Cursor tracking (page coordinates), updated by a passive listener.
+ this._cursorX = window.innerWidth * 0.5;
+ this._cursorMovedAt = 0;
+ this._yaw = 0;
+ this._targetYaw = 0;
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onLinkClick = this._onLinkClick.bind(this);
+ this._onVisibility = this._onVisibility.bind(this);
+ this._onPageHide = this._onPageHide.bind(this);
+ this._tick = this._tick.bind(this);
+ }
+
+ async mount() {
+ if (this.mounted || isExcludedRoute()) return;
+ if (!this._webglSupported()) return;
+ this.mounted = true;
+
+ this._buildDom();
+ reserveWebGLContext();
+
+ try {
+ await this._buildScene();
+ } catch (err) {
+ console.warn('[walk-companion] failed to load avatar:', err?.message || err);
+ this._teardownScene();
+ this._showError();
+ return;
+ }
+
+ this._restoreState();
+ this._bindEvents();
+ this._greetForRoute();
+ this.clock = new Clock();
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ unmount() {
+ if (!this.mounted) return;
+ this.mounted = false;
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+
+ window.removeEventListener('pointermove', this._onPointerMove);
+ document.removeEventListener('click', this._onLinkClick, true);
+ document.removeEventListener('visibilitychange', this._onVisibility);
+ window.removeEventListener('pagehide', this._onPageHide);
+
+ this._teardownScene();
+ if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
+ this.host = null;
+ }
+
+ // ── DOM / styles ────────────────────────────────────────────────────────
+ _buildDom() {
+ ensureStyles();
+ const host = document.createElement('div');
+ host.className = 'walk-companion';
+ host.setAttribute('role', 'complementary');
+ host.setAttribute('aria-label', 'Walk companion');
+ host.innerHTML = `
+ <button type="button" class="walk-companion-close" aria-label="Dismiss walk companion" title="Dismiss">×</button>
+ <div class="walk-companion-bubble" hidden></div>
+ <canvas class="walk-companion-canvas" width="${CANVAS_W}" height="${CANVAS_H}"></canvas>
+ `;
+ document.body.appendChild(host);
+ this.host = host;
+ this.canvas = host.querySelector('.walk-companion-canvas');
+ this.bubble = host.querySelector('.walk-companion-bubble');
+ host.querySelector('.walk-companion-close').addEventListener('click', () => disable());
+ // Clicking the avatar makes it wave + re-greet.
+ this.canvas.addEventListener('click', () => {
+ this.controller?.playWave();
+ this._say(contextGreeting());
+ });
+ requestAnimationFrame(() => host.classList.add('is-in'));
+ }
+
+ _showError() {
+ // Avatar couldn't load (offline / GLB 404). Don't leave a dead canvas —
+ // remove the host entirely; the toggle stays available to retry.
+ if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
+ this.host = null;
+ releaseWebGLContext();
+ this.mounted = false;
+ }
+
+ // ── Three.js scene ────────────────────────────────────────────────────────
+ async _buildScene() {
+ const renderer = new WebGLRenderer({
+ canvas: this.canvas,
+ alpha: true,
+ antialias: true,
+ });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
+ renderer.setSize(CANVAS_W, CANVAS_H, false);
+ this.renderer = renderer;
+
+ const scene = new Scene();
+ this.scene = scene;
+ scene.add(new AmbientLight(0xffffff, 0.85));
+ const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.7);
+ hemi.position.set(0, 4, 0);
+ scene.add(hemi);
+ const sun = new DirectionalLight(0xffffff, 1.6);
+ sun.position.set(2, 5, 4);
+ scene.add(sun);
+
+ const camera = new PerspectiveCamera(40, CANVAS_W / CANVAS_H, 0.05, 100);
+ this.camera = camera;
+
+ const rig = new Group();
+ scene.add(rig);
+ this.rig = rig;
+
+ const avatarId = this._resolveAvatarId();
+ if (avatarId) {
+ await this._loadAvatar(avatarId, rig, camera);
+ } else {
+ await this._loadRobot(rig, camera);
+ }
+ }
+
+ _resolveAvatarId() {
+ const param = new URLSearchParams(location.search).get('avatar');
+ if (param) {
+ lsSet(AVATAR_KEY, param);
+ return param;
+ }
+ return lsGet(AVATAR_KEY) || null;
+ }
+
+ // One GLTFLoader wired with the meshopt decoder only: the default robot rig
+ // is uncompressed, but server-baked avatars (the ?avatar= path) emit
+ // EXT_meshopt_compression — and crucially, draco/KTX2 are never used by the
+ // bake, so we avoid pulling KTX2Loader (keeps the chunk small and dodges a
+ // heavier decoder init). Mirrors src/voice/talk-scene.js.
+ async _makeLoader() {
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(await getMeshoptDecoder());
+ return loader;
+ }
+
+ async _loadRobot(rig, camera) {
+ const loader = await this._makeLoader();
+ const gltf = await loader.loadAsync(ROBOT_URL);
+ const model = gltf.scene;
+ this._frame(model, rig, camera);
+ this.controller = makeMixerController(model, gltf.animations || []);
+ }
+
+ async _loadAvatar(id, rig, camera) {
+ const url = `/api/avatars/${encodeURIComponent(id)}/glb`;
+ const loader = await this._makeLoader();
+ const gltf = await loader.loadAsync(url);
+ const model = gltf.scene;
+ this._frame(model, rig, camera);
+
+ const manager = new AnimationManager();
+ manager.attach(model);
+ const manifest = await fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`);
+ return r.json();
+ });
+ const wanted = new Set(Object.values(AVATAR_CLIPS));
+ const defs = manifest.filter((d) => wanted.has(d.name));
+ if (!defs.some((d) => d.name === AVATAR_CLIPS.idle)) {
+ throw new Error('animation manifest missing idle clip');
+ }
+ manager.setAnimationDefs(defs);
+ await manager.loadAll();
+ const walkName = defs.some((d) => d.name === AVATAR_CLIPS.walk)
+ ? AVATAR_CLIPS.walk
+ : AVATAR_CLIPS.idle;
+ this.controller = makeManagerController(manager, walkName);
+ }
+
+ // Center the model on X/Z, drop its feet to the floor, and frame the camera
+ // to show the full body within the portrait canvas.
+ _frame(model, rig, camera) {
+ model.traverse((n) => {
+ if (n.isMesh) n.frustumCulled = false;
+ });
+ const box = new Box3().setFromObject(model);
+ const size = box.getSize(new Vector3());
+ const center = box.getCenter(new Vector3());
+ model.position.x -= center.x;
+ model.position.z -= center.z;
+ model.position.y -= box.min.y;
+ rig.add(model);
+
+ const height = Math.max(0.6, size.y);
+ camera.position.set(0, height * 0.62, height * 2.25);
+ camera.lookAt(0, height * 0.52, 0);
+ this._height = height;
+ }
+
+ _teardownScene() {
+ try {
+ this.controller?.dispose();
+ } catch {
+ /* non-fatal */
+ }
+ this.controller = null;
+ if (this.scene) {
+ this.scene.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ mats.forEach((m) => {
+ if (!m) return;
+ for (const v of Object.values(m)) {
+ if (v && v.isTexture) v.dispose();
+ }
+ m.dispose?.();
+ });
+ }
+ });
+ }
+ this.scene = null;
+ if (this.renderer) {
+ this.renderer.dispose();
+ this.renderer.forceContextLoss?.();
+ this.renderer = null;
+ releaseWebGLContext();
+ }
+ }
+
+ // ── Events ────────────────────────────────────────────────────────────────
+ _bindEvents() {
+ window.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ document.addEventListener('click', this._onLinkClick, true);
+ document.addEventListener('visibilitychange', this._onVisibility);
+ window.addEventListener('pagehide', this._onPageHide);
+ }
+
+ _onPointerMove(e) {
+ this._cursorX = e.clientX;
+ this._cursorMovedAt = performance.now();
+ }
+
+ // Wave goodbye + flag the next page so the companion waves hello on arrival,
+ // giving the cross-navigation continuity. Never blocks the navigation.
+ _onLinkClick(e) {
+ const a = e.target.closest?.('a[href]');
+ if (!a) return;
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
+ const href = a.getAttribute('href');
+ if (!href || href.startsWith('#')) return;
+ if (a.target && a.target !== '_self') return;
+ let url;
+ try {
+ url = new URL(href, location.href);
+ } catch {
+ return;
+ }
+ if (url.origin !== location.origin) return;
+ if (url.pathname === location.pathname) return;
+ this.controller?.playWave();
+ ssSet(GREET_KEY, '1');
+ }
+
+ _onVisibility() {
+ if (document.hidden) {
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+ } else if (this.mounted && !this._raf) {
+ this.clock?.getDelta(); // discard the idle gap so dt stays bounded
+ this._raf = requestAnimationFrame(this._tick);
+ }
+ }
+
+ _onPageHide() {
+ this._persistState();
+ }
+
+ // ── Greeting / speech bubble ──────────────────────────────────────────────
+ _greetForRoute() {
+ const arrivedByNav = ssGet(GREET_KEY) === '1';
+ ssDel(GREET_KEY);
+ if (arrivedByNav) this.controller?.playWave();
+ // Orient toward a route-relevant element if there is one.
+ this._orientToContext();
+ this._say(contextGreeting());
+ }
+
+ _orientToContext() {
+ const el = contextTargetEl();
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const elCenterX = rect.left + rect.width / 2;
+ const hostRect = this.host.getBoundingClientRect();
+ const hostCenterX = hostRect.left + hostRect.width / 2;
+ this._targetYaw = clamp((elCenterX - hostCenterX) / window.innerWidth, -0.6, 0.6);
+ // Hold the context-facing pose briefly before cursor-follow takes over.
+ this._orientLock = true;
+ clearTimeout(this._orientTimer);
+ this._orientTimer = setTimeout(() => {
+ this._orientLock = false;
+ }, 4000);
+ }
+
+ _say(text) {
+ if (!this.bubble || !text) return;
+ this.bubble.textContent = text;
+ this.bubble.hidden = false;
+ this.bubble.classList.add('is-in');
+ clearTimeout(this._bubbleTimer);
+ this._bubbleTimer = setTimeout(() => {
+ this.bubble.classList.remove('is-in');
+ setTimeout(() => {
+ if (this.bubble) this.bubble.hidden = true;
+ }, 300);
+ }, 5200);
+ }
+
+ // ── Persistence (Option B: localStorage resume) ───────────────────────────
+ _persistState() {
+ if (!this.controller) return;
+ lsSet(STATE_KEY, JSON.stringify({ yaw: this._yaw }));
+ }
+
+ _restoreState() {
+ try {
+ const raw = lsGet(STATE_KEY);
+ if (!raw) return;
+ const s = JSON.parse(raw);
+ if (typeof s.yaw === 'number') {
+ this._yaw = s.yaw;
+ this._targetYaw = s.yaw;
+ }
+ } catch {
+ /* corrupt state — ignore */
+ }
+ }
+
+ // ── Render loop ───────────────────────────────────────────────────────────
+ _tick() {
+ if (!this.mounted) return;
+ const dt = Math.min(this.clock.getDelta(), 0.05);
+
+ // Decide motion: walking while the cursor is in motion and off to one
+ // side; idling once it settles. Reduced-motion users get a calm idle.
+ const movingRecently = performance.now() - this._cursorMovedAt < CURSOR_IDLE_MS;
+ if (!this._reduced && !this._orientLock) {
+ const rel = (this._cursorX - window.innerWidth / 2) / (window.innerWidth / 2);
+ this._targetYaw = clamp(rel * 0.7, -0.7, 0.7);
+ }
+ const turning = Math.abs(this._targetYaw - this._yaw) > 0.04;
+ const shouldWalk = !this._reduced && (movingRecently || turning);
+ this.controller?.setBase(shouldWalk ? 'walk' : 'idle');
+
+ // Smoothly turn the rig toward the cursor side.
+ this._yaw += (this._targetYaw - this._yaw) * 0.12;
+ if (this.rig) this.rig.rotation.y = this._yaw;
+
+ this.controller?.update(dt);
+ this.renderer.render(this.scene, this.camera);
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ _webglSupported() {
+ try {
+ const c = document.createElement('canvas');
+ return !!(
+ window.WebGLRenderingContext &&
+ (c.getContext('webgl2') || c.getContext('webgl'))
+ );
+ } catch {
+ return false;
+ }
+ }
+}
+
+function clamp(v, lo, hi) {
+ return Math.max(lo, Math.min(hi, v));
+}
+
+// ── Scoped styles (injected once) ───────────────────────────────────────────
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'walk-companion-style';
+ style.textContent = `
+.walk-companion{position:fixed;right:16px;bottom:16px;width:${CANVAS_W}px;height:${CANVAS_H}px;z-index:2147483000;pointer-events:none;opacity:0;transform:translateY(12px);transition:opacity .35s ease,transform .35s ease;-webkit-user-select:none;user-select:none}
+.walk-companion.is-in{opacity:1;transform:translateY(0)}
+.walk-companion-canvas{position:absolute;inset:0;width:100%;height:100%;z-index:1;pointer-events:auto;cursor:pointer;filter:drop-shadow(0 18px 22px rgba(0,0,0,.32))}
+.walk-companion-close{position:absolute;top:2px;right:2px;z-index:3;width:22px;height:22px;border:none;border-radius:50%;background:rgba(12,14,20,.55);color:#fff;font-size:15px;line-height:1;cursor:pointer;pointer-events:auto;opacity:0;transition:opacity .2s ease,background .2s ease;display:grid;place-items:center;padding:0}
+.walk-companion:hover .walk-companion-close,.walk-companion:focus-within .walk-companion-close{opacity:1}
+.walk-companion-close:hover{background:rgba(220,60,60,.85)}
+.walk-companion-close:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;opacity:1}
+.walk-companion-bubble{position:absolute;left:50%;bottom:calc(100% - 38px);z-index:2;transform:translateX(-50%) translateY(6px);max-width:230px;width:max-content;background:rgba(18,20,28,.94);color:#f2f4f8;font:500 12.5px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;padding:8px 11px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);pointer-events:none;opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
+.walk-companion-bubble.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.walk-companion-bubble::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:6px solid transparent;border-top-color:rgba(18,20,28,.94)}
+@media (max-width:520px){.walk-companion{width:148px;height:208px;right:10px;bottom:10px}.walk-companion-bubble{font-size:11.5px;max-width:170px}}
+@media (prefers-reduced-motion:reduce){.walk-companion,.walk-companion-bubble{transition:none}}
+`;
+ document.head.appendChild(style);
+}
+
+// ── Public API (driven by public/nav.js) ────────────────────────────────────
+let _instance = null;
+
+function emitChange() {
+ try {
+ window.dispatchEvent(
+ new CustomEvent('walk-companion:change', { detail: { enabled: isEnabled() } }),
+ );
+ } catch {
+ /* non-fatal */
+ }
+}
+
+function isEnabled() {
+ return lsGet(ENABLED_KEY) === '1';
+}
+
+function enable() {
+ lsSet(ENABLED_KEY, '1');
+ if (!_instance) _instance = new WalkCompanion();
+ _instance.mount();
+ emitChange();
+}
+
+function disable() {
+ lsSet(ENABLED_KEY, '0');
+ if (_instance) _instance.unmount();
+ emitChange();
+}
+
+function toggle() {
+ if (isEnabled() && _instance && _instance.mounted) disable();
+ else enable();
+}
+
+window.__walkCompanion = { enable, disable, toggle, isEnabled };
+
+// Auto-mount on load when enabled (nav.js only injects this module when the
+// flag is set or the user just toggled it on, so this is the common path).
+const _params = new URLSearchParams(location.search);
+if (_params.get('walk') === '0') {
+ disable();
+} else if (_params.get('walk') === '1' || isEnabled()) {
+ enable();
+}
diff --git a/src/wallet.js b/src/wallet.js
index ffb710a96..ed0fa7df8 100644
--- a/src/wallet.js
+++ b/src/wallet.js
@@ -51,8 +51,15 @@ async function onConnectWallet() {
export function updateWalletState(address) {
const btn = document.getElementById('connect-wallet-btn');
- if (!btn) return;
- btn.textContent = address ? `${address.slice(0, 4)}...${address.slice(-4)}` : 'Connect Wallet';
+ if (btn) {
+ btn.textContent = address ? `${address.slice(0, 4)}...${address.slice(-4)}` : 'Connect Wallet';
+ }
+ // Broadcast so consumers (dashboards, balance panels) can react to connect /
+ // disconnect without reaching into window.solana directly. Fires for both the
+ // click-connect and auto-connect-if-trusted paths.
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
+ window.dispatchEvent(new CustomEvent('wallet:changed', { detail: { address: address || null } }));
+ }
}
export function initWalletButton() {
diff --git a/src/widget-types.js b/src/widget-types.js
index 9d074826b..7abe90e87 100644
--- a/src/widget-types.js
+++ b/src/widget-types.js
@@ -56,6 +56,12 @@ export const WIDGET_TYPES = {
status: 'ready',
icon: '⬡',
},
+ 'bonding-curve': {
+ label: 'Bonding Curve',
+ desc: 'Live graduation progress and bonding-curve climb for a pump.fun token.',
+ status: 'ready',
+ icon: '◭',
+ },
};
export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);
@@ -124,6 +130,12 @@ const TYPE_DEFAULTS = {
bg: '#0a0a0a',
minUsd: 0,
},
+ 'bonding-curve': {
+ mint: '',
+ network: 'mainnet',
+ refreshMs: 15_000,
+ showUsd: true,
+ },
};
const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');
@@ -249,6 +261,12 @@ const TYPE_SCHEMAS = {
bg: hexColor.default('#0a0a0a'),
minUsd: z.number().min(0).default(0),
}),
+ 'bonding-curve': brandSchema.extend({
+ mint: z.string().max(64).default(''),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ refreshMs: z.number().int().min(5_000).max(300_000).default(15_000),
+ showUsd: z.boolean().default(true),
+ }),
};
export function defaultConfig(type) {
diff --git a/src/widgets/bonding-curve.js b/src/widgets/bonding-curve.js
new file mode 100644
index 000000000..ee5252941
--- /dev/null
+++ b/src/widgets/bonding-curve.js
@@ -0,0 +1,588 @@
+/**
+ * Bonding Curve widget — a live, animated view of a pump.fun token's climb
+ * toward graduation.
+ *
+ * Distinct from the trade-feed widgets (kol-trades / live-trades-canvas /
+ * pumpfun-feed): those show *flow* (individual trades). This shows *state* —
+ * how far a single token has progressed along its bonding curve and how close
+ * it is to graduating to an AMM pool.
+ *
+ * Data source: GET /api/pump/curve?mint=…&network=… (real on-chain reads via
+ * the pump SDK, edge-cached ~10s). USD figures are enriched client-side from
+ * Jupiter's public price API; if that fails we degrade gracefully to SOL.
+ *
+ * Exported functions:
+ * lamportsToSol / fmtSol / fmtUsd / fmtPrice — pure formatters (tested)
+ * curveValue / curvePoints / areaPathFor — pure curve geometry (tested)
+ * computeView(data, solUsd) — pure view-model (tested)
+ * renderCardShell(view, cfg) — pure HTML string (tested)
+ * mountBondingCurve(rootEl, opts) — full mount + polling + anim
+ *
+ * The generic <three-ws-widget type="bonding-curve" mint="…"> element is
+ * handled by the dispatcher in kol-trades.js.
+ */
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+// SVG geometry. viewBox is fixed; the element scales to its container.
+const VB = Object.freeze({ w: 320, h: 150, pl: 14, pr: 14, pt: 18, pb: 18 });
+const CURVE_EXP = 1.85; // convex/accelerating — mirrors the pump.fun price curve
+const CURVE_SAMPLES = 48;
+
+// ---------------------------------------------------------------------------
+// Pure helpers — no DOM, exported for unit testing.
+// ---------------------------------------------------------------------------
+
+export function lamportsToSol(lamports) {
+ const n = Number(lamports);
+ if (!Number.isFinite(n)) return 0;
+ return n / LAMPORTS_PER_SOL;
+}
+
+export function clamp01(n) {
+ if (!Number.isFinite(n)) return 0;
+ if (n < 0) return 0;
+ if (n > 1) return 1;
+ return n;
+}
+
+/** Compact SOL amount, e.g. "◎ 18.4" / "◎ 1.2K". */
+export function fmtSol(sol) {
+ const v = Number(sol);
+ if (!Number.isFinite(v)) return '◎ —';
+ if (v >= 1_000_000) return `◎ ${(v / 1_000_000).toFixed(2)}M`;
+ if (v >= 1_000) return `◎ ${(v / 1_000).toFixed(2)}K`;
+ if (v >= 1) return `◎ ${v.toFixed(2)}`;
+ if (v > 0) return `◎ ${v.toFixed(3)}`;
+ return '◎ 0';
+}
+
+/** Compact USD, e.g. "$12.3K". */
+export function fmtUsd(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '$—';
+ if (v >= 1_000_000_000) return `$${(v / 1_000_000_000).toFixed(2)}B`;
+ if (v >= 1_000_000) return `$${(v / 1_000_000).toFixed(2)}M`;
+ if (v >= 1_000) return `$${(v / 1_000).toFixed(1)}K`;
+ if (v >= 1) return `$${v.toFixed(2)}`;
+ if (v > 0) return `$${v.toPrecision(2)}`;
+ return '$0';
+}
+
+/** Per-token price — tiny numbers, shown with significant digits. */
+export function fmtPrice(value, { usd = false } = {}) {
+ const v = Number(value);
+ if (!Number.isFinite(v) || v <= 0) return usd ? '$—' : '◎ —';
+ const sym = usd ? '$' : '◎ ';
+ if (v >= 0.01) return `${sym}${v.toFixed(usd ? 4 : 5)}`;
+ // Sub-cent: trim a fixed-notation value so we never render "1e-7".
+ const fixed = v.toFixed(12).replace(/0+$/, '');
+ return `${sym}${fixed}`;
+}
+
+export function shortMint(mint, n = 4) {
+ const s = String(mint || '');
+ if (s.length <= n * 2 + 1) return s;
+ return `${s.slice(0, n)}…${s.slice(-n)}`;
+}
+
+/** Curve height fraction in [0,1] for a horizontal fraction t in [0,1]. */
+export function curveValue(t) {
+ return Math.pow(clamp01(t), CURVE_EXP);
+}
+
+/** Screen point for a fraction t along the curve. */
+export function curvePointAt(t, vb = VB) {
+ const innerW = vb.w - vb.pl - vb.pr;
+ const innerH = vb.h - vb.pt - vb.pb;
+ const baseY = vb.h - vb.pb;
+ const x = vb.pl + clamp01(t) * innerW;
+ const y = baseY - curveValue(t) * innerH;
+ return { x, y };
+}
+
+/** Sample the full curve as an SVG polyline `d` string. */
+export function curvePoints(samples = CURVE_SAMPLES, vb = VB) {
+ let d = '';
+ for (let i = 0; i <= samples; i++) {
+ const t = i / samples;
+ const { x, y } = curvePointAt(t, vb);
+ d += `${i === 0 ? 'M' : 'L'}${x.toFixed(2)} ${y.toFixed(2)}`;
+ if (i < samples) d += ' ';
+ }
+ return d;
+}
+
+/** Filled-area path under the curve from the origin up to `progress`. */
+export function areaPathFor(progress, samples = CURVE_SAMPLES, vb = VB) {
+ const p = clamp01(progress);
+ const baseY = vb.h - vb.pb;
+ const start = curvePointAt(0, vb);
+ let d = `M${start.x.toFixed(2)} ${baseY.toFixed(2)} L${start.x.toFixed(2)} ${start.y.toFixed(2)} `;
+ const steps = Math.max(1, Math.round(samples * p));
+ for (let i = 1; i <= steps; i++) {
+ const t = (p * i) / steps;
+ const { x, y } = curvePointAt(t, vb);
+ d += `L${x.toFixed(2)} ${y.toFixed(2)} `;
+ }
+ const end = curvePointAt(p, vb);
+ d += `L${end.x.toFixed(2)} ${baseY.toFixed(2)} Z`;
+ return d;
+}
+
+/**
+ * Build a render-ready view model from a /api/pump/curve response.
+ * @param {object|null} data Raw API payload, or null on error/empty.
+ * @param {number|null} solUsd SOL price in USD, or null when unavailable.
+ */
+export function computeView(data, solUsd = null) {
+ if (!data || !data.curve) {
+ return { status: 'empty', progress: 0, hasUsd: false };
+ }
+ const grad = data.graduation || {};
+ const price = data.price || {};
+ const isGraduated = Boolean(grad.isGraduated || price.isGraduated || data.curve.complete);
+ const progress = isGraduated ? 1 : clamp01(Number(grad.progressBps) / 10_000);
+
+ // The SDK can report a small negative market cap for a freshly-created
+ // curve (real reserves still at zero) — clamp so we never show "-$2".
+ const marketCapSol = Math.max(0, lamportsToSol(price.marketCap));
+ const raisedSol = Math.max(0, lamportsToSol(grad.solAccumulated ?? data.curve.realSolReserves));
+ const priceSol = Math.max(0, lamportsToSol(price.buyPricePerToken));
+ const hasUsd = Number.isFinite(Number(solUsd)) && Number(solUsd) > 0;
+
+ return {
+ status: isGraduated ? 'graduated' : 'bonding',
+ progress,
+ progressPct: progress * 100,
+ marketCapSol,
+ marketCapUsd: hasUsd ? marketCapSol * solUsd : null,
+ raisedSol,
+ raisedUsd: hasUsd ? raisedSol * solUsd : null,
+ priceSol,
+ priceUsd: hasUsd ? priceSol * solUsd : null,
+ isMayhem: Boolean(data.curve.isMayhemMode),
+ network: data.network === 'devnet' ? 'devnet' : 'mainnet',
+ mint: data.mint || '',
+ hasUsd,
+ };
+}
+
+function esc(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/**
+ * Render the static card shell (everything except the values that animate).
+ * Returns an HTML string. The mount step queries the marked nodes and updates
+ * them live, so this stays a pure, testable function.
+ */
+export function renderCardShell(view, cfg = {}) {
+ const mint = view.mint || cfg.mint || '';
+ const net = view.network || cfg.network || 'mainnet';
+ const pumpUrl = `https://pump.fun/${esc(mint)}`;
+ const netBadge = net === 'devnet' ? '<span class="bcw-net bcw-net--dev">devnet</span>' : '';
+ const mayhem = view.isMayhem
+ ? '<span class="bcw-mayhem" title="Mayhem mode">⚡ mayhem</span>'
+ : '';
+
+ const statusClass =
+ view.status === 'graduated'
+ ? 'is-grad'
+ : view.status === 'bonding'
+ ? 'is-bonding'
+ : 'is-empty';
+ const statusLabel =
+ view.status === 'graduated'
+ ? 'Graduated'
+ : view.status === 'bonding'
+ ? 'Bonding'
+ : 'No curve';
+
+ return `<div class="bcw-card ${statusClass}">
+ <header class="bcw-head">
+ <span class="bcw-status"><i class="bcw-led"></i>${esc(statusLabel)}</span>
+ <a class="bcw-mint" href="${pumpUrl}" target="_blank" rel="noopener noreferrer" title="${esc(mint)}">${esc(shortMint(mint))}</a>
+ ${netBadge}${mayhem}
+ </header>
+
+ <div class="bcw-meter">
+ <div class="bcw-pct" data-pct><span class="bcw-pct-num">0</span><span class="bcw-pct-sym">%</span></div>
+ <div class="bcw-pct-label">to graduation</div>
+ </div>
+
+ <svg class="bcw-curve" viewBox="0 0 ${VB.w} ${VB.h}" preserveAspectRatio="none" aria-hidden="true">
+ <defs>
+ <linearGradient id="bcw-fill" x1="0" y1="1" x2="1" y2="0">
+ <stop offset="0%" stop-color="var(--bcw-accent)" stop-opacity="0.04"/>
+ <stop offset="100%" stop-color="var(--bcw-accent)" stop-opacity="0.42"/>
+ </linearGradient>
+ <filter id="bcw-glow" x="-60%" y="-60%" width="220%" height="220%">
+ <feGaussianBlur stdDeviation="3.2" result="b"/>
+ <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
+ </filter>
+ </defs>
+ <line class="bcw-grad-line" x1="${VB.pl}" y1="${VB.pt}" x2="${VB.w - VB.pr}" y2="${VB.pt}"/>
+ <path class="bcw-area" data-area fill="url(#bcw-fill)" d=""/>
+ <path class="bcw-line" data-line fill="none" d="${curvePoints()}"/>
+ <g data-marker class="bcw-marker" filter="url(#bcw-glow)">
+ <circle class="bcw-marker-halo" r="6.5"/>
+ <circle class="bcw-marker-dot" r="3.2"/>
+ </g>
+ </svg>
+
+ <dl class="bcw-stats">
+ <div><dt>Market cap</dt><dd data-mc>—</dd></div>
+ <div><dt>Raised</dt><dd data-raised>—</dd></div>
+ <div><dt>Price</dt><dd data-price>—</dd></div>
+ </dl>
+
+ <a class="bcw-cta" href="${pumpUrl}" target="_blank" rel="noopener noreferrer" data-cta>Trade on pump.fun →</a>
+ ${cfg.showPoweredBy === false ? '' : '<a class="bcw-by" href="https://three.ws" target="_blank" rel="noopener noreferrer">three.ws</a>'}
+ </div>`;
+}
+
+// ---------------------------------------------------------------------------
+// Styles — injected once per document.
+// ---------------------------------------------------------------------------
+
+const STYLES = `
+.bcw {
+ font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ color: #f2f3f7; pointer-events: none;
+}
+.bcw-card {
+ pointer-events: auto;
+ width: min(420px, 92vw);
+ box-sizing: border-box;
+ padding: 18px 18px 16px;
+ border-radius: 18px;
+ background: rgba(12, 14, 22, 0.82);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ box-shadow: 0 24px 60px -20px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.05);
+ backdrop-filter: blur(14px) saturate(1.1);
+ -webkit-backdrop-filter: blur(14px) saturate(1.1);
+ position: relative; overflow: hidden;
+ animation: bcw-rise 0.5s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+.bcw-card::before {
+ content: ''; position: absolute; inset: 0; pointer-events: none;
+ background: radial-gradient(120% 70% at 85% 0%, var(--bcw-accent-soft), transparent 60%);
+ opacity: 0.7;
+}
+@keyframes bcw-rise { from { opacity: 0; transform: translateY(10px) scale(0.99); } to { opacity: 1; transform: none; } }
+
+.bcw-head { display: flex; align-items: center; gap: 8px; position: relative; }
+.bcw-status {
+ display: inline-flex; align-items: center; gap: 6px;
+ font-size: 0.72rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.62);
+}
+.bcw-led { width: 7px; height: 7px; border-radius: 50%; background: var(--bcw-accent); box-shadow: 0 0 0 0 var(--bcw-accent); }
+.is-bonding .bcw-led { animation: bcw-pulse 1.8s ease-out infinite; }
+.is-grad .bcw-led { background: #34d399; box-shadow: 0 0 8px #34d399; }
+.is-empty .bcw-led { background: rgba(255,255,255,0.3); }
+@keyframes bcw-pulse {
+ 0% { box-shadow: 0 0 0 0 var(--bcw-accent-soft); }
+ 70% { box-shadow: 0 0 0 7px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+.bcw-mint {
+ margin-left: auto; font-family: ui-monospace, 'SF Mono', monospace; font-size: 0.78rem;
+ color: rgba(190, 210, 255, 0.85); text-decoration: none; padding: 2px 7px; border-radius: 6px;
+ background: rgba(255, 255, 255, 0.05); transition: background 0.15s, color 0.15s;
+}
+.bcw-mint:hover { background: rgba(255, 255, 255, 0.1); color: #fff; }
+.bcw-net, .bcw-mayhem {
+ font-size: 0.62rem; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;
+ padding: 2px 6px; border-radius: 5px;
+}
+.bcw-net--dev { background: rgba(251, 191, 36, 0.16); color: #fbbf24; }
+.bcw-mayhem { background: rgba(244, 114, 182, 0.16); color: #f472b6; }
+
+.bcw-meter { margin: 14px 0 2px; }
+.bcw-pct {
+ display: flex; align-items: baseline; gap: 2px; line-height: 1;
+ font-weight: 700; letter-spacing: -0.02em;
+ font-variant-numeric: tabular-nums;
+}
+.bcw-pct-num { font-size: 2.9rem; background: linear-gradient(180deg, #fff, var(--bcw-accent)); -webkit-background-clip: text; background-clip: text; color: transparent; }
+.bcw-pct-sym { font-size: 1.3rem; color: var(--bcw-accent); font-weight: 600; }
+.bcw-pct-label { font-size: 0.74rem; color: rgba(255, 255, 255, 0.45); letter-spacing: 0.03em; margin-top: 2px; }
+.is-grad .bcw-pct-num { background: linear-gradient(180deg, #fff, #34d399); -webkit-background-clip: text; background-clip: text; }
+.is-grad .bcw-pct-sym { color: #34d399; }
+
+.bcw-curve { width: 100%; height: 92px; display: block; margin: 6px 0 12px; overflow: visible; }
+.bcw-grad-line { stroke: rgba(255, 255, 255, 0.16); stroke-width: 1; stroke-dasharray: 3 4; }
+.bcw-line { stroke: rgba(255, 255, 255, 0.28); stroke-width: 1.5; vector-effect: non-scaling-stroke; }
+.bcw-marker-halo { fill: var(--bcw-accent); opacity: 0.28; }
+.bcw-marker-dot { fill: #fff; stroke: var(--bcw-accent); stroke-width: 1.5; vector-effect: non-scaling-stroke; }
+.is-grad .bcw-marker-dot { stroke: #34d399; }
+.is-grad .bcw-marker-halo { fill: #34d399; }
+
+.bcw-stats {
+ display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 0 0 14px;
+ padding: 12px 0 0; border-top: 1px solid rgba(255, 255, 255, 0.06);
+}
+.bcw-stats div { min-width: 0; }
+.bcw-stats dt { font-size: 0.64rem; letter-spacing: 0.05em; text-transform: uppercase; color: rgba(255, 255, 255, 0.42); margin: 0 0 3px; }
+.bcw-stats dd { margin: 0; font-size: 0.95rem; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+.bcw-cta {
+ display: block; text-align: center; text-decoration: none;
+ font-size: 0.84rem; font-weight: 600; color: #0a0a0a;
+ padding: 9px 14px; border-radius: 10px;
+ background: var(--bcw-accent);
+ transition: transform 0.12s ease, filter 0.15s ease, box-shadow 0.15s ease;
+ box-shadow: 0 6px 18px -6px var(--bcw-accent-soft);
+}
+.bcw-cta:hover { transform: translateY(-1px); filter: brightness(1.07); }
+.bcw-cta:active { transform: translateY(0); }
+.bcw-cta:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.is-empty .bcw-cta { background: rgba(255, 255, 255, 0.08); color: rgba(255, 255, 255, 0.7); box-shadow: none; }
+
+.bcw-by {
+ display: block; text-align: center; margin-top: 9px;
+ font-size: 0.64rem; letter-spacing: 0.08em; text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.32); text-decoration: none; transition: color 0.15s;
+}
+.bcw-by:hover { color: rgba(255, 255, 255, 0.6); }
+
+.bcw-empty-msg { margin: 2px 0 14px; font-size: 0.82rem; color: rgba(255, 255, 255, 0.5); }
+.bcw-card.is-loading .bcw-pct-num,
+.bcw-card.is-loading .bcw-stats dd { color: transparent; background: rgba(255,255,255,0.08); border-radius: 6px; animation: bcw-shimmer 1.2s ease-in-out infinite; }
+@keyframes bcw-shimmer { 0%,100% { opacity: 0.5; } 50% { opacity: 1; } }
+
+@media (prefers-reduced-motion: reduce) {
+ .bcw-card, .is-bonding .bcw-led { animation: none; }
+}
+`;
+
+let _stylesInjected = false;
+function injectStyles(doc) {
+ if (_stylesInjected) return;
+ const tag = doc.createElement('style');
+ tag.setAttribute('data-bcw', '');
+ tag.textContent = STYLES;
+ doc.head.appendChild(tag);
+ _stylesInjected = true;
+}
+
+// ---------------------------------------------------------------------------
+// SOL/USD price — fetched once, refreshed lazily, shared across mounts.
+// ---------------------------------------------------------------------------
+
+let _solUsd = { value: null, at: 0, inflight: null };
+const SOL_USD_TTL = 60_000;
+
+async function getSolUsd() {
+ const now = Date.now();
+ if (_solUsd.value != null && now - _solUsd.at < SOL_USD_TTL) return _solUsd.value;
+ if (_solUsd.inflight) return _solUsd.inflight;
+ _solUsd.inflight = (async () => {
+ try {
+ const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${SOL_MINT}`);
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const d = await r.json();
+ const usd = Number(d?.[SOL_MINT]?.usdPrice ?? d?.[SOL_MINT]?.price);
+ if (Number.isFinite(usd) && usd > 0) {
+ _solUsd = { value: usd, at: Date.now(), inflight: null };
+ return usd;
+ }
+ } catch {
+ /* graceful — caller falls back to SOL-only display */
+ }
+ _solUsd.inflight = null;
+ return _solUsd.value;
+ })();
+ return _solUsd.inflight;
+}
+
+const _easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
+
+// ---------------------------------------------------------------------------
+// Mount.
+// ---------------------------------------------------------------------------
+
+/**
+ * Mount the bonding-curve widget inside `rootEl`.
+ * @param {HTMLElement} rootEl
+ * @param {{ mint?: string, network?: string, refreshMs?: number, showUsd?: boolean,
+ * accent?: string, showPoweredBy?: boolean }} opts
+ * @returns {{ destroy(): void }}
+ */
+export function mountBondingCurve(rootEl, opts = {}) {
+ const doc = rootEl.ownerDocument ?? (typeof document !== 'undefined' ? document : null);
+ if (!doc) return { destroy() {} };
+ injectStyles(doc);
+
+ const mint = String(opts.mint || '').trim();
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const refreshMs = Math.max(5_000, Number(opts.refreshMs) || 15_000);
+ const showUsd = opts.showUsd !== false;
+ const accent = /^#[0-9a-fA-F]{3,8}$/.test(opts.accent || '') ? opts.accent : '#8b5cf6';
+
+ const wrap = doc.createElement('div');
+ wrap.className = 'bcw';
+ wrap.style.setProperty('--bcw-accent', accent);
+ wrap.style.setProperty('--bcw-accent-soft', accentSoft(accent));
+ rootEl.appendChild(wrap);
+
+ let destroyed = false;
+ let timer = null;
+ let raf = null;
+ let displayedProgress = 0; // currently-rendered marker/percent position
+ let view = { status: mint ? 'loading' : 'empty', progress: 0 };
+
+ // Initial paint — shell + empty/loading state.
+ wrap.innerHTML = renderCardShell(view, { mint, network, showPoweredBy: opts.showPoweredBy });
+ const card = wrap.querySelector('.bcw-card');
+ if (mint) card.classList.add('is-loading');
+ const els = grab(wrap);
+ if (!mint) applyEmptyState(card, els);
+ paintGeometry(els, 0);
+
+ function setText(el, text) {
+ if (el && el.textContent !== text) el.textContent = text;
+ }
+
+ function renderValues(v) {
+ // Status class swap (bonding → graduated transitions live).
+ card.classList.remove('is-bonding', 'is-grad', 'is-empty', 'is-loading');
+ card.classList.add(
+ v.status === 'graduated' ? 'is-grad' : v.status === 'empty' ? 'is-empty' : 'is-bonding',
+ );
+ setText(els.status, v.status === 'graduated' ? 'Graduated' : 'Bonding');
+
+ if (v.hasUsd) {
+ setText(els.mc, fmtUsd(v.marketCapUsd));
+ setText(els.raised, `${fmtSol(v.raisedSol)} · ${fmtUsd(v.raisedUsd)}`);
+ setText(els.price, fmtPrice(v.priceUsd, { usd: true }));
+ } else {
+ setText(els.mc, fmtSol(v.marketCapSol));
+ setText(els.raised, fmtSol(v.raisedSol));
+ setText(els.price, fmtPrice(v.priceSol));
+ }
+ animateTo(v.progress);
+ }
+
+ function animateTo(target) {
+ const from = displayedProgress;
+ const to = clamp01(target);
+ if (Math.abs(to - from) < 0.0005) {
+ displayedProgress = to;
+ paintGeometry(els, to);
+ return;
+ }
+ const dur = 700;
+ const start = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (raf) cancelAnimationFrame(raf);
+ const step = (now) => {
+ if (destroyed) return;
+ const k = _easeOutCubic(Math.min(1, (now - start) / dur));
+ displayedProgress = from + (to - from) * k;
+ paintGeometry(els, displayedProgress);
+ if (k < 1) raf = requestAnimationFrame(step);
+ };
+ raf = requestAnimationFrame(step);
+ }
+
+ async function poll() {
+ if (destroyed || !mint) return;
+ try {
+ const [resp, solUsd] = await Promise.all([
+ fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}&network=${network}`),
+ showUsd ? getSolUsd() : Promise.resolve(null),
+ ]);
+ if (destroyed) return;
+ if (resp.status === 404) {
+ view = computeView(null);
+ applyEmptyState(
+ card,
+ els,
+ 'No active bonding curve — this token may have graduated or isn’t a pump.fun mint.',
+ );
+ return;
+ }
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const data = await resp.json();
+ if (destroyed) return;
+ view = computeView(data, solUsd);
+ if (view.status === 'empty') {
+ applyEmptyState(card, els);
+ } else {
+ renderValues(view);
+ }
+ } catch {
+ // Network blip — keep last good frame, retry on next tick.
+ }
+ }
+
+ poll();
+ timer = setInterval(poll, refreshMs);
+
+ return {
+ destroy() {
+ destroyed = true;
+ if (timer) clearInterval(timer);
+ if (raf) cancelAnimationFrame(raf);
+ wrap.remove();
+ },
+ };
+}
+
+// --- mount-local DOM helpers ------------------------------------------------
+
+function grab(wrap) {
+ return {
+ status: wrap.querySelector('.bcw-status'),
+ pctNum: wrap.querySelector('.bcw-pct-num'),
+ area: wrap.querySelector('[data-area]'),
+ marker: wrap.querySelector('[data-marker]'),
+ mc: wrap.querySelector('[data-mc]'),
+ raised: wrap.querySelector('[data-raised]'),
+ price: wrap.querySelector('[data-price]'),
+ meter: wrap.querySelector('.bcw-meter'),
+ };
+}
+
+function paintGeometry(els, progress) {
+ const p = clamp01(progress);
+ if (els.area) els.area.setAttribute('d', areaPathFor(p));
+ if (els.marker) {
+ const { x, y } = curvePointAt(p);
+ els.marker.setAttribute('transform', `translate(${x.toFixed(2)} ${y.toFixed(2)})`);
+ }
+ if (els.pctNum) els.pctNum.textContent = (p * 100).toFixed(p > 0 && p < 0.1 ? 1 : 0);
+}
+
+function applyEmptyState(card, els, msg) {
+ card.classList.remove('is-bonding', 'is-grad', 'is-loading');
+ card.classList.add('is-empty');
+ setTextSafe(els.status, 'No curve');
+ setTextSafe(els.mc, '—');
+ setTextSafe(els.raised, '—');
+ setTextSafe(els.price, '—');
+ if (els.pctNum) els.pctNum.textContent = '—';
+ if (els.meter && !els.meter.querySelector('.bcw-empty-msg') && msg) {
+ const p = document.createElement('p');
+ p.className = 'bcw-empty-msg';
+ p.textContent = msg;
+ els.meter.insertAdjacentElement('afterend', p);
+ }
+}
+
+function setTextSafe(el, text) {
+ if (el) el.textContent = text;
+}
+
+/** Derive a translucent accent for glows from a hex color. */
+function accentSoft(hex) {
+ const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
+ if (!m) return 'rgba(139, 92, 246, 0.22)';
+ return `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, 0.22)`;
+}
diff --git a/src/widgets/bonding-curve.test.js b/src/widgets/bonding-curve.test.js
new file mode 100644
index 000000000..cb8361998
--- /dev/null
+++ b/src/widgets/bonding-curve.test.js
@@ -0,0 +1,233 @@
+import { describe, it, expect } from 'vitest';
+import {
+ lamportsToSol,
+ clamp01,
+ fmtSol,
+ fmtUsd,
+ fmtPrice,
+ shortMint,
+ curveValue,
+ curvePointAt,
+ curvePoints,
+ areaPathFor,
+ computeView,
+ renderCardShell,
+} from './bonding-curve.js';
+
+const LAMPORTS = 1_000_000_000;
+
+describe('lamportsToSol', () => {
+ it('converts lamports (number or string) to SOL', () => {
+ expect(lamportsToSol(LAMPORTS)).toBe(1);
+ expect(lamportsToSol(String(5 * LAMPORTS))).toBe(5);
+ expect(lamportsToSol(0)).toBe(0);
+ });
+ it('returns 0 for non-finite input', () => {
+ expect(lamportsToSol('abc')).toBe(0);
+ expect(lamportsToSol(undefined)).toBe(0);
+ expect(lamportsToSol(null)).toBe(0);
+ });
+});
+
+describe('clamp01', () => {
+ it('clamps into [0,1]', () => {
+ expect(clamp01(-2)).toBe(0);
+ expect(clamp01(0.5)).toBe(0.5);
+ expect(clamp01(3)).toBe(1);
+ expect(clamp01(NaN)).toBe(0);
+ });
+});
+
+describe('fmtSol', () => {
+ it('renders compact suffixes and the ◎ glyph', () => {
+ expect(fmtSol(0)).toBe('◎ 0');
+ expect(fmtSol(0.123)).toBe('◎ 0.123');
+ expect(fmtSol(18.4)).toBe('◎ 18.40');
+ expect(fmtSol(1500)).toBe('◎ 1.50K');
+ expect(fmtSol(2_500_000)).toBe('◎ 2.50M');
+ });
+ it('handles bad input', () => {
+ expect(fmtSol(NaN)).toBe('◎ —');
+ });
+});
+
+describe('fmtUsd', () => {
+ it('renders compact USD', () => {
+ expect(fmtUsd(0)).toBe('$0');
+ expect(fmtUsd(12.5)).toBe('$12.50');
+ expect(fmtUsd(12_300)).toBe('$12.3K');
+ expect(fmtUsd(4_500_000)).toBe('$4.50M');
+ expect(fmtUsd(2_100_000_000)).toBe('$2.10B');
+ });
+ it('handles sub-dollar and bad input', () => {
+ expect(fmtUsd(0.42)).toBe('$0.42');
+ expect(fmtUsd(NaN)).toBe('$—');
+ });
+});
+
+describe('fmtPrice', () => {
+ it('renders tiny prices without scientific notation', () => {
+ const out = fmtPrice(0.0000003);
+ expect(out.startsWith('◎ ')).toBe(true);
+ expect(out).not.toContain('e');
+ expect(out).toContain('0.0000003');
+ });
+ it('renders USD prices and guards zero/negative', () => {
+ expect(fmtPrice(0.05, { usd: true })).toBe('$0.0500');
+ expect(fmtPrice(0, { usd: true })).toBe('$—');
+ expect(fmtPrice(-1)).toBe('◎ —');
+ });
+});
+
+describe('shortMint', () => {
+ it('truncates the middle', () => {
+ expect(shortMint('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')).toBe('EPjF…Dt1v');
+ });
+ it('leaves short strings intact', () => {
+ expect(shortMint('abc')).toBe('abc');
+ expect(shortMint('')).toBe('');
+ });
+});
+
+describe('curve geometry', () => {
+ it('curveValue is 0 at t=0, 1 at t=1, and monotonically increasing', () => {
+ expect(curveValue(0)).toBe(0);
+ expect(curveValue(1)).toBe(1);
+ expect(curveValue(0.25)).toBeLessThan(curveValue(0.75));
+ });
+
+ it('curveValue is convex (accelerating)', () => {
+ const a = curveValue(0.5) - curveValue(0.4);
+ const b = curveValue(0.9) - curveValue(0.8);
+ expect(b).toBeGreaterThan(a);
+ });
+
+ it('curvePointAt rises to the right (y decreases as t grows)', () => {
+ const left = curvePointAt(0);
+ const right = curvePointAt(1);
+ expect(right.x).toBeGreaterThan(left.x);
+ expect(right.y).toBeLessThan(left.y);
+ });
+
+ it('curvePoints starts with a move command and is non-empty', () => {
+ const d = curvePoints();
+ expect(d.startsWith('M')).toBe(true);
+ expect(d.length).toBeGreaterThan(20);
+ });
+
+ it('areaPathFor produces a closed path and grows with progress', () => {
+ const small = areaPathFor(0.1);
+ const big = areaPathFor(0.9);
+ expect(small.endsWith('Z')).toBe(true);
+ expect(big.endsWith('Z')).toBe(true);
+ expect(big.length).toBeGreaterThan(small.length);
+ });
+});
+
+describe('computeView', () => {
+ it('returns empty status with no data', () => {
+ expect(computeView(null).status).toBe('empty');
+ expect(computeView({}).status).toBe('empty');
+ });
+
+ it('derives progress and SOL figures from a bonding payload', () => {
+ const data = {
+ mint: 'MintAddr',
+ network: 'mainnet',
+ curve: { realSolReserves: String(20 * LAMPORTS), complete: false, isMayhemMode: false },
+ price: { buyPricePerToken: '30', marketCap: String(42 * LAMPORTS), isGraduated: false },
+ graduation: {
+ progressBps: 3450,
+ isGraduated: false,
+ solAccumulated: String(18 * LAMPORTS),
+ },
+ };
+ const v = computeView(data, null);
+ expect(v.status).toBe('bonding');
+ expect(v.progress).toBeCloseTo(0.345, 5);
+ expect(v.progressPct).toBeCloseTo(34.5, 5);
+ expect(v.marketCapSol).toBe(42);
+ expect(v.raisedSol).toBe(18);
+ expect(v.hasUsd).toBe(false);
+ expect(v.marketCapUsd).toBeNull();
+ });
+
+ it('enriches with USD when a SOL price is supplied', () => {
+ const data = {
+ mint: 'M',
+ curve: { realSolReserves: '0', complete: false },
+ price: { marketCap: String(10 * LAMPORTS), buyPricePerToken: '0' },
+ graduation: { progressBps: 5000, solAccumulated: String(2 * LAMPORTS) },
+ };
+ const v = computeView(data, 150);
+ expect(v.hasUsd).toBe(true);
+ expect(v.marketCapUsd).toBe(1500);
+ expect(v.raisedUsd).toBe(300);
+ });
+
+ it('clamps a graduated token to 100% regardless of bps', () => {
+ const data = {
+ mint: 'M',
+ curve: { complete: true, realSolReserves: '0' },
+ price: { marketCap: '0', isGraduated: true },
+ graduation: { progressBps: 10_000, isGraduated: true, solAccumulated: '0' },
+ };
+ const v = computeView(data);
+ expect(v.status).toBe('graduated');
+ expect(v.progress).toBe(1);
+ });
+
+ it('clamps the negative market cap a fresh curve can report to zero', () => {
+ const data = {
+ mint: 'M',
+ network: 'mainnet',
+ curve: { realSolReserves: '0', complete: false, isMayhemMode: false },
+ price: { marketCap: '-2041006523', buyPricePerToken: '30', isGraduated: false },
+ graduation: { progressBps: 0, isGraduated: false, solAccumulated: '0' },
+ };
+ const v = computeView(data, 150);
+ expect(v.status).toBe('bonding');
+ expect(v.progress).toBe(0);
+ expect(v.marketCapSol).toBe(0);
+ expect(v.marketCapUsd).toBe(0);
+ });
+});
+
+describe('renderCardShell', () => {
+ it('embeds a pump.fun link and the shortened mint', () => {
+ const html = renderCardShell(
+ {
+ status: 'bonding',
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ network: 'mainnet',
+ },
+ {},
+ );
+ expect(html).toContain('https://pump.fun/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
+ expect(html).toContain('EPjF…Dt1v');
+ expect(html).toContain('data-area');
+ expect(html).toContain('data-marker');
+ });
+
+ it('marks devnet and mayhem mode', () => {
+ const html = renderCardShell(
+ { status: 'bonding', mint: 'M', network: 'devnet', isMayhem: true },
+ {},
+ );
+ expect(html).toContain('devnet');
+ expect(html).toContain('mayhem');
+ });
+
+ it('omits the powered-by link when disabled', () => {
+ const html = renderCardShell({ status: 'bonding', mint: 'M' }, { showPoweredBy: false });
+ expect(html).not.toContain('>three.ws<');
+ });
+
+ it('escapes hostile mint input', () => {
+ const html = renderCardShell(
+ { status: 'bonding', mint: '"><script>x', network: 'mainnet' },
+ {},
+ );
+ expect(html).not.toContain('<script>x');
+ });
+});
diff --git a/src/widgets/kol-trades.js b/src/widgets/kol-trades.js
index 74da56979..e7c202946 100644
--- a/src/widgets/kol-trades.js
+++ b/src/widgets/kol-trades.js
@@ -9,9 +9,12 @@
* mountKolTradesWidget(root, opts) — full mount with polling + cleanup
*
* The <three-ws-widget type="kol-trades" mint="…"> custom element is registered
- * at the bottom of this file when running in a browser.
+ * at the bottom of this file when running in a browser. That same element also
+ * dispatches type="bonding-curve" to the bonding-curve runtime.
*/
+import { mountBondingCurve } from './bonding-curve.js';
+
const SOURCE_BADGE = {
kol: { label: 'KOL', color: '#ffffff' },
whale: { label: 'Whale', color: '#60a5fa' },
@@ -175,7 +178,7 @@ if (typeof customElements !== 'undefined' && !customElements.get('three-ws-widge
'three-ws-widget',
class ThreeWsWidget extends HTMLElement {
static get observedAttributes() {
- return ['type', 'mint', 'limit', 'refresh-ms'];
+ return ['type', 'mint', 'limit', 'refresh-ms', 'network', 'show-usd', 'accent'];
}
connectedCallback() {
@@ -197,12 +200,21 @@ if (typeof customElements !== 'undefined' && !customElements.get('three-ws-widge
_mount() {
const type = this.getAttribute('type');
- if (type !== 'kol-trades') return;
- this._ctrl = mountKolTradesWidget(this, {
- mint: this.getAttribute('mint') || '',
- limit: Number(this.getAttribute('limit') || '20'),
- refreshMs: Number(this.getAttribute('refresh-ms') || '30000'),
- });
+ if (type === 'kol-trades') {
+ this._ctrl = mountKolTradesWidget(this, {
+ mint: this.getAttribute('mint') || '',
+ limit: Number(this.getAttribute('limit') || '20'),
+ refreshMs: Number(this.getAttribute('refresh-ms') || '30000'),
+ });
+ } else if (type === 'bonding-curve') {
+ this._ctrl = mountBondingCurve(this, {
+ mint: this.getAttribute('mint') || '',
+ network: this.getAttribute('network') || 'mainnet',
+ refreshMs: Number(this.getAttribute('refresh-ms') || '15000'),
+ showUsd: this.getAttribute('show-usd') !== 'false',
+ accent: this.getAttribute('accent') || '',
+ });
+ }
}
},
);
diff --git a/tests/api/animation-clip-patch.test.js b/tests/api/animation-clip-patch.test.js
new file mode 100644
index 000000000..c4cb11f6a
--- /dev/null
+++ b/tests/api/animation-clip-patch.test.js
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi } from 'vitest';
+import { __test__ as idTest } from '../../api/animations/[id].js';
+import { validateClipTrackStrides, materializeClip, __test__ as clipsTest } from '../../api/animations/clips.js';
+
+const { patchSchema } = idTest;
+const { MAX_BYTES_INLINE } = clipsTest;
+
+// A minimal valid baked AnimationClip.toJSON() payload.
+const validClip = {
+ name: 'wave',
+ duration: 2,
+ tracks: [
+ { name: 'LeftArm.quaternion', type: 'quaternion', times: [0, 1, 2], values: new Array(12).fill(0) },
+ { name: 'Hips.position', type: 'vector', times: [0, 2], values: [0, 0, 0, 0, 0, 0] },
+ ],
+};
+
+const validEditorDoc = {
+ duration: 2,
+ fps: 30,
+ loop: true,
+ keyframes: [
+ { id: 'kf_1', time: 0, easing: 'ease-in-out', pose: { bones: { Hips: [0, 0, 0, 1] } } },
+ { time: 2, pose: { bones: { Hips: [0, 0, 0, 1] }, rootPosition: { x: 0, y: 1, z: 0 } } },
+ ],
+};
+
+describe('animation PATCH schema — re-saving edited keyframes (regression)', () => {
+ it('accepts a metadata-only patch', () => {
+ const r = patchSchema.safeParse({ name: 'Renamed', visibility: 'public' });
+ expect(r.success).toBe(true);
+ });
+
+ it('accepts clip + editor_doc + fps so edits persist (previously stripped → data loss)', () => {
+ const r = patchSchema.safeParse({ name: 'Updated', clip: validClip, editor_doc: validEditorDoc, fps: 24 });
+ expect(r.success).toBe(true);
+ expect(r.data.clip).toBeDefined();
+ expect(r.data.editor_doc).toBeDefined();
+ expect(r.data.fps).toBe(24);
+ });
+
+ it('rejects a malformed clip (no tracks) on update', () => {
+ expect(patchSchema.safeParse({ clip: { name: 'a', duration: 1, tracks: [] } }).success).toBe(false);
+ });
+
+ it('allows nulling fps and avatar_id', () => {
+ const r = patchSchema.safeParse({ fps: null, avatar_id: null });
+ expect(r.success).toBe(true);
+ });
+});
+
+describe('validateClipTrackStrides', () => {
+ it('passes a clip with correct quaternion (×4) and position (×3) strides', () => {
+ expect(validateClipTrackStrides(validClip)).toBeNull();
+ });
+
+ it('rejects a quaternion track whose values are not times×4', () => {
+ const bad = {
+ ...validClip,
+ tracks: [{ name: 'Hips.quaternion', type: 'quaternion', times: [0, 1], values: [0, 0, 0] }],
+ };
+ expect(validateClipTrackStrides(bad)).toMatch(/Hips\.quaternion/);
+ });
+});
+
+describe('materializeClip', () => {
+ it('inlines a small clip as JSON with no R2 key', async () => {
+ const { inlineClip, storageKey, error } = await materializeClip(validClip, { userId: 'u1', slug: 'wave' });
+ expect(error).toBeUndefined();
+ expect(storageKey).toBeNull();
+ expect(typeof inlineClip).toBe('string');
+ expect(JSON.parse(inlineClip).name).toBe('wave');
+ });
+
+ it('keeps the inline ceiling sane (R2 offload threshold is in bytes)', () => {
+ expect(MAX_BYTES_INLINE).toBeGreaterThan(100_000);
+ });
+});
diff --git a/tests/src/widget-types.test.js b/tests/src/widget-types.test.js
index 660a9ba43..b541859e1 100644
--- a/tests/src/widget-types.test.js
+++ b/tests/src/widget-types.test.js
@@ -23,6 +23,7 @@ describe('WIDGET_TYPES', () => {
'pumpfun-feed',
'kol-trades',
'live-trades-canvas',
+ 'bonding-curve',
].sort(),
);
});
diff --git a/tests/world-store.test.js b/tests/world-store.test.js
new file mode 100644
index 000000000..6199571cf
--- /dev/null
+++ b/tests/world-store.test.js
@@ -0,0 +1,272 @@
+// Unit tests for the generic per-world persistence store (T3).
+//
+// The store's orchestration (size limits, content hashing, inline-vs-R2 routing,
+// optimistic-concurrency conflict mapping, blob GC) is exercised against an
+// in-memory backend that honours the same compare-and-set contract as the
+// production Postgres+R2 backend. The service-token gate that keeps a browser
+// from forging a server write is tested against api/_lib/world-service-auth.js.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import crypto from 'node:crypto';
+import {
+ createWorldStore,
+ canWriteWorld,
+ isValidWorldId,
+ etagOf,
+ ConflictError,
+ TooLargeError,
+ INLINE_MAX_BYTES,
+ MAX_DOC_BYTES,
+} from '../api/_lib/world-store.js';
+import { verifyWorldServiceToken } from '../api/_lib/world-service-auth.js';
+
+// In-memory backend mirroring the production CAS contract exactly: an INSERT
+// happens only when no row exists (regardless of ifMatch); an UPDATE commits only
+// when ifMatch is '*' or equals the stored etag — otherwise it reports no commit.
+function makeBackend() {
+ const rows = new Map();
+ const blobs = new Map();
+ let clock = 0;
+ return {
+ rows,
+ blobs,
+ async readRow(worldId) {
+ return rows.has(worldId) ? { ...rows.get(worldId) } : null;
+ },
+ async readBlob(key) {
+ if (!blobs.has(key)) throw new Error(`no such blob: ${key}`);
+ return blobs.get(key);
+ },
+ async writeBlob(key, bytes) {
+ blobs.set(key, Buffer.from(bytes));
+ },
+ async deleteBlob(key) {
+ blobs.delete(key);
+ },
+ async upsert({ worldId, schemaVersion, etag, size, inlineDoc, r2Key, owner, writer, ifMatch }) {
+ const existing = rows.get(worldId);
+ if (existing) {
+ const ok = ifMatch === '*' || existing.etag === ifMatch;
+ if (!ok) return { committed: false };
+ const row = {
+ ...existing,
+ schema_version: schemaVersion,
+ doc_version: existing.doc_version + 1,
+ etag,
+ size_bytes: size,
+ inline_doc: inlineDoc,
+ r2_key: r2Key,
+ updated_by: writer,
+ updated_at: ++clock,
+ };
+ rows.set(worldId, row);
+ return { committed: true, version: row.doc_version, etag, ownerId: row.owner_id ?? null, updatedAt: row.updated_at };
+ }
+ const row = {
+ world_id: worldId,
+ schema_version: schemaVersion,
+ doc_version: 1,
+ etag,
+ size_bytes: size,
+ inline_doc: inlineDoc,
+ r2_key: r2Key,
+ owner_id: owner ?? null,
+ updated_by: writer,
+ updated_at: ++clock,
+ };
+ rows.set(worldId, row);
+ return { committed: true, version: 1, etag, ownerId: row.owner_id, updatedAt: row.updated_at };
+ },
+ async remove(worldId) {
+ if (!rows.has(worldId)) return false;
+ const r2 = rows.get(worldId).r2_key;
+ rows.delete(worldId);
+ return r2;
+ },
+ };
+}
+
+describe('world-store: validation', () => {
+ it('accepts mints, tier keys, and realm slugs; rejects junk', () => {
+ expect(isValidWorldId('So11111111111111111111111111111111111111112')).toBe(true);
+ expect(isValidWorldId('mint#holders')).toBe(true);
+ expect(isValidWorldId('realm:wilderness')).toBe(true);
+ expect(isValidWorldId('')).toBe(false);
+ expect(isValidWorldId('has space')).toBe(false);
+ expect(isValidWorldId('../etc/passwd')).toBe(false);
+ expect(isValidWorldId('x'.repeat(129))).toBe(false);
+ });
+
+ it('etag is deterministic and content-sensitive', () => {
+ const a = etagOf(Buffer.from('{"a":1}'));
+ const b = etagOf(Buffer.from('{"a":1}'));
+ const c = etagOf(Buffer.from('{"a":2}'));
+ expect(a).toBe(b);
+ expect(a).not.toBe(c);
+ });
+});
+
+describe('world-store: round-trip + concurrency', () => {
+ let backend;
+ let store;
+ beforeEach(() => {
+ backend = makeBackend();
+ store = createWorldStore(backend);
+ });
+
+ it('saves and restores an arbitrary JSON doc', async () => {
+ expect(await store.loadWorld('coinA')).toBeNull();
+
+ const doc = { objects: [{ id: 'o1', x: 3, y: 0, z: -2 }], theme: 'forest' };
+ const saved = await store.saveWorld({ worldId: 'coinA', doc, writer: 'service' });
+ expect(saved.version).toBe(1);
+ expect(saved.etag).toMatch(/^[0-9a-f]{24}$/);
+
+ const loaded = await store.loadWorld('coinA');
+ expect(loaded.doc).toEqual(doc);
+ expect(loaded.version).toBe(1);
+ expect(loaded.etag).toBe(saved.etag);
+ });
+
+ it('bumps the version and etag on each successful save', async () => {
+ const v1 = await store.saveWorld({ worldId: 'w', doc: { n: 1 }, writer: 's' });
+ const v2 = await store.saveWorld({ worldId: 'w', doc: { n: 2 }, ifMatch: v1.etag, writer: 's' });
+ expect(v2.version).toBe(2);
+ expect(v2.etag).not.toBe(v1.etag);
+ expect((await store.loadWorld('w')).doc).toEqual({ n: 2 });
+ });
+
+ it('rejects a stale write with ConflictError', async () => {
+ const v1 = await store.saveWorld({ worldId: 'w', doc: { n: 1 }, writer: 's' });
+ await store.saveWorld({ worldId: 'w', doc: { n: 2 }, ifMatch: v1.etag, writer: 's' });
+ // v1.etag is now stale — a second writer holding it must lose.
+ await expect(
+ store.saveWorld({ worldId: 'w', doc: { n: 99 }, ifMatch: v1.etag, writer: 's' }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ expect((await store.loadWorld('w')).doc).toEqual({ n: 2 });
+ });
+
+ it('treats a create (ifMatch=null) against an existing world as a conflict', async () => {
+ await store.saveWorld({ worldId: 'w', doc: { n: 1 }, writer: 's' });
+ await expect(
+ store.saveWorld({ worldId: 'w', doc: { n: 2 }, ifMatch: null, writer: 's' }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
+
+ it('ifMatch="*" overwrites unconditionally', async () => {
+ await store.saveWorld({ worldId: 'w', doc: { n: 1 }, writer: 's' });
+ const forced = await store.saveWorld({ worldId: 'w', doc: { n: 42 }, ifMatch: '*', writer: 's' });
+ expect(forced.version).toBe(2);
+ expect((await store.loadWorld('w')).doc).toEqual({ n: 42 });
+ });
+
+ it('preserves the original owner across later saves', async () => {
+ const a = await store.saveWorld({ worldId: 'w', doc: { n: 1 }, writer: 'alice', owner: 'alice' });
+ expect(a.ownerId).toBe('alice');
+ // A later save passing a different owner must not reassign ownership.
+ const b = await store.saveWorld({ worldId: 'w', doc: { n: 2 }, ifMatch: a.etag, writer: 'alice', owner: 'mallory' });
+ expect(b.ownerId).toBe('alice');
+ });
+});
+
+describe('world-store: large-doc R2 offload', () => {
+ let backend;
+ let store;
+ beforeEach(() => {
+ backend = makeBackend();
+ store = createWorldStore(backend);
+ });
+
+ it('offloads docs past the inline cap to a content-addressed blob and reads them back', async () => {
+ const big = { blob: 'x'.repeat(INLINE_MAX_BYTES + 1024) };
+ const saved = await store.saveWorld({ worldId: 'big', doc: big, writer: 's' });
+
+ // Stored out-of-line: index row carries an r2_key, no inline doc.
+ expect(backend.rows.get('big').inline_doc).toBeNull();
+ expect(backend.rows.get('big').r2_key).toContain('worlds/big/');
+ expect(backend.blobs.size).toBe(1);
+
+ const loaded = await store.loadWorld('big');
+ expect(loaded.doc).toEqual(big);
+ expect(loaded.etag).toBe(saved.etag);
+ });
+
+ it('GCs the previous blob when a large doc is superseded', async () => {
+ const v1 = await store.saveWorld({ worldId: 'big', doc: { blob: 'a'.repeat(INLINE_MAX_BYTES + 10) }, writer: 's' });
+ const firstKey = backend.rows.get('big').r2_key;
+ await store.saveWorld({ worldId: 'big', doc: { blob: 'b'.repeat(INLINE_MAX_BYTES + 10) }, ifMatch: v1.etag, writer: 's' });
+ const secondKey = backend.rows.get('big').r2_key;
+
+ expect(secondKey).not.toBe(firstKey);
+ expect(backend.blobs.has(firstKey)).toBe(false); // old blob retired
+ expect(backend.blobs.has(secondKey)).toBe(true);
+ expect(backend.blobs.size).toBe(1);
+ });
+
+ it('rejects a doc larger than the hard cap with TooLargeError', async () => {
+ const huge = { blob: 'x'.repeat(MAX_DOC_BYTES + 16) };
+ await expect(store.saveWorld({ worldId: 'huge', doc: huge, writer: 's' })).rejects.toBeInstanceOf(TooLargeError);
+ // Nothing partially persisted.
+ expect(backend.rows.has('huge')).toBe(false);
+ expect(backend.blobs.size).toBe(0);
+ });
+});
+
+describe('world-store: deleteWorld', () => {
+ it('removes the index row and any offloaded blob', async () => {
+ const backend = makeBackend();
+ const store = createWorldStore(backend);
+ const v1 = await store.saveWorld({ worldId: 'big', doc: { blob: 'x'.repeat(INLINE_MAX_BYTES + 10) }, writer: 's' });
+ expect(v1.version).toBe(1);
+ expect(await store.deleteWorld('big')).toBe(true);
+ expect(backend.rows.has('big')).toBe(false);
+ expect(backend.blobs.size).toBe(0);
+ expect(await store.deleteWorld('big')).toBe(false); // already gone
+ });
+});
+
+describe('world-store: write permission model (T16 hook)', () => {
+ it('the game server is always permitted', () => {
+ expect(canWriteWorld({ isService: true, account: null, currentOwner: 'alice' })).toBe(true);
+ });
+ it('anonymous browsers can never write', () => {
+ expect(canWriteWorld({ isService: false, account: null, currentOwner: null })).toBe(false);
+ });
+ it('the first writer may seed an unowned world; others are owner-gated', () => {
+ expect(canWriteWorld({ isService: false, account: 'alice', currentOwner: null })).toBe(true);
+ expect(canWriteWorld({ isService: false, account: 'alice', currentOwner: 'alice' })).toBe(true);
+ expect(canWriteWorld({ isService: false, account: 'mallory', currentOwner: 'alice' })).toBe(false);
+ });
+});
+
+describe('world-service-auth: only the multiplayer server can forge a service write', () => {
+ const secret = process.env.MULTIPLAYER_SHARED_SECRET || process.env.HOLDER_PASS_SECRET || 'dev-insecure-multiplayer-secret';
+ function sign(payloadObj, withSecret = secret) {
+ const payload = Buffer.from(JSON.stringify(payloadObj), 'utf8').toString('base64url');
+ const sig = crypto.createHmac('sha256', withSecret).update(payload).digest('base64url');
+ return `${payload}.${sig}`;
+ }
+ const future = Math.floor(Date.now() / 1000) + 120;
+ const past = Math.floor(Date.now() / 1000) - 10;
+
+ it('accepts a valid, unexpired world token', async () => {
+ expect(await verifyWorldServiceToken(sign({ svc: 'world', exp: future }))).toEqual({ svc: 'world' });
+ });
+ it('rejects an expired token', async () => {
+ expect(await verifyWorldServiceToken(sign({ svc: 'world', exp: past }))).toBeNull();
+ });
+ it('rejects a token for a different service', async () => {
+ expect(await verifyWorldServiceToken(sign({ svc: 'presence', exp: future }))).toBeNull();
+ });
+ it('rejects a token signed with the wrong secret', async () => {
+ expect(await verifyWorldServiceToken(sign({ svc: 'world', exp: future }, 'not-the-secret'))).toBeNull();
+ });
+ it('rejects a tampered signature and outright garbage', async () => {
+ const tok = sign({ svc: 'world', exp: future });
+ const tampered = tok.slice(0, -1) + (tok.endsWith('A') ? 'B' : 'A');
+ expect(await verifyWorldServiceToken(tampered)).toBeNull();
+ expect(await verifyWorldServiceToken('nope')).toBeNull();
+ expect(await verifyWorldServiceToken('')).toBeNull();
+ expect(await verifyWorldServiceToken(null)).toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index 9ced2ea45..33d0758dd 100644
--- a/vercel.json
+++ b/vercel.json
@@ -983,6 +983,10 @@
"src": "/api/agents/suggest",
"dest": "/api/agents/suggest"
},
+ {
+ "src": "/api/agents/featured",
+ "dest": "/api/agents/featured"
+ },
{
"src": "/api/agents/by-wallet",
"dest": "/api/agents/by-wallet"
diff --git a/vite.config.js b/vite.config.js
index 4fdb23e31..434f5448b 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -210,15 +210,17 @@ const appConfig = {
if (id.includes('node_modules/@solana/') || id.includes('node_modules/@coral-xyz/')) return 'solana';
if (id.includes('node_modules/@mediapipe/')) return 'mediapipe';
},
- // footer-bot.js needs a stable, unhashed filename so footer.js can
- // load it by a predictable URL without knowing the build hash.
+ // A few entries need stable, unhashed filenames so plain public/
+ // scripts can load them by a predictable URL without knowing the
+ // build hash: footer.js → /footer-bot.js, nav.js → /walk-companion.js.
entryFileNames: (chunk) =>
- chunk.name === 'footer-bot'
- ? 'footer-bot.js'
+ chunk.name === 'footer-bot' || chunk.name === 'walk-companion'
+ ? `${chunk.name}.js`
: 'assets/[name]-[hash].js',
},
input: {
'footer-bot': resolve(__dirname, 'src/footer-bot.js'),
+ 'walk-companion': resolve(__dirname, 'src/walk-companion.js'),
app: resolve(__dirname, 'pages/app.html'),
'app-demo': resolve(__dirname, 'pages/app-demo.html'),
'app-next': resolve(__dirname, 'pages/app-next.html'),
@@ -809,6 +811,12 @@ const appConfig = {
req.url = '/src/footer-bot.js';
return next();
}
+ // /walk-companion.js — same trick for nav.js's Walk Companion module
+ // (built to a stable, unhashed name in prod; served from src in dev).
+ if (path === '/walk-companion.js') {
+ req.url = '/src/walk-companion.js';
+ return next();
+ }
// Avatar Studio (rebranded Character Studio fork) — serve the
// production build out of character-studio/build/ at /avatar-studio/*
// so the demo iframe works in dev. Run `npm run build --prefix