Skip to content

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

feat: add risk acknowledgment module and tests for Jito tip accounts

nrpo545e56ffb24a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a25a59081..bd9b7e332 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Ring economy dashboard — watch the closed loop breathe** — The self-cycled x402 ring economy now has a live operator dashboard. A per-minute settlement pulse shows the heartbeat at a glance — a spark strip where any gap is instantly visible, plus a big “minutes since last settle” number that turns green, amber, then red as the tick slows or stops. A loop diagram traces payer → endpoint → treasury → sweep with live on-chain wallet balances and floor indicators; a streaming feed shows every paid call with the buying agent, endpoint, price, and its explorer link, and flags skips and failures with their exact reason instead of dropping them silently. Fee-burn efficiency, leak-scan and reconciliation integrity, and per-endpoint coverage each get a panel. It is admin-only and clearly labels all ring volume as internal dogfooding, not organic revenue — so “it stopped working” can never again go unnoticed for days. `[feature]`
- **Ring settlements stay in-house — routing made truthful, mis-config now caught** — The closed-loop agent economy is built so no third party ever touches a ring settlement — but the configuration used to say one thing while the code did another: the setup guide claimed the platform's own facilitator was 'always-on' while Solana payments still defaulted to an outside settlement service. That contradiction is gone. When the self-hosted facilitator is switched on, ring payments now settle through it by default, and an explicitly-set external facilitator is the only thing that overrides that — no other coin or user rail is affected. Just as important, a mis-configured deploy now says so loudly instead of silently sending volume elsewhere: the status and ring reports list every problem — facilitator disabled, settlement pointing at an outside service, a missing treasury or fee-payer key, a per-call price set above the per-run cap — so operators can confirm the whole envelope is correct before funding anything. A clean deploy shows an empty warnings list. `[fix, infra]`
- **Ring wallets: watched for drain, auto-refilled, and verifiable in one command** — The three platform wallets that power the closed-loop agent economy — the one that pays, the one that receives, and the one that covers network fees — are now monitored and self-healing so the loop can run unattended without silently stalling or draining. A balance monitor checks all three on-chain every ten minutes and pages operators before trouble: the fee and paying wallets alert when their SOL dips near the level where settlements would be refused, and the paying wallet alerts when its USDC float runs low. The receiving wallet is intentionally left unbounded — it fills up and gets swept back automatically, so a low balance there is healthy, not a problem. The fee and paying wallets are also registered with the platform's funding root, which now tops up their fee SOL automatically when they fall below floor — closing the failure where the fee wallet ran dry and the whole ring quietly halted. A new one-command check confirms every wallet is correctly configured, registered, and reachable, prints their live balances, and refuses to pass on any mismatch, without ever exposing a secret. A funding runbook documents exactly how much to send and how to confirm it landed. `[infra, security]`
+- **Shared wallet Trader Cards now unfurl with real stats** — Sharing a claimed wallet's Trader Card used to preview with the generic site image — only three.ws agents got the rich social card. Now /trader/<wallet>/share bakes a real card for any indexed wallet: smart-money score gauge, win rate, coins traded, realized P&L, and the wallet's archetype, all pulled from the same on-chain reputation ledger the profile shows. The share button on wallet profiles now hands out this link, and a wallet the engine hasn't indexed yet routes to the plain profile instead of shipping an empty preview. (`/claim-wallet`) `[improvement, fix]`
+- **Sniper dashboard now connects to everything your bots touch** — Monitoring your trading agents no longer dead-ends at a status badge. Every stat tile at the top of Sniper Strategies is now a shortcut — click Open positions to jump straight to the live feed, or Closed trades to land on your history. Each strategy card shows the bot's live open positions inside the card, with a running "2 open · +0.004 ◎" ticker right on the collapsed row so you can scan all your agents at a glance. Every coin name — in live positions and trade history — now opens that coin's full detail page (conviction score, holders, live trade tape), and the live positions panel links directly to your Portfolio and the Trading desk. (`/dashboard/sniper`) `[improvement]`
- **Status page now shows internal dependency health, not just uptime** — The public status page and the platform health API now report the health of the systems behind the surfaces — cache, database, Solana RPC, the x402 payment ring, and the world service — not only whether each page returns. A surface can answer normally while a dependency is quietly running on a fallback (cache on memory, RPC throttled, the payment ring half-configured); those states are now visible with a plain-language explanation and the exact fix, instead of being buried in server logs. The monitor also re-alerts on a degradation that persists rather than going silent after the first notice, and posts a recovery note when it clears. (`/status`) `[improvement]`
- **The leaderboard now shows what each trader made it on** — Every ranked trader now carries their signature coin — the single token they earned (or lost) the most on, with the realized P&L and ROI to match. It shows up right on the leaderboard row next to the name, on the trader's profile as a "Made it on" breakdown of their top three coins (each linking to the coin's on-chain account), and on the shareable PnL card. A new Most Profitable Trader spotlight now crowns the top earner in the selected window at the top of the board — avatar, realized P&L, win rate, and the coin behind the run. Every number is computed from the same on-chain closed-trade ledger the rest of the track record uses, so the coin credited on the leaderboard, the profile, and the card can never disagree — and self-dealt coins a trader launched themselves are excluded from the credit, exactly as they already are from the score. (`/leaderboard`) `[feature, improvement]`
- **The Live Trading Theater got more alive — and shows its guardrails** — A pass of polish across the 3D stage: performers now cast contact shadows so no one floats, the camera pushes in on a marquee fill, the celebration coin scales with the real size of the buy, and receipts show the coin ticker. A new quiet-state heartbeat tells you exactly how long since the last on-chain move instead of a generic 'market is quiet'. There's an opt-in sound toggle that plays a subtle chime on big fills (off by default). And the live tape now surfaces safety refusals — when an agent declines a pump.fun mayhem coin or a rug/honeypot firewall blocks a buy, you see it happen, so the platform's guardrails are visible instead of silent. (`/theater`) `[improvement]`
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index ba5d7a956..b4a0f8a65 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -348,6 +348,40 @@ export function checkDailyBudgetLamports(spentLamports, amountLamports, budgetLa
return null;
}
+/**
+ * Realized-loss circuit breaker. Blocked when an agent's NET realized P&L over
+ * the trailing window is a loss deeper than `lossLimitLamports`.
+ *
+ * This is the portfolio-layer guard the per-trade caps (budget, headroom, price
+ * impact) don't provide: a fleet armed with a valid band can still bleed out one
+ * losing entry at a time. Once the day's realized loss crosses the limit the
+ * agent stops opening new positions — and, critically, the auto-funder stops
+ * refilling it (see workers/agent-sniper/auto-funder.js), so the master wallet
+ * can't keep pouring SOL after a wallet that only loses. The exact shape of the
+ * rug-buy + auto-refill incident.
+ *
+ * `netRealizedLamports` is SIGNED: negative = net loss, positive = net profit.
+ * A profitable or break-even day never blocks. `null`/`0` limit disables it.
+ *
+ * @param {bigint|string|number} netRealizedLamports signed net realized P&L
+ * @param {bigint|string|number|null} lossLimitLamports max tolerated loss (positive magnitude)
+ * @returns {{ reason: string, detail: object }|null}
+ */
+export function checkDailyLoss(netRealizedLamports, lossLimitLamports) {
+ if (lossLimitLamports == null) return null;
+ const limit = BigInt(lossLimitLamports);
+ if (limit <= 0n) return null;
+ const net = BigInt(netRealizedLamports);
+ const loss = net < 0n ? -net : 0n;
+ if (loss >= limit) {
+ return {
+ reason: 'daily_loss_limit',
+ detail: { loss_lamports: loss.toString(), limit_lamports: limit.toString() },
+ };
+ }
+ return null;
+}
+
/** Wallet must cover the spend plus a fee/rent headroom. Blocked when short. */
export function checkSolHeadroom(walletLamports, spendLamports, headroomLamports = SOL_FEE_HEADROOM_LAMPORTS) {
const wallet = BigInt(walletLamports);
diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.js
index 8bd3d5ebc..71fa66a58 100644
--- a/api/_lib/execution-engine.js
+++ b/api/_lib/execution-engine.js
@@ -53,7 +53,7 @@ import {
const JITO_TIP_ACCOUNTS = [
'96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',
'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',
- 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghp5dF6',
+ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY',
'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',
'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',
'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',
diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.js
index c2143dbca..9072d381e 100644
--- a/api/_lib/trader-stats.js
+++ b/api/_lib/trader-stats.js
@@ -112,6 +112,33 @@ function maxDrawdown(closedOrderedLamports) {
return { sol: maxDropLamports / LAMPORTS_PER_SOL, pct: maxDropPct };
}
+/**
+ * Compact cumulative-realized-equity series (SOL) for a sparkline. Takes the
+ * per-close realized P&L in lamports, oldest→newest, and returns the running
+ * equity in SOL downsampled to at most `maxPoints` points — small enough to ship
+ * on every one of the ~100 leaderboard rows without bloating the payload, yet
+ * enough to read the shape of the run. The last point is always the final
+ * realized equity so the sparkline's endpoint matches the row's headline P&L.
+ * Fewer than two closes returns [] (the caller renders a flat "no trend yet"
+ * placeholder rather than a misleading single dot).
+ */
+function cumulativeEquitySeries(pnlsLamports, maxPoints = 24) {
+ if (!Array.isArray(pnlsLamports) || pnlsLamports.length < 2) return [];
+ const equity = [];
+ let running = 0;
+ for (const p of pnlsLamports) {
+ running += p;
+ equity.push(running / LAMPORTS_PER_SOL);
+ }
+ if (equity.length <= maxPoints) return equity.map((v) => Number(v.toFixed(4)));
+ // Even stride, but force-include the final point so the endpoint is exact.
+ const out = [];
+ const stride = (equity.length - 1) / (maxPoints - 1);
+ for (let i = 0; i < maxPoints - 1; i++) out.push(equity[Math.round(i * stride)]);
+ out.push(equity[equity.length - 1]);
+ return out.map((v) => Number(v.toFixed(4)));
+}
+
/**
* Compute the full metric set for one trader from their position rows.
*
@@ -348,6 +375,11 @@ export function computeTraderMetrics(positions, { solUsd = null, selfDealMints =
max_drawdown_sol: Number(drawdown.sol.toFixed(6)),
max_drawdown_pct: Number(drawdown.pct.toFixed(2)),
+ // Compact cumulative-realized-equity curve (SOL, oldest→newest, ≤24 pts) so
+ // the leaderboard row and profile can draw a P&L sparkline without a second
+ // query. Endpoint equals realized_pnl_sol; [] when < 2 closed trades.
+ pnl_series: cumulativeEquitySeries(equityPnls),
+
avg_hold_seconds: Math.round(avgHoldSeconds),
median_hold_seconds: Math.round(median(holdSorted)),
unique_coins: coins.size,
@@ -885,6 +917,7 @@ export async function getLeaderboard({
avg_pnl_pct: m.avg_pnl_pct,
best_pnl_pct: m.best_pnl_pct,
max_drawdown_pct: m.max_drawdown_pct,
+ pnl_series: m.pnl_series,
avg_hold_seconds: m.avg_hold_seconds,
unique_coins: m.unique_coins,
churn_pct: m.churn_pct,
diff --git a/api/legal/risk-ack.js b/api/legal/risk-ack.js
new file mode 100644
index 000000000..1f9558393
--- /dev/null
+++ b/api/legal/risk-ack.js
@@ -0,0 +1,52 @@
+// /api/legal/risk-ack — record a user's acceptance of the Risk Disclosure.
+//
+// POST /api/legal/risk-ack { version, context?, path? } → 200 { ok: true }
+//
+// The client-side gate (public/risk-ack.js) fires this after the user accepts
+// the real-funds risk acknowledgment. The acceptance itself lives in the
+// browser (localStorage, versioned); this endpoint writes the durable
+// server-side record into audit_log — who (when signed in), which disclosure
+// version, from which feature ('trade', 'snipe', 'x402-pay', …), when, from
+// where. audit_log has no retention pruning, so acceptance records persist.
+//
+// Anonymous acceptances are recorded too (userId null): the gate also runs in
+// third-party x402 embeds and pre-auth flows where no session exists.
+
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { logAudit } from '../_lib/audit.js';
+
+const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;
+const PATH = /^\/[\x20-\x7e]{0,199}$/;
+
+export default wrap(async function handler(req, res) {
+ // '*' origin: the acknowledgment modal also runs inside the drop-in x402
+ // embed on merchant sites; acceptance recording must not be blocked there.
+ // Those requests are credential-less, so '*' is safe.
+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req, 10_000).catch(() => null);
+ const version = Number(body?.version);
+ if (!Number.isInteger(version) || version < 1 || version > 1_000) {
+ return error(res, 400, 'invalid_version', 'version must be a positive integer');
+ }
+ const context = typeof body?.context === 'string' && SLUG.test(body.context) ? body.context : null;
+ const path = typeof body?.path === 'string' && PATH.test(body.path) ? body.path : null;
+
+ const user = await getSessionUser(req).catch(() => null);
+
+ logAudit({
+ userId: user?.id ?? null,
+ action: 'risk-ack-accept',
+ resourceId: null,
+ meta: { version, context, path },
+ req,
+ });
+
+ return json(res, 200, { ok: true });
+});
diff --git a/api/trader-og.js b/api/trader-og.js
index 11363e59b..3014dbbe4 100644
--- a/api/trader-og.js
+++ b/api/trader-og.js
@@ -1,9 +1,13 @@
/**
- * GET /api/trader-og?agent_id=<uuid>
+ * GET /api/trader-og?agent_id=<uuid> — three.ws agent card
+ * GET /api/trader-og?wallet=<base58> — claimed/external wallet card
+ * (a base58 value in agent_id is treated as a wallet, matching the
+ * /trader/<id>/share rewrite which passes either kind of id)
*
* Dynamic OG image for /trader/<id>/share — provable track record social card.
- * SVG 1200×630. Shows agent name, score gauge arc, win rate, realized P&L, and
- * closed trade count so every shared trader link previews with real data.
+ * SVG 1200×630. Agent cards read agent_sniper_positions; wallet cards read the
+ * Oracle wallet_reputation ledger + pump_coin_wallets aggregates, so every
+ * shared trader link — agent or claimed wallet — previews with real data.
*
* Card anatomy (1200×630, dark):
* top — three.ws wordmark + "proof.not.promises"
@@ -18,8 +22,17 @@ import { cors, wrap } from './_lib/http.js';
import { sql } from './_lib/db.js';
import { isUuid } from './_lib/validate.js';
-const LAMPORTS = 1e9;
-const CACHE = 'public, max-age=120, s-maxage=900, stale-while-revalidate=60';
+const LAMPORTS = 1e9;
+const CACHE = 'public, max-age=120, s-maxage=900, stale-while-revalidate=60';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+/** wallet_reputation stores win_rate as a 0–1 fraction; normalize to 0–100. */
+function pct(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ if (!Number.isFinite(n)) return null;
+ return Math.round(n <= 1 ? n * 100 : n);
+}
function x(s) {
return String(s || '')
@@ -34,43 +47,93 @@ function trunc(s, n) {
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
- const agentId = (url.searchParams.get('agent_id') || '').trim();
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const agentId = (url.searchParams.get('agent_id') || '').trim();
+ const walletParam = (url.searchParams.get('wallet') || '').trim();
+ const wallet = BASE58_RE.test(walletParam) ? walletParam
+ : (!isUuid(agentId) && BASE58_RE.test(agentId)) ? agentId
+ : '';
- if (!isUuid(agentId)) {
+ if (!isUuid(agentId) && !wallet) {
return fallback(res);
}
- let agent, stats;
- try {
- [agent] = await sql`
- select id, name, profile_image_url, avatar_url
- from agent_identities
- where id = ${agentId} and deleted_at is null
- limit 1
- `;
- if (!agent) return fallback(res);
-
- [stats] = await sql`
- select
- count(*) filter (where status = 'closed') as total,
- count(*) filter (where status = 'closed' and realized_pnl_pct >= 0) as wins,
- sum(realized_pnl_lamports) filter (where status = 'closed') as pnl_lam,
- max(realized_pnl_pct) as best_pct,
- avg(realized_pnl_pct) filter (where status = 'closed') as avg_pct
- from agent_sniper_positions
- where agent_id = ${agentId} and network = 'mainnet'
- `;
- } catch {
- return fallback(res);
- }
+ // Unified card shape, filled by whichever identity we were given.
+ let name, subtitle, initial, avatarUrl = null, footerPath;
+ let total, winRate, pnlSol, bestPct, gaugeVal, gaugeLabel, totalLabel;
- const name = trunc(agent.name || 'Agent', 28);
- const total = Number(stats?.total || 0);
- const wins = Number(stats?.wins || 0);
- const winRate = total > 0 ? Math.round((wins / total) * 100) : null;
- const pnlSol = stats?.pnl_lam != null ? Number(BigInt(stats.pnl_lam)) / LAMPORTS : null;
- const bestPct = stats?.best_pct != null ? Number(stats.best_pct) : null;
+ if (wallet) {
+ let rep, agg;
+ try {
+ [rep] = await sql`
+ select coins_traded, wins, win_rate, smart_money_score, label
+ from wallet_reputation
+ where wallet = ${wallet} and network = 'mainnet'
+ limit 1
+ `;
+ [agg] = await sql`
+ select
+ sum(sell_lamports - buy_lamports) as pnl_lam,
+ max(case when buy_lamports > 0
+ then (sell_lamports - buy_lamports) * 100.0 / buy_lamports end) as best_pct
+ from pump_coin_wallets
+ where wallet = ${wallet}
+ `;
+ } catch {
+ return fallback(res);
+ }
+ if (!rep) return fallback(res);
+
+ name = `${wallet.slice(0, 4)}…${wallet.slice(-4)}`;
+ initial = wallet[0].toUpperCase();
+ total = Number(rep.coins_traded || 0);
+ winRate = pct(rep.win_rate);
+ gaugeVal = rep.smart_money_score != null ? Math.round(Number(rep.smart_money_score)) : null;
+ gaugeLabel = 'SMART SCORE';
+ totalLabel = 'COINS TRADED';
+ pnlSol = agg?.pnl_lam != null ? Number(agg.pnl_lam) / LAMPORTS : null;
+ bestPct = agg?.best_pct != null ? Number(agg.best_pct) : null;
+ subtitle = `Claimed Solana wallet · ${rep.label ? String(rep.label).replace(/_/g, ' ') : 'trader'} · ${total || '—'} coins traded`;
+ footerPath = 'three.ws/claim-wallet';
+ } else {
+ let agent, stats;
+ try {
+ [agent] = await sql`
+ select id, name, profile_image_url, avatar_url
+ from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return fallback(res);
+
+ [stats] = await sql`
+ select
+ count(*) filter (where status = 'closed') as total,
+ count(*) filter (where status = 'closed' and realized_pnl_pct >= 0) as wins,
+ sum(realized_pnl_lamports) filter (where status = 'closed') as pnl_lam,
+ max(realized_pnl_pct) as best_pct,
+ avg(realized_pnl_pct) filter (where status = 'closed') as avg_pct
+ from agent_sniper_positions
+ where agent_id = ${agentId} and network = 'mainnet'
+ `;
+ } catch {
+ return fallback(res);
+ }
+
+ name = trunc(agent.name || 'Agent', 28);
+ initial = (agent.name || 'A')[0].toUpperCase();
+ avatarUrl = agent.profile_image_url || agent.avatar_url;
+ total = Number(stats?.total || 0);
+ const wins = Number(stats?.wins || 0);
+ winRate = total > 0 ? Math.round((wins / total) * 100) : null;
+ gaugeVal = winRate;
+ gaugeLabel = 'WIN RATE';
+ totalLabel = 'CLOSED TRADES';
+ pnlSol = stats?.pnl_lam != null ? Number(BigInt(stats.pnl_lam)) / LAMPORTS : null;
+ bestPct = stats?.best_pct != null ? Number(stats.best_pct) : null;
+ subtitle = `Provable pump.fun track record · ${total > 0 ? total : '—'} trades closed`;
+ footerPath = 'three.ws/leaderboard';
+ }
const winRateStr = winRate != null ? `${winRate}%` : '—';
const pnlStr = pnlSol != null
@@ -78,6 +141,9 @@ export default wrap(async (req, res) => {
: '—';
const bestStr = bestPct != null ? `+${Math.round(bestPct)}%` : '—';
const totalStr = total > 0 ? String(total) : '—';
+ const gaugeStr = gaugeVal != null
+ ? (gaugeLabel === 'WIN RATE' ? `${gaugeVal}%` : String(gaugeVal))
+ : '—';
const scoreColor = winRate == null ? '#94a3b8'
: winRate >= 60 ? '#34d399'
@@ -85,7 +151,7 @@ export default wrap(async (req, res) => {
: '#f87171';
// SVG gauge arc: 140° sweep, radius 52, center 156,180
- const arcScore = winRate ?? 0;
+ const arcScore = gaugeVal ?? 0;
const ARC_START_DEG = -200;
const ARC_SWEEP_DEG = 220;
const r = 52;
@@ -104,7 +170,6 @@ export default wrap(async (req, res) => {
// Fetch avatar if URL available (base64 embed)
let avatarData = null;
- const avatarUrl = agent.profile_image_url || agent.avatar_url;
if (avatarUrl && avatarUrl.startsWith('http')) {
try {
const imgResp = await fetch(avatarUrl, { signal: AbortSignal.timeout(3000) });
@@ -150,7 +215,7 @@ export default wrap(async (req, res) => {
x="${cx - 44}" y="28" width="88" height="88" clip-path="url(#avClip)"/>`
: `<circle cx="${cx}" cy="72" r="44" fill="#1e293b"/>
<text x="${cx}" y="80" text-anchor="middle" font-family="Inter,system-ui,sans-serif"
- font-size="36" font-weight="700" fill="#374151">${x((agent.name || 'A')[0].toUpperCase())}</text>`}
+ font-size="36" font-weight="700" fill="#374151">${x(initial)}</text>`}
<circle cx="${cx}" cy="72" r="44" fill="none" stroke="${x(scoreColor)}" stroke-width="2" opacity=".5"/>
<!-- score arc track -->
@@ -161,21 +226,21 @@ export default wrap(async (req, res) => {
fill="none" stroke="url(#gfill)" stroke-width="7" stroke-linecap="round"/>`
: ''}
<text x="${cx}" y="${cy - 8}" text-anchor="middle" font-family="Inter,system-ui,sans-serif"
- font-size="28" font-weight="800" fill="${x(scoreColor)}">${x(winRateStr)}</text>
+ font-size="28" font-weight="800" fill="${x(scoreColor)}">${x(gaugeStr)}</text>
<text x="${cx}" y="${cy + 10}" text-anchor="middle" font-family="Inter,system-ui,sans-serif"
- font-size="10" font-weight="600" fill="#6b7280" letter-spacing=".1em">WIN RATE</text>
+ font-size="10" font-weight="600" fill="#6b7280" letter-spacing=".1em">${x(gaugeLabel)}</text>
<!-- agent name -->
<text x="308" y="116" font-family="Inter,system-ui,sans-serif" font-size="44" font-weight="800"
fill="#f9fafb">${x(name)}</text>
<text x="308" y="146" font-family="Inter,system-ui,sans-serif" font-size="15" fill="#6b7280">
- Provable pump.fun track record · ${x(totalStr)} trades closed
+ ${x(subtitle)}
</text>
<!-- metric cards -->
${metricCard(308, 188, 'REALIZED P&amp;L', pnlStr, pnlSol != null && pnlSol >= 0 ? '#34d399' : pnlSol != null ? '#f87171' : '#6b7280')}
${metricCard(568, 188, 'WIN RATE', winRateStr, scoreColor)}
- ${metricCard(828, 188, 'CLOSED TRADES', totalStr, '#94a3b8')}
+ ${metricCard(828, 188, totalLabel, totalStr, '#94a3b8')}
${metricCard(1048, 188, 'BEST TRADE', bestStr, '#c084fc')}
<!-- separator -->
@@ -191,7 +256,7 @@ export default wrap(async (req, res) => {
<text x="24" y="618" font-family="Inter,system-ui,sans-serif" font-size="12" fill="#374151"
letter-spacing=".08em">PROVABLE TRACK RECORD</text>
<text x="1176" y="618" font-family="Inter,system-ui,sans-serif" font-size="12" fill="#374151"
- text-anchor="end">three.ws/leaderboard</text>
+ text-anchor="end">${x(footerPath)}</text>
</svg>`;
res.statusCode = 200;
diff --git a/api/trader-share.js b/api/trader-share.js
index 8d6342b7d..96dcb81e6 100644
--- a/api/trader-share.js
+++ b/api/trader-share.js
@@ -1,15 +1,17 @@
/**
* SSR share page for trader track records
* ----------------------------------------
- * GET /api/trader-share?agent_id=<uuid>
+ * GET /api/trader-share?agent_id=<uuid> — three.ws agent
+ * GET /api/trader-share?agent_id=<base58> — claimed/external wallet
*
- * Wired via vercel.json: /trader/<agent_id>/share → /api/trader-share?agent_id=$1
+ * Wired via vercel.json: /trader/<id>/share → /api/trader-share?agent_id=$1
+ * (the rewrite passes either kind of id; base58 is treated as a wallet)
*
* Bakes Open Graph + Twitter Card + Farcaster Frame meta into <head> so social
* crawlers render a rich preview with the trader's score, P&L, and win rate.
- * Real browsers are JS-redirected to /trader/<agent_id> for the full profile.
+ * Real browsers are JS-redirected to /trader/<id> for the full profile.
*
- * OG image: /api/trader-og?agent_id=<uuid>
+ * OG image: /api/trader-og?agent_id=<uuid> | /api/trader-og?wallet=<base58>
*/
import { sql } from './_lib/db.js';
@@ -17,7 +19,8 @@ import { cors, wrap } from './_lib/http.js';
import { env } from './_lib/env.js';
import { isUuid } from './_lib/validate.js';
-const LAMPORTS = 1e9;
+const LAMPORTS = 1e9;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -26,7 +29,10 @@ export default wrap(async (req, res) => {
const agentId = (url.searchParams.get('agent_id') || '').trim();
const origin = env.APP_ORIGIN || 'https://three.ws';
- if (!isUuid(agentId)) return redirect(res, `${origin}/leaderboard`);
+ if (!isUuid(agentId)) {
+ if (BASE58_RE.test(agentId)) return shareWallet(res, agentId, origin);
+ return redirect(res, `${origin}/leaderboard`);
+ }
let agent, stats;
try {
@@ -83,6 +89,59 @@ function redirect(res, to) {
res.end();
}
+/** wallet_reputation stores win_rate as a 0–1 fraction; normalize to 0–100. */
+function pct(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ if (!Number.isFinite(n)) return null;
+ return Math.round(n <= 1 ? n * 100 : n);
+}
+
+/**
+ * Share page for a claimed/external wallet — reads the Oracle wallet-reputation
+ * ledger. An unindexed wallet redirects to the plain profile rather than
+ * shipping a preview full of em-dashes.
+ */
+async function shareWallet(res, wallet, origin) {
+ const deepUrl = `${origin}/trader/${encodeURIComponent(wallet)}`;
+
+ let rep;
+ try {
+ [rep] = await sql`
+ select coins_traded, win_rate, smart_money_score, label
+ from wallet_reputation
+ where wallet = ${wallet} and network = 'mainnet'
+ limit 1
+ `;
+ } catch {
+ return redirect(res, deepUrl);
+ }
+ if (!rep) return redirect(res, deepUrl);
+
+ const short = `${wallet.slice(0, 4)}…${wallet.slice(-4)}`;
+ const winRate = pct(rep.win_rate);
+ const score = rep.smart_money_score != null ? Math.round(Number(rep.smart_money_score)) : null;
+ const coins = Number(rep.coins_traded || 0);
+ const label = rep.label ? String(rep.label).replace(/_/g, ' ') : null;
+
+ const title = `${short} · ${score != null ? `smart-money score ${score}` : 'Solana trader'} · three.ws Oracle`;
+ const parts = [`${short}'s on-chain pump.fun track record on three.ws`];
+ if (label) parts.push(label);
+ if (coins > 0) parts.push(`${coins} coin${coins === 1 ? '' : 's'} traded`);
+ if (winRate != null) parts.push(`${winRate}% win rate`);
+ if (score != null) parts.push(`smart-money score ${score}`);
+ parts.push('proof.not.promises');
+ const desc = parts.join(' · ');
+
+ const pageUrl = `${origin}/trader/${encodeURIComponent(wallet)}/share`;
+ const ogImage = `${origin}/api/trader-og?wallet=${encodeURIComponent(wallet)}`;
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');
+ res.end(renderHtml({ title, desc, pageUrl, deepUrl, ogImage, name: short, winRate, pnlStr: null, origin }));
+}
+
function buildDesc({ name, total, winRate, pnlStr, bestStr }) {
const parts = [`${name}'s provable pump.fun track record on three.ws`];
if (total > 0) parts.push(`${total} closed trade${total === 1 ? '' : 's'}`);
diff --git a/data/changelog.json b/data/changelog.json
index 88409ef3f..c774082ef 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-03",
+ "title": "Shared wallet Trader Cards now unfurl with real stats",
+ "summary": "Sharing a claimed wallet's Trader Card used to preview with the generic site image — only three.ws agents got the rich social card. Now /trader/<wallet>/share bakes a real card for any indexed wallet: smart-money score gauge, win rate, coins traded, realized P&L, and the wallet's archetype, all pulled from the same on-chain reputation ledger the profile shows. The share button on wallet profiles now hands out this link, and a wallet the engine hasn't indexed yet routes to the plain profile instead of shipping an empty preview.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/claim-wallet"
+ },
+ {
+ "date": "2026-07-03",
+ "title": "Sniper dashboard now connects to everything your bots touch",
+ "summary": "Monitoring your trading agents no longer dead-ends at a status badge. Every stat tile at the top of Sniper Strategies is now a shortcut — click Open positions to jump straight to the live feed, or Closed trades to land on your history. Each strategy card shows the bot's live open positions inside the card, with a running \"2 open · +0.004 ◎\" ticker right on the collapsed row so you can scan all your agents at a glance. Every coin name — in live positions and trade history — now opens that coin's full detail page (conviction score, holders, live trade tape), and the live positions panel links directly to your Portfolio and the Trading desk.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/dashboard/sniper"
+ },
{
"date": "2026-07-03",
"title": "Autonomous trader safety gates now fail closed — no more buying what it can't verify",
diff --git a/docs/internal/REPO-LEARNINGS-2026-07-03.md b/docs/internal/REPO-LEARNINGS-2026-07-03.md
new file mode 100644
index 000000000..c0c48822d
--- /dev/null
+++ b/docs/internal/REPO-LEARNINGS-2026-07-03.md
@@ -0,0 +1,39 @@
+# Cross-repo learnings — 2026-07-03
+
+Audit of nirholas/cluster + 10 other owned repos (HQ, four.ws, and 8 public) for patterns worth adopting in three.ws. Full analysis was done against shallow clones; this file records the actionable output. Audience: engineers.
+
+## Ranked adoption backlog
+
+| # | What | Source | Why | Effort |
+| --- | --- | --- | --- | --- |
+| 1 | **Needy-only auto-refill** for the economy master | `cluster` `src/services/fleet.js` `attemptRefill` | Replaces "master tops up everyone below floor" with: refill only wallets below an affordability floor, sized against a remaining *global* cap, bounded by max-refills, journaled. Gives `api/_lib/economy-master.js` a campaign-level spend ceiling. | Medium |
+| 2 | **AAD binding in wallet encryption** | improvement *over* `cluster` (which omits it) | Bind `agent_id`+pubkey as AES-GCM `additionalData` in the custodial keystore so a DB-write attacker can't swap encrypted secrets between agents — this is a *known unresolved weakness* listed in `docs/internal/AGENT-WALLET-CUSTODY.md`. | Small |
+| 3 | **Keyless-PDA escrow** | `solana-marketplace-escrow` `program/programs/keyless-escrow/src/lib.rs` | Escrow vault is a PDA with no private key; payout destinations fixed at funding time (release→seller, refund→buyer). Direct security upgrade for labor-market/marketplace escrow — can't leak a key that doesn't exist. Has an audit doc + SDK + x402/MCP wrappers. | Medium |
+| 4 | **Exact sweep-to-zero fee math** | `cluster` `fleet.js` `sweepBatchFees` | `cuLimit = 200·signers + 450`; per-signer fee reserve; computes the exact fee so the source wallet lands at precisely 0 (sub-rent-exempt dust gets the tx rejected). Replace any flat reserve in sweep/consolidation paths. | Small |
+| 5 | **Dry-run + honest landed/total reporting** | `cluster` fleet ops + `reportSwap` | Every spending op returns `{dryRun, plan}` without sending; live runs report `landed/total` *including build-failures*, surface the first error, keep the confirm UI open on total failure. Adopt across sniper/funding/swarm ops. | Small–Med |
+| 6 | **Payment circuit breaker + jittered retry** | `agenti` `packages/sdk/src/resilience.ts` | Closed/open/half-open breaker around x402 calls. Our payment paths retry naively or not at all. | Small |
+| 7 | **GPU force-graph engine** | `visualize-web3-realtime` `packages/core/src/engine/{ForceGraphSimulation,SpatialHash}.ts` | 5k nodes @ 60fps, one InstancedMesh draw call, framework-agnostic core (skip the React renderer). Scales agent-network / coin-community / oracle-graph visuals. | Medium |
+| 8 | **KOL multi-source fetcher fleet** | `kol-quest` `fetchers/sources/*` | 20+ adapters (birdeye, bitquery, dune, flipside, helius, moralis, debank, zerion, covalent, geckoterminal, solscan, gmgn, kolscan…) behind one interface — fattens `kol-mcp`/`signals-mcp` far beyond the current gmgn/kolscan pair. | Medium |
+| 9 | **Sanitizing append-only journal** | `cluster` `src/lib/journal.js` | Deep secret-strip at every nesting level, BigInt-safe, never-throw, 0600 append-only; doubles as offline P&L analytics source. Pattern for worker-side money ops alongside `agent_custody_events`. | Medium |
+| 10 | **x402 discovery manifest builder** | `agenti` `packages/sdk/src/discovery.ts` | Generates OpenAPI 3.1 + `/.well-known/x402` from route defs for x402scan discoverability. We advertise via bazaar but ship no machine manifest. | Small |
+
+## Also noted (unranked)
+
+- **Stateless HMAC session tokens + scrypt access codes + dep-free Ed25519 verify** — `cluster/dashboard/lib/{session-token,access-code,wallet-auth}.ts`; liftable nearly as-is if we ever need lightweight non-OAuth auth surfaces.
+- **On-device ML worker** (transformers.js NER/sentiment off-main-thread with capability fallback) — `HQ/src/services/ml-worker.ts`; free local moderation/sentiment without an LLM call.
+- **PumpFun live claim/fee-distribution monitors** — `pumpkit/packages/claim/src/rpc-monitor.ts`, `packages/core/src/monitor/FeeDistMonitor.ts`; we only have one-shot fee collection, no live creator-reward/whale event stream for coin communities.
+- **Price anomaly detector** (median/MAD spike scoring) — `agenti/packages/sdk/src/anomaly.ts` → feeds `alerts-mcp`/`signals-mcp`.
+- **Portable IP rate-limiter + Upstash-or-memory cache** — `HQ/api/_ip-rate-limit.js`, `_upstash-cache.js`.
+- **Resumable job + supervisor engine** (cooperative checkpoint cancellation, secret-stripped persisted params, exponential-backoff campaign restarts) — `cluster/src/services/{jobs,supervisor}.js`; large but the right shape for long-running sniper/spend campaigns.
+- **Recovery-snapshot keystore discipline** (timestamped ciphertext backups rotated to 20, atomic tmp+rename writes) — `cluster/src/lib/keystore.js` → mirror in `api/_lib/vault-wallet.js`.
+
+## Explicitly skipped
+
+- **three-ui** — pared-down three.ws snapshot, no improvements; nothing to port.
+- **boosty** — WIP, redundant with cluster's more mature fleet engine.
+- **four.ws Stripe stack** — subscription billing misaligned with x402/agent-wallet monetization. (Its NextAuth wallet-as-credentials config is a decent reference if we ever want cookie-session wallet login.)
+- **pumpfun-creator-rewards** — we already have `pump-fun-skills/coin-fees`; only its username→wallet→mint resolution is mildly interesting.
+
+## Caveat
+
+`cluster` is single-operator, password-per-action, localhost-trust: **no KMS, no AAD, single per-keystore salt**. Treat its crypto as a floor to improve on (see #2), not a ceiling to copy.
diff --git a/packages/agent-sniper/scripts/fleet.js b/packages/agent-sniper/scripts/fleet.js
index 70c76bf06..af92e3efe 100644
--- a/packages/agent-sniper/scripts/fleet.js
+++ b/packages/agent-sniper/scripts/fleet.js
@@ -280,7 +280,7 @@ async function cmdRun(flags) {
// Rule: no pump.fun Mayhem tokens — only normal launches. Reads each mint's
// bonding curve (cached, shared across agents) and skips isMayhemMode tokens.
// On by default; --allow-mayhem disables it.
- const { createMayhemFilter } = await import('./mayhem-filter.js');
+ const { createMayhemFilter } = await import('../src/mayhem-filter.js');
const mayhem = flags['allow-mayhem'] ? null
: createMayhemFilter({ rpcUrl, strictOnUnknown: Boolean(flags['mayhem-strict']) });
diff --git a/packages/agent-sniper/src/adapters/solana/executor-web3.js b/packages/agent-sniper/src/adapters/solana/executor-web3.js
index cb8a5a184..16b07c0c0 100644
--- a/packages/agent-sniper/src/adapters/solana/executor-web3.js
+++ b/packages/agent-sniper/src/adapters/solana/executor-web3.js
@@ -20,7 +20,7 @@ import {
const JITO_TIP_ACCOUNTS = [
'96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',
'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',
- 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghp5HJ8L',
+ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY',
'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',
'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',
'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',
diff --git a/packages/agent-sniper/src/index.js b/packages/agent-sniper/src/index.js
index f6cdf516d..590eb63d3 100644
--- a/packages/agent-sniper/src/index.js
+++ b/packages/agent-sniper/src/index.js
@@ -22,6 +22,7 @@ export { createSniper } from './engine.js';
export { loadConfig } from './config.js';
export { scoreMint, scoreIntel, learnedScore } from './scorer.js';
export { decideExit } from './exit-logic.js';
+export { createMayhemFilter } from './mayhem-filter.js';
export {
checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
makeThrottle, makeQueue, SOL_FEE_HEADROOM_LAMPORTS,
diff --git a/packages/agent-sniper/scripts/mayhem-filter.js b/packages/agent-sniper/src/mayhem-filter.js
similarity index 100%
rename from packages/agent-sniper/scripts/mayhem-filter.js
rename to packages/agent-sniper/src/mayhem-filter.js
diff --git a/pages/agent-trade.html b/pages/agent-trade.html
index 9ea4927a2..c19344ea4 100644
--- a/pages/agent-trade.html
+++ b/pages/agent-trade.html
@@ -27,13 +27,14 @@
<meta name="twitter:description" content="Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, in 3D." />
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Commerce&amp;d=Watch+two+AI+agents+pay+each+other+on-chain+using+x402+%E2%80%94+a+live+Solana+transaction%2C+rendered+in+3D.&amp;p=%2Fagent-trade" />
<link rel="stylesheet" href="/fonts/fonts.css">
+ <link rel="stylesheet" href="/tokens.css">
<style>
:root {
--blue: #4589ff;
--teal: #08bdba;
--gold: #f1c21b;
- --green: #42be65;
- --red: #fa4d56;
+ --green: var(--success, #42be65);
+ --red: var(--danger, #fa4d56);
--bg: #060606;
--surface: rgba(13,13,26,0.92);
--surface2: rgba(22,22,40,0.85);
@@ -42,7 +43,7 @@
--muted: #8d8d8d;
--font: var(--font-body, 'Inter', system-ui, sans-serif);
--mono: var(--font-mono, 'JetBrains Mono', 'SF Mono', ui-monospace, monospace);
- --radius: 12px;
+ --radius: var(--radius-lg, 12px);
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 100%; height: 100%; overflow: hidden; background: var(--bg); font-family: var(--font); color: var(--text); }
@@ -75,7 +76,7 @@
/* ── Agent labels (tracked to 3D positions by JS) ─────────────────── */
.agent-label {
position: fixed; display: flex; flex-direction: column; align-items: center;
- gap: 3px; pointer-events: none; z-index: 6; transition: opacity 0.4s;
+ gap: 3px; pointer-events: none; z-index: 6; transition: opacity var(--duration-slow) var(--ease-standard);
text-align: center;
}
.al-name { font-size: 1rem; font-weight: 600; letter-spacing: 0.02em; }
@@ -90,7 +91,7 @@
position: fixed; max-width: 210px; padding: 10px 14px; border-radius: 16px;
font-size: 0.82rem; line-height: 1.5; backdrop-filter: blur(14px);
z-index: 20; pointer-events: none; text-align: center;
- transition: opacity 0.3s, transform 0.3s;
+ transition: opacity var(--duration-base) var(--ease-standard), transform var(--duration-base) var(--ease-standard);
}
.bubble.hidden { opacity: 0; transform: translateY(8px); }
#buyerBubble { background: rgba(69,137,255,0.15); border: 1px solid rgba(69,137,255,0.35); }
@@ -103,7 +104,7 @@
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius); backdrop-filter: blur(18px);
padding: 18px 22px; z-index: 20;
- transition: opacity 0.35s, transform 0.35s;
+ transition: opacity var(--duration-base) var(--ease-standard), transform var(--duration-base) var(--ease-standard);
}
#centralCard.hidden { opacity: 0; transform: translateX(-50%) translateY(14px); pointer-events: none; }
.c-badge {
@@ -111,8 +112,8 @@
padding: 3px 10px; border-radius: 20px; font-size: 0.67rem;
font-family: var(--mono); letter-spacing: 0.05em; margin-bottom: 10px;
}
- .c-badge-402 { background: rgba(250,77,86,0.1); border: 1px solid rgba(250,77,86,0.3); color: #fa4d56; }
- .c-badge-ok { background: rgba(66,190,101,0.1); border: 1px solid rgba(66,190,101,0.3); color: var(--green); }
+ .c-badge-402 { background: color-mix(in srgb, var(--red) 10%, transparent); border: 1px solid color-mix(in srgb, var(--red) 30%, transparent); color: var(--red); }
+ .c-badge-ok { background: color-mix(in srgb, var(--green) 10%, transparent); border: 1px solid color-mix(in srgb, var(--green) 30%, transparent); color: var(--green); }
.c-label { font-size: 0.67rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin-bottom: 6px; font-family: var(--mono); }
.c-price { font-size: 1.7rem; font-weight: 600; font-family: var(--mono); margin: 8px 0 4px; }
.c-price.blue { color: var(--blue); }
@@ -134,11 +135,11 @@
padding: 4px 11px; border-radius: 20px; font-size: 0.68rem;
font-family: var(--mono); border: 1px solid var(--border);
color: var(--muted); background: var(--surface); backdrop-filter: blur(8px);
- transition: all 0.25s;
+ transition: all var(--duration-base) var(--ease-standard);
}
.step-chip.active { color: var(--text); border-color: var(--blue); background: rgba(69,137,255,0.1); }
- .step-chip.done { color: var(--green); border-color: rgba(66,190,101,0.35); background: rgba(66,190,101,0.06); }
- .step-chip.error { color: var(--red); border-color: rgba(250,77,86,0.35); }
+ .step-chip.done { color: var(--green); border-color: color-mix(in srgb, var(--green) 35%, transparent); background: color-mix(in srgb, var(--green) 6%, transparent); }
+ .step-chip.error { color: var(--red); border-color: color-mix(in srgb, var(--red) 35%, transparent); }
/* ── CTA bar ────────────────────────────────────────────────────────── */
#cta {
@@ -158,7 +159,7 @@
#startBtn {
padding: 10px 24px; background: var(--blue); color: #fff;
border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 500;
- cursor: pointer; font-family: var(--font); transition: background 0.18s, transform 0.1s;
+ cursor: pointer; font-family: var(--font); transition: background var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard);
white-space: nowrap;
}
#startBtn:hover:not(:disabled) { background: #6ea6ff; }
@@ -168,10 +169,10 @@
/* ── Toast ──────────────────────────────────────────────────────────── */
#toast {
position: fixed; bottom: 88px; left: 50%; transform: translateX(-50%);
- background: rgba(250,77,86,0.14); border: 1px solid rgba(250,77,86,0.4);
- color: #fa4d56; padding: 10px 20px; border-radius: 8px;
+ background: color-mix(in srgb, var(--red) 14%, transparent); border: 1px solid color-mix(in srgb, var(--red) 40%, transparent);
+ color: var(--red); padding: 10px 20px; border-radius: 8px;
font-size: 0.83rem; z-index: 30; opacity: 0;
- transition: opacity 0.3s; pointer-events: none; max-width: 420px; text-align: center;
+ transition: opacity var(--duration-base) var(--ease-standard); pointer-events: none; max-width: 420px; text-align: center;
}
#toast.show { opacity: 1; }
@@ -204,7 +205,7 @@
margin-top: 18px; padding: 9px 20px; background: rgba(69,137,255,0.15);
border: 1px solid rgba(69,137,255,0.35); color: var(--blue);
border-radius: 8px; font-family: var(--font); font-size: 0.86rem;
- cursor: pointer; transition: background 0.18s;
+ cursor: pointer; transition: background var(--duration-fast) var(--ease-standard);
}
.cfg-close:hover { background: rgba(69,137,255,0.25); }
.cfg-close:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
@@ -229,7 +230,7 @@
.cfg-links { display: flex; flex-wrap: wrap; gap: 10px 16px; margin-top: 18px; }
.cfg-link {
font-size: 0.8rem; color: var(--teal); text-decoration: none;
- border-bottom: 1px solid transparent; transition: border-color 0.16s, color 0.16s;
+ border-bottom: 1px solid transparent; transition: border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
}
.cfg-link:hover { color: #2fe3df; border-bottom-color: rgba(8,189,186,0.5); }
.cfg-link:focus-visible { outline: 2px solid var(--teal); outline-offset: 3px; border-radius: 3px; }
@@ -240,7 +241,7 @@
font-family: var(--mono); font-size: 0.68rem; letter-spacing: 0.02em;
color: var(--muted); text-decoration: none; padding: 4px 10px; border-radius: 20px;
border: 1px solid transparent;
- transition: color 0.16s, border-color 0.16s, background 0.16s, transform 0.1s;
+ transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard);
}
.header-links a:hover { color: var(--text); border-color: rgba(8,189,186,0.4); background: rgba(8,189,186,0.08); }
.header-links a:active { transform: scale(0.96); }
diff --git a/pages/dashboard-next/fleet.html b/pages/dashboard-next/fleet.html
new file mode 100644
index 000000000..eb2878fbd
--- /dev/null
+++ b/pages/dashboard-next/fleet.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Fleet Command · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ <link rel="stylesheet" href="/tokens.css" />
+ </head>
+ <body>
+ <script type="module" src="/src/dashboard-next/pages/fleet.js"></script>
+ </body>
+</html>
diff --git a/pages/home.html b/pages/home.html
index fd959ba01..eaab79d9a 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -2202,7 +2202,7 @@
.walk-minimap{width:100%;height:140px;display:block;cursor:crosshair}
.walk-minimap:focus{outline:2px solid rgba(255,255,255,.3);outline-offset:-2px}
.walk-minimap-hud{position:absolute;top:6px;left:8px;display:flex;align-items:center;gap:6px;font-family:var(--font-mono);font-size:9px;color:var(--text-3);letter-spacing:.08em}
- .walk-minimap-dot{width:5px;height:5px;border-radius:50%;background:var(--success);box-shadow:0 0 4px #4ade8088}
+ .walk-minimap-dot{width:5px;height:5px;border-radius:50%;background:var(--success);box-shadow:0 0 4px color-mix(in srgb, var(--success) 53%, transparent)}
.walk-minimap-hint{position:absolute;bottom:6px;left:50%;transform:translateX(-50%);font-family:var(--font-mono);font-size:8.5px;color:var(--text-3);letter-spacing:.06em;white-space:nowrap}
.walk-minimap-hint kbd{display:inline-block;padding:0 3px;border:1px solid var(--hairline-strong);border-radius:2px;font-family:var(--font-mono);font-size:8px;background:var(--surface-2)}
.x402-demo{display:flex;flex-direction:column;gap:8px}
@@ -2293,7 +2293,7 @@
.mktplace-item-name{position:absolute;bottom:0;left:0;right:0;padding:2px 4px;font-family:var(--font-mono);font-size:7px;color:var(--text);background:rgba(0,0,0,.7);text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mktplace-more{flex-shrink:0;width:52px;height:52px;border-radius:10px;border:1px dashed var(--hairline-strong);display:flex;align-items:center;justify-content:center;font-family:var(--font-mono);font-size:18px;color:var(--text-4);cursor:pointer;transition:border-color .15s,color .15s;text-decoration:none}
.mktplace-more:hover{border-color:var(--text-3);color:var(--text-2)}
- .analytics-demo{display:flex;flex-direction:column;gap:10px;--spark:#34d399;--spark-deep:#10b981}
+ .analytics-demo{display:flex;flex-direction:column;gap:10px;--spark:var(--success);--spark-deep:#10b981}
.analytics-example-tag{align-self:flex-start;font-family:var(--font-mono);font-size:9px;letter-spacing:.12em;text-transform:uppercase;color:var(--text-3);border:1px solid var(--hairline);border-radius:5px;padding:2px 7px}
.analytics-counters{display:flex;gap:16px}
.analytics-counter{display:flex;flex-direction:column;gap:1px}
@@ -2845,7 +2845,7 @@
display: block; font-size: clamp(30px, 4.4vw, 46px); font-weight: 800; line-height: 1;
letter-spacing: -.02em; color: var(--text); font-variant-numeric: tabular-nums;
}
- #home-sniper .snipe-stat-val.accent { color: #34d399; }
+ #home-sniper .snipe-stat-val.accent { color: var(--success); }
#home-sniper .snipe-stat-val.loading { color: var(--text-3); animation: snipe-shimmer-text 1.4s ease-in-out infinite; }
#home-sniper .snipe-stat-lbl {
display: block; margin-top: 12px; font-size: 13px; font-weight: 600; color: var(--text);
@@ -2873,7 +2873,7 @@
width: 8px; height: 8px; border-radius: 50%; background: var(--text-3);
box-shadow: 0 0 0 0 rgba(52,211,153,0.5); flex: none;
}
- #home-sniper .snipe-dot.live { background: #34d399; animation: snipe-pulse 2s ease-out infinite; }
+ #home-sniper .snipe-dot.live { background: var(--success); animation: snipe-pulse 2s ease-out infinite; }
#home-sniper .snipe-dot.degraded { background: #fbbf24; }
#home-sniper .snipe-dot.down { background: #f87171; }
@keyframes snipe-pulse {
@@ -2967,7 +2967,7 @@
font-size: 10px; font-weight: 700; letter-spacing: .04em; padding: 3px 7px; border-radius: 6px;
text-transform: uppercase; flex: none;
}
- #home-sniper .snipe-tag.buy { color: #34d399; background: rgba(52,211,153,0.12); }
+ #home-sniper .snipe-tag.buy { color: var(--success); background: color-mix(in srgb, var(--success) 12%, transparent); }
#home-sniper .snipe-tag.sell { color: #cbd5e1; background: rgba(203,213,225,0.1); }
#home-sniper .snipe-tag.open { color: #5fe3ff; background: rgba(95,227,255,0.12); }
#home-sniper .snipe-rmeta { min-width: 0; }
@@ -2977,7 +2977,7 @@
text-overflow: ellipsis; max-width: 100%;
}
#home-sniper .snipe-rpnl { font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; text-align: right; }
- #home-sniper .snipe-rpnl.up { color: #34d399; }
+ #home-sniper .snipe-rpnl.up { color: var(--success); }
#home-sniper .snipe-rpnl.down { color: #f87171; }
#home-sniper .snipe-rpnl.flat { color: var(--text-3); }
#home-sniper .snipe-tape-msg { padding: 40px 16px; text-align: center; color: var(--text-3); font-size: 13px; line-height: 1.5; }
@@ -2996,7 +2996,7 @@
#home-sniper .snipe-kpis { display: flex; gap: 26px; flex-wrap: wrap; }
#home-sniper .snipe-kpi { display: flex; flex-direction: column; gap: 2px; }
#home-sniper .snipe-kpi-val { font-size: 18px; font-weight: 700; color: var(--text); font-variant-numeric: tabular-nums; line-height: 1; }
- #home-sniper .snipe-kpi-val.accent { color: #34d399; }
+ #home-sniper .snipe-kpi-val.accent { color: var(--success); }
#home-sniper .snipe-kpi-val.loading { color: var(--text-3); animation: snipe-shimmer-text 1.4s ease-in-out infinite; }
@keyframes snipe-shimmer-text { 0%,100% { opacity: .4; } 50% { opacity: 1; } }
#home-sniper .snipe-kpi-lbl { font-size: 11px; color: var(--text-3); letter-spacing: .02em; }
@@ -3246,7 +3246,7 @@
<p class="wyg-card-body">Your agent reacts as it speaks, thinks, succeeds, and fails — emotion wired directly to model output, not scripted.</p>
<div class="wyg-card-pills">
<span class="wyg-card-pill"><span class="dot" style="background:#ffffff"></span>Celebration</span>
- <span class="wyg-card-pill"><span class="dot" style="background:#34d399"></span>Curiosity</span>
+ <span class="wyg-card-pill"><span class="dot" style="background:var(--success)"></span>Curiosity</span>
<span class="wyg-card-pill"><span class="dot" style="background:#60a5fa"></span>Empathy</span>
<span class="wyg-card-pill"><span class="dot" style="background:var(--warn)"></span>Concern</span>
</div>
@@ -4571,7 +4571,7 @@
<!-- Analytics -->
<div class="bento-card">
<div class="bento-icon">
- <span class="dot" style="background:#34d399;box-shadow:0 0 8px #34d39988"></span>
+ <span class="dot" style="background:var(--success);box-shadow:0 0 8px color-mix(in srgb, var(--success) 53%, transparent)"></span>
<span style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3)">Analytics</span>
</div>
<p class="bento-title">Track everything</p>
@@ -4584,7 +4584,7 @@
<div class="analytics-counter"><span class="analytics-val" id="an-retention">0%</span><span class="analytics-lbl">retention</span></div>
</div>
<svg class="analytics-spark" id="analytics-spark" viewBox="0 0 200 40" preserveAspectRatio="none">
- <defs><linearGradient id="spark-grad" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="#34d399" stop-opacity="0.35"/><stop offset="100%" stop-color="#34d399" stop-opacity="0"/></linearGradient></defs>
+ <defs><linearGradient id="spark-grad" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" style="stop-color:var(--success)" stop-opacity="0.35"/><stop offset="100%" style="stop-color:var(--success)" stop-opacity="0"/></linearGradient></defs>
</svg>
</div>
</div>
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index a4b3e55f5..5bf128c91 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -421,13 +421,13 @@ a:focus-visible{outline-offset:3px}
<link rel="canonical" href="https://three.ws/ibm/hello">
<meta property="og:site_name" content="three.ws">
<meta property="og:url" content="https://three.ws/ibm/x402-demo">
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
<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="x402 Live Demo (IBM × three.ws) · three.ws">
<meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 01).
Self-hosted (travels with this file under ./vendor/) so the page needs no
diff --git a/public/changelog.json b/public/changelog.json
index 82b1619d1..cea55b880 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-03T17:44:05.099Z",
+ "generated_at": "2026-07-03T17:53:35.657Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -248,6 +248,27 @@
"security"
]
},
+ {
+ "date": "2026-07-03",
+ "type": "update",
+ "title": "Shared wallet Trader Cards now unfurl with real stats",
+ "summary": "Sharing a claimed wallet's Trader Card used to preview with the generic site image — only three.ws agents got the rich social card. Now /trader/<wallet>/share bakes a real card for any indexed wallet: smart-money score gauge, win rate, coins traded, realized P&L, and the wallet's archetype, all pulled from the same on-chain reputation ledger the profile shows. The share button on wallet profiles now hands out this link, and a wallet the engine hasn't indexed yet routes to the plain profile instead of shipping an empty preview.",
+ "link": "/claim-wallet",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-07-03",
+ "type": "update",
+ "title": "Sniper dashboard now connects to everything your bots touch",
+ "summary": "Monitoring your trading agents no longer dead-ends at a status badge. Every stat tile at the top of Sniper Strategies is now a shortcut — click Open positions to jump straight to the live feed, or Closed trades to land on your history. Each strategy card shows the bot's live open positions inside the card, with a running \"2 open · +0.004 ◎\" ticker right on the collapsed row so you can scan all your agents at a glance. Every coin name — in live positions and trade history — now opens that coin's full detail page (conviction score, holders, live trade tape), and the live positions panel links directly to your Portfolio and the Trading desk.",
+ "link": "/dashboard/sniper",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-07-03",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 25f380cd5..b282b62e9 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -190,6 +190,22 @@
<category>infra</category>
<description>The three platform wallets that power the closed-loop agent economy — the one that pays, the one that receives, and the one that covers network fees — are now monitored and self-healing so the loop can run unattended without silently stalling or draining. A balance monitor checks all three on-chain every ten minutes and pages operators before trouble: the fee and paying wallets alert when their SOL dips near the level where settlements would be refused, and the paying wallet alerts when its USDC float runs low. The receiving wallet is intentionally left unbounded — it fills up and gets swept back automatically, so a low balance there is healthy, not a problem. The fee and paying wallets are also registered with the platform's funding root, which now tops up their fee SOL automatically when they fall below floor — closing the failure where the fee wallet ran dry and the whole ring quietly halted. A new one-command check confirms every wallet is correctly configured, registered, and reachable, prints their live balances, and refuses to pass on any mismatch, without ever exposing a secret. A funding runbook documents exactly how much to send and how to confirm it landed.</description>
</item>
+ <item>
+ <title>Shared wallet Trader Cards now unfurl with real stats</title>
+ <link>https://three.ws/claim-wallet</link>
+ <guid isPermaLink="false">2026-07-03:Shared wallet Trader Cards now unfurl with real stats</guid>
+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Sharing a claimed wallet's Trader Card used to preview with the generic site image — only three.ws agents got the rich social card. Now /trader/&lt;wallet&gt;/share bakes a real card for any indexed wallet: smart-money score gauge, win rate, coins traded, realized P&amp;L, and the wallet's archetype, all pulled from the same on-chain reputation ledger the profile shows. The share button on wallet profiles now hands out this link, and a wallet the engine hasn't indexed yet routes to the plain profile instead of shipping an empty preview.</description>
+ </item>
+ <item>
+ <title>Sniper dashboard now connects to everything your bots touch</title>
+ <link>https://three.ws/dashboard/sniper</link>
+ <guid isPermaLink="false">2026-07-03:Sniper dashboard now connects to everything your bots touch</guid>
+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Monitoring your trading agents no longer dead-ends at a status badge. Every stat tile at the top of Sniper Strategies is now a shortcut — click Open positions to jump straight to the live feed, or Closed trades to land on your history. Each strategy card shows the bot's live open positions inside the card, with a running &quot;2 open · +0.004 ◎&quot; ticker right on the collapsed row so you can scan all your agents at a glance. Every coin name — in live positions and trade history — now opens that coin's full detail page (conviction score, holders, live trade tape), and the live positions panel links directly to your Portfolio and the Trading desk.</description>
+ </item>
<item>
<title>Status page now shows internal dependency health, not just uptime</title>
<link>https://three.ws/status</link>
diff --git a/public/changelog/index.html b/public/changelog/index.html
index a718a19df..27203ba8d 100644
--- a/public/changelog/index.html
+++ b/public/changelog/index.html
@@ -9,36 +9,41 @@
<link rel="alternate" type="application/rss+xml" title="three.ws changelog" href="/changelog.xml" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+<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>
<style>
- :root { color-scheme: dark; }
- body { margin: 0; background: #000000; color: #e7e7e7; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }
+ /* Tokens arrive via /nav.css -> tokens.css. Page-local hue accents only for
+ the two tag families with no semantic token (feature/improvement) — a
+ theme layer, not a parallel palette. */
+ :root { --cl-feature: #7ec8ff; --cl-improvement: #d8b4ff; }
+ body { margin: 0; background: var(--bg-0); color: var(--ink); font-family: var(--font-body); -webkit-font-smoothing: antialiased; }
.cl-wrap { max-width: 760px; margin: 0 auto; padding: 96px 24px 64px; }
- .cl-hero h1 { font-size: clamp(34px, 5vw, 52px); margin: 0 0 12px; letter-spacing: -0.02em; }
- .cl-hero p { color: #b6b6b6; font-size: 17px; margin: 0 0 8px; line-height: 1.55; }
- .cl-hero a { color: #cccccc; }
+ .cl-hero h1 { font-size: clamp(34px, 5vw, 52px); margin: 0 0 12px; letter-spacing: -0.02em; color: var(--ink-bright); }
+ .cl-hero p { color: var(--ink-dim); font-size: 17px; margin: 0 0 8px; line-height: 1.55; }
+ .cl-hero a { color: var(--ink); }
.cl-filters { display: flex; flex-wrap: wrap; gap: 8px; margin: 24px 0 0; }
- .cl-filter { background: #0d0d0d; border: 1px solid #1d1d1d; color: #b6b6b6; font-size: 12px; font-weight: 600; letter-spacing: 0.03em; border-radius: 999px; padding: 6px 14px; cursor: pointer; transition: border-color .15s, color .15s; }
- .cl-filter:hover { border-color: #555555; color: #ffffff; }
- .cl-filter:focus-visible { outline: 2px solid #66ffaa; outline-offset: 2px; }
- .cl-filter[aria-pressed="true"] { border-color: #66ffaa; color: #66ffaa; background: #0c1c14; }
- .cl-day { margin: 44px 0 0; padding-top: 28px; border-top: 1px solid #1d1d1d; }
+ .cl-filter { background: var(--surface-1); border: 1px solid var(--stroke); color: var(--ink-dim); font-size: 12px; font-weight: var(--weight-semibold); letter-spacing: 0.03em; border-radius: var(--radius-pill); padding: 6px 14px; cursor: pointer; transition: border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard); }
+ .cl-filter:hover { border-color: var(--stroke-strong); color: var(--ink-bright); }
+ .cl-filter:focus-visible { outline: 2px solid var(--focus-ring-color); outline-offset: 2px; }
+ .cl-filter[aria-pressed="true"] { border-color: var(--success); color: var(--success); background: color-mix(in srgb, var(--success) 8%, transparent); }
+ .cl-day { margin: 44px 0 0; padding-top: 28px; border-top: 1px solid var(--stroke); }
.cl-day:first-of-type { border-top: none; padding-top: 0; }
- .cl-date { font-size: 13px; color: #777777; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: 0.04em; margin: 0 0 16px; }
- .cl-item { display: block; background: #0d0d0d; border: 1px solid #1d1d1d; border-radius: 12px; padding: 16px 18px; margin-bottom: 10px; text-decoration: none; transition: border-color .15s, transform .15s; }
- a.cl-item:hover, a.cl-item:focus-visible { border-color: #ffffff; transform: translateY(-1px); outline: none; }
- .cl-item-title { color: #fff; font-weight: 600; font-size: 15px; }
- .cl-item-path { color: #777777; font-size: 12px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; margin-left: 8px; }
- .cl-item-desc { color: #b6b6b6; font-size: 13px; line-height: 1.5; margin-top: 6px; }
- .cl-empty, .cl-error { color: #9a9a9a; font-size: 15px; }
- .cl-badge { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; border-radius: 999px; padding: 2px 8px; margin-left: 8px; vertical-align: middle; }
- .cl-badge-new { color: #66ffaa; border: 1px solid #1f4a3f; background: #0c1c14; }
- .cl-tag { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; border-radius: 999px; padding: 2px 8px; margin-right: 6px; border: 1px solid #2a2a2a; color: #9a9a9a; background: #111111; }
- .cl-tag-launch { color: #66ffaa; border-color: #1f4a3f; background: #0c1c14; }
- .cl-tag-feature { color: #7ec8ff; border-color: #1d3a52; background: #0b141d; }
- .cl-tag-improvement { color: #d8b4ff; border-color: #3a2752; background: #150d1d; }
- .cl-tag-fix { color: #ffd27e; border-color: #523f1d; background: #1d150b; }
- .cl-tag-security { color: #ff8e8e; border-color: #521d1d; background: #1d0b0b; }
- .cl-tag-sdk { color: #8effd9; border-color: #1d5240; background: #0b1d16; }
+ .cl-date { font-size: 13px; color: var(--ink-faint); font-family: var(--font-mono); letter-spacing: 0.04em; margin: 0 0 16px; }
+ .cl-item { display: block; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg); padding: 16px 18px; margin-bottom: 10px; text-decoration: none; transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard); }
+ a.cl-item:hover, a.cl-item:focus-visible { border-color: var(--accent); transform: translateY(-1px); outline: none; }
+ .cl-item-title { color: var(--ink-bright); font-weight: var(--weight-semibold); font-size: 15px; }
+ .cl-item-path { color: var(--ink-faint); font-size: 12px; font-family: var(--font-mono); margin-left: 8px; }
+ .cl-item-desc { color: var(--ink-dim); font-size: 13px; line-height: 1.5; margin-top: 6px; }
+ .cl-empty, .cl-error { color: var(--ink-dim); font-size: 15px; }
+ .cl-error a { color: var(--ink); }
+ .cl-badge { display: inline-block; font-size: 10px; font-weight: var(--weight-bold); letter-spacing: 0.05em; text-transform: uppercase; border-radius: var(--radius-pill); padding: 2px 8px; margin-left: 8px; vertical-align: middle; }
+ .cl-badge-new { color: var(--success); border: 1px solid color-mix(in srgb, var(--success) 35%, transparent); background: color-mix(in srgb, var(--success) 8%, transparent); }
+ .cl-tag { display: inline-block; font-size: 10px; font-weight: var(--weight-bold); letter-spacing: 0.05em; text-transform: uppercase; border-radius: var(--radius-pill); padding: 2px 8px; margin-right: 6px; border: 1px solid var(--stroke); color: var(--ink-dim); background: var(--surface-1); }
+ .cl-tag-launch { color: var(--success); border-color: color-mix(in srgb, var(--success) 35%, transparent); background: color-mix(in srgb, var(--success) 8%, transparent); }
+ .cl-tag-feature { color: var(--cl-feature); border-color: color-mix(in srgb, var(--cl-feature) 35%, transparent); background: color-mix(in srgb, var(--cl-feature) 8%, transparent); }
+ .cl-tag-improvement { color: var(--cl-improvement); border-color: color-mix(in srgb, var(--cl-improvement) 35%, transparent); background: color-mix(in srgb, var(--cl-improvement) 8%, transparent); }
+ .cl-tag-fix { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 8%, transparent); }
+ .cl-tag-security { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 8%, transparent); }
+ .cl-tag-sdk { color: var(--success); border-color: color-mix(in srgb, var(--success) 35%, transparent); background: color-mix(in srgb, var(--success) 8%, transparent); }
.cl-tags { margin-top: 10px; }
</style>
</head>
diff --git a/public/features.json b/public/features.json
index 879d480cf..6a3c8b399 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-03T17:44:05.037Z",
+ "generated_at": "2026-07-03T17:53:34.895Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/legal/risk.html b/public/legal/risk.html
new file mode 100644
index 000000000..fb77d3df1
--- /dev/null
+++ b/public/legal/risk.html
@@ -0,0 +1,116 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Risk Disclosure · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root { color-scheme: dark; }
+ * { box-sizing: border-box; }
+ body {
+ font: 16px/1.7 -apple-system, system-ui, 'Segoe UI', sans-serif;
+ background: #000000;
+ color: #ccc;
+ margin: 0;
+ padding: 48px 24px 80px;
+ }
+ .wrap { max-width: 720px; margin: 0 auto; }
+ .brand { font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #ffffff; margin: 0 0 32px; display: block; text-decoration: none; }
+ .header-logo { width: 14px; height: 14px; vertical-align: -2px; margin-right: 6px; }
+ h1 { font-size: 32px; color: #eee; margin: 0 0 6px; letter-spacing: -.02em; }
+ .meta { color: #555; font-size: 14px; margin: 0 0 40px; }
+ h2 { font-size: 18px; color: #eee; margin: 40px 0 10px; }
+ p, li { color: #aaa; font-size: 15px; }
+ ul { padding-left: 20px; }
+ li { margin-bottom: 6px; }
+ a { color: #cccccc; }
+ hr { border: none; border-top: 1px solid #1e1e1e; margin: 48px 0; }
+ .foot { color: #555; font-size: 13px; }
+ .callout {
+ border: 1px solid #3a2f14; background: #14100a; border-radius: 10px;
+ padding: 14px 18px; margin: 0 0 32px;
+ }
+ .callout p { color: #d8b96a; margin: 0; font-size: 15px; }
+ </style>
+
+ <meta name="description" content="Risk disclosure for real-funds features on three.ws: experimental software, total-loss risk, autonomous agents, no liability.">
+ <link rel="canonical" href="https://three.ws/legal/risk">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Risk Disclosure · three.ws">
+ <meta property="og:description" content="Risk disclosure for real-funds features on three.ws: experimental software, total-loss risk, autonomous agents, no liability.">
+ <meta property="og:url" content="https://three.ws/legal/risk">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=legal&amp;t=Risk+Disclosure&amp;d=Risk+disclosure+for+real-funds+features+on+three.ws.&amp;p=%2Flegal%2Frisk">
+ <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="Risk Disclosure · three.ws">
+ <meta name="twitter:description" content="Risk disclosure for real-funds features on three.ws: experimental software, total-loss risk, autonomous agents, no liability.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=legal&amp;t=Risk+Disclosure&amp;d=Risk+disclosure+for+real-funds+features+on+three.ws.&amp;p=%2Flegal%2Frisk">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Risk Disclosure","description":"Risk disclosure for real-funds features on three.ws.","url":"https://three.ws/legal/risk","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Risk Disclosure — three.ws">
+ <meta name="twitter:site" content="@trythreews">
+</head>
+<body>
+<div class="wrap">
+ <a class="brand" href="/"><img src="/three.svg" alt="" class="header-logo" aria-hidden="true" />three.ws</a>
+ <h1>Risk Disclosure</h1>
+ <p class="meta">Effective: July 3, 2026 &nbsp;·&nbsp; Version 1 &nbsp;·&nbsp; <a href="/legal/tos.html">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/privacy.html">Privacy Policy</a></p>
+
+ <div class="callout">
+ <p><strong>Plain summary:</strong> three.ws is experimental software — an attempt at innovation, not a financial product. Do not use real funds unless you understand and accept that you can lose all of them, and that three.ws is not responsible for any loss.</p>
+ </div>
+
+ <p>This Risk Disclosure ("Disclosure") applies to every feature of three.ws ("Service") that can move real money or real digital assets — including but not limited to agent wallets, trading, token sniping, automated strategies, autopilot, token launches, swaps, transfers, withdrawals, x402 payments, and fiat onramps ("Real-Funds Features"). Before first using a Real-Funds Feature you are asked to acknowledge this Disclosure. By accepting it, or by using any Real-Funds Feature, you agree to everything below.</p>
+
+ <h2>1. Experimental software</h2>
+ <p>The Service is an ongoing experiment in agentic and on-chain software. It is provided <strong>"as is" and "as available"</strong>, without warranties of any kind, express or implied. Features may be incomplete, may change or disappear without notice, and may contain defects. A bug, outage, network failure, chain reorganization, RPC error, or third-party dependency failure can cause transactions to fail, execute unexpectedly, or result in loss of funds.</p>
+
+ <h2>2. Not financial advice</h2>
+ <p>Nothing on the Service — including scores, signals, conviction ratings, strategies, leaderboards, agent behavior, documentation, or any generated content — is financial, investment, legal, accounting, or tax advice, or a recommendation to buy, sell, or hold any asset. The Service does not know your circumstances. Make your own decisions and consult qualified professionals where appropriate.</p>
+
+ <h2>3. Digital asset risk</h2>
+ <ul>
+ <li><strong>Total loss.</strong> Digital assets — SOL, USDC, $THREE, memecoins, and any other token — are volatile and speculative. Their value can go to zero. Any amount you commit can be lost entirely, quickly, and permanently.</li>
+ <li><strong>Irreversibility.</strong> Blockchain transactions cannot be reversed, recalled, or refunded once confirmed. A transfer to a wrong address is unrecoverable.</li>
+ <li><strong>Newly launched tokens.</strong> Tokens on launchpads such as pump.fun carry extreme risk, including abandonment, illiquidity, manipulation, and fraudulent schemes by their creators ("rug pulls"). Most such tokens lose most or all of their value.</li>
+ <li><strong>Execution risk.</strong> Prices move between quote and fill. Slippage, failed transactions, front-running, and MEV can produce results materially worse than displayed estimates. Fees are consumed even by failed transactions.</li>
+ <li><strong>Protocol risk.</strong> Smart contracts, bonding curves, DEX routers, bridges, and payment protocols the Service integrates with may contain vulnerabilities or behave unexpectedly.</li>
+ </ul>
+
+ <h2>4. Autonomous agent risk</h2>
+ <p>The Service's defining capability — autonomous agents — is also its sharpest risk. When you arm a strategy, enable a sniper, configure autopilot, or grant an agent spending capability:</p>
+ <ul>
+ <li>The agent can <strong>execute trades, payments, and transfers on your behalf without asking you again</strong>, within the limits you configure, at any time, including while you are away.</li>
+ <li>Agent decision-making is driven by software rules and, in places, machine-learning models. Both can be wrong. An agent can systematically lose money while operating exactly as designed.</li>
+ <li>Spend caps, safety bands, stop-losses, and other guardrails are best-effort software controls, not guarantees. They can fail, lag the market, or be mis-configured.</li>
+ <li>You are responsible for everything an agent you configured does with real funds, and for disarming it when you no longer want it to act.</li>
+ </ul>
+
+ <h2>5. Custody and security</h2>
+ <p>Agent wallets on the Service are custodial: keys are held server-side so agents can sign autonomously. Custodial funds are exposed to platform risk, including compromise, operational error, and loss of key material. Self-custody wallets (e.g. Phantom) you connect remain entirely your responsibility — the Service never holds those keys, and cannot recover them, reverse your signatures, or restore funds lost to phishing or device compromise. Keep balances on the Service limited to what you are actively using.</p>
+
+ <h2>6. Assumption of risk; no liability</h2>
+ <p><strong>You use Real-Funds Features entirely at your own risk.</strong> To the maximum extent permitted by law, three.ws, its operators, contributors, and affiliates accept no responsibility and shall have no liability for any loss of funds, tokens, or value of any kind, however caused — including losses arising from software defects, agent behavior, market movements, third-party failures, security incidents, or your own configuration — whether based in contract, tort, or any other theory. This section supplements, and does not limit, the Limitation of Liability in the <a href="/legal/tos.html">Terms of Service</a>.</p>
+
+ <h2>7. Only funds you can afford to lose</h2>
+ <p>Do not commit real funds to the Service unless you can afford to lose all of them without hardship. Simulation and devnet modes exist for exploring the platform without real exposure — prefer them wherever they are offered.</p>
+
+ <h2>8. Eligibility and jurisdiction</h2>
+ <p>You are solely responsible for ensuring that your use of Real-Funds Features is lawful where you live, including compliance with securities, tax, and exchange-control rules. The Service is not offered where such use would be unlawful. Real-Funds Features are not intended for persons under 18.</p>
+
+ <h2>9. How acknowledgment works</h2>
+ <p>The Service asks you to accept this Disclosure once per browser before your first real-funds action. Your acceptance is versioned and recorded, including the date and the feature you were using. If this Disclosure changes materially, the version number increases and you will be asked to accept it again before your next real-funds action. Declining keeps you on the platform — you simply cannot execute real-funds actions until you accept.</p>
+
+ <h2>10. Contact</h2>
+ <p>Questions about this Disclosure: <a href="mailto:[email protected]">[email protected]</a>.</p>
+
+ <hr />
+ <p class="foot">three.ws · <a href="/legal/tos.html">Terms of Service</a> · <a href="/legal/privacy.html">Privacy Policy</a> · <a href="/legal/content-policy.html">Content Policy</a></p>
+</div>
+</body>
+</html>
diff --git a/public/risk-ack.js b/public/risk-ack.js
new file mode 100644
index 000000000..5c5377ff5
--- /dev/null
+++ b/public/risk-ack.js
@@ -0,0 +1,331 @@
+// risk-ack.js — the real-funds risk acknowledgment gate for three.ws.
+//
+// three.ws is an experiment in innovation. Before ANY feature commits real
+// money (trades, snipes, withdrawals, launches, swaps, x402 payments, fiat
+// onramp), the user must have accepted the Risk Disclosure (/legal/risk):
+// they use real funds entirely at their own risk and three.ws is not
+// responsible for losses.
+//
+// This file is dependency-free on purpose. It lives in public/ so it is
+// importable at runtime from BOTH worlds:
+// - Vite-bundled app modules, via the src/shared/risk-ack.js wrapper
+// (dynamic import of '/risk-ack.js')
+// - plain public/ scripts and third-party embeds (x402.js on merchant
+// sites), where root-relative import resolves against the three.ws origin
+//
+// Usage — gate any money-committing action:
+//
+// import { ensureRiskAck } from '/risk-ack.js';
+// async function onTrade() {
+// if (!(await ensureRiskAck({ context: 'trade' }))) return; // declined
+// … move real funds …
+// }
+//
+// Acceptance is versioned. Bump RISK_ACK_VERSION when the disclosure changes
+// materially and every user re-acknowledges on their next money action.
+// Acceptance persists in localStorage and is recorded server-side
+// (POST /api/legal/risk-ack → audit_log) for record-keeping.
+
+export const RISK_ACK_VERSION = 1;
+export const RISK_ACK_STORAGE_KEY = 'threews:risk-ack';
+export const RISK_ACK_ENDPOINT = '/api/legal/risk-ack';
+
+/**
+ * Parse a raw stored acceptance record. Pure — safe to unit-test.
+ * @param {string|null|undefined} raw
+ * @returns {{version:number, acceptedAt:string, context?:string}|null}
+ */
+export function parseAckRecord(raw) {
+ if (!raw || typeof raw !== 'string') return null;
+ try {
+ const rec = JSON.parse(raw);
+ if (!rec || typeof rec !== 'object') return null;
+ const version = Number(rec.version);
+ if (!Number.isInteger(version) || version < 1) return null;
+ if (typeof rec.acceptedAt !== 'string' || Number.isNaN(Date.parse(rec.acceptedAt))) return null;
+ const out = { version, acceptedAt: rec.acceptedAt };
+ if (typeof rec.context === 'string') out.context = rec.context;
+ return out;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Is a parsed acceptance record current for the given disclosure version?
+ * Pure — safe to unit-test.
+ * @param {{version:number}|null} record
+ * @param {number} [version]
+ */
+export function isAckCurrent(record, version = RISK_ACK_VERSION) {
+ return !!record && Number.isInteger(record.version) && record.version >= version;
+}
+
+// localStorage can be unavailable (private mode, embeds with blocked storage).
+// Keep an in-memory fallback so one acceptance at least covers the page session.
+let _sessionAck = null;
+
+function _readStored() {
+ try {
+ return parseAckRecord(globalThis.localStorage?.getItem(RISK_ACK_STORAGE_KEY));
+ } catch {
+ return null;
+ }
+}
+
+/** Has the user accepted the current version of the Risk Disclosure? */
+export function hasRiskAck() {
+ return isAckCurrent(_readStored()) || isAckCurrent(_sessionAck);
+}
+
+function _persist(record) {
+ _sessionAck = record;
+ try {
+ globalThis.localStorage?.setItem(RISK_ACK_STORAGE_KEY, JSON.stringify(record));
+ } catch {
+ /* storage blocked — session fallback above still applies */
+ }
+}
+
+function _recordServerSide(record) {
+ try {
+ // Resolve against this module's origin so third-party embeds (x402.js on
+ // merchant sites) record to three.ws, not the host page. Same-origin
+ // requests carry the session cookie; cross-origin ones record anonymously.
+ const url = new URL(RISK_ACK_ENDPOINT, import.meta.url);
+ fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'same-origin',
+ keepalive: true,
+ body: JSON.stringify({
+ version: record.version,
+ context: record.context || null,
+ path: globalThis.location ? globalThis.location.pathname : null,
+ }),
+ }).catch(() => {});
+ } catch {
+ /* best-effort — client-side acceptance already stands */
+ }
+}
+
+const STYLE_ID = 'risk-ack-styles';
+
+function _ensureStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.risk-ack {
+ border: none; padding: 0; background: transparent; color: inherit;
+ max-width: min(560px, calc(100vw - 2rem));
+ max-height: calc(100svh - 2rem);
+ opacity: 1; transform: scale(1) translateY(0);
+ transition: opacity .2s ease, transform .2s ease;
+ font-family: var(--sans, -apple-system, system-ui, 'Segoe UI', sans-serif);
+}
+.risk-ack::backdrop { background: var(--modal-backdrop, rgba(0, 0, 0, .72)); }
+@starting-style {
+ .risk-ack[open] { opacity: 0; transform: scale(.96) translateY(10px); }
+}
+.risk-ack--closing { opacity: 0 !important; transform: scale(.96) translateY(10px) !important; }
+.risk-ack-inner {
+ background: var(--modal-bg, rgba(10, 11, 18, .97));
+ border: 1px solid var(--modal-border, rgba(255, 255, 255, .14));
+ border-radius: var(--modal-radius, 16px);
+ box-shadow: var(--modal-shadow, 0 24px 64px rgba(0, 0, 0, .6));
+ display: flex; flex-direction: column;
+ max-height: calc(100svh - 4rem); overflow: hidden;
+}
+.risk-ack-header {
+ display: flex; align-items: center; gap: .6rem;
+ padding: 1rem 1.5rem;
+ border-bottom: 1px solid var(--modal-border, rgba(255, 255, 255, .14));
+}
+.risk-ack-badge {
+ font-size: 1.15rem; line-height: 1;
+ color: var(--amber, #f2c063);
+}
+.risk-ack-title {
+ margin: 0; font-size: 1.05rem; font-weight: 600;
+ color: var(--ink, #f5f7fa); line-height: 1.25;
+}
+.risk-ack-body {
+ padding: 1.25rem 1.5rem; overflow-y: auto;
+ color: var(--ink-dim, rgba(245, 247, 250, .68));
+ font-size: .92rem; line-height: 1.55;
+}
+.risk-ack-body p { margin: 0 0 .75rem; }
+.risk-ack-body ul { margin: 0 0 .75rem; padding-left: 1.2rem; }
+.risk-ack-body li { margin-bottom: .45rem; }
+.risk-ack-body strong { color: var(--ink, #f5f7fa); font-weight: 600; }
+.risk-ack-body a { color: var(--accent, #a4f0bc); }
+.risk-ack-check {
+ display: flex; align-items: flex-start; gap: .6rem;
+ margin-top: .9rem; padding: .75rem .85rem;
+ background: var(--surface-2, rgba(255, 255, 255, .05));
+ border: 1px solid var(--line, rgba(255, 255, 255, .12));
+ border-radius: var(--radius-md, 10px);
+ cursor: pointer; user-select: none;
+ color: var(--ink, #f5f7fa); font-size: .88rem; line-height: 1.45;
+ transition: border-color .15s;
+}
+.risk-ack-check:hover { border-color: var(--ink-dim, rgba(245, 247, 250, .4)); }
+.risk-ack-check:focus-within { outline: 2px solid var(--accent, #a4f0bc); outline-offset: 2px; }
+.risk-ack-check input {
+ margin: .15rem 0 0; flex-shrink: 0;
+ width: 1rem; height: 1rem;
+ accent-color: var(--accent, #a4f0bc);
+ cursor: pointer;
+}
+.risk-ack-actions {
+ display: flex; justify-content: flex-end; gap: .75rem; flex-wrap: wrap;
+ padding: 1rem 1.5rem;
+ border-top: 1px solid var(--modal-border, rgba(255, 255, 255, .14));
+}
+.risk-ack-btn {
+ font: inherit; font-size: .9rem; font-weight: 600;
+ padding: .55rem 1.1rem; border-radius: var(--radius-md, 10px);
+ cursor: pointer; transition: background .15s, color .15s, opacity .15s;
+ border: 1px solid var(--line, rgba(255, 255, 255, .16));
+ background: transparent; color: var(--ink-dim, rgba(245, 247, 250, .68));
+}
+.risk-ack-btn:hover { color: var(--ink, #f5f7fa); background: var(--surface-2, rgba(255, 255, 255, .06)); }
+.risk-ack-btn:focus-visible { outline: 2px solid var(--accent, #a4f0bc); outline-offset: 2px; }
+.risk-ack-btn--accept {
+ border-color: transparent;
+ background: var(--accent, #a4f0bc); color: var(--accent-ink, #08130c);
+}
+.risk-ack-btn--accept:hover:not(:disabled) { background: var(--accent, #a4f0bc); color: var(--accent-ink, #08130c); opacity: .88; }
+.risk-ack-btn--accept:disabled { opacity: .4; cursor: not-allowed; }
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+function _buildDialog() {
+ const dialog = document.createElement('dialog');
+ dialog.className = 'risk-ack';
+ dialog.setAttribute('aria-modal', 'true');
+ dialog.setAttribute('aria-labelledby', 'risk-ack-title');
+ dialog.setAttribute('aria-describedby', 'risk-ack-body');
+ dialog.innerHTML = `
+ <div class="risk-ack-inner">
+ <div class="risk-ack-header">
+ <span class="risk-ack-badge" aria-hidden="true">&#9888;</span>
+ <h2 class="risk-ack-title" id="risk-ack-title">Real funds — risk acknowledgment</h2>
+ </div>
+ <div class="risk-ack-body" id="risk-ack-body">
+ <p><strong>three.ws is experimental software</strong> — an attempt at innovation, provided
+ &ldquo;as is&rdquo;, with no warranties of any kind. Before using any feature that moves real
+ money, you must acknowledge:</p>
+ <ul>
+ <li><strong>You can lose everything you commit.</strong> Digital assets are volatile;
+ losses can be total, fast, and irreversible.</li>
+ <li><strong>Autonomous features act on your behalf.</strong> Agents, snipers, strategies,
+ and autopilot can execute trades and payments without asking you again.</li>
+ <li><strong>Nothing here is advice.</strong> No content on three.ws is financial,
+ investment, legal, or tax advice.</li>
+ <li><strong>three.ws is not responsible for losses.</strong> The operators accept no
+ liability for any loss of funds, however it occurs.</li>
+ <li><strong>Only use funds you can fully afford to lose</strong>, and only where lawful
+ in your jurisdiction.</li>
+ </ul>
+ <p>Full text: <a href="/legal/risk" target="_blank" rel="noopener">Risk Disclosure</a> ·
+ <a href="/legal/tos" target="_blank" rel="noopener">Terms of Service</a></p>
+ <label class="risk-ack-check">
+ <input type="checkbox" data-risk-ack-check />
+ <span>I have read and understood the Risk Disclosure. I accept that three.ws is not
+ responsible for any losses and that I use real funds entirely at my own risk.</span>
+ </label>
+ </div>
+ <div class="risk-ack-actions">
+ <button type="button" class="risk-ack-btn" data-risk-ack-decline>Not now</button>
+ <button type="button" class="risk-ack-btn risk-ack-btn--accept" data-risk-ack-accept disabled>
+ I accept the risks
+ </button>
+ </div>
+ </div>
+ `;
+ return dialog;
+}
+
+let _inFlight = null;
+
+/**
+ * Ensure the user has accepted the current Risk Disclosure. Resolves
+ * immediately with true if already accepted; otherwise shows the
+ * acknowledgment dialog and resolves with the user's decision.
+ *
+ * Concurrent calls share one dialog and one resulting promise.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.context] — short slug of the gated action ('trade',
+ * 'snipe', 'withdraw', 'swap', 'launch', 'x402-pay', 'onramp', …), stored
+ * with the acceptance record for audit.
+ * @returns {Promise<boolean>} true = accepted (now or previously), false = declined
+ */
+export function ensureRiskAck({ context = 'real-funds' } = {}) {
+ if (hasRiskAck()) return Promise.resolve(true);
+ if (typeof document === 'undefined') return Promise.resolve(false);
+ if (_inFlight) return _inFlight;
+
+ _inFlight = new Promise((resolve) => {
+ _ensureStyles();
+ const dialog = _buildDialog();
+ document.body.appendChild(dialog);
+
+ const checkbox = dialog.querySelector('[data-risk-ack-check]');
+ const acceptBtn = dialog.querySelector('[data-risk-ack-accept]');
+ const declineBtn = dialog.querySelector('[data-risk-ack-decline]');
+ const prevOverflow = document.body.style.overflow;
+ const trigger = document.activeElement;
+ let settled = false;
+
+ const finish = (accepted) => {
+ if (settled) return;
+ settled = true;
+ dialog.classList.add('risk-ack--closing');
+ setTimeout(() => {
+ if (dialog.open) dialog.close();
+ dialog.remove();
+ document.body.style.overflow = prevOverflow;
+ if (trigger instanceof Element) trigger.focus?.();
+ }, 210);
+ _inFlight = null;
+ resolve(accepted);
+ };
+
+ checkbox.addEventListener('change', () => {
+ acceptBtn.disabled = !checkbox.checked;
+ });
+ acceptBtn.addEventListener('click', () => {
+ if (!checkbox.checked) return;
+ const record = {
+ version: RISK_ACK_VERSION,
+ acceptedAt: new Date().toISOString(),
+ context,
+ };
+ _persist(record);
+ _recordServerSide(record);
+ finish(true);
+ });
+ declineBtn.addEventListener('click', () => finish(false));
+ dialog.addEventListener('cancel', (e) => {
+ e.preventDefault();
+ finish(false);
+ });
+ dialog.addEventListener('click', (e) => {
+ const rect = dialog.getBoundingClientRect();
+ const outside =
+ e.clientX < rect.left || e.clientX > rect.right ||
+ e.clientY < rect.top || e.clientY > rect.bottom;
+ if (outside) finish(false);
+ });
+
+ document.body.style.overflow = 'hidden';
+ dialog.showModal();
+ checkbox.focus();
+ });
+
+ return _inFlight;
+}
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 197477ee3..e8f4e53df 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,25 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:locale" content="en_US">
- <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/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Sitemap — three.ws">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@trythreews">
- <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/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@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"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index c4e445277..9c68b76fb 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -22,6 +22,7 @@
import { ACTION_TYPES } from './agent-protocol.js';
import { THREE_WS_MARK } from './solana/vanity/brand.js';
import { mountCoinStatus } from './pump/coin-status-card.js';
+import { ensureRiskAck } from './shared/risk-ack.js';
const REFRESH_MS = 30_000;
const QUOTE_DEBOUNCE_MS = 250;
@@ -680,6 +681,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
const executeTrade = async () => {
if (!isExecutable(state)) return;
+ if (state.network !== 'devnet' && !(await ensureRiskAck({ context: 'pump-trade' }))) return;
const isBuy = state.tradeOpen === 'buy';
const btn = cardBody.querySelector('[data-action="confirm-trade"]');
if (btn) {
diff --git a/src/agent-wallet-hub/tabs/autopilot.js b/src/agent-wallet-hub/tabs/autopilot.js
index 0c89fbfce..09dd5672e 100644
--- a/src/agent-wallet-hub/tabs/autopilot.js
+++ b/src/agent-wallet-hub/tabs/autopilot.js
@@ -17,6 +17,7 @@
import { registerWalletTab } from '../registry.js';
import { formatUsd, formatSol, explorerTxUrl } from '../util.js';
import { consumeCsrfToken } from '../../api.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const STYLE_ID = 'awh-autopilot-style';
@@ -436,6 +437,7 @@ registerWalletTab({
if (!sweep.ok) { ctx.toast(sweep.message); return; }
const needsSweepDest = c.rules.some((r) => r.kind === 'sweep') && !(sweep.value || c.sweep_destination);
if (needsSweepDest) { ctx.toast('Set a sweep destination — your policy sweeps profit.'); return; }
+ if (!(await ensureRiskAck({ context: 'autopilot' }))) return;
await savePolicy({
rules: c.rules,
buffer_sol: c.buffer_sol,
diff --git a/src/agent-wallet-hub/tabs/give.js b/src/agent-wallet-hub/tabs/give.js
index 74c092b7b..2da137f72 100644
--- a/src/agent-wallet-hub/tabs/give.js
+++ b/src/agent-wallet-hub/tabs/give.js
@@ -24,6 +24,7 @@
import { registerWalletTab } from '../registry.js';
import { formatUsd, explorerTxUrl, shortAddress as shortAddr } from '../util.js';
import { consumeCsrfToken } from '../../api.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const PREF_KEY = (agentId) => `awh:give:${agentId}`;
@@ -502,6 +503,7 @@ registerWalletTab({
async function submitDonation() {
const it = state.intent;
if (!it || state.phase === 'sending') return;
+ if (ctx.getNetwork() !== 'devnet' && !(await ensureRiskAck({ context: 'give' }))) return;
state.phase = 'sending';
render();
const res = await call(base('withdraw'), {
diff --git a/src/agent-wallet-hub/tabs/pay.js b/src/agent-wallet-hub/tabs/pay.js
index 47133d898..040063f4c 100644
--- a/src/agent-wallet-hub/tabs/pay.js
+++ b/src/agent-wallet-hub/tabs/pay.js
@@ -15,6 +15,7 @@
*/
import { registerWalletTab } from '../registry.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
import {
searchBazaarServices,
previewX402,
@@ -496,6 +497,7 @@ registerWalletTab({
const sel = state.selected;
const p = state.preview;
if (!sel || !p || !p.payable) return;
+ if (!(await ensureRiskAck({ context: 'x402-pay' }))) return;
state.paying = true;
state.payError = null;
state.progress = [{ key: 'start', label: 'Submitting payment…', active: true }];
diff --git a/src/agent-wallet-hub/tabs/snipe.js b/src/agent-wallet-hub/tabs/snipe.js
index e4c0ddb16..044664d04 100644
--- a/src/agent-wallet-hub/tabs/snipe.js
+++ b/src/agent-wallet-hub/tabs/snipe.js
@@ -19,6 +19,7 @@
import { registerWalletTab } from '../registry.js';
import { consumeCsrfToken } from '../../api.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
import { formatSol, shortAddress, explorerAddressUrl } from '../util.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
@@ -456,6 +457,7 @@ registerWalletTab({
if (!(BigInt(s.per_trade_lamports || '0') > 0n) || !(BigInt(s.daily_budget_lamports || '0') > 0n)) {
ctx.toast('Set a per-trade size and a daily budget first.'); return;
}
+ if (ctx.getNetwork() !== 'devnet' && !(await ensureRiskAck({ context: 'snipe' }))) return;
state.arming = true; render();
const res = await call('/api/sniper/strategy', {
method: 'POST',
diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.js
index b8f04d56e..aa37840cd 100644
--- a/src/agent-wallet-hub/tabs/trade.js
+++ b/src/agent-wallet-hub/tabs/trade.js
@@ -24,6 +24,7 @@ import {
previewAgentTrade, executeAgentTrade, fetchAgentHoldings, fetchAgentTradeHistory, TradeError,
} from '../../agent-solana-wallet.js';
import { createSafetyPanel } from '../../shared/safety-panel.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
import { solToUsd } from '../../shared/usd-price.js';
import { formatSol, timeAgo, explorerTxUrl } from '../util.js';
@@ -364,6 +365,7 @@ registerWalletTab({
async function submit() {
const args = tradeArgs();
if (!args || state.submitting) return;
+ if (ctx.getNetwork() !== 'devnet' && !(await ensureRiskAck({ context: 'trade' }))) return;
state.submitting = true;
state.confirming = false;
state.result = null;
diff --git a/src/agent-wallet-hub/tabs/withdraw.js b/src/agent-wallet-hub/tabs/withdraw.js
index a1332218a..e53e5d273 100644
--- a/src/agent-wallet-hub/tabs/withdraw.js
+++ b/src/agent-wallet-hub/tabs/withdraw.js
@@ -21,6 +21,7 @@
import { registerWalletTab } from '../registry.js';
import { formatUsd, explorerTxUrl, explorerAddressUrl } from '../util.js';
import { consumeCsrfToken } from '../../api.js';
+import { ensureRiskAck } from '../../shared/risk-ack.js';
const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -435,6 +436,7 @@ registerWalletTab({
async function submitWithdraw() {
const it = state.intent;
if (!it || state.phase === 'sending') return;
+ if (ctx.getNetwork() !== 'devnet' && !(await ensureRiskAck({ context: 'withdraw' }))) return;
state.phase = 'sending';
render();
const res = await call(base('withdraw'), {
diff --git a/src/arm.js b/src/arm.js
index ea30840be..55919753c 100644
--- a/src/arm.js
+++ b/src/arm.js
@@ -2,6 +2,8 @@
// Reuses the Oracle watch API: /api/agents, /api/oracle/watch, /api/oracle/test-alert.
// Self-contained: no imports from oracle.js so this page stands on its own.
+import { ensureRiskAck } from './shared/risk-ack.js';
+
const NETWORK = 'mainnet';
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
@@ -399,6 +401,8 @@ async function loadWatch(agentId) {
}
async function saveWatch() {
+ // Arming in live mode commits the agent's real SOL — gate on the risk ack.
+ if (modeIsLive() && isOn('#armToggle') && !(await ensureRiskAck({ context: 'oracle-arm' }))) return;
const btn = $('#saveBtn');
btn.disabled = true; btn.textContent = 'Saving…';
const cats = $$('#catChips .cchip.on').map((b) => b.dataset.cat);
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index 3f1190c2e..43189b68d 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -42,6 +42,7 @@ export const NAV = [
{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },
{ path: '/dashboard/copy', label: 'Copy Trading', icon: 'live', group: 'Monetize', tags: ['copy', 'copy-trade', 'mirror', 'leader', 'follow', 'traders', 'intents', 'pump.fun', 'sniper'] },
{ path: '/dashboard/sniper', label: 'Sniper Strategies', icon: 'live', group: 'Monetize', tags: ['sniper', 'autonomous', 'strategy', 'pump.fun', 'auto-trade', 'budget', 'positions', 'pnl', 'kill-switch'] },
+ { path: '/dashboard/fleet', label: 'Fleet Command', icon: 'pulse', group: 'Monetize', tags: ['fleet', 'swarm', 'command', 'sniper', 'agents', 'bulk', 'arm all', 'kill switch', 'emergency stop', 'pooled', 'roster', 'live trades', 'mission control'] },
{ path: '/dashboard/capabilities', label: 'Capabilities', icon: 'live', group: 'Monetize', tags: ['alpha hunt', 'launcher', 'coin launcher', 'auto-claim', 'creator fees', 'market maker', 'jito', 'autonomous', 'capabilities'] },
{ path: '/launcher', label: 'Memetic Launcher', icon: 'sparkle', group: 'Monetize', tags: ['memetic', 'launcher', 'coin launcher', 'autonomous', 'narrative', 'meme', 'preview', 'rotation', 'cadence', 'pump.fun'] },
{ path: '/dashboard/prelaunch-radar', label: 'Pre-Launch Radar', icon: 'live', group: 'Monetize', tags: ['radar', 'pre-launch', 'precursor', 'block-zero', 'snipe', 'creator', 'smart-money', 'pump.fun', 'pre-cog', 'watchlist'] },
diff --git a/src/dashboard-next/pages/fleet.js b/src/dashboard-next/pages/fleet.js
new file mode 100644
index 000000000..eaaadfa1e
--- /dev/null
+++ b/src/dashboard-next/pages/fleet.js
@@ -0,0 +1,654 @@
+// dashboard-next — Fleet Command.
+//
+// A command center for running many autonomous sniper agents at once. The
+// per-strategy Sniper page (/dashboard/sniper) is the right surface for tuning a
+// single bot; it does not scale to a 30+ agent swarm — you cannot see the whole
+// fleet's health, move money in bulk, or hit one emergency stop. This page fills
+// that gap:
+// 1. Fleet KPIs — armed count, pooled wallet SOL, low-balance count,
+// open positions (live), realized PnL, win rate.
+// 2. Fleet actions — Arm all / Disarm all / Emergency Stop, each gated by a
+// confirm dialog and reporting honest partial results
+// ("Armed 30/33 · 3 failed · <first error>").
+// 3. Roster — one sortable, multi-select row per agent: status,
+// wallet balance (low-balance warning), open/closed,
+// win rate, realized PnL, per-row arm/disarm/kill.
+// 4. Live trade feed — the SSE stream of buys/sells across the whole fleet.
+//
+// It drives the exact same endpoints as the Sniper page — no new backend:
+// GET /api/sniper/strategy → { strategies: [...] }
+// GET /api/sniper/leaderboard → seed of open positions
+// GET /api/sniper/stream → SSE: buy/update/sell position events
+// POST /api/sniper/strategy → { agent_id, network, enabled|kill_switch }
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, post, esc, relTime } from '../api.js';
+
+const lamportsToSol = (l) => Number(BigInt(l || '0')) / 1e9;
+const fmtSol = (sol) => {
+ const v = Number(sol) || 0;
+ if (Math.abs(v) < 0.001 && v !== 0) return `${v.toFixed(4)} ◎`;
+ return `${v.toFixed(3)} ◎`;
+};
+const clr = (n) => (Number(n) > 0 ? 'fc-pos' : Number(n) < 0 ? 'fc-neg' : '');
+const signed = (n, f) => `${Number(n) > 0 ? '+' : ''}${f(n)}`;
+
+// A fleet agent counts as "low balance" when its wallet can't cover one more
+// trade plus a little fee headroom — the point at which arming is futile.
+function isLowBalance(s) {
+ if (s.wallet_sol == null) return false;
+ return s.wallet_sol < lamportsToSol(s.per_trade_lamports || '0') + 0.003;
+}
+function statusOf(s) {
+ if (s.kill_switch) return 'kill';
+ if (s.enabled) return 'armed';
+ return 'disarmed';
+}
+
+// ── Styles ──────────────────────────────────────────────────────────────────
+// Uses the dashboard's own --nxt-* design tokens so it reads as one product with
+// the rest of dashboard-next. `.fc-` prefix keeps it clear of the Sniper page's
+// `.sn-` styles. Mono, sign-coloured numbers do the "trading desk" work.
+
+const STYLE = `<style>
+.fc-wrap { display: grid; gap: 18px; }
+
+/* KPI deck */
+.fc-deck { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
+.fc-kpi { position: relative; background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 14px 16px; overflow: hidden; }
+.fc-kpi::before { content: ''; position: absolute; inset: 0 0 auto 0; height: 2px; background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--nxt-accent) 55%, transparent), transparent); opacity: .5; }
+.fc-kpi-label { font-size: 11px; color: var(--nxt-ink-faint); text-transform: uppercase; letter-spacing: .05em; margin-bottom: 5px; }
+.fc-kpi-val { font-size: 23px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; font-family: var(--nxt-mono, ui-monospace, monospace); }
+.fc-kpi-sub { font-size: 11px; color: var(--nxt-ink-faint); margin-top: 4px; }
+
+/* action + filter bar */
+.fc-bar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
+.fc-actions { display: flex; gap: 8px; flex-wrap: wrap; }
+.fc-btn { font-size: 12.5px; font-family: inherit; padding: 7px 14px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; transition: border-color .12s, background .12s, transform .12s, opacity .12s; }
+.fc-btn:hover:not(:disabled) { border-color: var(--nxt-stroke-strong); transform: translateY(-1px); }
+.fc-btn:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+.fc-btn:disabled { opacity: .45; cursor: not-allowed; }
+.fc-btn.primary { background: var(--nxt-accent); color: #061018; border-color: transparent; font-weight: 600; }
+.fc-btn.danger { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 45%, transparent); }
+.fc-btn.danger:hover:not(:disabled) { background: color-mix(in srgb, var(--nxt-danger, #f87171) 12%, transparent); }
+.fc-spacer { flex: 1; }
+.fc-search { flex: 0 1 220px; }
+.fc-search input { width: 100%; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); color: var(--nxt-ink); padding: 7px 11px; font-size: 13px; font-family: inherit; transition: border-color .12s; }
+.fc-search input:focus { outline: none; border-color: var(--nxt-accent); }
+.fc-chips { display: inline-flex; gap: 6px; flex-wrap: wrap; }
+.fc-chip { font-size: 12px; font-family: inherit; padding: 6px 11px; border-radius: 999px; border: 1px solid var(--nxt-stroke); background: transparent; color: var(--nxt-ink-dim); cursor: pointer; transition: color .12s, border-color .12s, background .12s; }
+.fc-chip:hover { color: var(--nxt-ink); }
+.fc-chip.active { background: color-mix(in srgb, var(--nxt-accent) 14%, transparent); color: var(--nxt-ink); border-color: color-mix(in srgb, var(--nxt-accent) 45%, transparent); }
+.fc-chip:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+.fc-selinfo { font-size: 12px; color: var(--nxt-ink-faint); }
+
+/* roster table */
+.fc-panel { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); overflow: hidden; }
+.fc-tablewrap { overflow-x: auto; }
+.fc-table { width: 100%; border-collapse: collapse; font-size: 13px; min-width: 720px; }
+.fc-table th { padding: 10px 14px; text-align: left; font: 600 10px/1 var(--nxt-mono, monospace); letter-spacing: .07em; text-transform: uppercase; color: var(--nxt-ink-faint); border-bottom: 1px solid var(--nxt-line); white-space: nowrap; user-select: none; }
+.fc-table th.sortable { cursor: pointer; }
+.fc-table th.sortable:hover { color: var(--nxt-ink); }
+.fc-table th .fc-sort-ind { opacity: .5; font-size: 9px; }
+.fc-table th.r, .fc-table td.r { text-align: right; }
+.fc-table th.c, .fc-table td.c { text-align: center; }
+.fc-row td { padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.04); vertical-align: middle; white-space: nowrap; }
+.fc-row:last-child td { border-bottom: none; }
+.fc-row:hover { background: var(--nxt-bg-2); }
+.fc-row.sel { background: color-mix(in srgb, var(--nxt-accent) 8%, transparent); }
+.fc-mono { font-family: var(--nxt-mono, monospace); font-variant-numeric: tabular-nums; }
+.fc-ag { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.fc-av { width: 30px; height: 30px; border-radius: 8px; object-fit: cover; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); flex-shrink: 0; }
+.fc-agname { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; }
+.fc-agsub { font-size: 11px; color: var(--nxt-ink-faint); }
+.fc-pill { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; padding: 3px 9px; border-radius: 999px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-dim); white-space: nowrap; }
+.fc-pill .fc-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
+.fc-pill.armed { color: var(--nxt-success); border-color: color-mix(in srgb, var(--nxt-success) 35%, transparent); background: color-mix(in srgb, var(--nxt-success) 8%, transparent); }
+.fc-pill.armed .fc-dot { animation: fc-pulse 2s ease infinite; }
+.fc-pill.kill { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 35%, transparent); background: color-mix(in srgb, var(--nxt-danger, #f87171) 8%, transparent); }
+.fc-pill.disarmed { color: var(--nxt-ink-faint); }
+@keyframes fc-pulse { 0%,100% { opacity: 1 } 50% { opacity: .3 } }
+.fc-warn { color: var(--nxt-warn, #f59e0b); font-size: 11px; }
+.fc-rowbtns { display: inline-flex; gap: 6px; }
+.fc-rowbtn { font-size: 11px; font-family: inherit; padding: 4px 9px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; transition: border-color .12s, background .12s; text-decoration: none; }
+.fc-rowbtn:hover { border-color: var(--nxt-stroke-strong); }
+.fc-rowbtn.danger { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 40%, transparent); }
+.fc-rowbtn:disabled { opacity: .5; cursor: progress; }
+.fc-check { width: 15px; height: 15px; accent-color: var(--nxt-accent); cursor: pointer; }
+.fc-pos { color: var(--nxt-success); }
+.fc-neg { color: var(--nxt-danger, #f87171); }
+
+/* live feed */
+.fc-live-head { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid var(--nxt-line); }
+.fc-live-title { font-size: 13px; font-weight: 600; display: flex; gap: 8px; align-items: center; }
+.fc-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--nxt-success); animation: fc-pulse 2s ease infinite; flex-shrink: 0; }
+.fc-live-dot.connecting { background: var(--nxt-warn, #f59e0b); }
+.fc-live-dot.offline { background: var(--nxt-danger, #f87171); animation: none; }
+.fc-conn { font-size: 11px; color: var(--nxt-ink-faint); }
+.fc-feed { max-height: 320px; overflow-y: auto; }
+.fc-frow { display: grid; grid-template-columns: auto 1fr auto auto; gap: 10px; align-items: center; padding: 9px 16px; border-bottom: 1px solid var(--nxt-line); font-size: 13px; }
+.fc-frow:last-child { border-bottom: none; }
+.fc-fdir { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 2px 7px; border-radius: 5px; }
+.fc-fdir.buy { color: var(--nxt-success); background: color-mix(in srgb, var(--nxt-success) 12%, transparent); }
+.fc-fdir.sell { color: var(--nxt-danger, #f87171); background: color-mix(in srgb, var(--nxt-danger, #f87171) 12%, transparent); }
+.fc-fsym { font-weight: 600; }
+.fc-fsub { font-size: 11px; color: var(--nxt-ink-faint); }
+.fc-fpnl { font-family: var(--nxt-mono, monospace); font-variant-numeric: tabular-nums; text-align: right; }
+.fc-ftime { font-size: 11px; color: var(--nxt-ink-faint); font-variant-numeric: tabular-nums; }
+
+/* states */
+.fc-empty { color: var(--nxt-ink-faint); font-size: 13px; padding: 28px 16px; text-align: center; }
+.fc-empty b { color: var(--nxt-ink); }
+.fc-sk { height: 46px; border-radius: 8px; background: var(--nxt-bg-2); animation: fc-sk 1.4s ease infinite; margin: 8px 0; }
+@keyframes fc-sk { 0%,100% { opacity: .5 } 50% { opacity: 1 } }
+
+/* confirm dialog */
+.fc-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.6); backdrop-filter: blur(6px); z-index: 950; display: flex; align-items: center; justify-content: center; padding: 16px; animation: fc-fade .14s ease; }
+@keyframes fc-fade { from { opacity: 0 } to { opacity: 1 } }
+.fc-modal { background: var(--nxt-bg); border: 1px solid var(--nxt-stroke-strong); border-radius: var(--nxt-radius); padding: 22px; width: 100%; max-width: 440px; }
+.fc-modal h2 { font-size: 16px; margin: 0 0 10px; }
+.fc-modal p { font-size: 13.5px; color: var(--nxt-ink-dim); line-height: 1.5; margin: 0 0 6px; }
+.fc-modal-foot { display: flex; gap: 10px; justify-content: flex-end; margin-top: 18px; }
+
+/* toast */
+.fc-toasts { position: fixed; bottom: 20px; right: 20px; z-index: 980; display: flex; flex-direction: column; gap: 8px; align-items: flex-end; }
+.fc-toast { background: var(--nxt-bg); border: 1px solid var(--nxt-stroke-strong); border-left: 3px solid var(--nxt-accent); border-radius: var(--nxt-radius-sm); padding: 11px 15px; font-size: 13px; color: var(--nxt-ink); max-width: 360px; box-shadow: 0 8px 26px rgba(0,0,0,.4); animation: fc-slide .18s ease; }
+.fc-toast.err { border-left-color: var(--nxt-danger, #f87171); }
+@keyframes fc-slide { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: none } }
+@media (prefers-reduced-motion: reduce) {
+ .fc-pill.armed .fc-dot, .fc-live-dot, .fc-sk { animation: none; }
+ .fc-btn:hover:not(:disabled) { transform: none; }
+}
+</style>`;
+
+// ── State ───────────────────────────────────────────────────────────────────
+
+let _strategies = [];
+let _positions = new Map(); // id → normalized open position
+let _feed = []; // rolling recent buy/sell events (newest first)
+let _sel = new Set(); // selected agent_ids
+let _sort = { key: 'status', dir: 1 };
+let _filter = { q: '', status: 'all' };
+let _sse = null;
+let _sseTimer = null;
+let _sseRetry = 0;
+
+// ── Boot ────────────────────────────────────────────────────────────────────
+
+(async function boot() {
+ try {
+ const main = await mountShell();
+ await requireUser();
+ main.innerHTML = `
+ <h1 class="dn-h1">Fleet Command</h1>
+ <p class="dn-h1-sub">Every autonomous sniper agent on one deck — pooled balances, live trades, and fleet-wide controls.</p>
+ <div id="fc-root">${STYLE}<div class="fc-sk"></div><div class="fc-sk"></div><div class="fc-sk"></div></div>
+ `;
+ await refresh();
+ window.addEventListener('beforeunload', stopSse);
+ } catch (e) {
+ const root = document.getElementById('fc-root');
+ if (root) root.innerHTML = `${STYLE}<div class="fc-panel"><p class="fc-empty">${esc(e.message || 'Error loading the fleet')}</p></div>`;
+ }
+})();
+
+async function refresh() {
+ const data = await get('/api/sniper/strategy').catch(() => ({ strategies: [] }));
+ _strategies = data.strategies || [];
+ // Drop selections for agents that no longer exist.
+ _sel = new Set([..._sel].filter((id) => _strategies.some((s) => s.agent_id === id)));
+ render();
+ startSse();
+}
+
+// ── Render ──────────────────────────────────────────────────────────────────
+
+function render() {
+ const root = document.getElementById('fc-root');
+ if (!root) return;
+ if (!_strategies.length) {
+ root.innerHTML = `${STYLE}
+ <div class="fc-panel"><div class="fc-empty">
+ <p style="font-size:15px;color:var(--nxt-ink);margin-bottom:6px">No armed agents yet</p>
+ Arm your first autonomous trader on the <a class="fc-link" href="/dashboard/sniper" style="color:var(--nxt-accent);text-decoration:none">Sniper Strategies</a> page, then command the whole fleet from here.
+ </div></div>`;
+ return;
+ }
+ root.innerHTML = `${STYLE}
+ <div class="fc-wrap">
+ ${kpiDeck()}
+ ${actionBar()}
+ <div class="fc-panel"><div class="fc-tablewrap">${rosterTable()}</div></div>
+ <div class="fc-panel">
+ <div class="fc-live-head">
+ <div class="fc-live-title"><span class="fc-live-dot connecting" id="fc-live-dot"></span> Live Trade Feed <span class="fc-conn" id="fc-conn" role="status" aria-live="polite">Connecting…</span></div>
+ <a class="fc-btn" href="/leaderboard" target="_blank" rel="noopener" style="padding:5px 12px">Leaderboard ↗</a>
+ </div>
+ <div class="fc-feed" id="fc-feed">${feedRows()}</div>
+ </div>
+ </div>`;
+ wire(root);
+}
+
+function kpiDeck() {
+ const armed = _strategies.filter((s) => statusOf(s) === 'armed').length;
+ const killed = _strategies.filter((s) => s.kill_switch).length;
+ const low = _strategies.filter(isLowBalance).length;
+ const walletSol = _strategies.reduce((a, s) => a + (Number(s.wallet_sol) || 0), 0);
+ const funded = _strategies.filter((s) => (Number(s.wallet_sol) || 0) > 0).length;
+ const openLive = [..._positions.values()].filter((p) => ['opening', 'open'].includes(p.status)).length;
+ const pnlLam = _strategies.reduce((a, s) => a + BigInt(s.summary?.realized_pnl_lamports || '0'), 0n);
+ const pnlSol = lamportsToSol(String(pnlLam));
+ const closed = _strategies.reduce((a, s) => a + (s.summary?.closed_positions || 0), 0);
+ const wins = _strategies.reduce((a, s) => a + (s.summary?.wins || 0), 0);
+ const wr = closed > 0 ? Math.round((wins / closed) * 100) : null;
+
+ const kpi = (label, val, sub = '', cls = '') =>
+ `<div class="fc-kpi"><div class="fc-kpi-label">${label}</div><div class="fc-kpi-val ${cls}">${val}</div>${sub ? `<div class="fc-kpi-sub">${sub}</div>` : ''}</div>`;
+
+ return `<div class="fc-deck">
+ ${kpi('Armed', `${armed}<span style="font-size:14px;color:var(--nxt-ink-faint)"> / ${_strategies.length}</span>`, killed ? `${killed} kill-switched` : 'agents on the deck')}
+ ${kpi('Pooled wallet', fmtSol(walletSol), `${funded}/${_strategies.length} funded${low ? ` · <span class="fc-warn">${low} low</span>` : ''}`)}
+ ${kpi('Open positions', `<span data-kpi-open>${openLive}</span>`, 'live across the fleet')}
+ ${kpi('Realized PnL', signed(pnlSol, fmtSol), `${closed} closed trades`, clr(pnlSol))}
+ ${kpi('Win rate', wr != null ? `${wr}%` : '—', `${wins} wins`)}
+ </div>`;
+}
+
+function actionBar() {
+ const n = _sel.size;
+ const target = n ? `${n} selected` : `all ${visibleRows().length}`;
+ const chip = (key, label) => `<button class="fc-chip ${_filter.status === key ? 'active' : ''}" data-chip="${key}" role="tab" aria-selected="${_filter.status === key}">${label}</button>`;
+ return `<div class="fc-bar">
+ <div class="fc-actions">
+ <button class="fc-btn primary" data-act="arm-all">Arm ${target}</button>
+ <button class="fc-btn" data-act="disarm-all">Disarm ${target}</button>
+ <button class="fc-btn danger" data-act="stop-all">■ Emergency stop</button>
+ </div>
+ <span class="fc-selinfo">${n ? `${n} selected` : 'Acting on all filtered agents'}</span>
+ <div class="fc-spacer"></div>
+ <div class="fc-chips" role="tablist" aria-label="Filter by status">
+ ${chip('all', 'All')}${chip('armed', 'Armed')}${chip('disarmed', 'Disarmed')}${chip('kill', 'Kill switch')}${chip('low', 'Low balance')}
+ </div>
+ <div class="fc-search"><input type="search" id="fc-q" placeholder="Search agents…" value="${esc(_filter.q)}" aria-label="Search agents" /></div>
+ </div>`;
+}
+
+// The set of agents matching the active search + status filter.
+function visibleRows() {
+ const q = _filter.q.trim().toLowerCase();
+ return _strategies.filter((s) => {
+ if (q && !(`${s.agent_name || ''} ${s.agent_id}`.toLowerCase().includes(q))) return false;
+ if (_filter.status === 'all') return true;
+ if (_filter.status === 'low') return isLowBalance(s);
+ return statusOf(s) === _filter.status;
+ });
+}
+
+const COLS = [
+ { key: 'sel', label: '', sortable: false, cls: 'c' },
+ { key: 'agent_name', label: 'Agent', sortable: true },
+ { key: 'status', label: 'Status', sortable: true },
+ { key: 'wallet_sol', label: 'Wallet', sortable: true, cls: 'r' },
+ { key: 'open', label: 'Open', sortable: true, cls: 'r' },
+ { key: 'closed', label: 'Closed', sortable: true, cls: 'r' },
+ { key: 'wr', label: 'Win%', sortable: true, cls: 'r' },
+ { key: 'pnl', label: 'Realized PnL', sortable: true, cls: 'r' },
+ { key: 'act', label: '', sortable: false, cls: 'r' },
+];
+
+function sortVal(s, key) {
+ switch (key) {
+ case 'agent_name': return (s.agent_name || s.agent_id || '').toLowerCase();
+ case 'status': return { armed: 0, disarmed: 1, kill: 2 }[statusOf(s)];
+ case 'wallet_sol': return Number(s.wallet_sol) || 0;
+ case 'open': return openCountFor(s.agent_id);
+ case 'closed': return s.summary?.closed_positions || 0;
+ case 'wr': { const c = s.summary?.closed_positions || 0; return c ? (s.summary?.wins || 0) / c : -1; }
+ case 'pnl': return Number(lamportsToSol(s.summary?.realized_pnl_lamports || '0'));
+ default: return 0;
+ }
+}
+
+function rosterTable() {
+ const rows = visibleRows().slice().sort((a, b) => {
+ const va = sortVal(a, _sort.key), vb = sortVal(b, _sort.key);
+ if (va < vb) return -1 * _sort.dir;
+ if (va > vb) return 1 * _sort.dir;
+ return 0;
+ });
+ const allSel = rows.length > 0 && rows.every((s) => _sel.has(s.agent_id));
+ const head = COLS.map((c) => {
+ if (c.key === 'sel') return `<th class="c"><input type="checkbox" class="fc-check" id="fc-all" ${allSel ? 'checked' : ''} aria-label="Select all" /></th>`;
+ const ind = _sort.key === c.key ? `<span class="fc-sort-ind">${_sort.dir > 0 ? '▲' : '▼'}</span>` : '';
+ return `<th class="${c.cls || ''} ${c.sortable ? 'sortable' : ''}" ${c.sortable ? `data-sort="${c.key}"` : ''}>${esc(c.label)} ${ind}</th>`;
+ }).join('');
+ const body = rows.length
+ ? rows.map(rosterRow).join('')
+ : `<tr><td colspan="${COLS.length}"><div class="fc-empty">No agents match this filter.</div></td></tr>`;
+ return `<table class="fc-table"><thead><tr>${head}</tr></thead><tbody id="fc-tbody">${body}</tbody></table>`;
+}
+
+function openCountFor(agentId) {
+ let n = 0;
+ for (const p of _positions.values()) if (p.agent_id === agentId && ['opening', 'open'].includes(p.status)) n++;
+ return n;
+}
+
+function rosterRow(s) {
+ const st = statusOf(s);
+ const pill = st === 'armed' ? '<span class="fc-pill armed"><span class="fc-dot"></span>Armed</span>'
+ : st === 'kill' ? '<span class="fc-pill kill"><span class="fc-dot"></span>Kill switch</span>'
+ : '<span class="fc-pill disarmed"><span class="fc-dot"></span>Disarmed</span>';
+ const bal = s.wallet_sol != null ? fmtSol(s.wallet_sol) : '—';
+ const low = isLowBalance(s) ? ' <span class="fc-warn" title="Balance too low for a trade">⚠</span>' : '';
+ const closed = s.summary?.closed_positions || 0;
+ const wins = s.summary?.wins || 0;
+ const wr = closed ? Math.round((wins / closed) * 100) : null;
+ const pnlSol = lamportsToSol(s.summary?.realized_pnl_lamports || '0');
+ const open = openCountFor(s.agent_id);
+ const armLabel = s.enabled ? 'Disarm' : 'Arm';
+ return `<tr class="fc-row ${_sel.has(s.agent_id) ? 'sel' : ''}" data-agent="${esc(s.agent_id)}">
+ <td class="c"><input type="checkbox" class="fc-check" data-check="${esc(s.agent_id)}" ${_sel.has(s.agent_id) ? 'checked' : ''} aria-label="Select ${esc(s.agent_name || s.agent_id)}" /></td>
+ <td><div class="fc-ag">
+ <img class="fc-av" loading="lazy" decoding="async" src="${esc(s.image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />
+ <div style="min-width:0"><div class="fc-agname">${esc(s.agent_name || s.agent_id)}</div><div class="fc-agsub fc-mono">${esc(String(s.agent_id).slice(0, 8))}</div></div>
+ </div></td>
+ <td>${pill}</td>
+ <td class="r fc-mono">${bal}${low}</td>
+ <td class="r fc-mono">${open || '—'}</td>
+ <td class="r fc-mono">${closed || '—'}</td>
+ <td class="r fc-mono ${wr != null && wr >= 50 ? 'fc-pos' : ''}">${wr != null ? `${wr}%` : '—'}</td>
+ <td class="r fc-mono ${clr(pnlSol)}">${pnlSol !== 0 ? signed(pnlSol, fmtSol) : fmtSol(0)}</td>
+ <td class="r"><div class="fc-rowbtns">
+ <button class="fc-rowbtn" data-row-act="toggle" data-agent="${esc(s.agent_id)}">${armLabel}</button>
+ <button class="fc-rowbtn danger" data-row-act="kill" data-agent="${esc(s.agent_id)}" title="${s.kill_switch ? 'Clear kill switch' : 'Kill switch'}">${s.kill_switch ? 'Clear' : 'Kill'}</button>
+ <a class="fc-rowbtn" href="/dashboard/sniper" title="Tune this strategy">Tune ↗</a>
+ </div></td>
+ </tr>`;
+}
+
+function feedRows() {
+ if (!_feed.length) return '<div class="fc-empty">No trades yet — armed agents post their buys and sells here the moment they fire.</div>';
+ return _feed.slice(0, 40).map((f) => {
+ const pnl = f.kind === 'sell' && f.pnl_sol != null
+ ? `<span class="fc-fpnl ${clr(f.pnl_sol)}">${signed(f.pnl_sol, fmtSol)}</span>`
+ : f.entry_sol != null ? `<span class="fc-fpnl">${fmtSol(f.entry_sol)}</span>` : '<span class="fc-fpnl">—</span>';
+ return `<div class="fc-frow">
+ <span class="fc-fdir ${f.kind}">${f.kind === 'sell' ? 'Sell' : 'Buy'}</span>
+ <div style="min-width:0"><span class="fc-fsym">${esc(f.symbol || '—')}</span> <span class="fc-fsub">${esc(f.agent_name || '')}</span></div>
+ ${pnl}
+ <span class="fc-ftime">${f.at ? relTime(f.at) : 'now'}</span>
+ </div>`;
+ }).join('');
+}
+
+// ── Events ──────────────────────────────────────────────────────────────────
+
+function wire(root) {
+ // Sort headers
+ root.querySelectorAll('th[data-sort]').forEach((th) => th.addEventListener('click', () => {
+ const key = th.dataset.sort;
+ if (_sort.key === key) _sort.dir *= -1; else { _sort.key = key; _sort.dir = 1; }
+ refreshTable();
+ }));
+ // Select-all + per-row checkboxes
+ root.querySelector('#fc-all')?.addEventListener('change', (e) => {
+ const on = e.target.checked;
+ for (const s of visibleRows()) { if (on) _sel.add(s.agent_id); else _sel.delete(s.agent_id); }
+ refreshTable(); refreshBar();
+ });
+ root.querySelectorAll('[data-check]').forEach((cb) => cb.addEventListener('change', (e) => {
+ const id = cb.dataset.check;
+ if (e.target.checked) _sel.add(id); else _sel.delete(id);
+ root.querySelector(`.fc-row[data-agent="${CSS.escape(id)}"]`)?.classList.toggle('sel', e.target.checked);
+ refreshBar();
+ }));
+ // Filter chips + search
+ root.querySelectorAll('[data-chip]').forEach((c) => c.addEventListener('click', () => {
+ _filter.status = c.dataset.chip; refreshTable(); refreshBar();
+ }));
+ root.querySelector('#fc-q')?.addEventListener('input', (e) => {
+ _filter.q = e.target.value; refreshTable(); refreshBar();
+ });
+ // Fleet actions
+ root.querySelector('[data-act="arm-all"]')?.addEventListener('click', () => bulkAction('arm'));
+ root.querySelector('[data-act="disarm-all"]')?.addEventListener('click', () => bulkAction('disarm'));
+ root.querySelector('[data-act="stop-all"]')?.addEventListener('click', () => bulkAction('stop'));
+ // Per-row actions
+ root.querySelectorAll('[data-row-act]').forEach((b) => b.addEventListener('click', () => rowAction(b)));
+}
+
+function refreshTable() {
+ const wrap = document.querySelector('.fc-tablewrap');
+ if (wrap) { wrap.innerHTML = rosterTable(); wireTable(wrap); }
+}
+function wireTable(scope) {
+ scope.querySelectorAll('th[data-sort]').forEach((th) => th.addEventListener('click', () => {
+ const key = th.dataset.sort;
+ if (_sort.key === key) _sort.dir *= -1; else { _sort.key = key; _sort.dir = 1; }
+ refreshTable();
+ }));
+ scope.querySelector('#fc-all')?.addEventListener('change', (e) => {
+ const on = e.target.checked;
+ for (const s of visibleRows()) { if (on) _sel.add(s.agent_id); else _sel.delete(s.agent_id); }
+ refreshTable(); refreshBar();
+ });
+ scope.querySelectorAll('[data-check]').forEach((cb) => cb.addEventListener('change', (e) => {
+ const id = cb.dataset.check;
+ if (e.target.checked) _sel.add(id); else _sel.delete(id);
+ scope.querySelector(`.fc-row[data-agent="${CSS.escape(id)}"]`)?.classList.toggle('sel', e.target.checked);
+ refreshBar();
+ }));
+ scope.querySelectorAll('[data-row-act]').forEach((b) => b.addEventListener('click', () => rowAction(b)));
+}
+function refreshBar() {
+ const bar = document.querySelector('.fc-bar');
+ if (!bar) return;
+ const tmp = document.createElement('div');
+ tmp.innerHTML = actionBar();
+ bar.replaceWith(tmp.firstElementChild);
+ // re-wire the fresh bar
+ const root = document.getElementById('fc-root');
+ const nb = document.querySelector('.fc-bar');
+ nb.querySelector('[data-act="arm-all"]')?.addEventListener('click', () => bulkAction('arm'));
+ nb.querySelector('[data-act="disarm-all"]')?.addEventListener('click', () => bulkAction('disarm'));
+ nb.querySelector('[data-act="stop-all"]')?.addEventListener('click', () => bulkAction('stop'));
+ nb.querySelectorAll('[data-chip]').forEach((c) => c.addEventListener('click', () => { _filter.status = c.dataset.chip; refreshTable(); refreshBar(); }));
+ const q = nb.querySelector('#fc-q');
+ if (q) { q.addEventListener('input', (e) => { _filter.q = e.target.value; refreshTable(); refreshBar(); }); q.focus(); q.setSelectionRange(q.value.length, q.value.length); }
+ void root;
+}
+
+// The agents a bulk action targets: the current selection, or every filtered row
+// when nothing is selected.
+function bulkTargets() {
+ if (_sel.size) return _strategies.filter((s) => _sel.has(s.agent_id));
+ return visibleRows();
+}
+
+async function bulkAction(kind) {
+ const targets = bulkTargets();
+ if (!targets.length) { toast('No agents to act on', true); return; }
+ const verb = kind === 'arm' ? 'Arm' : kind === 'disarm' ? 'Disarm' : 'Emergency-stop';
+ const body = kind === 'stop'
+ ? `Trip the kill switch on <b>${targets.length}</b> agent${targets.length > 1 ? 's' : ''}. Each stops trading immediately and holds its open positions. This does not sell — clear the kill switch to resume.`
+ : `${verb} <b>${targets.length}</b> agent${targets.length > 1 ? 's' : ''}. ${kind === 'arm' ? 'Armed agents trade real SOL from their own wallets the moment a trigger fires.' : 'Disarmed agents stop opening new positions.'}`;
+ const ok = await confirmDialog(`${verb} ${targets.length} agent${targets.length > 1 ? 's' : ''}?`, body, kind === 'stop' ? 'Emergency stop' : verb, kind !== 'arm');
+ if (!ok) return;
+
+ const patch = kind === 'arm' ? { enabled: true, kill_switch: false }
+ : kind === 'disarm' ? { enabled: false }
+ : { kill_switch: true, enabled: false };
+
+ setActionsBusy(true);
+ const res = await mapLimit(targets, 6, async (s) => {
+ try { await post('/api/sniper/strategy', { agent_id: s.agent_id, network: s.network || 'mainnet', ...patch }); return { ok: true }; }
+ catch (e) { return { ok: false, err: e?.message || 'failed' }; }
+ });
+ const okN = res.filter((r) => r.ok).length;
+ const failN = res.length - okN;
+ const firstErr = res.find((r) => !r.ok)?.err;
+ toast(`${verb}ed ${okN}/${res.length}${failN ? ` · ${failN} failed${firstErr ? ` · ${esc(firstErr)}` : ''}` : ''}`, failN > 0);
+ setActionsBusy(false);
+ await refresh();
+}
+
+async function rowAction(btn) {
+ const id = btn.dataset.agent;
+ const s = _strategies.find((x) => x.agent_id === id);
+ if (!s) return;
+ btn.disabled = true;
+ try {
+ if (btn.dataset.rowAct === 'toggle') {
+ await post('/api/sniper/strategy', { agent_id: id, network: s.network || 'mainnet', enabled: !s.enabled, ...(!s.enabled ? { kill_switch: false } : {}) });
+ } else {
+ await post('/api/sniper/strategy', { agent_id: id, network: s.network || 'mainnet', kill_switch: !s.kill_switch, ...(!s.kill_switch ? { enabled: false } : {}) });
+ }
+ await refresh();
+ } catch (e) {
+ toast(e?.message || 'Update failed', true);
+ btn.disabled = false;
+ }
+}
+
+function setActionsBusy(busy) {
+ document.querySelectorAll('.fc-actions .fc-btn').forEach((b) => { b.disabled = busy; });
+}
+
+// Order-preserving bounded-concurrency map — never fire N writes at once.
+async function mapLimit(items, limit, fn) {
+ const out = new Array(items.length);
+ let i = 0;
+ async function worker() {
+ while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx], idx); }
+ }
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
+ return out;
+}
+
+// ── Confirm dialog ──────────────────────────────────────────────────────────
+
+function confirmDialog(title, bodyHtml, confirmLabel, danger) {
+ return new Promise((resolve) => {
+ const ov = document.createElement('div');
+ ov.className = 'fc-overlay';
+ ov.innerHTML = `<div class="fc-modal" role="dialog" aria-modal="true" aria-label="${esc(title)}">
+ <h2>${esc(title)}</h2><p>${bodyHtml}</p>
+ <div class="fc-modal-foot">
+ <button class="fc-btn" data-x="cancel">Cancel</button>
+ <button class="fc-btn ${danger ? 'danger' : 'primary'}" data-x="ok">${esc(confirmLabel)}</button>
+ </div>
+ </div>`;
+ const done = (v) => { ov.remove(); document.removeEventListener('keydown', onKey); resolve(v); };
+ const onKey = (e) => { if (e.key === 'Escape') done(false); if (e.key === 'Enter') done(true); };
+ ov.addEventListener('click', (e) => { if (e.target === ov) done(false); });
+ ov.querySelector('[data-x="cancel"]').addEventListener('click', () => done(false));
+ ov.querySelector('[data-x="ok"]').addEventListener('click', () => done(true));
+ document.addEventListener('keydown', onKey);
+ document.body.appendChild(ov);
+ ov.querySelector('[data-x="ok"]').focus();
+ });
+}
+
+// ── Toast ───────────────────────────────────────────────────────────────────
+
+function toast(msg, isErr = false) {
+ let host = document.querySelector('.fc-toasts');
+ if (!host) { host = document.createElement('div'); host.className = 'fc-toasts'; document.body.appendChild(host); }
+ const t = document.createElement('div');
+ t.className = `fc-toast ${isErr ? 'err' : ''}`;
+ t.innerHTML = msg;
+ host.appendChild(t);
+ setTimeout(() => { t.style.opacity = '0'; t.style.transition = 'opacity .3s'; setTimeout(() => t.remove(), 300); }, 4200);
+}
+
+// ── Live stream ─────────────────────────────────────────────────────────────
+
+function normPos(p) {
+ const entry = p.entry_sol != null ? Number(p.entry_sol) : null;
+ const current = p.current_sol != null ? Number(p.current_sol) : entry;
+ const pnlSol = p.pnl_sol != null ? Number(p.pnl_sol) : (entry != null && current != null ? current - entry : null);
+ return {
+ id: p.id, agent_id: p.agent_id, agent_name: p.agent_name, network: p.network || 'mainnet',
+ mint: p.mint, symbol: p.symbol || p.name, status: p.status || 'open',
+ entry_sol: entry, current_sol: current, pnl_sol: pnlSol,
+ at: p.at || p.opened_at || p.closed_at || null,
+ };
+}
+
+function ownedIds() { return new Set(_strategies.map((s) => s.agent_id)); }
+
+function setConn(state, label) {
+ const dot = document.getElementById('fc-live-dot');
+ const txt = document.getElementById('fc-conn');
+ if (dot) dot.className = `fc-live-dot ${state}`;
+ if (txt) txt.textContent = label;
+}
+
+function renderLive() {
+ const feed = document.getElementById('fc-feed');
+ if (feed) feed.innerHTML = feedRows();
+ const openKpi = document.querySelector('[data-kpi-open]');
+ if (openKpi) openKpi.textContent = String([..._positions.values()].filter((p) => ['opening', 'open'].includes(p.status)).length);
+ // keep the roster's Open column live without a full re-render
+ document.querySelectorAll('.fc-row[data-agent]').forEach((tr) => {
+ const cell = tr.children[4];
+ if (cell) { const n = openCountFor(tr.dataset.agent); cell.textContent = n || '—'; }
+ });
+}
+
+async function seed() {
+ try {
+ const data = await get('/api/sniper/leaderboard?network=mainnet');
+ const owned = ownedIds();
+ for (const p of (data.positions || [])) if (owned.has(p.agent_id)) _positions.set(p.id, normPos(p));
+ } catch { /* the live stream will populate */ }
+ renderLive();
+}
+
+function stopSse() {
+ if (_sse) { try { _sse.close(); } catch { /* already closed */ } _sse = null; }
+ if (_sseTimer) { clearTimeout(_sseTimer); _sseTimer = null; }
+}
+
+function startSse() {
+ stopSse();
+ _positions = new Map();
+ if (!_strategies.length) return;
+ setConn('connecting', 'Connecting…');
+ seed();
+ connectSse();
+}
+
+function connectSse() {
+ const owned = ownedIds();
+ const src = new EventSource('/api/sniper/stream?network=mainnet');
+ _sse = src;
+ const ingest = (kind) => (e) => {
+ try {
+ const p = normPos(JSON.parse(e.data));
+ if (!owned.has(p.agent_id)) return;
+ if (kind === 'sell') p.status = 'closed';
+ _positions.set(p.id, { ...(_positions.get(p.id) || {}), ...p });
+ if (kind !== 'update') {
+ _feed.unshift({ kind, symbol: p.symbol, agent_name: p.agent_name, pnl_sol: p.pnl_sol, entry_sol: p.entry_sol, at: p.at || new Date().toISOString() });
+ _feed = _feed.slice(0, 60);
+ }
+ renderLive();
+ } catch { /* ignore malformed frame */ }
+ };
+ src.addEventListener('open', () => { _sseRetry = 0; setConn('live', 'Live'); });
+ src.addEventListener('buy', ingest('buy'));
+ src.addEventListener('update', ingest('update'));
+ src.addEventListener('sell', ingest('sell'));
+ src.addEventListener('close', () => { try { src.close(); } catch { /* noop */ } scheduleReconnect(); });
+ src.onerror = () => { try { src.close(); } catch { /* noop */ } setConn('offline', 'Reconnecting…'); scheduleReconnect(); };
+}
+
+function scheduleReconnect() {
+ if (_sseTimer) return;
+ const delay = Math.min(1000 * 2 ** _sseRetry, 15000);
+ _sseRetry++;
+ _sseTimer = setTimeout(() => { _sseTimer = null; if (_strategies.length) connectSse(); }, delay);
+}
diff --git a/src/leaderboard.css b/src/leaderboard.css
index 490759ec6..8ac2555cc 100644
--- a/src/leaderboard.css
+++ b/src/leaderboard.css
@@ -531,6 +531,44 @@
.lb-neg { color: var(--danger); }
.lb-muted { color: var(--ink-faint); }
+/* ---- P&L sparkline (per-row realized-equity trend) ---- */
+/* The P&L cell pairs the headline number with a tiny cumulative-equity curve, so
+ two traders with the same total read differently when one ground it out and the
+ other spiked once. The SVG sits above the numbers on wide rows and tucks inline
+ when the column is tight. */
+.lb-pnl-cell { display: inline-flex; flex-direction: column; align-items: flex-end; gap: 3px; }
+.lb-pnl-nums { display: inline-flex; flex-direction: column; align-items: flex-end; line-height: 1.15; }
+.lb-spark { display: inline-block; width: 68px; height: 22px; line-height: 0; color: var(--ink-faint); }
+.lb-spark svg { display: block; overflow: visible; }
+.lb-spark.is-up { color: var(--success); }
+.lb-spark.is-down { color: var(--danger); }
+.lb-spark--empty { display: inline-flex; align-items: center; }
+.lb-spark-flat {
+ display: block; width: 68px; height: 1px; border-radius: var(--radius-pill);
+ background: repeating-linear-gradient(90deg, var(--stroke) 0 3px, transparent 3px 6px);
+ opacity: 0.5;
+}
+/* End-dot pulse marks the latest point — the row's "live" tell. Motion-gated. */
+.lb-spark-dot { transform-box: fill-box; transform-origin: center; }
+@media (prefers-reduced-motion: no-preference) {
+ .lb-spark-dot { animation: lb-spark-pulse 2.4s var(--ease-standard) infinite; }
+}
+@keyframes lb-spark-pulse { 0%, 100% { opacity: 1; r: 1.9px; } 50% { opacity: 0.55; r: 2.6px; } }
+
+/* Win/loss distribution micro-bar under the win-rate % — green wins vs red losses. */
+.lb-wl {
+ display: block; height: 3px; margin-top: 4px; border-radius: var(--radius-pill);
+ background: var(--danger); overflow: hidden;
+}
+.lb-wl-win { display: block; height: 100%; background: var(--success); border-radius: var(--radius-pill); }
+.lb-winrate { position: relative; }
+
+@media (max-width: 640px) {
+ /* On narrow rows the sparkline would crowd the number — keep the number, drop the chart. */
+ .lb-spark, .lb-spark--empty { display: none; }
+ .lb-pnl-cell { gap: 0; }
+}
+
.lb-view {
display: inline-flex;
align-items: center;
diff --git a/src/leaderboard.js b/src/leaderboard.js
index ec77d611a..7afb8926a 100644
--- a/src/leaderboard.js
+++ b/src/leaderboard.js
@@ -9,7 +9,7 @@
import {
escapeHtml, fmtSol, fmtUsd, fmtPct, pnlClass, shortAddr, holdTime, relTime,
- identicon, verifiedBadge, signatureCoin,
+ identicon, verifiedBadge, signatureCoin, pnlSparkline,
} from './trader-format.js';
import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
import { updateValue, flipReorder, setLiveDot } from './ui-juice.js';
@@ -92,6 +92,12 @@ function rowMarkup(r) {
const dd = r.max_drawdown_pct > 0
? `<span class="lb-neg">−${r.max_drawdown_pct.toFixed(1)}%</span>` : '<span class="lb-muted">0%</span>';
const scoreBar = Math.max(4, Math.min(100, r.score));
+ const spark = pnlSparkline(r.pnl_series, { label: `${r.agent_name || 'Trader'} P&L trend` });
+ // Win/loss distribution micro-bar — the same wins/closed the cell already shows,
+ // as a proportion you can read at a glance. Only meaningful with closed trades.
+ const wlBar = r.closed > 0
+ ? `<span class="lb-wl" aria-hidden="true"><span class="lb-wl-win" style="width:${((r.wins / r.closed) * 100).toFixed(1)}%"></span></span>`
+ : '';
const rowLabel = [
`Rank ${r.rank}`,
r.agent_name || 'Unnamed agent',
@@ -113,8 +119,8 @@ function rowMarkup(r) {
<span class="lb-score">${r.score}</span>
<span class="lb-score-track"><span class="lb-score-bar" style="width:${scoreBar}%"></span></span>
</span>
- <span class="lb-num">${pnlSol}${pnlUsd}</span>
- <span class="lb-num lb-winrate">${fmtPct(r.win_rate * 100)}<span class="lb-sub-num">${r.wins}/${r.closed}</span></span>
+ <span class="lb-num lb-pnl-cell">${spark}<span class="lb-pnl-nums">${pnlSol}${pnlUsd}</span></span>
+ <span class="lb-num lb-winrate">${fmtPct(r.win_rate * 100)}<span class="lb-sub-num">${r.wins}/${r.closed}</span>${wlBar}</span>
<span class="lb-num lb-hide-sm"><span class="${pnlClass(r.roi_pct)}">${fmtPct(r.roi_pct, { sign: true })}</span></span>
<span class="lb-num lb-hide-sm">${dd}</span>
<span class="lb-num lb-hide-md">${r.closed}<span class="lb-sub-num">${holdTime(r.avg_hold_seconds)} avg</span></span>
diff --git a/src/payment-modal.js b/src/payment-modal.js
index d481e5859..484785448 100644
--- a/src/payment-modal.js
+++ b/src/payment-modal.js
@@ -12,6 +12,7 @@
import { formatUsdcEq, formatSolEq } from './shared/usd-price.js';
import { buildReceiptHTML, buildReceiptText } from './shared/payment-receipt.js';
import { showAddFunds } from './shared/add-funds.js';
+import { ensureRiskAck } from './shared/risk-ack.js';
import { log } from './shared/log.js';
const USDC_DECIMALS = 6;
@@ -448,6 +449,7 @@ export class SkillPaymentModal {
}
async _purchase() {
+ if (!(await ensureRiskAck({ context: 'skill-purchase' }))) return;
const confirm = this._el.querySelector('.skill-pay-confirm');
confirm.disabled = true;
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
index da0162747..0babeec4d 100644
--- a/src/pump/launch-token-modal.js
+++ b/src/pump/launch-token-modal.js
@@ -10,6 +10,7 @@
import { mountLaunchBondingCurve } from './bonding-curve-chart.js';
import { log } from '../shared/log.js';
+import { ensureRiskAck } from '../shared/risk-ack.js';
import { THREE_WS_MARK } from '../solana/vanity/brand.js';
const _isDev =
@@ -761,6 +762,8 @@ export class LaunchTokenModal {
// ── Launch: prep → sign → broadcast → confirm ─────────────────────────────
async _doLaunch(walletAddress) {
+ // Launching costs real SOL (fees + optional dev buy) on mainnet.
+ if (this._d.cluster !== 'devnet' && !(await ensureRiskAck({ context: 'launch' }))) return;
const launchBtn = this._overlay.querySelector('#ltm-launch');
const backBtn = this._overlay.querySelector('#ltm-s3-back');
launchBtn.disabled = true;
diff --git a/src/shared/risk-ack.js b/src/shared/risk-ack.js
new file mode 100644
index 000000000..841336576
--- /dev/null
+++ b/src/shared/risk-ack.js
@@ -0,0 +1,36 @@
+/**
+ * risk-ack — bundler-side wrapper around the canonical /risk-ack.js module.
+ *
+ * The implementation lives in public/risk-ack.js so plain public/ scripts and
+ * third-party embeds (x402.js on merchant sites) can import it at runtime from
+ * the three.ws origin. App code imports THIS wrapper; the @vite-ignore dynamic
+ * import defers resolution to the browser, where /risk-ack.js is served from
+ * the public root in both dev and production.
+ *
+ * Gate every money-committing action:
+ *
+ * import { ensureRiskAck } from '../shared/risk-ack.js';
+ * if (!(await ensureRiskAck({ context: 'trade' }))) return; // user declined
+ */
+
+function _mod() {
+ return import(/* @vite-ignore */ '/risk-ack.js');
+}
+
+/**
+ * Ensure the user has accepted the current Risk Disclosure — shows the
+ * acknowledgment dialog if not. Resolves true when accepted, false when
+ * declined; the caller must abort the money action on false.
+ * @param {{context?: string}} [opts]
+ * @returns {Promise<boolean>}
+ */
+export async function ensureRiskAck(opts) {
+ const m = await _mod();
+ return m.ensureRiskAck(opts);
+}
+
+/** @returns {Promise<boolean>} whether the current disclosure version is already accepted */
+export async function hasRiskAck() {
+ const m = await _mod();
+ return m.hasRiskAck();
+}
diff --git a/src/swap-jupiter.js b/src/swap-jupiter.js
index 5e8bcb185..712db956e 100644
--- a/src/swap-jupiter.js
+++ b/src/swap-jupiter.js
@@ -19,6 +19,7 @@ import {
VersionedTransaction,
} from '@solana/web3.js';
import { log } from './shared/log.js';
+import { ensureRiskAck } from './shared/risk-ack.js';
import { trackFunnelStep, trackError, ANALYTICS_EVENTS } from './analytics.js';
// The $THREE conversion funnel only counts swaps that actually touch $THREE —
@@ -795,6 +796,7 @@ async function executeSwap() {
// After a settled swap the primary button becomes a "Close" action.
if (_phase === 'done') { closeSwap(); return; }
if (!_ctx || !_quote) return;
+ if (!(await ensureRiskAck({ context: 'swap' }))) return;
const btn = $('sj-confirm');
btn.disabled = true;
btn.textContent = 'Preparing transaction…';
diff --git a/src/token-pay.js b/src/token-pay.js
index 11b61c6dd..f148b808a 100644
--- a/src/token-pay.js
+++ b/src/token-pay.js
@@ -21,6 +21,8 @@
* if (result.ok) grantSpin();
*/
+import { ensureRiskAck } from './shared/risk-ack.js';
+
const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
// Lazy-load the Solana SDKs so they stay out of the initial bundle — Vite
@@ -103,6 +105,13 @@ export async function payWithToken({
wallet,
onStatus = () => {},
}) {
+ // 0. Real funds — the user must have accepted the Risk Disclosure.
+ if (network !== 'devnet' && !(await ensureRiskAck({ context: 'token-pay' }))) {
+ throw Object.assign(new Error('Payment cancelled — risk acknowledgment declined.'), {
+ code: 'user_cancelled',
+ });
+ }
+
// 1. Quote
onStatus('quoting');
const quoteResp = await fetch('/api/token/quote', {
diff --git a/src/trader-format.js b/src/trader-format.js
index acd73733f..f86ceae4f 100644
--- a/src/trader-format.js
+++ b/src/trader-format.js
@@ -130,4 +130,50 @@ export function signatureCoin(coin, { compact = false } = {}) {
return `<span class="sig-coin ${cls}" title="${verb}: ${label} · ${escapeHtml(pnl)} realized${coin.roi_pct != null ? ` · ${coin.roi_pct > 0 ? '+' : ''}${coin.roi_pct}% ROI` : ''}">${lead}<span class="sig-coin-sym">${label}</span><span class="sig-coin-pnl">${escapeHtml(pnl)}</span></span>`;
}
+/**
+ * Compact P&L sparkline from a cumulative-realized-equity series (SOL, oldest→
+ * newest — the `pnl_series` the trader-stats truth layer ships on every board row
+ * and profile). Draws the shape of the run in a tiny inline SVG: a line + soft
+ * area fill, a dashed break-even baseline, and a pulsing end-dot at the latest
+ * point. Green when the trader is up on the window, red when down. Returns a muted
+ * "no trend yet" placeholder under two closed trades so a new trader's row is never
+ * a jarring empty cell. Purely presentational — every number is still proven in the
+ * row's headline P&L and on-chain on the profile.
+ *
+ * @param {number[]} series cumulative realized SOL, oldest→newest
+ * @param {{ w?: number, h?: number, label?: string }} [opts]
+ */
+export function pnlSparkline(series, { w = 68, h = 22, label = 'P&L trend' } = {}) {
+ const pts = Array.isArray(series) ? series.filter((v) => Number.isFinite(v)) : [];
+ if (pts.length < 2) {
+ return `<span class="lb-spark lb-spark--empty" aria-hidden="true"><span class="lb-spark-flat"></span></span>`;
+ }
+ const data = [0, ...pts]; // anchor the curve at break-even so direction reads honestly
+ const min = Math.min(...data), max = Math.max(...data);
+ const range = (max - min) || 1;
+ const pad = 2;
+ const x = (i) => pad + (i / (data.length - 1)) * (w - pad * 2);
+ const y = (v) => h - pad - ((v - min) / range) * (h - pad * 2);
+ const line = data.map((v, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(' ');
+ const last = data[data.length - 1];
+ const up = last >= 0;
+ const stroke = up ? 'var(--success, #22c55e)' : 'var(--danger, #ef4444)';
+ const area = `${line} L${x(data.length - 1).toFixed(1)} ${(h - pad).toFixed(1)} L${x(0).toFixed(1)} ${(h - pad).toFixed(1)} Z`;
+ const zeroY = y(0).toFixed(1);
+ const ex = x(data.length - 1).toFixed(1), ey = y(last).toFixed(1);
+ const gid = `sp${Math.abs(Math.round(last * 1e4))}${data.length}`;
+ return `<span class="lb-spark ${up ? 'is-up' : 'is-down'}" role="img" aria-label="${escapeHtml(label)}: ${up ? 'up' : 'down'} over the window">
+ <svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" preserveAspectRatio="none" aria-hidden="true">
+ <defs><linearGradient id="${gid}" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="${stroke}" stop-opacity="0.22"/>
+ <stop offset="1" stop-color="${stroke}" stop-opacity="0"/>
+ </linearGradient></defs>
+ <line x1="${pad}" y1="${zeroY}" x2="${w - pad}" y2="${zeroY}" stroke="currentColor" stroke-width="1" stroke-dasharray="2 3" opacity="0.28"/>
+ <path d="${area}" fill="url(#${gid})"/>
+ <path d="${line}" fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round"/>
+ <circle class="lb-spark-dot" cx="${ex}" cy="${ey}" r="1.9" fill="${stroke}"/>
+ </svg>
+ </span>`;
+}
+
export { SOL };
diff --git a/src/trader.js b/src/trader.js
index db413c9a6..6a08dbcb8 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -768,7 +768,8 @@ function renderWalletProfile(data) {
const shareBtn = content.querySelector('#tp-share-wallet');
shareBtn?.addEventListener('click', () => {
- const url = `${location.origin}/trader/${encodeURIComponent(addr)}`;
+ // /trader/<wallet>/share → SSR page with a real OG card for social crawlers
+ const url = `${location.origin}/trader/${encodeURIComponent(addr)}/share`;
if (navigator.share) {
navigator.share({ title: `${a.title || 'Wallet'} · ${shortAddr(addr)} on three.ws`, url }).catch(() => {});
} else {
diff --git a/tests/jito-tip-accounts.test.js b/tests/jito-tip-accounts.test.js
new file mode 100644
index 000000000..7de747d9d
--- /dev/null
+++ b/tests/jito-tip-accounts.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+// Guard against a corrupted Jito tip account silently leaking real SOL.
+//
+// Every code path that pays a Jito tip hardcodes the block engine's tip-account
+// list and picks one (random or by modulo of a wallet byte / attempt index). If
+// a single address is mistyped, that fraction of tips is transferred to a pubkey
+// nobody at Jito controls — real SOL burned AND the transaction gets no Jito
+// priority / MEV protection. This exact bug shipped three times (two different
+// mangled `Cw8C…` values and one mangled `ADaU…`), so it is worth pinning.
+//
+// The canonical set below is Jito's mainnet `getTipAccounts` response
+// (https://mainnet.block-engine.jito.wtf/api/v1/getTipAccounts). It changes very
+// rarely; if Jito ever rotates it, update this set (from the live endpoint) and
+// the source lists together — the test failing is the signal to do exactly that.
+const CANONICAL = new Set([
+ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY',
+ 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',
+ '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',
+ 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',
+ 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',
+ 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',
+ 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL',
+ '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT',
+]);
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+// Every file that declares a `JITO_TIP_ACCOUNTS` array literal. Kept explicit
+// (rather than a repo-wide grep) so a NEW copy of the list added somewhere is a
+// deliberate act that also adds its path here — the reviewer's prompt to dedupe.
+const SOURCES = [
+ 'api/_lib/execution-engine.js',
+ 'workers/oracle/executor.js',
+ 'packages/agent-sniper/src/adapters/solana/executor-web3.js',
+ 'packages/avatar-agent-mcp/src/lib/jito.js',
+];
+
+/** Extract the addresses from the first `JITO_TIP_ACCOUNTS = [ … ]` literal. */
+function extractTipAccounts(source) {
+ const m = source.match(/JITO_TIP_ACCOUNTS\s*=\s*\[([\s\S]*?)\]/);
+ if (!m) return null;
+ return [...m[1].matchAll(/['"]([1-9A-HJ-NP-Za-km-z]{32,44})['"]/g)].map((x) => x[1]);
+}
+
+describe('Jito tip accounts are canonical (no leaked SOL)', () => {
+ for (const rel of SOURCES) {
+ it(`${rel} lists only real Jito tip accounts`, () => {
+ const accounts = extractTipAccounts(readFileSync(resolve(ROOT, rel), 'utf8'));
+ expect(accounts, `no JITO_TIP_ACCOUNTS array found in ${rel}`).not.toBeNull();
+ // Every entry must be an address Jito actually controls.
+ for (const addr of accounts) {
+ expect(CANONICAL.has(addr), `${rel}: "${addr}" is not a canonical Jito tip account`).toBe(true);
+ }
+ // And no duplicates within a file (a paste error that skews the rotation).
+ expect(new Set(accounts).size, `${rel} has duplicate tip accounts`).toBe(accounts.length);
+ });
+ }
+
+ it('the canonical set is the full 8 Jito publishes', () => {
+ expect(CANONICAL.size).toBe(8);
+ });
+});
diff --git a/tests/sniper-safety-guards.test.js b/tests/sniper-safety-guards.test.js
index bad044234..167bc9024 100644
--- a/tests/sniper-safety-guards.test.js
+++ b/tests/sniper-safety-guards.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Query-aware fake `sql` for launcher-funding's ledger reads. Each source can be
// toggled to throw (missing-table simulation) to prove the fail-open contract.
@@ -22,6 +22,8 @@ vi.mock('../api/_lib/db.js', () => {
import { parseAgentIds } from '../workers/agent-sniper/config.js';
import { mayhemVerdict, mayhemGate } from '../workers/agent-sniper/mayhem-gate.js';
import { marketCapBandReason, scoreMint } from '../workers/agent-sniper/scorer.js';
+import { checkDailyLoss } from '../api/_lib/agent-trade-guards.js';
+import { effectiveDailyLossLimitLamports } from '../workers/agent-sniper/strategy-store.js';
import { criticalFirewallReason } from '../api/_lib/trade-firewall.js';
import { withinMasterDailyCap, masterDailyOutflowSol } from '../api/_lib/launcher-funding.js';
@@ -134,6 +136,58 @@ describe('withinMasterDailyCap (hard master outflow ceiling)', () => {
});
});
+describe('checkDailyLoss (realized-loss circuit breaker)', () => {
+ const SOL = 1_000_000_000n;
+ it('no breaker when limit is null / 0 / negative', () => {
+ expect(checkDailyLoss(-5n * SOL, null)).toBeNull();
+ expect(checkDailyLoss(-5n * SOL, 0n)).toBeNull();
+ expect(checkDailyLoss(-5n * SOL, -1n)).toBeNull();
+ });
+ it('a profitable or break-even day never blocks', () => {
+ expect(checkDailyLoss(3n * SOL, SOL)).toBeNull();
+ expect(checkDailyLoss(0n, SOL)).toBeNull();
+ });
+ it('a loss shallower than the limit passes', () => {
+ expect(checkDailyLoss(-1n * SOL, 2n * SOL)).toBeNull();
+ });
+ it('blocks once the net loss reaches the limit (inclusive)', () => {
+ const atCap = checkDailyLoss(-2n * SOL, 2n * SOL);
+ expect(atCap?.reason).toBe('daily_loss_limit');
+ const over = checkDailyLoss(-3n * SOL, 2n * SOL);
+ expect(over?.reason).toBe('daily_loss_limit');
+ expect(over.detail.loss_lamports).toBe((3n * SOL).toString());
+ });
+ it('accepts string / number net values (DB numeric text)', () => {
+ expect(checkDailyLoss('-2000000000', 1_000_000_000n)?.reason).toBe('daily_loss_limit');
+ });
+});
+
+describe('effectiveDailyLossLimitLamports (env band ∧ per-strategy, tighter wins)', () => {
+ const OLD = process.env.SNIPER_MAX_DAILY_LOSS_SOL;
+ afterEach(() => {
+ if (OLD == null) delete process.env.SNIPER_MAX_DAILY_LOSS_SOL;
+ else process.env.SNIPER_MAX_DAILY_LOSS_SOL = OLD;
+ });
+ it('null when neither env nor strategy sets a cap', () => {
+ delete process.env.SNIPER_MAX_DAILY_LOSS_SOL;
+ expect(effectiveDailyLossLimitLamports({})).toBeNull();
+ });
+ it('env floor alone protects an unconfigured strategy', () => {
+ process.env.SNIPER_MAX_DAILY_LOSS_SOL = '0.5';
+ expect(effectiveDailyLossLimitLamports({})).toBe(500_000_000n);
+ });
+ it('per-strategy alone applies when env is unset', () => {
+ delete process.env.SNIPER_MAX_DAILY_LOSS_SOL;
+ expect(effectiveDailyLossLimitLamports({ daily_loss_limit_lamports: '250000000' })).toBe(250_000_000n);
+ });
+ it('takes the tighter (smaller) of env and per-strategy', () => {
+ process.env.SNIPER_MAX_DAILY_LOSS_SOL = '1'; // 1e9
+ expect(effectiveDailyLossLimitLamports({ daily_loss_limit_lamports: '250000000' })).toBe(250_000_000n);
+ process.env.SNIPER_MAX_DAILY_LOSS_SOL = '0.1'; // 1e8
+ expect(effectiveDailyLossLimitLamports({ daily_loss_limit_lamports: '250000000' })).toBe(100_000_000n);
+ });
+});
+
describe('masterDailyOutflowSol (fails open per-source)', () => {
beforeEach(() => { H.launcherRunsThrows = false; H.sniperEventsThrows = false; H.launcherSol = 0; H.sniperLamports = 0; });
it('sums both ledgers', async () => {
diff --git a/tests/trader-stats.test.js b/tests/trader-stats.test.js
index 276c151c4..fb3d13637 100644
--- a/tests/trader-stats.test.js
+++ b/tests/trader-stats.test.js
@@ -305,6 +305,38 @@ describe('strategy-origin records earn the same verified badge', () => {
});
});
+describe('computeTraderMetrics — pnl_series (sparkline source)', () => {
+ it('is the cumulative realized-equity curve, oldest→newest, ending at realized P&L', () => {
+ const m = computeTraderMetrics(FIXTURE, { solUsd: 200 });
+ // Closes ordered A(+2) → B(−0.5) → C(+0.5) → D(+0.01): cumulative 2, 1.5, 2, 2.01.
+ expect(m.pnl_series).toEqual([2, 1.5, 2, 2.01]);
+ // Endpoint must equal the headline realized P&L so the sparkline can't lie.
+ expect(m.pnl_series[m.pnl_series.length - 1]).toBeCloseTo(m.realized_pnl_sol, 6);
+ });
+
+ it('is empty under two closed trades (renders the "no trend" placeholder)', () => {
+ const one = computeTraderMetrics(
+ [{ status: 'closed', mint: 'X', realized_pnl_lamports: String(SOL), realized_pnl_pct: 100,
+ entry_quote_lamports: String(SOL), opened_at: '2026-01-01T00:00:00.000Z', closed_at: '2026-01-01T00:01:00.000Z' }],
+ { solUsd: 200 },
+ );
+ expect(one.pnl_series).toEqual([]);
+ expect(computeTraderMetrics([], { solUsd: 200 }).pnl_series).toEqual([]);
+ });
+
+ it('downsamples to at most 24 points while preserving the final equity', () => {
+ const many = Array.from({ length: 60 }, (_, i) => ({
+ status: 'closed', mint: `M${i}`, realized_pnl_lamports: String(0.1 * SOL), realized_pnl_pct: 10,
+ entry_quote_lamports: String(SOL),
+ opened_at: `2026-01-01T00:${String(i).padStart(2, '0')}:00.000Z`,
+ closed_at: `2026-01-01T01:${String(i).padStart(2, '0')}:00.000Z`,
+ }));
+ const m = computeTraderMetrics(many, { solUsd: 200 });
+ expect(m.pnl_series.length).toBeLessThanOrEqual(24);
+ expect(m.pnl_series[m.pnl_series.length - 1]).toBeCloseTo(m.realized_pnl_sol, 4);
+ });
+});
+
describe('windowStartIso', () => {
const NOW = Date.parse('2026-06-15T12:00:00.000Z');
diff --git a/vercel.json b/vercel.json
index e2aa89f43..edf9e0170 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1658,6 +1658,10 @@
"src": "/dashboard/sniper/?",
"dest": "/dashboard-next/sniper.html"
},
+ {
+ "src": "/dashboard/fleet/?",
+ "dest": "/dashboard-next/fleet.html"
+ },
{
"src": "/dashboard/capabilities/?",
"dest": "/dashboard-next/capabilities.html"
@@ -4275,6 +4279,10 @@
"src": "/legal/content-policy/?",
"dest": "/legal/content-policy.html"
},
+ {
+ "src": "/legal/risk/?",
+ "dest": "/legal/risk.html"
+ },
{
"src": "/content-policy/?",
"dest": "/legal/content-policy.html"
diff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.js
index 97ca84537..d966530e7 100644
--- a/workers/agent-sniper/auto-funder.js
+++ b/workers/agent-sniper/auto-funder.js
@@ -22,7 +22,8 @@ import { getSolBalance } from '../../api/_lib/avatar-wallet.js';
import { solanaConnection } from '../../api/_lib/agent-pumpfun.js';
import { log } from './log.js';
import { screenPush } from './screen-push.js';
-import { cachedStrategies } from './strategy-store.js';
+import { cachedStrategies, getRealizedNetLamports, effectiveDailyLossLimitLamports } from './strategy-store.js';
+import { checkDailyLoss } from '../../api/_lib/agent-trade-guards.js';
const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
@@ -40,6 +41,12 @@ const MIN_SOL = Math.max(0, num('SNIPER_AUTO_FUND_MIN_SOL', 0.02));
const TARGET_SOL = Math.max(MIN_SOL, num('SNIPER_AUTO_FUND_TARGET_SOL', 0.05));
const PER_TX_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_PER_TX_SOL', 0.1));
const DAILY_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_DAILY_SOL', 1.0));
+// Per-agent daily refill ceiling — the guard the incident lacked. The fleet cap
+// alone let a SINGLE wallet that only bought rugs consume the whole day's budget:
+// buy rug → drop below MIN → refill → repeat. This bounds how much any one agent
+// can draw from the master per UTC day (default 0.25 SOL ≈ 5 top-ups), so a
+// bleeding wallet can't starve healthy agents or drain the master after it. 0 = off.
+const PER_AGENT_DAILY_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_PER_AGENT_DAILY_SOL', 0.25));
/**
* Agent ids eligible for auto-funding on this network.
@@ -84,6 +91,37 @@ async function dailyFundedSol(network) {
return Number(row?.sol || 0);
}
+/** SOL moved (live) to EACH agent since the start of the UTC day — the per-agent cap base. */
+async function perAgentFundedSol(network) {
+ const rows = await sql`
+ SELECT agent_id, coalesce(sum(lamports), 0)::float8 / 1e9 AS sol
+ FROM sniper_funding_events
+ WHERE network = ${network}
+ AND mode = 'live'
+ AND created_at >= date_trunc('day', now())
+ GROUP BY agent_id
+ `;
+ const m = new Map();
+ for (const r of rows) m.set(r.agent_id, Number(r.sol || 0));
+ return m;
+}
+
+/**
+ * Tightest effective daily-loss cap (lamports) across an agent's opted-in
+ * strategies — an agent may run more than one. Used to decide whether to keep
+ * refilling a wallet: once realized loss crosses this, the refills stop.
+ */
+function agentLossLimit(agentId, network) {
+ let tightest = null;
+ for (const s of cachedStrategies()) {
+ if (s.agent_id !== agentId || s.network !== network) continue;
+ const lim = effectiveDailyLossLimitLamports(s);
+ if (lim == null) continue;
+ if (tightest == null || lim < tightest) tightest = lim;
+ }
+ return tightest;
+}
+
/** Resolve each armed agent's Solana address from its identity meta. */
async function agentAddresses(agentIds) {
if (!agentIds.length) return new Map();
@@ -109,6 +147,8 @@ async function tick(cfg) {
// One daily-spend read per tick; decremented locally as we fund so several
// agents in the same tick can't collectively blow past the cap.
let dailyRemaining = DAILY_CAP_SOL > 0 ? Math.max(0, DAILY_CAP_SOL - (await dailyFundedSol(cfg.network))) : Infinity;
+ // Per-agent funded-today, so one wallet can't consume the whole fleet budget.
+ const perAgentFunded = PER_AGENT_DAILY_CAP_SOL > 0 ? await perAgentFundedSol(cfg.network) : new Map();
const conn = solanaConnection(cfg.network);
for (const [agentId, address] of addresses) {
@@ -127,9 +167,39 @@ async function tick(cfg) {
if (balanceSol >= MIN_SOL) continue; // healthy — nothing to do
- // Top up to the target, bounded by the per-transfer cap.
+ // LOSS GATE — stop refilling a wallet that has bled past its daily loss cap.
+ // This is the fix for the rug-buy + auto-refill loop: a wallet that only
+ // loses stops getting topped up, so the master can't keep pouring SOL after
+ // it. Only priced when a loss cap is configured; a DB hiccup never blocks a
+ // legitimate refill (the per-agent + daily SOL caps below stay the backstop).
+ const lossLimit = agentLossLimit(agentId, cfg.network);
+ if (lossLimit != null) {
+ try {
+ const netRealized = await getRealizedNetLamports(agentId, cfg.network);
+ if (checkDailyLoss(netRealized, lossLimit)) {
+ log.warn('auto-fund paused — agent hit daily loss cap', { agentId, wallet: address, net_realized_sol: Number(netRealized) / 1e9 });
+ screenPush(`Paused refills for ${address.slice(0, 4)}… — daily loss cap reached`, 'guard');
+ continue;
+ }
+ } catch (err) {
+ log.warn('auto-fund loss check failed — allowing on SOL-cap backstop', { agentId, err: err?.message });
+ }
+ }
+
+ // PER-AGENT DAILY CAP — bound how much any one wallet can draw per day.
+ let agentRemaining = Infinity;
+ if (PER_AGENT_DAILY_CAP_SOL > 0) {
+ agentRemaining = Math.max(0, PER_AGENT_DAILY_CAP_SOL - (perAgentFunded.get(agentId) || 0));
+ if (agentRemaining <= 0) {
+ log.warn('auto-fund per-agent daily cap reached — skipping', { agentId, wallet: address, perAgentCapSol: PER_AGENT_DAILY_CAP_SOL });
+ continue;
+ }
+ }
+
+ // Top up to the target, bounded by the per-transfer, per-agent, and fleet caps.
let topUp = TARGET_SOL - balanceSol;
if (PER_TX_CAP_SOL > 0) topUp = Math.min(topUp, PER_TX_CAP_SOL);
+ if (PER_AGENT_DAILY_CAP_SOL > 0) topUp = Math.min(topUp, agentRemaining);
if (DAILY_CAP_SOL > 0) topUp = Math.min(topUp, dailyRemaining);
topUp = Math.round(topUp * 1e9) / 1e9; // lamport precision
if (topUp <= 0) continue;
@@ -141,6 +211,7 @@ async function tick(cfg) {
await recordFunding({ agentId, wallet: address, network: cfg.network, sol: topUp, balanceBeforeSol: balanceSol, signature: 'SIMULATED', mode: 'simulate' });
log.info('simulate — would top up wallet', { agentId, wallet: address, top_up_sol: topUp });
if (DAILY_CAP_SOL > 0) dailyRemaining -= topUp;
+ if (PER_AGENT_DAILY_CAP_SOL > 0) perAgentFunded.set(agentId, (perAgentFunded.get(agentId) || 0) + topUp);
continue;
}
@@ -169,6 +240,7 @@ async function tick(cfg) {
balanceBeforeSol: balanceSol, signature: result.signature, mode: 'live',
});
if (DAILY_CAP_SOL > 0) dailyRemaining -= topUp;
+ if (PER_AGENT_DAILY_CAP_SOL > 0) perAgentFunded.set(agentId, (perAgentFunded.get(agentId) || 0) + topUp);
log.trade('wallet-funded', { agentId, wallet: address, top_up_sol: topUp, balance_before_sol: balanceSol, sig: result.signature });
screenPush(`Funded ${address.slice(0, 4)}… +${topUp.toFixed(3)} SOL`, 'trade');
@@ -213,6 +285,8 @@ export function startAutoFunderWatch({ cfg, signal } = {}) {
log.info('auto-funder armed', {
network: cfg.network, mode: cfg.mode, pollMs: POLL_INTERVAL_MS,
minSol: MIN_SOL, targetSol: TARGET_SOL, perTxCapSol: PER_TX_CAP_SOL, dailyCapSol: DAILY_CAP_SOL,
+ perAgentDailyCapSol: PER_AGENT_DAILY_CAP_SOL,
+ lossCapSol: num('SNIPER_MAX_DAILY_LOSS_SOL', null),
// Consent is explicit and per-strategy — this is how many agents can be funded at all.
optedInAgents: activeAgentIds(cfg.network).length,
});
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index e0f64c2db..2805c3600 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -12,13 +12,13 @@ import { mayhemGate } from './mayhem-gate.js';
import { marketCapBandReason } from './scorer.js';
import { recordJournal, journalEntry } from './journal.js';
import { getTradeCtx, signAndSend, submitProtectedTrade } from './trade-client.js';
-import { countOpenPositions, getDailySpend } from './strategy-store.js';
+import { countOpenPositions, getDailySpend, getRealizedNetLamports, effectiveDailyLossLimitLamports } from './strategy-store.js';
import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';
import { getPolicyRules } from '../../api/_lib/spend-policy-rules.js';
import {
getSpendLimits, enforceSpendLimit, SpendLimitError, recordSpend, lamportsToUsd,
checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
- recordCustodyEvent,
+ checkDailyLoss, recordCustodyEvent,
SOL_FEE_HEADROOM_LAMPORTS,
} from '../../api/_lib/agent-trade-guards.js';
import { buildAmmSellInstructions } from './amm-exit.js';
@@ -267,6 +267,25 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
const budget = checkDailyBudgetLamports(spent, perTrade, BigInt(strat.daily_budget_lamports));
if (budget) return skip(tag, budget.reason);
+ // 3c. realized-loss circuit breaker (portfolio layer). The per-trade caps
+ // above (budget, headroom, impact) can't stop a fleet that bleeds one
+ // losing entry at a time — this does. Once the day's NET realized loss
+ // crosses the cap the agent stops opening positions AND the auto-funder
+ // stops refilling its wallet, so the master can't keep pouring SOL after
+ // a wallet that only loses. Priced only when a cap is configured (env
+ // SNIPER_MAX_DAILY_LOSS_SOL or per-strategy), so the hot path stays free
+ // otherwise. A DB hiccup never blocks — the lamports caps stay the backstop.
+ const lossLimit = effectiveDailyLossLimitLamports(strat);
+ if (lossLimit != null) {
+ try {
+ const netRealized = await getRealizedNetLamports(strat.agent_id, cfg.network);
+ const loss = checkDailyLoss(netRealized, lossLimit);
+ if (loss) return skip(tag, loss.reason);
+ } catch (err) {
+ log.warn('realized-loss check failed — allowing on lamports backstop', { ...tag, err: err?.message });
+ }
+ }
+
// 3b. shared per-agent spend policy (the same ceiling that governs
// withdraw / x402 / trade). Opt-in: only priced + enforced when the owner
// has actually set a USD ceiling, so the hot snipe path stays price-call-
diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.js
index 80fc49447..96f5f9a43 100644
--- a/workers/agent-sniper/strategy-store.js
+++ b/workers/agent-sniper/strategy-store.js
@@ -6,6 +6,34 @@ import { log } from './log.js';
let _strategies = [];
let _loadedAt = 0;
+function envPositiveNum(name) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return null;
+ const n = Number(raw);
+ return Number.isFinite(n) && n > 0 ? n : null;
+}
+
+/**
+ * The daily realized-loss cap (lamports) that actually applies to a strategy,
+ * combining the fleet-wide env floor with any per-strategy column by taking the
+ * TIGHTER (smaller) of the two — the same "safety band" shape as the market-cap
+ * floor/ceil. `SNIPER_MAX_DAILY_LOSS_SOL` set on the worker protects EVERY agent
+ * at once (including ones whose strategy predates the per-strategy column), which
+ * is the immediately-deployable lever. Returns null when neither is set (no cap).
+ *
+ * @param {{ daily_loss_limit_lamports?: string|number|null }} strat
+ * @returns {bigint|null}
+ */
+export function effectiveDailyLossLimitLamports(strat) {
+ const envSol = envPositiveNum('SNIPER_MAX_DAILY_LOSS_SOL');
+ const envLamports = envSol == null ? null : BigInt(Math.round(envSol * 1e9));
+ const raw = strat?.daily_loss_limit_lamports;
+ const stratLamports = raw == null || raw === '' ? null : BigInt(raw);
+ if (envLamports == null) return stratLamports;
+ if (stratLamports == null) return envLamports;
+ return envLamports < stratLamports ? envLamports : stratLamports;
+}
+
/**
* Active strategies for the worker's network: enabled, not killed, with a real
* budget and a positive stop-loss. The stop-loss filter is the runtime half of
@@ -61,6 +89,28 @@ export async function getDailySpend(agentId, network) {
return BigInt(r?.spent ?? '0');
}
+/**
+ * Net realized P&L (lamports, SIGNED) for an agent over the trailing window —
+ * the denominator of the realized-loss circuit breaker. Negative = the agent is
+ * net down. Only positions the agent has actually exited count (realized, not
+ * mark-to-market), matching how the daily budget counts only committed spend.
+ *
+ * @param {string} agentId
+ * @param {string} network
+ * @param {number} sinceHours trailing window (default 24h)
+ * @returns {Promise<bigint>} signed net realized lamports
+ */
+export async function getRealizedNetLamports(agentId, network, sinceHours = 24) {
+ const [r] = await sql`
+ SELECT coalesce(sum(realized_pnl_lamports), 0)::text AS net
+ FROM agent_sniper_positions
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND realized_pnl_lamports IS NOT NULL
+ AND coalesce(closed_at, opened_at) >= now() - (${sinceHours} || ' hours')::interval
+ `;
+ return BigInt(r?.net ?? '0');
+}
+
/**
* Open positions across all agents — the position-loop work set.
*
diff --git a/workers/oracle/executor.js b/workers/oracle/executor.js
index 783dd2452..66a352b1a 100644
--- a/workers/oracle/executor.js
+++ b/workers/oracle/executor.js
@@ -20,7 +20,7 @@ const JITO_TIP_ACCOUNTS = [
'96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',
'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',
'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY',
- 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt13UZKZr1',
+ 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',
'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',
'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',
'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL',