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.

Add Oracle settle/signal loop, copy-engine, and watchlist

nirholas3c8b09e737e3
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 3dd982c1a..31368743d 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -273,6 +273,52 @@ export async function searchPublicAvatars({ q, tag, limit = 24, cursor, withTota
return result;
}
+// Public forks of an avatar — the GitHub-style "forked by" network. Only
+// public/unlisted forks are listed (private forks stay invisible to the source
+// owner), newest first, with the forker's display name for attribution.
+export async function listForks({ avatarId, limit = 24, cursor }) {
+ if (!isUuid(avatarId)) return { forks: [], next_cursor: null };
+ limit = Math.min(Math.max(limit, 1), 100);
+ const params = [avatarId];
+ const conds = [
+ 'a.parent_avatar_id = $1',
+ 'a.deleted_at is null',
+ `a.visibility in ('public','unlisted')`,
+ ];
+ if (cursor) {
+ params.push(new Date(cursor));
+ conds.push(`a.created_at < $${params.length}`);
+ }
+ params.push(limit + 1);
+ const rows = await sql(
+ `select a.id, a.slug, a.name, a.thumbnail_key, a.storage_key, a.visibility,
+ a.created_at, a.fork_count, u.display_name as owner_name
+ from avatars a join users u on u.id = a.owner_id
+ where ${conds.join(' and ')}
+ order by a.created_at desc limit $${params.length}`,
+ params,
+ );
+ const hasMore = rows.length > limit;
+ const page = hasMore ? rows.slice(0, limit) : rows;
+ return {
+ forks: page.map((r) => ({
+ id: r.id,
+ slug: r.slug,
+ name: r.name,
+ owner_name: r.owner_name || null,
+ visibility: r.visibility,
+ fork_count: Number(r.fork_count || 0),
+ created_at: r.created_at,
+ thumbnail_url: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ model_url:
+ r.visibility === 'public' || r.visibility === 'unlisted'
+ ? publicUrl(r.storage_key)
+ : null,
+ })),
+ next_cursor: hasMore ? new Date(page[page.length - 1].created_at).toISOString() : null,
+ };
+}
+
export async function resolveAvatarUrl(row, { expiresIn = 600 } = {}) {
const key = _servedStorageKey(row);
if (row.visibility === 'public' || row.visibility === 'unlisted') {
diff --git a/api/_lib/copy-engine.js b/api/_lib/copy-engine.js
new file mode 100644
index 000000000..65b0e68f2
--- /dev/null
+++ b/api/_lib/copy-engine.js
@@ -0,0 +1,163 @@
+/**
+ * Copy-trading decision engine — PURE, deterministic, no DB / no network.
+ *
+ * Given a copier's subscription, the leader's triggering position, and the coin's
+ * safety context, it decides whether to generate a copy intent and at what size.
+ * This is the money-adjacent core, so it's isolated and exhaustively tested
+ * (tests/copy-engine.test.js). Every "skip" carries a machine + human reason so
+ * the dashboard can explain exactly why a copy didn't fire.
+ *
+ * Non-custodial: this never signs or moves funds — it produces an INTENT the
+ * copier acts on. Sizing is always clamped to the per-trade cap and the remaining
+ * daily budget, so a runaway leader can never drain a copier.
+ */
+
+/** Clamp helper. */
+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
+
+/**
+ * Validate + normalize a subscription's tunables coming from user input.
+ * Returns { ok, value, error }. Never throws.
+ */
+export function normalizeSubscriptionInput(raw = {}) {
+ const sizing = ['fixed', 'multiplier', 'pct_balance'].includes(raw.sizing_rule) ? raw.sizing_rule : 'fixed';
+ const fixed = n(raw.fixed_sol);
+ const mult = n(raw.multiplier);
+ const pct = n(raw.pct_balance);
+ const cap = n(raw.per_trade_cap_sol);
+ const minOrder = n(raw.min_order_sol);
+ const daily = n(raw.daily_budget_sol);
+ const maxOpen = Math.floor(n(raw.max_open_copies));
+ const perfBps = Math.floor(n(raw.perf_fee_bps ?? 1000));
+
+ if (cap <= 0) return { ok: false, error: 'per_trade_cap_sol must be greater than 0' };
+ if (minOrder < 0) return { ok: false, error: 'min_order_sol cannot be negative' };
+ if (daily <= 0) return { ok: false, error: 'daily_budget_sol must be greater than 0' };
+ if (minOrder > cap) return { ok: false, error: 'min_order_sol cannot exceed per_trade_cap_sol' };
+ if (sizing === 'fixed' && fixed <= 0) return { ok: false, error: 'fixed_sol must be greater than 0' };
+ if (sizing === 'multiplier' && mult <= 0) return { ok: false, error: 'multiplier must be greater than 0' };
+ if (sizing === 'pct_balance' && !(pct > 0 && pct <= 100)) return { ok: false, error: 'pct_balance must be between 0 and 100' };
+ if (perfBps < 0 || perfBps > 3000) return { ok: false, error: 'perf_fee_bps must be between 0 and 3000' };
+
+ const mcapFloor = raw.mcap_floor_usd == null || raw.mcap_floor_usd === '' ? null : n(raw.mcap_floor_usd);
+ const mcapCeil = raw.mcap_ceiling_usd == null || raw.mcap_ceiling_usd === '' ? null : n(raw.mcap_ceiling_usd);
+ if (mcapFloor != null && mcapCeil != null && mcapFloor > mcapCeil) {
+ return { ok: false, error: 'mcap_floor_usd cannot exceed mcap_ceiling_usd' };
+ }
+
+ return {
+ ok: true,
+ value: {
+ sizing_rule: sizing,
+ fixed_sol: fixed,
+ multiplier: mult,
+ pct_balance: pct,
+ per_trade_cap_sol: cap,
+ min_order_sol: minOrder,
+ daily_budget_sol: daily,
+ max_open_copies: clamp(maxOpen || 5, 1, 100),
+ mcap_floor_usd: mcapFloor,
+ mcap_ceiling_usd: mcapCeil,
+ copy_sells: raw.copy_sells !== false,
+ require_safety_pass: raw.require_safety_pass === true,
+ perf_fee_bps: perfBps,
+ },
+ };
+}
+
+/** Raw order size from the sizing rule, before any clamping. */
+export function rawOrderSol(sub, { leaderEntrySol = 0, copierBalanceSol = null } = {}) {
+ switch (sub.sizing_rule) {
+ case 'fixed': return n(sub.fixed_sol);
+ case 'multiplier': return n(leaderEntrySol) * n(sub.multiplier);
+ case 'pct_balance':
+ return copierBalanceSol == null ? NaN : n(copierBalanceSol) * (n(sub.pct_balance) / 100);
+ default: return 0;
+ }
+}
+
+/**
+ * Decide a copy for a single (subscription, leader-position, coin) tuple.
+ *
+ * @param {object} p
+ * @param {object} p.subscription normalized subscription row.
+ * @param {object} p.position triggering agent_sniper_positions row (entry_sol, mint, direction…).
+ * @param {object} [p.coin] coin context: { market_cap_usd, dev_holding_pct, liquidity_usd, honeypot, graduated }.
+ * @param {number} [p.copierBalanceSol] copier's spendable SOL (required only for pct_balance sizing).
+ * @param {number} [p.spentTodaySol] SOL already fanned out for this sub today.
+ * @param {number} [p.openCopies] copier's current pending intents on this sub.
+ * @returns {{ action:'copy'|'skip', direction:'buy'|'sell', order_sol?:number, reason?:string, detail?:string }}
+ */
+export function planCopyOrder({ subscription: sub, position, coin = null, copierBalanceSol = null, spentTodaySol = 0, openCopies = 0 }) {
+ const direction = position.direction === 'sell' ? 'sell' : 'buy';
+
+ if (sub.status !== 'active') return skip('subscription_inactive', 'Subscription is not active.');
+ if (direction === 'sell' && !sub.copy_sells) return skip('sells_disabled', 'This subscription does not mirror sells.');
+
+ // --- Safety gate (entries only; exits should always be allowed to mirror) ---
+ if (direction === 'buy') {
+ const safety = evaluateSafety(sub, coin);
+ if (!safety.ok) return skip(safety.reason, safety.detail);
+
+ if (openCopies >= sub.max_open_copies) {
+ return skip('max_open_copies', `You already have ${openCopies} open copy intents (cap ${sub.max_open_copies}).`);
+ }
+ }
+
+ // --- Sizing (buys size the order; sells mirror "exit your copy" with no new SOL) ---
+ if (direction === 'sell') {
+ return { action: 'copy', direction, order_sol: 0, reason: 'mirror_exit' };
+ }
+
+ let order = rawOrderSol(sub, { leaderEntrySol: n(position.entry_sol), copierBalanceSol });
+ if (!Number.isFinite(order) || order <= 0) {
+ return skip('sizing_unavailable', 'Could not size this order (missing balance for % sizing).');
+ }
+
+ order = clamp(order, 0, sub.per_trade_cap_sol);
+
+ const remainingDaily = sub.daily_budget_sol - n(spentTodaySol);
+ if (remainingDaily <= 0) return skip('daily_budget_spent', 'Daily copy budget is already used up.');
+ order = Math.min(order, remainingDaily);
+
+ if (order < sub.min_order_sol) {
+ return skip('below_min_order', `Sized order ${order.toFixed(4)} SOL is below your ${sub.min_order_sol} SOL minimum.`);
+ }
+
+ return { action: 'copy', direction, order_sol: round6(order), reason: 'sized' };
+}
+
+/** Coin safety gate. Conservative: when context is missing, honor require_safety_pass. */
+export function evaluateSafety(sub, coin) {
+ if (!coin) {
+ return sub.require_safety_pass
+ ? { ok: false, reason: 'safety_unknown', detail: 'Coin safety could not be confirmed and you require a safety pass.' }
+ : { ok: true };
+ }
+ if (coin.honeypot === true) return { ok: false, reason: 'honeypot', detail: 'Coin flagged as a honeypot (sells blocked).' };
+
+ const mcap = n(coin.market_cap_usd);
+ if (sub.mcap_floor_usd != null && mcap > 0 && mcap < sub.mcap_floor_usd) {
+ return { ok: false, reason: 'below_mcap_floor', detail: `Market cap $${fmt(mcap)} is below your $${fmt(sub.mcap_floor_usd)} floor.` };
+ }
+ if (sub.mcap_ceiling_usd != null && mcap > sub.mcap_ceiling_usd) {
+ return { ok: false, reason: 'above_mcap_ceiling', detail: `Market cap $${fmt(mcap)} is above your $${fmt(sub.mcap_ceiling_usd)} ceiling.` };
+ }
+ if (coin.dev_holding_pct != null && coin.dev_holding_pct >= 30) {
+ return { ok: false, reason: 'dev_heavy', detail: `Dev holds ${n(coin.dev_holding_pct).toFixed(0)}% of supply — dump risk.` };
+ }
+ if (coin.liquidity_usd != null && coin.liquidity_usd > 0 && coin.liquidity_usd < 1000) {
+ return { ok: false, reason: 'low_liquidity', detail: `Liquidity $${fmt(coin.liquidity_usd)} is too thin to copy safely.` };
+ }
+ return { ok: true };
+}
+
+function skip(reason, detail) { return { action: 'skip', direction: 'buy', reason, detail }; }
+function round6(x) { return Math.round(x * 1e6) / 1e6; }
+function fmt(x) {
+ const v = n(x);
+ if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
+ if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';
+ return String(Math.round(v));
+}
diff --git a/api/_lib/migrations/20260616000000_copy_trading.sql b/api/_lib/migrations/20260616000000_copy_trading.sql
new file mode 100644
index 000000000..2be9a8422
--- /dev/null
+++ b/api/_lib/migrations/20260616000000_copy_trading.sql
@@ -0,0 +1,92 @@
+-- Migration: non-custodial copy trading.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260616000000_copy_trading.sql
+-- Idempotent.
+--
+-- A copier follows a leader (an agent with a sniper track record) and, when the
+-- leader opens/closes a position, we generate a sized, safety-checked copy INTENT
+-- the copier acts on from their own wallet. We never take custody and never sign
+-- for them in this phase — the copier executes (Co-Pilot model). The perf-fee /
+-- high-water-mark columns are seeded here but only settled in Phase 3.
+
+begin;
+
+create table if not exists copy_subscriptions (
+ id uuid primary key default gen_random_uuid(),
+ copier_user_id uuid not null references users(id) on delete cascade,
+ copier_wallet text not null, -- wallet the copier trades from
+ leader_agent_id uuid not null references agent_identities(id) on delete cascade,
+ leader_wallet text, -- denormalized; matches sniper positions
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ status text not null default 'active' check (status in ('active','paused','stopped')),
+
+ -- sizing: how the copier's order is derived from the leader's entry
+ sizing_rule text not null default 'fixed' check (sizing_rule in ('fixed','multiplier','pct_balance')),
+ fixed_sol numeric not null default 0, -- sizing_rule=fixed
+ multiplier numeric not null default 0.1, -- sizing_rule=multiplier (× leader entry)
+ pct_balance numeric not null default 0, -- sizing_rule=pct_balance (% of copier SOL)
+
+ -- guards
+ per_trade_cap_sol numeric not null default 0.5, -- hard ceiling on any one copy
+ min_order_sol numeric not null default 0.02, -- skip dust copies below this
+ daily_budget_sol numeric not null default 1, -- max copy SOL fanned out per UTC day
+ max_open_copies int not null default 5, -- cap concurrent pending intents
+ mcap_floor_usd numeric, -- null = ignore
+ mcap_ceiling_usd numeric, -- null = ignore
+ copy_sells boolean not null default true, -- mirror exits, not just entries
+ require_safety_pass boolean not null default false, -- skip when coin safety can't be confirmed
+
+ -- perf fee (Phase 3)
+ perf_fee_bps int not null default 1000, -- leader's cut of copier profit (10%)
+ high_water_mark_sol numeric not null default 0,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (copier_user_id, leader_agent_id, network),
+ constraint copy_cap_positive check (per_trade_cap_sol > 0),
+ constraint copy_perf_fee_range check (perf_fee_bps >= 0 and perf_fee_bps <= 3000)
+);
+
+create index if not exists copy_subscriptions_copier
+ on copy_subscriptions (copier_user_id, status);
+create index if not exists copy_subscriptions_leader_active
+ on copy_subscriptions (leader_agent_id, network)
+ where status = 'active';
+
+create table if not exists copy_executions (
+ id uuid primary key default gen_random_uuid(),
+ subscription_id uuid not null references copy_subscriptions(id) on delete cascade,
+ copier_user_id uuid not null,
+ leader_agent_id uuid not null,
+ leader_position_id uuid not null, -- agent_sniper_positions.id that triggered it
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ mint text not null,
+ symbol text,
+ name text,
+ direction text not null default 'buy' check (direction in ('buy','sell')),
+
+ planned_sol numeric, -- sized order (null when skipped)
+ leader_entry_sol numeric,
+ status text not null default 'pending'
+ check (status in ('pending','acted','dismissed','skipped','expired')),
+ skip_reason text,
+ safety jsonb, -- coin-context snapshot used for the decision
+ quote jsonb, -- live quote snapshot at fanout time
+ leader_buy_sig text,
+ tx_signature text, -- set if the copier records their fill
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ expires_at timestamptz not null default (now() + interval '30 minutes'),
+ -- idempotency: one copy intent per leader position per direction per subscription
+ unique (subscription_id, leader_position_id, direction)
+);
+
+create index if not exists copy_executions_copier
+ on copy_executions (copier_user_id, status, created_at desc);
+create index if not exists copy_executions_pending
+ on copy_executions (status, expires_at)
+ where status = 'pending';
+create index if not exists copy_executions_sub
+ on copy_executions (subscription_id, created_at desc);
+
+commit;
diff --git a/api/_lib/oracle/settle.js b/api/_lib/oracle/settle.js
new file mode 100644
index 000000000..4a11a4b46
--- /dev/null
+++ b/api/_lib/oracle/settle.js
@@ -0,0 +1,70 @@
+// Oracle — outcome grading (pure).
+//
+// Closes the learning loop. Once the data brain labels a coin's ground-truth
+// outcome (graduated / rugged / all-time-high multiple), every agent action on
+// that coin is graded here: did the conviction call pay off? This is what turns
+// the action ledger into an honest win-rate record and what lets the conviction
+// backtest report real numbers instead of promises.
+//
+// Pure: takes one action row + the coin's outcome and returns the settled
+// fields. The worker does the I/O.
+
+const num = (v) => (v == null ? null : Number(v));
+
+/**
+ * @param {object} action oracle_watch_actions row { size_sol, entry_mc_usd }
+ * @param {object|null} outcome pump_coin_outcomes row { graduated, rugged, ath_multiple, last_market_cap_usd }
+ * @returns {{ settled:boolean, outcome:string, peak_multiple:number|null, realized_pnl_sol:number|null }}
+ */
+export function gradeAction(action, outcome) {
+ if (!outcome) return { settled: false, outcome: 'open', peak_multiple: null, realized_pnl_sol: null };
+
+ const graduated = !!outcome.graduated;
+ const rugged = !!outcome.rugged;
+ const peak = num(outcome.ath_multiple);
+ const entryMc = num(action?.entry_mc_usd);
+ const lastMc = num(outcome.last_market_cap_usd);
+
+ // Nothing to grade yet — outcome row exists but carries no resolved signal.
+ if (!graduated && !rugged && peak == null && lastMc == null) {
+ return { settled: false, outcome: 'open', peak_multiple: peak, realized_pnl_sol: null };
+ }
+
+ const size = num(action?.size_sol) || 0;
+ // Honest mark-to-market: value vs. entry from the last observed market cap.
+ // We don't model an exit, so this is the position's standing mark, not a
+ // realized sell. Null when we can't anchor an entry.
+ const mark = entryMc && lastMc ? lastMc / entryMc : null;
+ const realized_pnl_sol = mark != null ? +(size * (mark - 1)).toFixed(6) : null;
+
+ let label;
+ if (graduated || (peak != null && peak >= 2)) label = 'win';
+ else if (rugged || (mark != null && mark < 0.5) || (peak != null && peak < 1.2)) label = 'loss';
+ else label = 'flat';
+
+ return { settled: true, outcome: label, peak_multiple: peak, realized_pnl_sol };
+}
+
+/**
+ * Roll a set of graded actions into an agent's win-rate summary. Pure.
+ * @param {Array<{outcome:string, realized_pnl_sol:number|null, size_sol:number}>} actions
+ */
+export function summarizeActions(actions = []) {
+ let wins = 0, losses = 0, open = 0, pnl = 0, sized = 0;
+ for (const a of actions) {
+ if (a.outcome === 'win') wins += 1;
+ else if (a.outcome === 'loss') losses += 1;
+ else if (a.outcome === 'open' || a.outcome == null) open += 1;
+ if (a.realized_pnl_sol != null) pnl += Number(a.realized_pnl_sol);
+ if (a.size_sol != null) sized += Number(a.size_sol);
+ }
+ const resolved = wins + losses;
+ return {
+ total: actions.length,
+ wins, losses, open,
+ win_rate: resolved ? Math.round((wins / resolved) * 100) : null,
+ realized_pnl_sol: +pnl.toFixed(6),
+ deployed_sol: +sized.toFixed(6),
+ roi_pct: sized > 0 ? Math.round((pnl / sized) * 100) : null,
+ };
+}
diff --git a/api/_lib/oracle/store.js b/api/_lib/oracle/store.js
index 854c60b39..cfdf4d227 100644
--- a/api/_lib/oracle/store.js
+++ b/api/_lib/oracle/store.js
@@ -8,6 +8,7 @@ import { sql } from '../db.js';
import { assembleIntel, walletProfile, coinOutcome } from './sources.js';
import { classifyNarrative } from './narrative.js';
import { convict } from './conviction.js';
+import { summarizeActions } from './settle.js';
/** Persist a narrative classification. */
export async function upsertNarrative(mint, network, narr) {
@@ -274,3 +275,17 @@ export async function recentActions(agentId, network = 'mainnet', limit = 50) {
order by acted_at desc limit ${Math.min(100, Math.max(1, limit))}
`.catch(() => []);
}
+
+/** Agent win-rate summary across all its actions. */
+export async function actionsSummary(agentId, network = 'mainnet') {
+ const rows = await sql`
+ select outcome, realized_pnl_sol, size_sol
+ from oracle_watch_actions
+ where agent_id = ${agentId} and network = ${network}
+ `.catch(() => []);
+ return summarizeActions(rows.map((r) => ({
+ outcome: r.outcome,
+ realized_pnl_sol: r.realized_pnl_sol != null ? Number(r.realized_pnl_sol) : null,
+ size_sol: r.size_sol != null ? Number(r.size_sol) : 0,
+ })));
+}
diff --git a/api/agents.js b/api/agents.js
index c0dee13f7..89a0ba588 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -478,18 +478,51 @@ async function handleDelete(req, res, id, auth) {
// ── Wallet ────────────────────────────────────────────────────────────────
export async function handleWallet(req, res, id, action = null) {
- if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- if (!(await requireCsrf(req, res, auth.userId))) return;
const [existing] = await sql`
- SELECT id, user_id, wallet_address FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ SELECT id, user_id, wallet_address, chain_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
if (!existing) return error(res, 404, 'not_found', 'agent not found');
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ // GET /api/agents/:id/wallet — owner-only wallet status: addresses + live
+ // balances. Balances are best-effort (RPC hiccups return null, never a 500)
+ // so the panel can render addresses immediately and fill balances in after.
+ if (req.method === 'GET') {
+ const evmAddr = existing.wallet_address || null;
+ const solAddr = existing.meta?.solana_address || null;
+ const chainId = existing.chain_id || 8453;
+ let evmBalanceEth = null;
+ let sol = null;
+ let usdc = null;
+ if (evmAddr || solAddr) {
+ const { getAgentBalance, getSolanaAddressBalances } = await import('./_lib/agent-wallet.js');
+ const [evmRes, solRes] = await Promise.allSettled([
+ evmAddr ? getAgentBalance(id) : Promise.resolve(null),
+ solAddr ? getSolanaAddressBalances(solAddr, 'mainnet') : Promise.resolve(null),
+ ]);
+ if (evmRes.status === 'fulfilled' && evmRes.value) evmBalanceEth = evmRes.value.balance_eth;
+ if (solRes.status === 'fulfilled' && solRes.value) {
+ sol = solRes.value.sol;
+ usdc = solRes.value.usdc;
+ }
+ }
+ return json(res, 200, {
+ wallet_address: evmAddr,
+ chain_id: chainId,
+ solana_address: solAddr,
+ balance_eth: evmBalanceEth,
+ solana_balance: sol,
+ usdc_balance: usdc,
+ });
+ }
+
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
// POST /api/agents/:id/wallet/provision — idempotently generate the agent's
// custodial EVM + Solana wallets. This is the "Create wallet" action surfaced
// on every avatar surface; safe to call repeatedly (returns existing addresses).
diff --git a/api/avatars/fork.js b/api/avatars/fork.js
index 67996d992..f1da5788d 100644
--- a/api/avatars/fork.js
+++ b/api/avatars/fork.js
@@ -9,7 +9,7 @@
// alone; the original owner's avatar, agent, and wallet are untouched.
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { createAvatar, storageKeyFor } from '../_lib/avatars.js';
+import { createAvatar, storageKeyFor, listForks } from '../_lib/avatars.js';
import { copyObject, headObject } from '../_lib/r2.js';
import { provisionAgentWallets } from '../_lib/agent-wallet.js';
import { sql } from '../_lib/db.js';
@@ -20,8 +20,22 @@ import { recordEvent } from '../_lib/usage.js';
import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // GET /api/avatars/fork?of=<avatarId> — public fork network of an avatar.
+ // Anonymous-safe: it only exposes public/unlisted forks.
+ if (req.method === 'GET') {
+ const url = new URL(req.url, 'http://x');
+ const of = String(url.searchParams.get('of') || '').trim();
+ if (!isUuid(of)) return error(res, 400, 'validation_error', 'of=<avatarId> required');
+ const result = await listForks({
+ avatarId: of,
+ limit: Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 100),
+ cursor: url.searchParams.get('cursor'),
+ });
+ return json(res, 200, result);
+ }
const auth = await resolveAuth(req, 'avatars:write');
if (!auth) return error(res, 401, 'unauthorized', 'avatars:write scope required');
diff --git a/api/avatars/index.js b/api/avatars/index.js
index b6da635db..56eac500f 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -166,13 +166,14 @@ async function handleCreate(req, res) {
return created?.id ?? null;
});
- // Every avatar's agent gets a custodial wallet on first save so it
- // can transact immediately. Idempotent — a claimed agent that already
- // has a wallet is left untouched.
+ // Every 3D avatar's agent gets a custodial Solana wallet on first
+ // save so it can transact immediately. Solana-only by product
+ // decision — EVM is opt-in via the wallet panel, never auto-minted.
+ // Idempotent: an agent that already has a Solana wallet is untouched.
if (agentId) {
- const { provisionAgentWallets } = await import('../_lib/agent-wallet.js');
- await provisionAgentWallets(agentId).catch((e) =>
- console.warn('[avatars] wallet provision failed', agentId, e?.message),
+ const { getOrCreateAgentSolanaWallet } = await import('../_lib/agent-wallet.js');
+ await getOrCreateAgentSolanaWallet(agentId).catch((e) =>
+ console.warn('[avatars] solana wallet provision failed', agentId, e?.message),
);
}
} catch (err) {
diff --git a/api/cron/oracle-score.js b/api/cron/oracle-score.js
new file mode 100644
index 000000000..56d1ead81
--- /dev/null
+++ b/api/cron/oracle-score.js
@@ -0,0 +1,86 @@
+// GET/POST /api/cron/oracle-score — serverless driver for the Oracle engine.
+//
+// The Oracle ships a long-lived worker (workers/oracle) with two loops: a score
+// loop that keeps oracle_conviction warm from the data brain, and an agent loop
+// that acts on fresh verdicts for every armed watch. This platform deploys on
+// Vercel (no host for a long-lived process), so this cron drives the same two
+// passes serverlessly — exactly the pattern the intel-learn / smart-money-rollup
+// crons use. With it scheduled, the /oracle feed warms up and armed agents act
+// without anything else running.
+//
+// Reuses the worker's real code paths (no duplicated logic):
+// 1. runScorePass — score recent brain coins missing/stale in the cache.
+// 2. actOnFreshCoins — run every armed watch against the just-scored window.
+//
+// Simulate-default and idempotent: scoring upserts by (mint, network); each
+// (agent, mint) acts at most once. Live trading only happens when an operator
+// sets ORACLE_MODE=live (gated again by a hard per-trade SOL cap in the
+// executor) and a watch is itself armed in live mode.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { loadConfig } from '../../workers/oracle/config.js';
+import { runScorePass } from '../../workers/oracle/score-loop.js';
+import { actOnFreshCoins, freshlyScored } from '../../workers/oracle/agent-loop.js';
+import { runSettlePass } from '../../workers/oracle/settle-loop.js';
+
+// How far back the agent pass looks for scored coins. Wider than the cron
+// cadence so a missed tick still catches up; the per-(agent,mint) dedup makes
+// the overlap harmless.
+const AGENT_WINDOW_SEC = 15 * 60;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const started = Date.now();
+
+ // loadConfig validates env once and resolves mode/network the same way the
+ // worker does — a single source of config truth shared by both deploys.
+ let cfg;
+ try {
+ cfg = loadConfig();
+ } catch (e) {
+ return error(res, 503, 'not_configured', e.message);
+ }
+
+ // 1) Warm the conviction cache from the brain (bounded by ORACLE_SCORE_BATCH).
+ const scored = await runScorePass(cfg);
+
+ // 2) Act on a recent window of scored coins for every armed watch. Driven by
+ // an explicit window (not the worker's in-memory cursor) so it works across
+ // stateless invocations.
+ const sinceIso = new Date(Date.now() - AGENT_WINDOW_SEC * 1000).toISOString();
+ const coins = await freshlyScored(cfg.network, sinceIso, 100);
+ const acted = await actOnFreshCoins(cfg, coins);
+
+ // 3) Close the learning loop: grade any acted-on coin that has since resolved
+ // to a ground-truth outcome (graduated / rugged / ATH). Idempotent — only
+ // open actions whose outcome is known get settled.
+ const settled = await runSettlePass(cfg);
+
+ return json(res, 200, {
+ ok: true,
+ network: cfg.network,
+ mode: cfg.mode,
+ global_kill: cfg.globalKill,
+ scored,
+ window_coins: coins.length,
+ acted,
+ settled,
+ ms: Date.now() - started,
+ });
+});
diff --git a/api/oracle/signal.js b/api/oracle/signal.js
new file mode 100644
index 000000000..b7f53b255
--- /dev/null
+++ b/api/oracle/signal.js
@@ -0,0 +1,90 @@
+/**
+ * Oracle — agent signal endpoint (machine-optimized).
+ *
+ * GET /api/oracle/signal?network=mainnet&min_score=72&category=ai&limit=5
+ * GET /api/oracle/signal?mint=<mint> → verdict for one coin
+ *
+ * The compact read a user's 3D AI agent polls to act fast. Returns the current
+ * highest-conviction plays (or a single coin's verdict) with an explicit,
+ * agent-friendly recommendation derived from the fused tier — so an autonomous
+ * agent doesn't have to re-implement the decision rules to decide whether to buy.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { readFeed, scoreCoin } from '../_lib/oracle/store.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const CATEGORIES = new Set(['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown']);
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// Tier → agent-readable recommendation + a suggested fraction of the agent's
+// per-trade size. Conservative by design: only prime/strong are "act".
+const REC = {
+ prime: { action: 'buy', confidence: 'high', size_factor: 1.0, note: 'top-conviction play — proven money in a clean, on-narrative launch' },
+ strong: { action: 'buy', confidence: 'medium', size_factor: 0.75, note: 'strong conviction — favorable across pedigree and structure' },
+ lean: { action: 'watch', confidence: 'low', size_factor: 0, note: 'leaning positive but not decisive — watch for confirmation' },
+ watch: { action: 'skip', confidence: 'low', size_factor: 0, note: 'inconclusive — no edge yet' },
+ avoid: { action: 'skip', confidence: 'high', size_factor: 0, note: 'structural or pedigree red flags — avoid' },
+};
+
+function shape(it) {
+ const rec = REC[it.tier] || REC.avoid;
+ return {
+ mint: it.mint,
+ symbol: it.symbol,
+ conviction: it.score,
+ tier: it.tier,
+ category: it.category,
+ smart_wallet_count: it.smart_wallet_count,
+ pillars: it.pillars,
+ badges: it.badges,
+ recommendation: rec,
+ scored_at: it.scored_at,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const p = url.searchParams;
+ const network = NETWORKS.has(p.get('network')) ? p.get('network') : 'mainnet';
+
+ // Single-coin verdict.
+ const mint = (p.get('mint') || '').trim();
+ if (mint) {
+ if (!MINT_RE.test(mint)) return error(res, 400, 'validation_error', 'invalid mint');
+ const scored = await scoreCoin(mint, { network, classify: true, persist: true }).catch(() => null);
+ if (!scored) return error(res, 404, 'not_found', 'mint not observed yet');
+ const v = scored.verdict;
+ return json(res, 200, {
+ network, mint,
+ signal: shape({
+ mint, symbol: scored.intel.symbol, score: v.score, tier: v.tier,
+ category: scored.intel.category, smart_wallet_count: scored.intel.smartMoney?.smartWalletCount || 0,
+ pillars: v.pillars, badges: v.badges, scored_at: new Date().toISOString(),
+ }),
+ generated_at: new Date().toISOString(),
+ });
+ }
+
+ // Top plays.
+ const minScore = Math.max(0, Math.min(100, Number(p.get('min_score')) || 72));
+ const category = CATEGORIES.has(p.get('category')) ? p.get('category') : null;
+ const limit = Math.min(25, Math.max(1, Number(p.get('limit')) || 5));
+
+ const items = await readFeed({ network, limit, minScore, category, sinceSeconds: 6 * 3600 }).catch(() => []);
+ const plays = items.map(shape);
+ return json(res, 200, {
+ network,
+ count: plays.length,
+ top: plays[0] || null,
+ plays,
+ generated_at: new Date().toISOString(),
+ }, { 'Cache-Control': 'public, max-age=3, stale-while-revalidate=15' });
+});
diff --git a/api/oracle/watch.js b/api/oracle/watch.js
index 10807273c..e25bb0b76 100644
--- a/api/oracle/watch.js
+++ b/api/oracle/watch.js
@@ -19,7 +19,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { z } from 'zod';
-import { getWatch, upsertWatch, recentActions } from '../_lib/oracle/store.js';
+import { getWatch, upsertWatch, recentActions, actionsSummary } from '../_lib/oracle/store.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);
@@ -74,11 +74,12 @@ export default wrap(async (req, res) => {
if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
if (!(await ownsAgent(userId, agentId))) return error(res, 403, 'forbidden', 'you do not own this agent');
- const [watch, actions] = await Promise.all([
+ const [watch, actions, summary] = await Promise.all([
getWatch(agentId, network),
recentActions(agentId, network, 50),
+ actionsSummary(agentId, network),
]);
- return json(res, 200, { agent_id: agentId, network, watch: watch || defaultWatch(agentId, network), actions });
+ return json(res, 200, { agent_id: agentId, network, watch: watch || defaultWatch(agentId, network), actions, summary });
}
// POST — arm / update.
diff --git a/api/pump/[action].js b/api/pump/[action].js
index d4014f637..0295714f3 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -59,6 +59,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/
import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';
import { env } from '../_lib/env.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { resolveOrCreateAgentForAvatar as resolveLaunchAgentId } from '../_lib/agent-identity.js';
import { parse, isUuid } from '../_lib/validate.js';
import { randomToken } from '../_lib/crypto.js';
import { publishFeedEvent } from '../_lib/feed.js';
@@ -1150,67 +1151,6 @@ const launchPrepSchema = z
path: ['agent_id'],
});
-// Resolve a usable agent_identities.id for the launch. If the caller passed
-// avatar_id (e.g. from /studio, where users pick an avatar and not a separate
-// agent), find the agent_identity already linked to that avatar — or create
-// one inline so the launch can proceed without a detour through the agent
-// registration wizard.
-async function resolveLaunchAgentId({ userId, agentId, avatarId }) {
- if (agentId) {
- const [row] = await sql`
- select id, name from agent_identities
- where id=${agentId} and user_id=${userId} and deleted_at is null
- limit 1
- `;
- return row || null;
- }
- const [linked] = await sql`
- select id, name from agent_identities
- where user_id=${userId} and avatar_id=${avatarId} and deleted_at is null
- order by created_at asc limit 1
- `;
- if (linked) return linked;
-
- const [avatar] = await sql`
- select id, name, description from avatars
- where id=${avatarId} and owner_id=${userId} and deleted_at is null
- limit 1
- `;
- if (!avatar) return null;
-
- const agentName = (avatar.name || 'Agent').slice(0, 100);
- const agentDesc = avatar.description ? String(avatar.description).slice(0, 1000) : null;
- try {
- const [created] = await sql`
- insert into agent_identities (user_id, name, description, avatar_id)
- values (${userId}, ${agentName}, ${agentDesc}, ${avatar.id})
- returning id, name
- `;
- return created;
- } catch (err) {
- if (err?.code !== '23505') throw err;
- // Unique-per-user constraint: reuse the user's existing identity and
- // link it to this avatar if it has none yet.
- const [unlinked] = await sql`
- select id, name from agent_identities
- where user_id=${userId} and avatar_id is null and deleted_at is null
- order by created_at asc limit 1
- `;
- if (unlinked) {
- await sql`
- update agent_identities set avatar_id=${avatar.id}, updated_at=now()
- where id=${unlinked.id}
- `;
- return unlinked;
- }
- const [any] = await sql`
- select id, name from agent_identities
- where user_id=${userId} and deleted_at is null
- order by created_at asc limit 1
- `;
- return any || null;
- }
-}
async function handleLaunchPrep(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
diff --git a/pages/club.html b/pages/club.html
index b3de6c6de..fab7794c5 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -630,6 +630,85 @@
/* ── Entrance controller UI ─────────────────────────── */
/* Sit above the scene canvas (9400), below the cover card (9500). */
+ /* Cinematic intro / loading screen for the walk in. Sits above the
+ entrance canvas, below the cover card; fades out once the alley is
+ ready (driven by src/club-entrance.js with real byte progress). */
+ .club-loader {
+ position: fixed;
+ inset: 0;
+ z-index: 9480;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 24px;
+ background:
+ radial-gradient(120% 90% at 50% 18%, rgba(255, 59, 214, 0.14), transparent 55%),
+ radial-gradient(110% 80% at 50% 100%, rgba(74, 214, 255, 0.1), transparent 60%),
+ #050308;
+ opacity: 1;
+ transition: opacity 0.7s ease;
+ }
+ .club-loader.is-done { opacity: 0; pointer-events: none; }
+ .club-loader-inner { max-width: 460px; width: 100%; }
+ .club-loader-kicker {
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.42em;
+ text-transform: uppercase;
+ color: var(--accent-2, #4ad6ff);
+ opacity: 0.85;
+ margin-bottom: 14px;
+ }
+ .club-loader-title {
+ margin: 0;
+ font-size: clamp(40px, 11vw, 76px);
+ font-weight: 800;
+ line-height: 0.96;
+ letter-spacing: -0.02em;
+ color: #fff;
+ text-shadow: 0 0 28px rgba(255, 59, 214, 0.55);
+ }
+ .club-loader-title span {
+ display: block;
+ background: linear-gradient(92deg, #ff3bd6, #ff8a3b 60%, #4ad6ff);
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+ color: transparent;
+ text-shadow: none;
+ }
+ .club-loader-tagline {
+ margin: 16px auto 28px;
+ max-width: 360px;
+ font-size: 14px;
+ line-height: 1.5;
+ color: var(--text-2, #c2a8d8);
+ }
+ .club-loader-track {
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+ overflow: hidden;
+ }
+ .club-loader-bar {
+ height: 100%;
+ width: 4%;
+ border-radius: 999px;
+ background: linear-gradient(90deg, #ff3bd6, #4ad6ff);
+ box-shadow: 0 0 16px rgba(255, 59, 214, 0.8);
+ transition: width 0.35s cubic-bezier(0.22, 1, 0.36, 1);
+ }
+ .club-loader-status {
+ margin-top: 14px;
+ font-size: 12px;
+ letter-spacing: 0.04em;
+ color: var(--text-3, #7c5d92);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .club-loader, .club-loader-bar { transition: none; }
+ }
+
/* Journey progress — where you are on the walk in (Alley → Stage). */
.club-journey {
position: fixed;
@@ -1493,6 +1572,17 @@
pay. Sits behind the cover card, above the pole stage. -->
<canvas id="club-door-canvas" class="club-door-canvas" aria-hidden="true"></canvas>
+ <!-- Cinematic intro + real load progress while the alley streams in. -->
+ <div id="club-loader" class="club-loader" role="status" aria-live="polite">
+ <div class="club-loader-inner">
+ <div class="club-loader-kicker">three.ws</div>
+ <h1 class="club-loader-title">Pole<span>Club</span></h1>
+ <p class="club-loader-tagline">Step into the alley and walk it in. Tip a dancer and she takes the pole.</p>
+ <div class="club-loader-track"><div id="club-loader-bar" class="club-loader-bar"></div></div>
+ <div id="club-loader-status" class="club-loader-status">Loading the night…</div>
+ </div>
+ </div>
+
<!-- Controller UI for the walk in (toggled by src/club-entrance.js). -->
<nav id="club-journey" class="club-journey" aria-label="Walk-in progress">
<ol class="club-journey-steps">
diff --git a/pages/launch-detail.html b/pages/launch-detail.html
index 6897d3bdc..17738dd9a 100644
--- a/pages/launch-detail.html
+++ b/pages/launch-detail.html
@@ -58,6 +58,7 @@
<div class="ld-body">
<div class="ld-main">
<section id="ld-verdict" class="ld-section" aria-label="Coin Intelligence verdict"></section>
+ <section id="ld-smart" class="ld-section" aria-label="Smart money in this coin"></section>
<section id="ld-chart" class="ld-section" aria-label="Price history"></section>
<section id="ld-distribution" class="ld-section" aria-label="Holder distribution"></section>
<section id="ld-economics" class="ld-section" aria-label="Buyback &amp; burn economics"></section>
diff --git a/pages/launch.html b/pages/launch.html
index 3bab9e766..45ce8c9b8 100644
--- a/pages/launch.html
+++ b/pages/launch.html
@@ -144,7 +144,11 @@
<script src="/footer.js"></script>
<script type="module">
- import { mountLaunchCoin } from '/launch/launch.js';
+ // launch.js and its dependency chain (/studio/launch-panel.js,
+ // /studio/fees-panel.js) live in public/ and are loaded by URL at
+ // runtime. @vite-ignore keeps rollup from trying to bundle a
+ // public-dir asset (which it cannot resolve) and aborting build:app.
+ const { mountLaunchCoin } = await import(/* @vite-ignore */ '/launch/launch.js');
mountLaunchCoin(document.getElementById('launch-root'));
</script>
<script src="/brand.js" defer></script>
diff --git a/pages/launches.html b/pages/launches.html
index a862575bc..f9e8cfd82 100644
--- a/pages/launches.html
+++ b/pages/launches.html
@@ -119,7 +119,9 @@
</section>
<nav class="lx-explore" aria-label="Explore the launchpad">
- <a class="lx-explore-link" href="/pump-live">Live stream →</a>
+ <a class="lx-explore-link" href="/watchlist">★ Watchlist →</a>
+ <a class="lx-explore-link" href="/radar">Coin radar →</a>
+ <a class="lx-explore-link" href="/pump-live">Live stream →</a>
<a class="lx-explore-link" href="/pump-visualizer">3D Visualizer →</a>
<a class="lx-explore-link" href="/launchpad">Launchpad Studio →</a>
</nav>
diff --git a/pages/oracle.html b/pages/oracle.html
index 072d1bb58..202d54b08 100644
--- a/pages/oracle.html
+++ b/pages/oracle.html
@@ -1,6 +1,7 @@
<!doctype html>
<html lang="en" data-theme="dark">
<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Oracle — fused pump.fun conviction · three.ws</title>
@@ -258,6 +259,7 @@
<option value="72">≥ 72 (Strong)</option>
<option value="86">≥ 86 (Prime)</option>
</select>
+ <input class="sel" id="mintSearch" placeholder="Paste a mint to score it…" aria-label="Score any coin by mint address" style="min-width:230px;flex:1;max-width:320px" />
</div>
<div class="grid" id="feedGrid"></div>
</section>
diff --git a/pages/play/arena.html b/pages/play/arena.html
index d0069200a..0b38bd6af 100644
--- a/pages/play/arena.html
+++ b/pages/play/arena.html
@@ -160,6 +160,55 @@
font-size: 11.5px; color: var(--faint); display: flex; gap: 6px; align-items: center; pointer-events: none; }
.disc b { color: color-mix(in srgb, var(--gold) 80%, #fff); }
+ /* agent detail drawer */
+ .drawer { position: fixed; top: 0; right: 0; bottom: 0; width: 360px; max-width: calc(100vw - 24px); z-index: 12;
+ background: var(--panel-solid); border-left: 1px solid var(--line); box-shadow: -24px 0 60px -24px rgba(0,0,0,0.8);
+ transform: translateX(calc(100% + 24px)); transition: transform .36s cubic-bezier(.22,1,.36,1);
+ display: flex; flex-direction: column; overflow: hidden; }
+ .drawer.open { transform: none; }
+ .drawer-x { position: absolute; top: 14px; right: 14px; z-index: 2; width: 32px; height: 32px; border-radius: 9px;
+ border: 1px solid var(--line); background: rgba(255,255,255,0.04); display: grid; place-items: center; color: var(--muted); }
+ .drawer-x:hover { color: var(--ink); border-color: var(--cyan); }
+ .drawer-body { overflow-y: auto; padding: 20px 18px 24px; }
+ .dw-skel { height: 56px; border-radius: 12px; margin-bottom: 12px; background: linear-gradient(90deg, rgba(255,255,255,0.03) 25%, rgba(255,255,255,0.07) 37%, rgba(255,255,255,0.03) 63%); background-size: 400% 100%; animation: sh 1.3s infinite; }
+ @keyframes sh { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+ .dw-empty { color: var(--muted); font-size: 13px; text-align: center; padding: 30px 10px; }
+ .dw-empty b { color: var(--ink); display: block; margin-bottom: 6px; }
+ .dw-empty a { color: var(--cyan); }
+ .dw-head { display: grid; grid-template-columns: 48px 1fr auto; gap: 12px; align-items: center; margin: 4px 0 16px; }
+ .dw-head img, .dw-av-fallback { width: 48px; height: 48px; border-radius: 12px; object-fit: cover; background: radial-gradient(120% 100% at 50% 0%, #233, #0d1018); border: 1px solid var(--line); }
+ .dw-name { font-size: 18px; font-weight: 700; letter-spacing: -0.01em; }
+ .dw-sub { margin-top: 4px; }
+ .dw-badge { font-size: 10.5px; font-weight: 600; padding: 3px 8px; border-radius: 999px; background: rgba(255,255,255,0.06); border: 1px solid var(--line); color: var(--muted); }
+ .dw-badge.ok { background: color-mix(in srgb, var(--up) 16%, transparent); border-color: color-mix(in srgb, var(--up) 40%, var(--line)); color: var(--up); }
+ .dw-score { text-align: center; line-height: 1; }
+ .dw-score b { font: 800 26px/1 var(--mono); display: block; }
+ .dw-score.up b { color: var(--up); } .dw-score.down b { color: var(--down); }
+ .dw-score span { font-size: 9px; text-transform: uppercase; letter-spacing: .08em; color: var(--faint); }
+ .dw-spark { width: 100%; height: 56px; margin: 4px 0 16px; display: block; }
+ .dw-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; margin-bottom: 18px; }
+ .dw-stat { background: var(--panel-solid); padding: 11px 13px; }
+ .dw-stat span { display: block; font-size: 10px; text-transform: uppercase; letter-spacing: .06em; color: var(--faint); margin-bottom: 4px; }
+ .dw-stat b { font: 700 16px/1.1 var(--mono); }
+ .dw-stat b small { font-size: 11px; color: var(--faint); font-weight: 500; }
+ .dw-stat b.up { color: var(--up); } .dw-stat b.down { color: var(--down); }
+ .dw-section-h { font-size: 10.5px; text-transform: uppercase; letter-spacing: .08em; color: var(--faint); margin: 4px 2px 10px; }
+ .dw-trades { display: flex; flex-direction: column; gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
+ .dw-trade { display: grid; grid-template-columns: 1fr auto auto 16px; gap: 8px; align-items: center; background: var(--panel-solid); padding: 9px 12px; font-size: 12.5px; }
+ .dw-t-sym { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .dw-t-reason { font-size: 10.5px; color: var(--faint); }
+ .dw-t-pnl { font: 700 12px/1 var(--mono); white-space: nowrap; }
+ .dw-t-pnl.up { color: var(--up); } .dw-t-pnl.down { color: var(--down); }
+ .dw-trade a { color: var(--cyan); text-decoration: none; }
+ .dw-sim { font-size: 9px; color: var(--faint); }
+ .dw-cta { display: flex; gap: 8px; margin-top: 18px; }
+ .dw-cta .btn { flex: 1; justify-content: center; }
+ @media (max-width: 560px) {
+ .drawer { top: auto; left: 0; right: 0; width: 100%; max-width: none; height: 82vh; border-left: none; border-top: 1px solid var(--line);
+ border-radius: 18px 18px 0 0; transform: translateY(calc(100% + 24px)); }
+ .drawer.open { transform: none; }
+ }
+
/* avatar picker */
.picker { position: fixed; inset: 0; z-index: 20; display: none; }
.picker.open { display: block; }
@@ -277,6 +326,14 @@
<div id="joystick"></div>
+ <!-- agent detail drawer -->
+ <aside class="drawer" id="agentDrawer" aria-label="Agent track record">
+ <button class="drawer-x" id="drawerClose" aria-label="Close">
+ <svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"><path d="M5 5l10 10M15 5L5 15"/></svg>
+ </button>
+ <div class="drawer-body" id="drawerBody"></div>
+ </aside>
+
<!-- avatar picker -->
<div class="picker" id="picker">
<div class="pick-backdrop" id="pickBackdrop"></div>
diff --git a/pages/smart-money.html b/pages/smart-money.html
index 08ed71b8f..f0da147bf 100644
--- a/pages/smart-money.html
+++ b/pages/smart-money.html
@@ -1,6 +1,7 @@
<!doctype html>
<html lang="en" data-theme="dark">
<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Smart Money Radar — follow the wallets that actually win on pump.fun · three.ws</title>
diff --git a/pages/watchlist.html b/pages/watchlist.html
new file mode 100644
index 000000000..fa3f988f3
--- /dev/null
+++ b/pages/watchlist.html
@@ -0,0 +1,64 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Watchlist · three.ws</title>
+ <meta
+ name="description"
+ content="Your watched coins on three.ws — live market caps, graduation status, and the Coin Intelligence verdict for every mint you're tracking."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/watchlist" />
+ <meta property="og:title" content="Watchlist · three.ws" />
+ <meta property="og:description" content="Your watched coins on three.ws — live market caps, graduation status, and intelligence for every mint you track." />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/watchlist.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/watchlist" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <canvas id="wl-field" aria-hidden="true"></canvas>
+ <div class="wl-aurora" aria-hidden="true"></div>
+
+ <main class="wl-shell">
+ <section class="wl-hero">
+ <p class="wl-kicker"><span class="wl-live-dot" aria-hidden="true"></span>Saved on this device</p>
+ <h1 class="wl-title">Watchlist</h1>
+ <p class="wl-sub">
+ Coins you're tracking, with live market caps and graduation status. Tap any card for the
+ full profile. Your list is stored privately in this browser.
+ </p>
+ <div class="wl-hero-row">
+ <span id="wl-count" class="wl-count" aria-live="polite"></span>
+ <div class="wl-hero-ctas">
+ <a class="wl-btn" href="/launches">Browse launches</a>
+ <button id="wl-clear" class="wl-btn wl-btn-ghost" type="button" hidden>Clear all</button>
+ </div>
+ </div>
+ </section>
+
+ <section id="wl-feed" class="wl-grid" aria-label="Watched coins" aria-busy="true"></section>
+ <div id="wl-state" class="wl-state"></div>
+ </main>
+
+ <script type="module" src="/src/watchlist.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index bd1096d41..e2b7d3a47 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -78,6 +78,8 @@ button.primary:hover { filter: brightness(1.08); background: var(--aa-acc); }
.addr code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--aa-fg); }
.copy { padding: 3px 7px; font-size: 11px; }
.copy.copied { color: var(--aa-good); border-color: var(--aa-good); }
+.bal { margin-left: auto; font-size: 11px; color: var(--aa-dim); font-variant-numeric: tabular-nums; white-space: nowrap; }
+.bal.has { color: var(--aa-fg); }
.manage { color: var(--aa-acc); text-decoration: none; font-size: 12px; font-weight: 600; }
.manage:hover { text-decoration: underline; }
.msg { font-size: 12px; padding: 8px 10px; border-radius: 8px; }
@@ -226,15 +228,16 @@ class AvatarActions extends HTMLElement {
<button class="primary" data-act="create-wallet">Create wallet</button>
</div>`;
}
- const addr = (chain, a) =>
+ const addr = (chain, a, balKey) =>
a
? `<div class="addr"><span class="chain">${chain}</span><code>${short(a)}</code>
- <button class="copy" data-copy="${a}" title="Copy ${chain} address">Copy</button></div>`
+ <button class="copy" data-copy="${a}" title="Copy ${chain} address">Copy</button>
+ <span class="bal" data-bal="${balKey}"></span></div>`
: '';
return `<div class="wallet">
<div class="row spread"><h4>Agent wallet</h4>${manage}</div>
- ${addr('EVM', evm)}
- ${addr('SOL', sol)}
+ ${addr('EVM', evm, 'eth')}
+ ${addr('SOL', sol, 'sol')}
${evm && sol ? '' : `<button data-act="create-wallet">Provision missing chain</button>`}
</div>`;
}
@@ -261,6 +264,38 @@ class AvatarActions extends HTMLElement {
root
.querySelector('[data-act="create-wallet"]')
?.addEventListener('click', () => this._createWallet());
+
+ // Fill live balances after the addresses are on screen (owner + has wallet).
+ if (this.isOwner && this._agent && root.querySelector('.bal')) this._loadBalances();
+ }
+
+ async _loadBalances() {
+ const ag = this._agent;
+ if (!ag) return;
+ let d;
+ try {
+ const r = await fetch(`${API}/api/agents/${ag.id}/wallet`, { credentials: 'include' });
+ if (!r.ok) return;
+ d = await r.json();
+ } catch {
+ return;
+ }
+ const root = this.shadowRoot;
+ const fmt = (n, unit) =>
+ n == null ? '' : `${Number(n).toLocaleString(undefined, { maximumFractionDigits: 4 })} ${unit}`;
+ const eth = root.querySelector('[data-bal="eth"]');
+ if (eth && d.balance_eth != null) {
+ eth.textContent = fmt(d.balance_eth, 'ETH');
+ eth.classList.add('has');
+ }
+ const sol = root.querySelector('[data-bal="sol"]');
+ if (sol && (d.solana_balance != null || d.usdc_balance != null)) {
+ const parts = [];
+ if (d.solana_balance != null) parts.push(fmt(d.solana_balance, 'SOL'));
+ if (d.usdc_balance) parts.push(fmt(d.usdc_balance, 'USDC'));
+ sol.textContent = parts.join(' · ');
+ sol.classList.add('has');
+ }
}
_msg(kind, html) {
diff --git a/public/changelog.json b/public/changelog.json
index 0bc28c68b..b8c7c8669 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-16T01:40:04.863Z",
+ "generated_at": "2026-06-16T02:11:58.980Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 1111b0b9c..8f86eda9d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-16T01:40:04.848Z",
+ "generated_at": "2026-06-16T02:11:58.958Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/gallery/gallery.css b/public/gallery/gallery.css
index 70915c515..4c78e073f 100644
--- a/public/gallery/gallery.css
+++ b/public/gallery/gallery.css
@@ -502,6 +502,18 @@ body.gallery-page {
.gallery-card-dot {
opacity: 0.5;
}
+.gallery-card-fork {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 1px 6px;
+ border-radius: 999px;
+ background: rgba(153, 69, 255, 0.14);
+ color: rgba(184, 138, 255, 0.95);
+ font-size: 10px;
+ font-weight: 600;
+ white-space: nowrap;
+}
.gallery-card-actions {
display: inline-flex;
gap: 6px;
diff --git a/public/gallery/gallery.js b/public/gallery/gallery.js
index 5045f1ff9..f87c7980a 100644
--- a/public/gallery/gallery.js
+++ b/public/gallery/gallery.js
@@ -344,6 +344,8 @@ function renderCard(a) {
<div class="gallery-card-foot">
<span class="gallery-card-meta">
<span title="${escapeAttr(new Date(a.created_at || Date.now()).toLocaleString())}">${escapeHtml(created)}</span>
+ ${a.forked_from ? `<span class="gallery-card-fork" title="Forked from ${escapeAttr(a.forked_from.owner_name || a.forked_from.name || 'another avatar')}">⑂ fork</span>` : ''}
+ ${a.fork_count > 0 ? `<span class="gallery-card-fork" title="${a.fork_count} ${a.fork_count === 1 ? 'fork' : 'forks'}">⑂ ${a.fork_count}</span>` : ''}
</span>
<div class="gallery-card-actions">
<button type="button" class="gallery-card-btn gallery-card-btn--ghost" data-role="card-embed"
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 3de7f87f3..7b93cf38d 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,6 +56,20 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
+
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Sitemap · three.ws">
+ <meta property="og:description" content="Human-readable index of every page on three.ws.">
+ <meta property="og:url" content="https://three.ws/sitemap">
+ <meta property="og:image" content="https://three.ws/og-image.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Sitemap · three.ws">
+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 643513668..a6fa9d737 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -110,6 +110,7 @@ async function init() {
loadPlugins();
loadRelated();
loadUsedBy();
+ loadForks();
measureModel(glbUrl);
}
@@ -333,6 +334,10 @@ function renderShell(glbUrl) {
<h3 class="av-used-by-heading" id="av-used-by-heading">Used by</h3>
<div class="av-used-by-grid" id="av-used-by-grid"></div>
</section>
+ <section class="av-used-by" id="av-forks" hidden aria-labelledby="av-forks-heading">
+ <h3 class="av-used-by-heading" id="av-forks-heading">Forks</h3>
+ <div class="av-used-by-grid" id="av-forks-grid"></div>
+ </section>
${renderAttribution()}
${renderAttached()}
</div>
@@ -1727,6 +1732,41 @@ async function loadUsedBy() {
.join('');
}
+// ── Forks (GitHub-style network) ──────────────────────────────────────
+
+async function loadForks() {
+ const grid = $('av-forks-grid');
+ const section = $('av-forks');
+ if (!grid || !section) return;
+
+ let forks;
+ try {
+ const r = await fetch(`/api/avatars/fork?of=${encodeURIComponent(avatarId)}&limit=12`);
+ if (!r.ok) return;
+ ({ forks } = await r.json());
+ } catch {
+ return; // optional section — stays hidden on network failure
+ }
+ if (!Array.isArray(forks) || forks.length === 0) return;
+
+ section.hidden = false;
+ grid.innerHTML = forks
+ .map((f) => {
+ const thumb = f.thumbnail_url
+ ? `<img class="av-used-by-thumb" src="${esc(f.thumbnail_url)}" alt="${esc(f.name)}" loading="lazy" />`
+ : `<div class="av-used-by-thumb av-used-by-thumb--placeholder" aria-hidden="true">${esc((f.name || 'A').slice(0, 1).toUpperCase())}</div>`;
+ const by = f.owner_name ? `<span class="av-used-by-badge">by ${esc(f.owner_name)}</span>` : '';
+ return `<a class="av-used-by-card" href="/avatars/${encodeURIComponent(f.id)}" title="${esc(f.name)}">
+ ${thumb}
+ <div class="av-used-by-meta">
+ <span class="av-used-by-name">${esc(f.name)}</span>
+ ${by}
+ </div>
+ </a>`;
+ })
+ .join('');
+}
+
// ── Related avatars ───────────────────────────────────────────────────
async function loadRelated() {
diff --git a/src/club-entrance.js b/src/club-entrance.js
index 33c6aaf6e..5ef4ae1aa 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -89,15 +89,37 @@ window.addEventListener('club:admitted', () => {
if (onAdmit) onAdmit();
}, { once: true });
+// ── Cinematic loader / intro ────────────────────────────────────────────────
+// Real byte progress across the alley + avatar; no fake timers. Fades out the
+// branded overlay once the scene is ready (or on failure, so nobody's stuck).
+const loaderBar = document.getElementById('club-loader-bar');
+const loaderStatus = document.getElementById('club-loader-status');
+const loadFrac = { alley: 0, avatar: 0 };
+function setLoaderProgress(which, e) {
+ if (which && e && e.total) loadFrac[which] = Math.min(1, e.loaded / e.total);
+ const pct = Math.round(((loadFrac.alley + loadFrac.avatar) / 2) * 100);
+ if (loaderBar) loaderBar.style.width = `${Math.max(4, pct)}%`;
+ if (loaderStatus && pct >= 100) loaderStatus.textContent = 'Step inside.';
+}
+function hideLoader() {
+ const el = document.getElementById('club-loader');
+ if (!el) return;
+ if (loaderBar) loaderBar.style.width = '100%';
+ el.classList.add('is-done');
+}
+
if (canvas && door && !hasValidPass()) {
start(canvas).catch((err) => {
log.warn('[club-entrance] scene failed', err);
// Scene is dead — let the player into the cover flow directly so they're
// never stuck in a broken alley.
+ hideLoader();
try { canvas.remove(); } catch {}
window.dispatchEvent(new CustomEvent('club:enter-door'));
});
} else {
+ // Paid already (or no canvas) — nothing to walk; clear the intro overlay.
+ hideLoader();
canvas?.remove();
}
@@ -184,10 +206,10 @@ async function start(canvasEl) {
];
// Land in the alley + the avatar first; prefetch the rest so each place is
- // ready the moment you walk into it.
+ // ready the moment you walk into it. The loader bar tracks real bytes.
const [firstGltf, avatarGltf, manifest] = await Promise.all([
- loader.loadAsync(SEQUENCE[0].url),
- loader.loadAsync(AVATAR_URL),
+ loader.loadAsync(SEQUENCE[0].url, (e) => setLoaderProgress('alley', e)),
+ loader.loadAsync(AVATAR_URL, (e) => setLoaderProgress('avatar', e)),
fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []),
]);
const loaded = SEQUENCE.map(() => null); // index-aligned gltf cache
@@ -519,6 +541,9 @@ async function start(canvasEl) {
composer.render(dt);
raf = requestAnimationFrame(frame);
}
+ // Draw one frame so the alley is on screen, then lift the intro overlay.
+ composer.render(0);
+ hideLoader();
raf = requestAnimationFrame(frame);
// Move + face the avatar, clamp to the corridor, and drive the walk clip.
diff --git a/src/club.js b/src/club.js
index e3e5b4c75..63543a06e 100644
--- a/src/club.js
+++ b/src/club.js
@@ -15,10 +15,14 @@ import {
BufferGeometry,
Timer,
Color,
+ ConeGeometry,
+ DoubleSide,
EquirectangularReflectionMapping,
Fog,
Group,
HemisphereLight,
+ Mesh,
+ MeshBasicMaterial,
PerspectiveCamera,
PMREMGenerator,
PointLight,
@@ -484,6 +488,43 @@ class PoleStation {
this.spotActiveIntensity = 12.0;
spot.intensity = this.spotIdleIntensity;
+ // Volumetric beam — a translucent cone of light from the spot down to the
+ // stage, additively blended so it reads as haze in the air rather than a
+ // solid object. A per-vertex gradient (bright at the source → black at the
+ // floor) gives the soft falloff without a custom shader; opacity tracks the
+ // spotlight and pulses with the beat (see the render loop). The single
+ // biggest "it feels real" upgrade for the room.
+ const beamH = 6.0;
+ const beamGeo = new ConeGeometry(1.15, beamH, 28, 1, true);
+ const beamColor = new Color(POLE_COLORS[idx % POLE_COLORS.length]);
+ const bpos = beamGeo.attributes.position;
+ const bcol = new Float32Array(bpos.count * 3);
+ for (let i = 0; i < bpos.count; i += 1) {
+ const t = (bpos.getY(i) + beamH / 2) / beamH; // 1 at the apex, 0 at the floor
+ const f = t * t; // bias the glow toward the source
+ bcol[i * 3] = beamColor.r * f;
+ bcol[i * 3 + 1] = beamColor.g * f;
+ bcol[i * 3 + 2] = beamColor.b * f;
+ }
+ beamGeo.setAttribute('color', new BufferAttribute(bcol, 3));
+ const beamMat = new MeshBasicMaterial({
+ vertexColors: true,
+ transparent: true,
+ opacity: 0,
+ blending: AdditiveBlending,
+ depthWrite: false,
+ side: DoubleSide,
+ fog: false,
+ toneMapped: false,
+ });
+ const beam = new Mesh(beamGeo, beamMat);
+ beam.position.set(layout.x, beamH / 2, layout.z); // apex at the spot height, base on the floor
+ beam.renderOrder = 2;
+ scene.add(beam);
+ this.beam = beam;
+ this.beamMat = beamMat;
+ this.beamBaseOpacity = 0.05;
+
// Floor accent point light — sits at the base of the pole.
const accent = new PointLight(POLE_COLORS[idx % POLE_COLORS.length], 0.9, 4.5, 1.6);
accent.position.set(layout.x, 0.6, layout.z);
@@ -807,6 +848,15 @@ class PoleStation {
this.accent.intensity += (this._accentTarget - this.accent.intensity) * Math.min(1, dt * 4);
}
+ // Volumetric beam brightness rides the spotlight: a faint haze when idle,
+ // a thick shaft of light when she's under the hot spot. The beat pulse is
+ // layered on in the render loop.
+ if (this.beamMat) {
+ const span = Math.max(0.001, this.spotActiveIntensity - this.spotIdleIntensity);
+ const norm = Math.max(0, Math.min(1, (this.spot.intensity - this.spotIdleIntensity) / span));
+ this.beamBaseOpacity = 0.045 + norm * 0.17;
+ }
+
// Drive avatar walk between waypoints.
if (this.walkPhase === 'to-pole' || this.walkPhase === 'returning') {
const target = this._phaseTarget;
@@ -1224,6 +1274,9 @@ async function tipDancer({ dancer, dance, button }) {
if (!ticket?.ok) {
throw new Error(ticket?.error || 'tip did not settle');
}
+ // A short triple buzz on phones the moment USDC settles — the tip lands
+ // in your hand the way it lands on stage.
+ try { navigator.vibrate?.([18, 40, 60]); } catch { /* unsupported */ }
station.startPerformance(ticket);
// Crossfade ambience → style loop in sync with the dancer walking
@@ -1585,6 +1638,9 @@ function animate() {
watchdog.tick(dt);
+ // Beat level — drives both the bloom and the volumetric beams this frame.
+ const peak = audio.getPeak();
+
for (const station of stations) {
station.tick(dt);
@@ -1595,6 +1651,13 @@ function animate() {
station.spot.intensity = station.spotIdleIntensity * pulse;
}
+ // Volumetric beam — rides the spotlight (set in tick) and breathes with
+ // the beat so the haze pulses in time with her routine.
+ if (station.beamMat) {
+ station.beamMat.opacity = station.beamBaseOpacity * (1 + peak * 0.9)
+ + Math.sin(t * 1.5 + station.idx) * 0.01;
+ }
+
// Update progress bar for performing stations.
if (station.performing && station.activeUntil > 0) {
const total = (station.activeTicket?.durationSec || 12) * 1000;
@@ -1622,7 +1685,6 @@ function animate() {
clubCam.tick(dt);
// Audio-reactive bloom — pulse intensity with the beat.
- const peak = audio.getPeak();
bloomEffect.intensity = 1.0 + peak * 1.5;
composer.render(dt);
diff --git a/src/launch-detail.css b/src/launch-detail.css
index 714affd9d..b10f80342 100644
--- a/src/launch-detail.css
+++ b/src/launch-detail.css
@@ -519,6 +519,8 @@ body {
.ld-community p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }
.ld-community-ctas, .ld-action-grid { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.ld-action-grid .ld-btn { flex: 1 1 auto; justify-content: center; }
+.ld-actions-foot { display: inline-block; margin-top: var(--space-md); font-size: var(--text-xs); color: var(--ink-dim); text-decoration: none; transition: color var(--duration-fast); }
+.ld-actions-foot:hover { color: var(--ink-bright); }
/* ── Buttons ──────────────────────────────────────────────────────────────── */
diff --git a/src/launch-detail.js b/src/launch-detail.js
index 6633c1fc6..1c02cf551 100644
--- a/src/launch-detail.js
+++ b/src/launch-detail.js
@@ -429,6 +429,142 @@ function renderVerdict() {
section(target, 'Coin Intelligence', body, { tag: 'first ~90s, on-chain' });
}
+// ════════════════════════════════════════════════════════════════════════════
+// SMART MONEY — who is in this coin, and what is their track record
+//
+// The single most actionable question a trader has isn't "what is the chart" —
+// it's "who else is in, and do they win." The Smart Money Radar answers it: it
+// crosses every wallet's footprint in this coin against which coins those same
+// wallets historically graduated, scoring the *pedigree of the money* buying in.
+// Data: /api/pump/smart-money?mint= (404 until the rollup has scored this coin).
+// ════════════════════════════════════════════════════════════════════════════
+
+const WALLET_LABEL = {
+ smart_money: { label: 'Smart money', tone: 'good', tip: 'A wallet with a proven record of buying coins that went on to graduate.' },
+ sniper: { label: 'Sniper', tone: 'warn', tip: 'Habitually grabs supply in the first moments of a launch.' },
+ dumper: { label: 'Dumper', tone: 'danger', tip: 'Tends to sell into early buyers — exits fast.' },
+ rugger: { label: 'Rugger', tone: 'danger', tip: 'Has been tied to coins that rugged.' },
+ fresh: { label: 'Fresh', tone: 'muted', tip: 'A brand-new wallet with no track record yet.' },
+ neutral: { label: 'Neutral', tone: 'muted', tip: 'Trades both ways with no decisive edge.' },
+ unproven: { label: 'Unproven', tone: 'muted', tip: 'Not enough history to judge.' },
+};
+
+function walletRow(w) {
+ const meta = WALLET_LABEL[w.label] || { label: (w.label || 'wallet').replace(/_/g, ' '), tone: 'muted', tip: '' };
+ const winPct = w.win_rate != null ? Math.round(w.win_rate * 100) : null;
+ const record =
+ w.wins != null && w.duds != null && w.wins + w.duds > 0 ? `${w.wins}–${w.duds}` : null;
+
+ return el(
+ 'a',
+ {
+ class: 'ld-sm-row',
+ href: `https://solscan.io/account/${w.wallet}`,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ 'aria-label': `${meta.label} ${shortAddr(w.wallet)} — bought ${fmtSol(w.buy_sol, { sign: false })}`,
+ },
+ [
+ el('span', { class: `ld-sm-dot ld-fill-${meta.tone}`, 'aria-hidden': 'true' }),
+ el('div', { class: 'ld-sm-who' }, [
+ el('span', { class: 'ld-sm-addr', text: shortAddr(w.wallet, 4, 4) }),
+ el('span', { class: `ld-sm-label ld-${meta.tone}`, title: meta.tip, text: meta.label }),
+ ]),
+ el('div', { class: 'ld-sm-rec' }, [
+ winPct != null ? el('span', { class: 'ld-sm-win', text: `${winPct}% win` }) : null,
+ record ? el('span', { class: 'ld-sm-wd', text: record }) : null,
+ ]),
+ el('span', { class: 'ld-sm-buy', text: fmtSol(w.buy_sol, { sign: false }) }),
+ ],
+ );
+}
+
+async function renderSmartMoney() {
+ const target = $('ld-smart');
+ if (state.network !== 'mainnet') {
+ target.hidden = true;
+ return;
+ }
+
+ let data = null;
+ try {
+ data = await fetchJson(`/api/pump/smart-money?mint=${encodeURIComponent(state.mint)}`);
+ } catch {
+ // 404 = the rollup hasn't scored this coin yet (too new, or pre-dates the
+ // engine). Render an honest "not scored yet" rather than hiding the panel.
+ section(
+ target,
+ 'Smart money',
+ el('div', { class: 'ld-empty ld-empty-sm' }, [
+ el('p', { class: 'ld-empty-title', text: 'No smart-money read yet.' }),
+ el('p', {
+ text: 'The radar scores a coin once proven wallets touch it. New launches are picked up within minutes — check back, or watch the live radar.',
+ }),
+ el('a', { class: 'ld-btn ld-btn-ghost', href: '/radar', text: 'Open the Smart Money radar →' }),
+ ]),
+ { tag: 'wallet pedigree' },
+ );
+ return;
+ }
+
+ const coin = data.coin || {};
+ const notable = (data.notable || [])
+ .filter((w) => w && w.wallet)
+ .sort((a, b) => Number(b.buy_sol || 0) - Number(a.buy_sol || 0));
+ const score = Number(coin.smart_money_score);
+ const tone = scoreTone(Number.isFinite(score) ? score : null);
+ const provenSol = Number(coin.proven_buy_sol) || 0;
+ const smartCount =
+ Number(coin.smart_wallet_count) || notable.filter((w) => w.label === 'smart_money').length;
+
+ // The hook line — concrete, FOMO-honest, never synthesized.
+ const lede =
+ smartCount > 0
+ ? `${smartCount} proven ${smartCount === 1 ? 'wallet has' : 'wallets have'} put ${fmtSol(provenSol, { sign: false })} into this coin.`
+ : provenSol > 0
+ ? `${fmtSol(provenSol, { sign: false })} of the money here traces to wallets with a track record.`
+ : 'No wallets with a proven track record have bought this coin yet.';
+
+ const headline = el('div', { class: 'ld-sm-head' }, [
+ el('div', { class: `ld-quality ld-quality-${tone}` }, [
+ el('span', { class: 'ld-quality-num', text: Number.isFinite(score) ? String(Math.round(score)) : '—' }),
+ el('span', { class: 'ld-quality-max', text: 'pedigree' }),
+ ]),
+ el('div', { class: 'ld-verdict-copy' }, [
+ el('span', { class: 'ld-verdict-label', text: 'Smart-money score' }),
+ el('p', { class: 'ld-narrative', text: lede }),
+ ]),
+ ]);
+
+ const children = [headline];
+
+ if (notable.length) {
+ children.push(
+ el('div', { class: 'ld-sm-list' }, [
+ el('div', { class: 'ld-sm-list-head' }, [
+ el('span', { text: 'Wallet' }),
+ el('span', { text: 'Record' }),
+ el('span', { text: 'Bought' }),
+ ]),
+ ...notable.slice(0, 8).map(walletRow),
+ ]),
+ );
+ } else {
+ children.push(
+ el('p', {
+ class: 'ld-agent-note',
+ text: 'The radar is watching, but no notable wallets have surfaced in this coin yet.',
+ }),
+ );
+ }
+
+ children.push(
+ el('a', { class: 'ld-actions-foot', href: '/radar', text: 'See everything the smart money is buying →' }),
+ );
+
+ section(target, 'Smart money', el('div', { class: 'ld-sm' }, children), { tag: 'wallet pedigree' });
+}
+
// ════════════════════════════════════════════════════════════════════════════
// PRICE CHART
// ════════════════════════════════════════════════════════════════════════════
@@ -1013,7 +1149,8 @@ function renderActions() {
buttons.push(watchBtn, shareBtn);
const body = el('div', { class: 'ld-action-grid' }, buttons);
- section(target, 'Take action', body);
+ const foot = el('a', { class: 'ld-actions-foot', href: '/watchlist', text: 'View your watchlist →' });
+ section(target, 'Take action', el('div', {}, [body, foot]));
}
// ════════════════════════════════════════════════════════════════════════════
@@ -1177,6 +1314,7 @@ async function boot() {
// missing data source never blanks the page.
renderHero();
renderVerdict();
+ renderSmartMoney();
renderChart();
renderDistribution();
renderEconomics();
diff --git a/src/oracle.js b/src/oracle.js
index 572678a15..a25d09d54 100644
--- a/src/oracle.js
+++ b/src/oracle.js
@@ -83,6 +83,13 @@ function boot() {
});
$('#catSel').addEventListener('change', (e) => { state.category = e.target.value; loadFeed(); });
$('#minSel').addEventListener('change', (e) => { state.minScore = Number(e.target.value) || 0; loadFeed(); });
+ const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+ $('#mintSearch').addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter') return;
+ const v = e.target.value.trim();
+ if (MINT_RE.test(v)) { openCoin(v); e.target.blur(); }
+ else if (v) { e.target.style.borderColor = 'var(--down)'; setTimeout(() => { e.target.style.borderColor = ''; }, 900); }
+ });
$('#labelSeg').addEventListener('click', (e) => {
const b = e.target.closest('button'); if (!b) return;
$$('#labelSeg button').forEach((x) => x.classList.toggle('on', x === b));
@@ -523,11 +530,21 @@ async function loadActions(agentId) {
const body = $('#actionsBody');
const { ok, data } = await api(`/api/oracle/watch?agent_id=${encodeURIComponent(agentId)}&network=${NETWORK}`);
const actions = ok && data ? (data.actions || []) : [];
+ const s = (ok && data && data.summary) || null;
+ const header = s && s.total ? `
+ <div class="coin-meta" style="margin-bottom:12px">
+ <span class="chip">actions <b>${s.total}</b></span>
+ <span class="chip sm">wins <b>${s.wins}</b></span>
+ <span class="chip flag">losses <b>${s.losses}</b></span>
+ <span class="chip">win rate <b>${s.win_rate == null ? '—' : s.win_rate + '%'}</b></span>
+ <span class="chip ${s.realized_pnl_sol >= 0 ? 'sm' : 'flag'}">PnL <b>${s.realized_pnl_sol >= 0 ? '+' : ''}${fmtSol(s.realized_pnl_sol)}</b></span>
+ ${s.roi_pct != null ? `<span class="chip">ROI <b>${s.roi_pct >= 0 ? '+' : ''}${s.roi_pct}%</b></span>` : ''}
+ </div>` : '';
if (!actions.length) {
- body.innerHTML = '<div class="state">No actions yet. Once armed, your agent\'s moves will appear here and get graded against outcomes.</div>';
+ body.innerHTML = `${header}<div class="state">No actions yet. Once armed, your agent's moves will appear here and get graded against outcomes.</div>`;
return;
}
- body.innerHTML = `<div class="lwrap">${actions.map(actionRow).join('')}</div>`;
+ body.innerHTML = `${header}<div class="lwrap">${actions.map(actionRow).join('')}</div>`;
}
function actionRow(a) {
diff --git a/src/play/arena-world.js b/src/play/arena-world.js
index 3854c0024..d21c3a922 100644
--- a/src/play/arena-world.js
+++ b/src/play/arena-world.js
@@ -66,6 +66,7 @@ export class ArenaWorld {
this._running = false;
this._raf = 0;
this._labels = new Set(); // ArenaAvatar with DOM labels to project
+ this._focus = null; // { x, z, dist, until } cinematic agent focus
this._initRenderer();
this._initScene();
@@ -489,6 +490,7 @@ export class ArenaWorld {
mx += this._move.x; mz -= this._move.y;
const mag = Math.hypot(mx, mz);
const moving = mag > 0.08;
+ if (moving && this._focus) this._focus = null; // walking breaks a focus lock
if (moving) {
const len = Math.max(mag, 1);
mx /= len; mz /= len;
@@ -508,16 +510,33 @@ export class ArenaWorld {
p.setMoving(moving);
}
+ // Cinematically push the camera in on one agent for a few seconds (opening
+ // their detail drawer). Cleared early if the spectator starts walking.
+ focusOnAgent(agentId, ms = 5000) {
+ const a = this.agents.get(agentId);
+ if (!a) return;
+ const p = a.root.position;
+ this._focus = { x: p.x, z: p.z, dist: a.leader ? 6.5 : 5.2, until: performance.now() + ms };
+ // Swing the orbit so the camera ends up looking at the agent from the
+ // spectator's side of the floor (agents are at −Z, viewer at +Z).
+ this._cam.targetYaw = Math.atan2(p.x, p.z + 9) * 0.6;
+ }
+ clearFocus() { this._focus = null; }
+
_updateCamera(dt) {
const c = this._cam;
c.yaw = dampAngle(c.yaw, c.targetYaw, 8 * dt);
- c.dist += (c.targetDist - c.dist) * Math.min(1, 8 * dt);
+ const focusing = this._focus && performance.now() < this._focus.until;
const p = this.player ? this.player.root.position : new Vector3(0, 0, 0);
- // Orbit a point biased from the spectator toward the arena centre so the
- // agent line-up stays in frame while we still follow the player.
- const tx = p.x * 0.55;
- const tz = p.z * 0.5 - 2.0;
- const ty = 1.2;
+ // Orbit the focused agent when one is selected, otherwise a point biased
+ // from the spectator toward the arena centre (keeps the line-up framed).
+ let tx, tz, ty, distTarget;
+ if (focusing) {
+ tx = this._focus.x; tz = this._focus.z; ty = 1.45; distTarget = this._focus.dist;
+ } else {
+ tx = p.x * 0.55; tz = p.z * 0.5 - 2.0; ty = 1.2; distTarget = c.targetDist;
+ }
+ c.dist += (distTarget - c.dist) * Math.min(1, (focusing ? 4 : 8) * dt);
const cx = tx + Math.sin(c.yaw) * Math.cos(c.pitch) * c.dist;
const cz = tz + Math.cos(c.yaw) * Math.cos(c.pitch) * c.dist;
const cy = ty + Math.sin(c.pitch) * c.dist + 1.0;
diff --git a/src/play/arena.js b/src/play/arena.js
index 3c81d5b04..390029c69 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -247,12 +247,129 @@ function updateLabels() {
function focusAgent(id) {
const row = world.agents.get(id);
- if (!row) return;
- world._ringPulse?.(row.root.position, row.color);
- row.emote('buy');
- // Promote into the top card for a beat.
+ if (row) {
+ world._ringPulse?.(row.root.position, row.color);
+ row.emote('buy');
+ world.focusOnAgent(id);
+ }
const L = labelEls.get(id);
if (L) { L.el.classList.add('active'); setTimeout(() => L.el.classList.remove('active'), 2200); }
+ openAgentDrawer(id);
+}
+
+// ── agent detail drawer (real on-chain track record) ────────────────────────────
+
+let drawerAbort = null;
+async function openAgentDrawer(id) {
+ const el = $('agentDrawer');
+ el.classList.add('open');
+ const body = $('drawerBody');
+ body.innerHTML = `<div class="dw-skel"></div><div class="dw-skel"></div><div class="dw-skel" style="height:120px"></div>`;
+ // Cancel any in-flight previous fetch.
+ if (drawerAbort) drawerAbort.abort();
+ drawerAbort = new AbortController();
+ try {
+ const r = await fetch(`/api/sniper/trader?agent_id=${encodeURIComponent(id)}&network=${NETWORK}&window=all`, { signal: drawerAbort.signal });
+ if (!r.ok) throw new Error(r.status === 404 ? 'This trader isn’t public yet.' : `HTTP ${r.status}`);
+ renderAgentDrawer(await r.json(), id);
+ } catch (e) {
+ if (e.name === 'AbortError') return;
+ body.innerHTML = `<div class="dw-empty"><b>Couldn’t load this trader</b>${esc(e.message)}<br/><a href="/trader/${encodeURIComponent(id)}" target="_blank" rel="noopener">Open full profile ↗</a></div>`;
+ }
+}
+
+function closeAgentDrawer() {
+ $('agentDrawer').classList.remove('open');
+ if (drawerAbort) { drawerAbort.abort(); drawerAbort = null; }
+ world.clearFocus?.();
+}
+
+function renderAgentDrawer(data, id) {
+ const m = data.metrics || {};
+ const a = data.agent || {};
+ const verified = m.verified
+ ? '<span class="dw-badge ok">✓ Verified profitable</span>'
+ : '<span class="dw-badge">Building track record</span>';
+ const scoreCls = m.score >= 70 ? 'up' : m.score >= 40 ? '' : 'down';
+ const stat = (label, val, cls = '') => `<div class="dw-stat"><span>${label}</span><b class="${cls}">${val}</b></div>`;
+ const pnlCls = (m.realized_pnl_sol ?? 0) >= 0 ? 'up' : 'down';
+
+ const grid = [
+ stat('Realized P&L', fmtSol(m.realized_pnl_sol) + (m.realized_pnl_usd != null ? `<small> ${fmtUsd(m.realized_pnl_usd)}</small>` : ''), pnlCls),
+ stat('Win rate', m.closed_count ? Math.round(m.win_rate * 100) + '%' : '—'),
+ stat('ROI', m.closed_count ? fmtPct(m.roi_pct) : '—', (m.roi_pct ?? 0) >= 0 ? 'up' : 'down'),
+ stat('Closed trades', m.closed_count ?? 0),
+ stat('Best trade', m.best_pnl_pct != null ? fmtPct(m.best_pnl_pct) : '—', 'up'),
+ stat('Max drawdown', m.max_drawdown_pct != null ? '−' + Math.abs(m.max_drawdown_pct).toFixed(1) + '%' : '—', 'down'),
+ stat('Avg hold', holdLabel(m.avg_hold_seconds)),
+ stat('Open now', m.open_count ?? 0),
+ ].join('');
+
+ const trades = (data.closed || []).slice(0, 8).map((t) => {
+ const win = (t.pnl_sol ?? 0) >= 0;
+ const proof = t.sell_url || t.buy_url;
+ return `<div class="dw-trade">
+ <span class="dw-t-sym">${esc(t.symbol || t.name || (t.mint || '').slice(0, 6))}</span>
+ <span class="dw-t-reason">${esc(t.exit_reason || 'closed')}</span>
+ <span class="dw-t-pnl ${win ? 'up' : 'down'}">${fmtSol(t.pnl_sol)} ${fmtPct(t.pnl_pct)}</span>
+ ${proof ? `<a href="${esc(proof)}" target="_blank" rel="noopener" title="On-chain proof">↗</a>` : '<span class="dw-sim">sim</span>'}
+ </div>`;
+ }).join('') || '<div class="dw-empty" style="padding:14px">No closed trades yet.</div>';
+
+ $('drawerBody').innerHTML = `
+ <div class="dw-head">
+ ${a.image ? `<img src="${esc(a.image)}" alt="" onerror="this.remove()"/>` : '<span class="dw-av-fallback"></span>'}
+ <div>
+ <div class="dw-name">${esc(a.name || 'Agent')}</div>
+ <div class="dw-sub">${verified}</div>
+ </div>
+ <div class="dw-score ${scoreCls}"><b>${m.score ?? 0}</b><span>score</span></div>
+ </div>
+ ${sparkline(data.closed || [])}
+ <div class="dw-grid">${grid}</div>
+ <div class="dw-section-h">Recent closed trades · every one on-chain</div>
+ <div class="dw-trades">${trades}</div>
+ <div class="dw-cta">
+ <a class="btn primary" href="/trader/${encodeURIComponent(id)}" target="_blank" rel="noopener">Full proof &amp; copy ↗</a>
+ ${a.wallet ? `<a class="btn" href="https://solscan.io/account/${esc(a.wallet)}" target="_blank" rel="noopener">Wallet ↗</a>` : ''}
+ </div>`;
+}
+
+// Cumulative realized-P&L equity curve from the closed ledger (chronological).
+function sparkline(closed) {
+ const chron = [...closed].filter((t) => t.pnl_sol != null)
+ .sort((x, y) => new Date(x.closed_at) - new Date(y.closed_at));
+ if (chron.length < 2) return '';
+ let cum = 0; const pts = [0];
+ for (const t of chron) { cum += t.pnl_sol; pts.push(cum); }
+ const min = Math.min(...pts), max = Math.max(...pts), range = (max - min) || 1;
+ const W = 280, H = 56;
+ const coords = pts.map((v, i) => [
+ (i / (pts.length - 1)) * W,
+ H - ((v - min) / range) * (H - 6) - 3,
+ ]);
+ const d = coords.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
+ const up = cum >= 0;
+ const col = up ? 'var(--up)' : 'var(--down)';
+ const area = `${d} L${W},${H} L0,${H} Z`;
+ const zeroY = (H - ((0 - min) / range) * (H - 6) - 3).toFixed(1);
+ return `<svg class="dw-spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true">
+ <line x1="0" y1="${zeroY}" x2="${W}" y2="${zeroY}" stroke="rgba(255,255,255,.12)" stroke-dasharray="3 3"/>
+ <path d="${area}" fill="${col}" opacity="0.12"/>
+ <path d="${d}" fill="none" stroke="${col}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
+ </svg>`;
+}
+
+function fmtUsd(n) {
+ if (n == null) return '';
+ const s = Math.abs(n) >= 1000 ? `$${Math.round(n).toLocaleString('en-US')}` : `$${Number(n).toFixed(2)}`;
+ return (n < 0 ? '−' : '') + s.replace('-', '');
+}
+function holdLabel(sec) {
+ if (!sec) return '—';
+ if (sec < 90) return `${Math.round(sec)}s`;
+ if (sec < 5400) return `${Math.round(sec / 60)}m`;
+ return `${(sec / 3600).toFixed(1)}h`;
}
// ── HUD: leaderboard, top card, tape, banner ────────────────────────────────────
@@ -342,7 +459,8 @@ function mountControls() {
$('emptyPick')?.addEventListener('click', openPicker);
// Collapse side panels on mobile.
$('togglePanels')?.addEventListener('click', () => document.body.classList.toggle('panels-open'));
- window.addEventListener('keydown', (e) => { if (e.key === 'Escape') closePicker(); });
+ $('drawerClose')?.addEventListener('click', closeAgentDrawer);
+ window.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePicker(); closeAgentDrawer(); } });
}
let pickerLoaded = false;
diff --git a/src/watchlist.css b/src/watchlist.css
new file mode 100644
index 000000000..b43220b92
--- /dev/null
+++ b/src/watchlist.css
@@ -0,0 +1,205 @@
+/* /watchlist — coins the trader is tracking (device-local).
+ Token-driven (public/tokens.css via nav.css); shares the editorial language
+ of /launches. The coin cards themselves are rendered by the shared
+ coin-status widget (csc-* classes); this file styles the page chrome, the
+ card wrapper, and the empty state. */
+
+body {
+ margin: 0;
+ background: var(--bg-0);
+ color: var(--ink);
+ font-family: var(--font-body);
+ overflow-x: hidden;
+}
+
+#wl-field {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ pointer-events: none;
+ opacity: 0.8;
+}
+.wl-aurora {
+ position: fixed;
+ inset: -20%;
+ z-index: 0;
+ pointer-events: none;
+ background:
+ radial-gradient(36% 28% at 16% 10%, var(--accent-soft), transparent 70%),
+ radial-gradient(30% 26% at 86% 26%, var(--surface-3), transparent 70%),
+ radial-gradient(40% 34% at 60% 96%, var(--surface-2), transparent 72%);
+ filter: blur(52px);
+ animation: wl-drift 28s var(--ease-standard) infinite alternate;
+}
+@keyframes wl-drift {
+ from { transform: translate3d(-1.5%, -1%, 0) scale(1); }
+ to { transform: translate3d(1.5%, 2%, 0) scale(1.06); }
+}
+@media (prefers-reduced-motion: reduce) { .wl-aurora { animation: none; } }
+
+.wl-shell {
+ position: relative;
+ z-index: 1;
+ max-width: 1120px;
+ margin: 0 auto;
+ padding: calc(var(--header-h) + var(--space-2xl)) var(--space-lg) var(--space-2xl);
+}
+
+/* ── Hero ─────────────────────────────────────────────────────────────────── */
+
+.wl-hero { margin-bottom: var(--space-xl); }
+.wl-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-semibold);
+ letter-spacing: 0.2em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-md);
+ padding: var(--space-xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-1);
+ backdrop-filter: blur(var(--blur-sm));
+}
+.wl-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--success);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent);
+ animation: wl-pulse 1.8s var(--ease-standard) infinite;
+}
+@keyframes wl-pulse {
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent); }
+ 70% { box-shadow: 0 0 0 6px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+@media (prefers-reduced-motion: reduce) { .wl-live-dot { animation: none; } }
+
+.wl-title {
+ margin: 0 0 var(--space-sm);
+ font-family: var(--font-display);
+ font-size: var(--text-3xl);
+ font-weight: var(--weight-bold);
+ letter-spacing: -0.03em;
+ color: var(--ink-bright);
+ line-height: 1;
+}
+.wl-sub {
+ margin: 0 0 var(--space-lg);
+ max-width: 56ch;
+ font-size: var(--text-md);
+ color: var(--ink-dim);
+ line-height: 1.55;
+}
+.wl-hero-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: var(--space-sm);
+}
+.wl-count { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-dim); }
+.wl-hero-ctas { display: flex; gap: var(--space-sm); }
+
+/* ── Grid + cards ─────────────────────────────────────────────────────────── */
+
+.wl-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: var(--space-md);
+}
+.wl-card {
+ position: relative;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: linear-gradient(165deg, var(--surface-2), transparent 55%), var(--surface-1);
+ box-shadow: var(--shadow-1);
+ backdrop-filter: blur(var(--blur-sm));
+ padding: var(--space-md);
+ overflow: hidden;
+ transition: border-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-base) var(--ease-standard), transform var(--duration-base) var(--ease-standard);
+}
+.wl-card:hover { border-color: var(--stroke-strong); box-shadow: var(--shadow-3); transform: translateY(-2px); }
+.wl-in { animation: wl-reveal var(--duration-slow) var(--ease-emphasized) both; }
+@keyframes wl-reveal { from { opacity: 0; transform: translateY(14px) scale(0.985); } to { opacity: 1; transform: none; } }
+@media (prefers-reduced-motion: reduce) { .wl-in { animation: none; } .wl-card:hover { transform: none; } }
+
+.wl-card-link {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ border-radius: inherit;
+ cursor: pointer;
+}
+.wl-card-link:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: -2px;
+}
+.wl-market { position: relative; z-index: 0; }
+
+.wl-remove {
+ position: absolute;
+ top: var(--space-xs);
+ right: var(--space-xs);
+ z-index: 2;
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ background: var(--surface-2);
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity var(--duration-fast), color var(--duration-fast), border-color var(--duration-fast);
+}
+.wl-card:hover .wl-remove,
+.wl-remove:focus-visible { opacity: 1; }
+.wl-remove:hover { color: var(--danger); border-color: var(--danger); }
+@media (hover: none) { .wl-remove { opacity: 1; } }
+
+/* ── Empty state ──────────────────────────────────────────────────────────── */
+
+.wl-state { margin-top: var(--space-md); }
+.wl-empty {
+ text-align: center;
+ max-width: 460px;
+ margin: var(--space-2xl) auto;
+}
+.wl-empty-glyph { width: 72px; height: 72px; margin: 0 auto var(--space-md); opacity: 0.7; }
+.wl-empty-glyph svg { width: 100%; height: 100%; }
+.wl-empty h2 { font-family: var(--font-display); font-size: var(--text-xl); color: var(--ink-bright); margin: 0 0 var(--space-sm); }
+.wl-empty p { color: var(--ink-dim); margin: 0 0 var(--space-lg); line-height: 1.55; }
+.wl-empty-ctas { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; }
+
+/* ── Buttons ──────────────────────────────────────────────────────────────── */
+
+.wl-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-medium);
+ text-decoration: none;
+ cursor: pointer;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm) var(--space-md);
+ background: var(--surface-2);
+ color: var(--ink);
+ transition: transform var(--duration-fast) var(--ease-standard), background var(--duration-fast), border-color var(--duration-fast), color var(--duration-fast);
+}
+.wl-btn:hover { transform: translateY(-1px); border-color: var(--ink-dim); color: var(--ink-bright); }
+.wl-btn:active { transform: translateY(0); }
+.wl-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }
+.wl-btn-primary { background: var(--accent); color: var(--bg-0); border-color: var(--accent); }
+.wl-btn-primary:hover { color: var(--bg-0); filter: brightness(1.08); }
+.wl-btn-ghost { background: transparent; }
diff --git a/src/watchlist.js b/src/watchlist.js
new file mode 100644
index 000000000..691206bfb
--- /dev/null
+++ b/src/watchlist.js
@@ -0,0 +1,307 @@
+// ════════════════════════════════════════════════════════════════════════════
+// /watchlist — the coins a trader is tracking.
+//
+// Closes the loop opened by the "Watch" button on every coin profile
+// (/launches/<mint>): that button writes a mint into localStorage under
+// `ld_watchlist`; this page reads it back and renders each as a live status
+// card (shared coin-status widget → one /api/pump/coin fetch per coin), linking
+// straight back to the full profile. The list is device-local and private —
+// no account required — and stays in sync across tabs via the storage event.
+// ════════════════════════════════════════════════════════════════════════════
+
+import { mountCoinStatus } from './pump/coin-status-card.js';
+
+const WATCH_KEY = 'ld_watchlist'; // shared with src/launch-detail.js
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const feedEl = document.getElementById('wl-feed');
+const stateEl = document.getElementById('wl-state');
+const countEl = document.getElementById('wl-count');
+const clearBtn = document.getElementById('wl-clear');
+
+const handles = new Set();
+
+// ── DOM helper ───────────────────────────────────────────────────────────────
+
+function el(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children || [])) {
+ if (c == null || c === false) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+}
+
+const SVG_NS = 'http://www.w3.org/2000/svg';
+function svgEl(tag, attrs) {
+ const node = document.createElementNS(SVG_NS, tag);
+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
+ return node;
+}
+
+// Deterministic orbital glyph seeded from the mint — the placeholder behind the
+// real pump.fun logo (matches the /launches feed identicon language).
+function hashString(str) {
+ let h = 2166136261;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+function mulberry32(seed) {
+ let a = seed;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+function mintIdenticon(mint) {
+ const rand = mulberry32(hashString(String(mint)));
+ const svg = svgEl('svg', { viewBox: '0 0 64 64', 'aria-hidden': 'true' });
+ svg.style.color = 'var(--ink-dim)';
+ const cx = 32;
+ const cy = 32;
+ const rings = 3 + Math.floor(rand() * 2);
+ for (let i = 0; i < rings; i++) {
+ const r = 8 + i * (20 / rings) + rand() * 4;
+ const circumference = 2 * Math.PI * r;
+ const dashOn = circumference * (0.18 + rand() * 0.55);
+ svg.appendChild(
+ svgEl('circle', {
+ cx, cy, r: r.toFixed(1), fill: 'none', stroke: 'currentColor',
+ 'stroke-width': (0.7 + rand() * 0.9).toFixed(2),
+ 'stroke-dasharray': `${dashOn.toFixed(1)} ${(circumference - dashOn).toFixed(1)}`,
+ 'stroke-linecap': 'round', opacity: (0.3 + rand() * 0.45).toFixed(2),
+ transform: `rotate(${Math.floor(rand() * 360)} ${cx} ${cy})`,
+ }),
+ );
+ if (rand() > 0.35) {
+ const theta = rand() * Math.PI * 2;
+ svg.appendChild(
+ svgEl('circle', {
+ cx: (cx + Math.cos(theta) * r).toFixed(1),
+ cy: (cy + Math.sin(theta) * r).toFixed(1),
+ r: (1 + rand() * 1.8).toFixed(1), fill: 'currentColor',
+ opacity: (0.5 + rand() * 0.5).toFixed(2),
+ }),
+ );
+ }
+ }
+ svg.appendChild(svgEl('circle', { cx, cy, r: '3.2', fill: 'currentColor', opacity: '0.9', style: 'color: var(--ink-bright)' }));
+ return svg;
+}
+
+// ── storage ──────────────────────────────────────────────────────────────────
+
+function readList() {
+ try {
+ const arr = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
+ return Array.isArray(arr) ? arr.filter((m) => MINT_RE.test(m)) : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeList(list) {
+ try {
+ localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, 200)));
+ } catch {
+ /* storage blocked — non-fatal */
+ }
+}
+
+function remove(mint) {
+ writeList(readList().filter((m) => m !== mint));
+ render();
+}
+
+// ── teardown ─────────────────────────────────────────────────────────────────
+
+function teardown() {
+ for (const h of handles) {
+ try {
+ h.destroy();
+ } catch {
+ /* ignore */
+ }
+ }
+ handles.clear();
+}
+
+// ── cards ────────────────────────────────────────────────────────────────────
+
+function watchCard(mint, index) {
+ const link = el('a', {
+ class: 'wl-card-link',
+ href: `/launches/${mint}`,
+ 'aria-label': 'Open coin profile',
+ });
+ const market = el('div', { class: 'wl-market' });
+ const removeBtn = el('button', {
+ class: 'wl-remove',
+ type: 'button',
+ 'aria-label': 'Remove from watchlist',
+ title: 'Remove from watchlist',
+ text: '✕',
+ onclick: (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ remove(mint);
+ },
+ });
+ const card = el('article', { class: 'wl-card' }, [link, removeBtn, market]);
+ if (!REDUCED_MOTION) {
+ card.style.animationDelay = `${Math.min(index, 12) * 40}ms`;
+ card.classList.add('wl-in');
+ }
+ handles.add(mountCoinStatus(market, mint, { variant: 'card', placeholder: mintIdenticon(mint) }));
+ return card;
+}
+
+// ── states ───────────────────────────────────────────────────────────────────
+
+function renderEmpty() {
+ stateEl.replaceChildren(
+ el('div', { class: 'wl-empty' }, [
+ el('div', { class: 'wl-empty-glyph', 'aria-hidden': 'true' }, [mintIdenticon('three.ws-watchlist-empty')]),
+ el('h2', { text: 'Nothing on your watchlist yet' }),
+ el('p', { text: 'Tap ☆ Watch on any coin to pin it here. Your list lives privately in this browser and updates with live market data.' }),
+ el('div', { class: 'wl-empty-ctas' }, [
+ el('a', { class: 'wl-btn wl-btn-primary', href: '/launches', text: 'Explore launches' }),
+ el('a', { class: 'wl-btn', href: '/radar', text: 'Open the radar' }),
+ ]),
+ ]),
+ );
+}
+
+function render() {
+ teardown();
+ feedEl.replaceChildren();
+ stateEl.replaceChildren();
+
+ const list = readList();
+ const n = list.length;
+ countEl.textContent = n ? `${n} coin${n === 1 ? '' : 's'} watched` : '';
+ clearBtn.hidden = n === 0;
+
+ if (n === 0) {
+ feedEl.setAttribute('aria-busy', 'false');
+ renderEmpty();
+ return;
+ }
+
+ list.forEach((mint, i) => feedEl.appendChild(watchCard(mint, i)));
+ feedEl.setAttribute('aria-busy', 'false');
+}
+
+// ── ambient field (shared visual language) ──────────────────────────────────
+
+function startParticleField() {
+ const canvas = document.getElementById('wl-field');
+ if (!canvas) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+ let width = 0;
+ let height = 0;
+ let particles = [];
+ let inkRGB = '232,232,232';
+ let raf = 0;
+ const readInk = () => {
+ const scheme = getComputedStyle(document.documentElement).getPropertyValue('color-scheme');
+ inkRGB = scheme.includes('light') ? '20,24,34' : '232,232,232';
+ };
+ const resize = () => {
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
+ width = window.innerWidth;
+ height = window.innerHeight;
+ canvas.width = width * dpr;
+ canvas.height = height * dpr;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ const target = Math.min(60, Math.floor((width * height) / 32000));
+ particles = Array.from({ length: target }, () => ({
+ x: Math.random() * width,
+ y: Math.random() * height,
+ vx: (Math.random() - 0.5) * 0.1,
+ vy: (Math.random() - 0.5) * 0.1,
+ r: 0.6 + Math.random() * 1,
+ }));
+ };
+ const draw = () => {
+ ctx.clearRect(0, 0, width, height);
+ for (const p of particles) {
+ p.x += p.vx;
+ p.y += p.vy;
+ if (p.x < -10) p.x = width + 10;
+ if (p.x > width + 10) p.x = -10;
+ if (p.y < -10) p.y = height + 10;
+ if (p.y > height + 10) p.y = -10;
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
+ ctx.fillStyle = `rgba(${inkRGB},0.13)`;
+ ctx.fill();
+ }
+ for (let i = 0; i < particles.length; i++) {
+ for (let j = i + 1; j < particles.length; j++) {
+ const a = particles[i];
+ const b = particles[j];
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ const d2 = dx * dx + dy * dy;
+ if (d2 < 12100) {
+ const alpha = 0.04 * (1 - Math.sqrt(d2) / 110);
+ ctx.beginPath();
+ ctx.moveTo(a.x, a.y);
+ ctx.lineTo(b.x, b.y);
+ ctx.strokeStyle = `rgba(${inkRGB},${alpha.toFixed(3)})`;
+ ctx.lineWidth = 0.6;
+ ctx.stroke();
+ }
+ }
+ }
+ };
+ const loop = () => {
+ draw();
+ raf = requestAnimationFrame(loop);
+ };
+ readInk();
+ resize();
+ window.addEventListener('resize', resize, { passive: true });
+ new MutationObserver(readInk).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
+ if (REDUCED_MOTION) {
+ draw();
+ return;
+ }
+ loop();
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) cancelAnimationFrame(raf);
+ else loop();
+ });
+}
+
+// ── boot ─────────────────────────────────────────────────────────────────────
+
+clearBtn.addEventListener('click', () => {
+ if (!readList().length) return;
+ writeList([]);
+ render();
+});
+
+// Keep in sync if the user watches/unwatches a coin in another tab.
+window.addEventListener('storage', (e) => {
+ if (e.key === WATCH_KEY) render();
+});
+
+startParticleField();
+render();
diff --git a/tests/copy-engine.test.js b/tests/copy-engine.test.js
new file mode 100644
index 000000000..a04f48854
--- /dev/null
+++ b/tests/copy-engine.test.js
@@ -0,0 +1,156 @@
+/**
+ * Copy-trading decision engine — pure logic tests.
+ * Money-adjacent, so every sizing path, cap, budget, and safety gate is pinned.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ planCopyOrder, normalizeSubscriptionInput, rawOrderSol, evaluateSafety,
+} from '../api/_lib/copy-engine.js';
+
+const baseSub = {
+ status: 'active',
+ sizing_rule: 'fixed',
+ fixed_sol: 0.2,
+ multiplier: 0.1,
+ pct_balance: 10,
+ per_trade_cap_sol: 0.5,
+ min_order_sol: 0.02,
+ daily_budget_sol: 1,
+ max_open_copies: 5,
+ mcap_floor_usd: null,
+ mcap_ceiling_usd: null,
+ copy_sells: true,
+ require_safety_pass: false,
+};
+const buy = (entry = 1) => ({ direction: 'buy', entry_sol: entry, mint: 'M', symbol: 'X' });
+
+describe('rawOrderSol', () => {
+ it('fixed → the fixed amount', () => {
+ expect(rawOrderSol(baseSub, { leaderEntrySol: 5 })).toBe(0.2);
+ });
+ it('multiplier → leader entry × multiplier', () => {
+ expect(rawOrderSol({ ...baseSub, sizing_rule: 'multiplier' }, { leaderEntrySol: 4 })).toBeCloseTo(0.4, 6);
+ });
+ it('pct_balance → % of copier balance, NaN without balance', () => {
+ expect(rawOrderSol({ ...baseSub, sizing_rule: 'pct_balance' }, { copierBalanceSol: 2 })).toBeCloseTo(0.2, 6);
+ expect(Number.isNaN(rawOrderSol({ ...baseSub, sizing_rule: 'pct_balance' }, {}))).toBe(true);
+ });
+});
+
+describe('planCopyOrder — sizing & caps', () => {
+ it('sizes a fixed buy', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: buy(1) });
+ expect(d.action).toBe('copy');
+ expect(d.order_sol).toBe(0.2);
+ });
+
+ it('clamps to the per-trade cap', () => {
+ const sub = { ...baseSub, sizing_rule: 'multiplier', multiplier: 1 };
+ const d = planCopyOrder({ subscription: sub, position: buy(5) }); // raw 5 → cap 0.5
+ expect(d.order_sol).toBe(0.5);
+ });
+
+ it('clamps to remaining daily budget', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: buy(1), spentTodaySol: 0.9 });
+ expect(d.order_sol).toBeCloseTo(0.1, 6); // 1.0 budget − 0.9 spent
+ });
+
+ it('skips when the daily budget is exhausted', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: buy(1), spentTodaySol: 1 });
+ expect(d.action).toBe('skip');
+ expect(d.reason).toBe('daily_budget_spent');
+ });
+
+ it('skips when the sized order is below the minimum', () => {
+ const sub = { ...baseSub, sizing_rule: 'multiplier', multiplier: 0.001 };
+ const d = planCopyOrder({ subscription: sub, position: buy(1) }); // 0.001 < 0.02
+ expect(d.action).toBe('skip');
+ expect(d.reason).toBe('below_min_order');
+ });
+
+ it('skips pct_balance sizing when balance is unknown', () => {
+ const d = planCopyOrder({ subscription: { ...baseSub, sizing_rule: 'pct_balance' }, position: buy(1) });
+ expect(d.action).toBe('skip');
+ expect(d.reason).toBe('sizing_unavailable');
+ });
+});
+
+describe('planCopyOrder — guards', () => {
+ it('skips an inactive subscription', () => {
+ const d = planCopyOrder({ subscription: { ...baseSub, status: 'paused' }, position: buy(1) });
+ expect(d.reason).toBe('subscription_inactive');
+ });
+
+ it('enforces the open-copies cap', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: buy(1), openCopies: 5 });
+ expect(d.action).toBe('skip');
+ expect(d.reason).toBe('max_open_copies');
+ });
+
+ it('mirrors a sell with zero new SOL when copy_sells is on', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: { direction: 'sell', mint: 'M', entry_sol: 1 } });
+ expect(d.action).toBe('copy');
+ expect(d.direction).toBe('sell');
+ expect(d.order_sol).toBe(0);
+ });
+
+ it('skips a sell when copy_sells is off', () => {
+ const d = planCopyOrder({ subscription: { ...baseSub, copy_sells: false }, position: { direction: 'sell', mint: 'M' } });
+ expect(d.reason).toBe('sells_disabled');
+ });
+});
+
+describe('evaluateSafety / planCopyOrder safety gate', () => {
+ it('passes when no context and safety not required', () => {
+ expect(evaluateSafety(baseSub, null).ok).toBe(true);
+ });
+ it('fails when no context and safety required', () => {
+ const r = evaluateSafety({ ...baseSub, require_safety_pass: true }, null);
+ expect(r.ok).toBe(false);
+ expect(r.reason).toBe('safety_unknown');
+ });
+ it('blocks a honeypot', () => {
+ expect(evaluateSafety(baseSub, { honeypot: true }).reason).toBe('honeypot');
+ });
+ it('enforces the market-cap floor and ceiling', () => {
+ expect(evaluateSafety({ ...baseSub, mcap_floor_usd: 20000 }, { market_cap_usd: 5000 }).reason).toBe('below_mcap_floor');
+ expect(evaluateSafety({ ...baseSub, mcap_ceiling_usd: 50000 }, { market_cap_usd: 90000 }).reason).toBe('above_mcap_ceiling');
+ expect(evaluateSafety({ ...baseSub, mcap_floor_usd: 1000, mcap_ceiling_usd: 100000 }, { market_cap_usd: 30000 }).ok).toBe(true);
+ });
+ it('blocks dev-heavy supply and thin liquidity', () => {
+ expect(evaluateSafety(baseSub, { dev_holding_pct: 40 }).reason).toBe('dev_heavy');
+ expect(evaluateSafety(baseSub, { liquidity_usd: 500 }).reason).toBe('low_liquidity');
+ });
+ it('a buy into a flagged coin is skipped end-to-end', () => {
+ const d = planCopyOrder({ subscription: baseSub, position: buy(1), coin: { honeypot: true } });
+ expect(d.action).toBe('skip');
+ expect(d.reason).toBe('honeypot');
+ });
+});
+
+describe('normalizeSubscriptionInput', () => {
+ it('accepts a valid fixed config and applies defaults', () => {
+ const r = normalizeSubscriptionInput({ sizing_rule: 'fixed', fixed_sol: 0.3, per_trade_cap_sol: 1, daily_budget_sol: 2 });
+ expect(r.ok).toBe(true);
+ expect(r.value.fixed_sol).toBe(0.3);
+ expect(r.value.max_open_copies).toBe(5);
+ expect(r.value.perf_fee_bps).toBe(1000);
+ });
+ it('rejects a non-positive cap / budget', () => {
+ expect(normalizeSubscriptionInput({ per_trade_cap_sol: 0, daily_budget_sol: 1, fixed_sol: 1 }).ok).toBe(false);
+ expect(normalizeSubscriptionInput({ per_trade_cap_sol: 1, daily_budget_sol: 0, fixed_sol: 1 }).ok).toBe(false);
+ });
+ it('rejects min above cap', () => {
+ const r = normalizeSubscriptionInput({ per_trade_cap_sol: 0.1, min_order_sol: 0.5, daily_budget_sol: 1, fixed_sol: 0.05 });
+ expect(r.ok).toBe(false);
+ });
+ it('validates per-rule required fields', () => {
+ expect(normalizeSubscriptionInput({ sizing_rule: 'fixed', fixed_sol: 0, per_trade_cap_sol: 1, daily_budget_sol: 1 }).ok).toBe(false);
+ expect(normalizeSubscriptionInput({ sizing_rule: 'multiplier', multiplier: 0, per_trade_cap_sol: 1, daily_budget_sol: 1 }).ok).toBe(false);
+ expect(normalizeSubscriptionInput({ sizing_rule: 'pct_balance', pct_balance: 150, per_trade_cap_sol: 1, daily_budget_sol: 1 }).ok).toBe(false);
+ });
+ it('clamps perf fee to the allowed band', () => {
+ expect(normalizeSubscriptionInput({ perf_fee_bps: 5000, per_trade_cap_sol: 1, daily_budget_sol: 1, fixed_sol: 1 }).ok).toBe(false);
+ });
+});
diff --git a/tests/oracle/settle.test.js b/tests/oracle/settle.test.js
new file mode 100644
index 000000000..deddff8c4
--- /dev/null
+++ b/tests/oracle/settle.test.js
@@ -0,0 +1,63 @@
+// Oracle settle — grading & summary. The honest win-rate record depends on this.
+
+import { describe, it, expect } from 'vitest';
+import { gradeAction, summarizeActions } from '../../api/_lib/oracle/settle.js';
+
+describe('gradeAction', () => {
+ it('stays open with no outcome row', () => {
+ expect(gradeAction({ size_sol: 0.05 }, null).outcome).toBe('open');
+ });
+
+ it('stays open when the outcome row carries no resolved signal', () => {
+ const g = gradeAction({ size_sol: 0.05, entry_mc_usd: 10000 }, { graduated: false, rugged: false, ath_multiple: null, last_market_cap_usd: null });
+ expect(g.settled).toBe(false);
+ expect(g.outcome).toBe('open');
+ });
+
+ it('grades a graduation as a win', () => {
+ const g = gradeAction({ size_sol: 0.1, entry_mc_usd: 10000 }, { graduated: true, ath_multiple: 8, last_market_cap_usd: 60000 });
+ expect(g.outcome).toBe('win');
+ expect(g.peak_multiple).toBe(8);
+ expect(g.realized_pnl_sol).toBeCloseTo(0.1 * (6 - 1), 5); // last/entry = 6
+ });
+
+ it('grades a high ATH multiple as a win even without graduation', () => {
+ expect(gradeAction({ size_sol: 0.05 }, { graduated: false, ath_multiple: 3 }).outcome).toBe('win');
+ });
+
+ it('grades a rug as a loss', () => {
+ expect(gradeAction({ size_sol: 0.05, entry_mc_usd: 10000 }, { rugged: true, last_market_cap_usd: 1000 }).outcome).toBe('loss');
+ });
+
+ it('grades a deep markdown as a loss', () => {
+ expect(gradeAction({ size_sol: 0.05, entry_mc_usd: 10000 }, { ath_multiple: 1.1, last_market_cap_usd: 3000 }).outcome).toBe('loss');
+ });
+
+ it('computes honest mark-to-market PnL from entry vs last', () => {
+ const g = gradeAction({ size_sol: 1, entry_mc_usd: 10000 }, { graduated: true, ath_multiple: 2, last_market_cap_usd: 5000 });
+ expect(g.realized_pnl_sol).toBeCloseTo(-0.5, 5); // halved
+ });
+});
+
+describe('summarizeActions', () => {
+ it('rolls wins/losses into a win rate and ROI', () => {
+ const s = summarizeActions([
+ { outcome: 'win', realized_pnl_sol: 0.5, size_sol: 0.1 },
+ { outcome: 'win', realized_pnl_sol: 0.2, size_sol: 0.1 },
+ { outcome: 'loss', realized_pnl_sol: -0.1, size_sol: 0.1 },
+ { outcome: 'open', realized_pnl_sol: null, size_sol: 0.1 },
+ ]);
+ expect(s.wins).toBe(2);
+ expect(s.losses).toBe(1);
+ expect(s.open).toBe(1);
+ expect(s.win_rate).toBe(67); // 2/3
+ expect(s.realized_pnl_sol).toBeCloseTo(0.6, 5);
+ expect(s.roi_pct).toBe(150); // 0.6 / 0.4
+ });
+
+ it('handles an empty ledger', () => {
+ const s = summarizeActions([]);
+ expect(s.total).toBe(0);
+ expect(s.win_rate).toBeNull();
+ });
+});
diff --git a/tests/oracle/sources.test.js b/tests/oracle/sources.test.js
new file mode 100644
index 000000000..7bcbc6507
--- /dev/null
+++ b/tests/oracle/sources.test.js
@@ -0,0 +1,71 @@
+// Oracle source adapter — toCoinIntel mapping. Pure given its row inputs, so we
+// pin the brain→CoinIntel translation (lamports, proxies, narrative fallback)
+// that the conviction engine depends on.
+
+import { describe, it, expect } from 'vitest';
+import { toCoinIntel } from '../../api/_lib/oracle/sources.js';
+
+const coinRow = {
+ mint: 'MintAAA', symbol: 'AAA', name: 'Alpha', image_uri: 'x', category: 'ai',
+ narrative: 'an AI agent', classify_confidence: 0.7,
+ created_at: '2026-06-16T00:00:00Z', first_seen_at: '2026-06-16T00:00:01Z',
+ dev_buy_lamports: '500000000', dev_sold: false, dev_sell_lamports: '0',
+ buy_count: 30, sell_count: 4, buy_volume_lamports: '5000000000', sell_volume_lamports: '400000000',
+ unique_buyers: 42, largest_buy_lamports: '1000000000',
+ bundle_score: 0.2, organic_score: 0.8, concentration_top10: 0.35, bubblemap_connectivity: 0.1,
+ quality_score: 74, risk_flags: [],
+};
+
+describe('toCoinIntel', () => {
+ it('maps lamports to SOL and percentages to 0..100', () => {
+ const ci = toCoinIntel({ coin: coinRow, smart: null, narr: null });
+ expect(ci.behavior.devBuySol).toBeCloseTo(0.5, 6);
+ expect(ci.behavior.buyVolSol).toBeCloseTo(5, 6);
+ expect(ci.structure.organicScore).toBeCloseTo(80, 6);
+ expect(ci.structure.bundleScore).toBeCloseTo(20, 6);
+ expect(ci.structure.top10Pct).toBeCloseTo(35, 6);
+ // largest buy 1 SOL / 5 SOL volume = 20% top-holder proxy
+ expect(ci.structure.topHolderPct).toBeCloseTo(20, 6);
+ });
+
+ it('flags a bundle when bundle_score is high or risk_flags say so', () => {
+ expect(toCoinIntel({ coin: { ...coinRow, bundle_score: 0.7 }, smart: null, narr: null }).structure.bundleFlag).toBe(true);
+ expect(toCoinIntel({ coin: { ...coinRow, risk_flags: ['bundle_launch'] }, smart: null, narr: null }).structure.bundleFlag).toBe(true);
+ expect(toCoinIntel({ coin: coinRow, smart: null, narr: null }).structure.bundleFlag).toBe(false);
+ });
+
+ it('computes devSoldPct only when the dev has sold', () => {
+ const sold = toCoinIntel({ coin: { ...coinRow, dev_sold: true, dev_sell_lamports: '250000000' }, smart: null, narr: null });
+ expect(sold.structure.devSoldPct).toBeCloseTo(50, 6); // 0.25 / 0.5
+ expect(toCoinIntel({ coin: coinRow, smart: null, narr: null }).structure.devSoldPct).toBe(0);
+ });
+
+ it('prefers an Oracle narrative (with virality) over the brain category', () => {
+ const withNarr = toCoinIntel({ coin: coinRow, smart: null, narr: { category: 'news', narrative: 'live headline', virality: 88, confidence: 0.9 } });
+ expect(withNarr.narrative.category).toBe('news');
+ expect(withNarr.narrative.virality).toBe(88);
+ expect(withNarr.category).toBe('news');
+ });
+
+ it('falls back to the brain category with a virality proxy when no Oracle narrative', () => {
+ const ci = toCoinIntel({ coin: coinRow, smart: null, narr: null });
+ expect(ci.narrative.category).toBe('ai');
+ expect(ci.narrative.virality).toBeGreaterThan(0); // proxy from quality + organic
+ });
+
+ it('reads smart-money pedigree and notable wallets', () => {
+ const ci = toCoinIntel({
+ coin: coinRow,
+ smart: { smart_money_score: 82, smart_wallet_count: 3, proven_buy_lamports: '2000000000', total_buy_lamports: '5000000000', notable: [{ wallet: 'w', label: 'smart_money', score: 90 }] },
+ narr: null,
+ });
+ expect(ci.smartMoney.score).toBe(82);
+ expect(ci.smartMoney.smartWalletCount).toBe(3);
+ expect(ci.smartMoney.notable).toHaveLength(1);
+ });
+
+ it('parses notable when stored as a JSON string', () => {
+ const ci = toCoinIntel({ coin: coinRow, smart: { notable: '[{"wallet":"w","label":"sniper","score":50}]' }, narr: null });
+ expect(ci.smartMoney.notable[0].label).toBe('sniper');
+ });
+});
diff --git a/vercel.json b/vercel.json
index f1a325f43..5b5e69555 100644
--- a/vercel.json
+++ b/vercel.json
@@ -65,6 +65,10 @@
"api/cron/forge-seed-cron.js": {
"maxDuration": 55
},
+ "api/cron/oracle-score.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 120
+ },
"api/cron/[name].js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
@@ -117,6 +121,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
},
+ "api/pump/coin-intel.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 30
+ },
"api/**/*.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
@@ -529,6 +537,10 @@
"src": "/launches/?",
"dest": "/launches.html"
},
+ {
+ "src": "/watchlist/?",
+ "dest": "/watchlist.html"
+ },
{
"src": "/leaderboard/?",
"dest": "/leaderboard.html"
@@ -1683,6 +1695,10 @@
"src": "/api/pump/launch-detail",
"dest": "/api/pump/launch-detail.js"
},
+ {
+ "src": "/api/pump/coin-intel",
+ "dest": "/api/pump/coin-intel.js"
+ },
{
"src": "/api/pump/build-metadata",
"dest": "/api/pump/[action]?action=build-metadata"
@@ -3163,6 +3179,10 @@
"path": "/api/cron/intel-learn",
"schedule": "*/15 * * * *"
},
+ {
+ "path": "/api/cron/oracle-score",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/quota-check",
"schedule": "0 * * * *"
diff --git a/vite.config.js b/vite.config.js
index 7142dba7e..3f78446e1 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -313,6 +313,7 @@ const appConfig = {
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
launches: resolve(__dirname, 'pages/launches.html'),
'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),
+ watchlist: resolve(__dirname, 'pages/watchlist.html'),
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
trader: resolve(__dirname, 'pages/trader.html'),
'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),
@@ -667,6 +668,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/bounties/': resolve(root, 'pages/bounties.html'),
'/launches': resolve(root, 'pages/launches.html'),
'/launches/': resolve(root, 'pages/launches.html'),
+ '/watchlist': resolve(root, 'pages/watchlist.html'),
+ '/watchlist/': resolve(root, 'pages/watchlist.html'),
'/leaderboard': resolve(root, 'pages/leaderboard.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
'/trader': resolve(root, 'pages/trader.html'),
diff --git a/workers/oracle/agent-loop.js b/workers/oracle/agent-loop.js
index b23a8b42b..ca99a63d9 100644
--- a/workers/oracle/agent-loop.js
+++ b/workers/oracle/agent-loop.js
@@ -23,7 +23,9 @@ async function armedWatches(network) {
`.catch(() => []);
}
-async function freshlyScored(network, sinceIso, limit = 60) {
+/** Coins scored since a cursor — the work list for the agent loop. Exported so
+ * the serverless cron can pull a fixed recent window instead of a live cursor. */
+export async function freshlyScored(network, sinceIso, limit = 60) {
return sql`
select mint, symbol, score, tier, category, smart_wallet_count, scored_at
from oracle_conviction
@@ -41,15 +43,17 @@ async function alreadyActed(agentId, mint, network) {
return r.length > 0;
}
-export async function runAgentPass(cfg) {
- if (cfg.globalKill) return 0;
+/**
+ * Run every armed watch against a given set of freshly-scored coins. Pure of the
+ * cursor so both the long-lived loop and the serverless cron share one code path.
+ * Each (agent, mint) acts at most once via the `alreadyActed` guard, so passing
+ * an overlapping window across invocations is safe and idempotent.
+ */
+export async function actOnFreshCoins(cfg, coins) {
+ if (cfg.globalKill || !coins.length) return 0;
const watches = await armedWatches(cfg.network);
if (!watches.length) return 0;
- const coins = await freshlyScored(cfg.network, cursor);
- if (coins.length) cursor = coins[coins.length - 1].scored_at;
- if (!coins.length) return 0;
-
let acted = 0;
for (const watch of watches) {
const { openCount, spentTodaySol } = await agentBudget(watch.agent_id, cfg.network);
@@ -65,3 +69,10 @@ export async function runAgentPass(cfg) {
if (acted) log.info(`agent loop: ${acted} action(s) across ${watches.length} armed agent(s)`);
return acted;
}
+
+export async function runAgentPass(cfg) {
+ if (cfg.globalKill) return 0;
+ const coins = await freshlyScored(cfg.network, cursor);
+ if (coins.length) cursor = coins[coins.length - 1].scored_at;
+ return actOnFreshCoins(cfg, coins);
+}
diff --git a/workers/oracle/config.js b/workers/oracle/config.js
index 294e9ad28..f87d2c06b 100644
--- a/workers/oracle/config.js
+++ b/workers/oracle/config.js
@@ -16,6 +16,7 @@ export function loadConfig() {
globalKill: process.env.ORACLE_GLOBAL_KILL === '1',
scoreIntervalMs: num(process.env.ORACLE_SCORE_INTERVAL_MS, 15_000),
agentIntervalMs: num(process.env.ORACLE_AGENT_INTERVAL_MS, 3_000),
+ settleIntervalMs: num(process.env.ORACLE_SETTLE_INTERVAL_MS, 60_000),
scoreBatch: num(process.env.ORACLE_SCORE_BATCH, 20),
rescoreAfterSec: num(process.env.ORACLE_RESCORE_AFTER_SEC, 180),
// Hard ceiling on any single live action, regardless of a watch's config —
diff --git a/workers/oracle/index.js b/workers/oracle/index.js
index 6e87faae2..3e76978b3 100644
--- a/workers/oracle/index.js
+++ b/workers/oracle/index.js
@@ -15,6 +15,7 @@ import { loadConfig } from './config.js';
import { log } from './log.js';
import { runScorePass } from './score-loop.js';
import { runAgentPass } from './agent-loop.js';
+import { runSettlePass } from './settle-loop.js';
async function main() {
const cfg = loadConfig();
@@ -38,6 +39,7 @@ async function main() {
loop('score', runScorePass, cfg.scoreIntervalMs);
loop('agent', runAgentPass, cfg.agentIntervalMs);
+ loop('settle', runSettlePass, cfg.settleIntervalMs);
}
main().catch((e) => { log.error('fatal:', e?.message || e); process.exit(1); });
diff --git a/workers/oracle/settle-loop.js b/workers/oracle/settle-loop.js
new file mode 100644
index 000000000..2d7b83c99
--- /dev/null
+++ b/workers/oracle/settle-loop.js
@@ -0,0 +1,51 @@
+// Oracle worker — settle loop (the learning loop).
+//
+// Grades open agent actions against the data brain's ground-truth outcomes. Once
+// a coin an agent acted on has resolved (graduated / rugged / ATH known), the
+// action's win/loss + mark-to-market PnL is written back. This is what makes the
+// agent's win-rate ledger honest and what feeds the conviction backtest.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+import { gradeAction } from '../../api/_lib/oracle/settle.js';
+
+/** Open actions whose coin now has a resolved outcome. */
+async function settleableActions(cfg, limit = 100) {
+ return sql`
+ select a.id, a.size_sol, a.entry_mc_usd,
+ o.graduated, o.rugged, o.ath_multiple, o.last_market_cap_usd
+ from oracle_watch_actions a
+ join pump_coin_outcomes o on o.mint = a.mint
+ where a.network = ${cfg.network}
+ and (a.outcome is null or a.outcome = 'open')
+ and (o.graduated is true or o.rugged is true or o.ath_multiple is not null or o.last_market_cap_usd is not null)
+ order by a.acted_at asc
+ limit ${limit}
+ `.catch((e) => { log.warn('settleable query failed:', e.message); return []; });
+}
+
+export async function runSettlePass(cfg) {
+ const rows = await settleableActions(cfg);
+ if (!rows.length) return 0;
+ let settled = 0;
+ for (const r of rows) {
+ const g = gradeAction(
+ { size_sol: r.size_sol, entry_mc_usd: r.entry_mc_usd },
+ { graduated: r.graduated, rugged: r.rugged, ath_multiple: r.ath_multiple, last_market_cap_usd: r.last_market_cap_usd },
+ );
+ if (!g.settled) continue;
+ try {
+ await sql`
+ update oracle_watch_actions
+ set outcome = ${g.outcome}, peak_multiple = ${g.peak_multiple},
+ realized_pnl_sol = ${g.realized_pnl_sol}, settled_at = now()
+ where id = ${r.id}
+ `;
+ settled += 1;
+ } catch (e) {
+ log.warn(`settle action ${r.id} failed:`, e.message);
+ }
+ }
+ if (settled) log.info(`settled ${settled} action(s)`);
+ return settled;
+}