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: coin3d, strategy lab, watchlist, and pump visualizer enhancements

nirholas2df1b7a82e5c
diff --git a/.gitignore b/.gitignore
index 1626fb8dc..0fff2d58b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -287,3 +287,4 @@ three-ws-prod-log-export-2026-06-24T13-33-58.json
three-ws-prod-log-export-2026-06-25T07-22-45.json
three-ws-prod-log-export-2026-06-25T19-38-22.json
three-ws-prod-log-export-2026-06-26T03-40-50.json
+three-ws-prod-log-export-2026-06-26T07-25-42.json
diff --git a/.sm-check.mjs b/.sm-check.mjs
deleted file mode 100644
index f32cac9da..000000000
--- a/.sm-check.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-import { chromium } from 'playwright';
-const browser = await chromium.launch({ args: ['--no-sandbox'] });
-const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
-const errors = [], warns = [];
-page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); if (m.type() === 'warning') warns.push(m.text()); });
-page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));
-await page.goto('http://localhost:3003/smart-money', { waitUntil: 'networkidle', timeout: 30000 });
-await page.waitForTimeout(1500);
-
-const stats = await page.evaluate(() => ({
- proven: document.getElementById('stProven').textContent,
- winrate: document.getElementById('stWinRate').textContent,
- capital: document.getElementById('stCapital').textContent,
- coins: document.getElementById('stCoins').textContent,
- ctWallets: document.getElementById('ctWallets').textContent,
- walletRows: document.querySelectorAll('#walletList .lrow').length,
- headCols: document.querySelectorAll('#walletHead th').length,
- distVisible: !document.getElementById('dist').hidden,
-}));
-console.log('STATS', JSON.stringify(stats));
-
-await page.evaluate(() => document.querySelector('.tab[data-view="wallets"]').click());
-await page.waitForTimeout(300);
-await page.evaluate(() => document.querySelector('#walletHead th[data-sort="win"]').click());
-await page.waitForTimeout(200);
-console.log('AFTER WIN SORT', await page.evaluate(() => [...document.querySelectorAll('#walletList .lrow td.lstat')].slice(0,3).map(td=>td.textContent)));
-
-await page.evaluate(() => document.querySelector('#walletLabel button[data-l="smart_money"]').click());
-await page.waitForTimeout(200);
-console.log('SMART_MONEY ROWS', await page.evaluate(() => document.querySelectorAll('#walletList .lrow').length));
-await page.evaluate(() => document.querySelector('#walletLabel button[data-l="all"]').click());
-
-await page.evaluate(() => { const r = document.querySelector('#walletList .lrow'); if (r) r.click(); });
-await page.waitForTimeout(1300);
-console.log('WALLET DRAWER', await page.evaluate(() => ({
- open: document.getElementById('drawer').classList.contains('open'),
- title: document.getElementById('drTitle').textContent,
- stats: document.querySelectorAll('#drBody .dr-stat').length,
- recent: document.querySelectorAll('#drBody .nwallet').length,
- hasCopy: !!document.querySelector('#drBody .copybtn'),
-})));
-
-const crossNav = await page.evaluate(() => { const c = document.querySelector('#drBody .nwallet[data-mint]'); if (c) { c.click(); return true; } return false; });
-await page.waitForTimeout(1300);
-console.log('CROSS NAV', crossNav, await page.evaluate(() => ({ back: document.getElementById('drBackBtn').classList.contains('show'), title: document.getElementById('drTitle').textContent })));
-await page.evaluate(() => document.getElementById('drBackBtn').click());
-await page.waitForTimeout(800);
-console.log('AFTER BACK', await page.evaluate(() => document.getElementById('drTitle').textContent));
-await page.evaluate(() => document.getElementById('drClose').click());
-
-await page.evaluate(() => document.querySelector('.tab[data-view="feed"]').click());
-await page.evaluate(() => document.querySelector('#feedFilter button[data-f="graduated"]').click());
-await page.waitForTimeout(300);
-console.log('GRADUATED FEED', await page.evaluate(() => document.getElementById('feedGrid').querySelector('.state') ? 'empty-state' : document.querySelectorAll('#feedGrid .coin').length + ' cards'));
-await page.evaluate(() => document.querySelector('#feedFilter button[data-f="fresh"]').click());
-await page.waitForTimeout(200);
-console.log('FRESH EMPTY CTA', await page.evaluate(() => { const b = document.querySelector('#feedGrid .state .btn'); return b ? b.textContent.trim() : 'cards'; }));
-
-await page.evaluate(() => document.querySelector('.tab[data-view="watchlist"]').click());
-await page.waitForTimeout(500);
-console.log('WATCHLIST', await page.evaluate(() => document.getElementById('watchGrid').textContent.slice(0, 50).trim()));
-
-await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/d2084531-cdf7-4764-ac91-c6d43645d958/scratchpad/wallets.png', fullPage: true });
-console.log('ERRORS', JSON.stringify(errors));
-console.log('WARNS', JSON.stringify(warns.slice(0,5)));
-await browser.close();
diff --git a/CHANGELOG.md b/CHANGELOG.md
index afd460d32..d945750bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The marketplace now has a living economy of autonomous agents transacting on-chain** — The platform's own pool of autonomous agents now does real marketplace commerce, not just peer tips and trades. They list skills and their 3D avatars for sale, buy each other's skills, take free trials, and purchase avatars — every transaction a genuine on-chain $THREE payment settled through the exact same flow a person uses, landing in the live sales feed and each agent's revenue. The pool also scales far beyond its original handful: it grows toward a configurable target of hundreds of distinct, wallet-backed agent accounts, so the marketplace reads as an active, liquid economy instead of an empty shelf. (`/marketplace`) `[feature, improvement]`
- **The marketplace now shows a live feed of what's selling** — The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering. (`/marketplace`) `[feature]`
- **The post-create screen now greets you with a living agent** — After you create an avatar or agent, the 'what's next' screen no longer shows your character frozen in a stiff T-pose. It now renders a live, gently breathing 3D agent you can spin with a drag — the same idle motion your embeds use — so the moment your agent is ready actually feels ready. A one-time confetti burst celebrates the milestone (and stays out of the way if you prefer reduced motion). For agents, the embed snippet is right there to copy without leaving the page, plus one-tap buttons to copy your agent's public link or share it on X. The steps you've already done — giving your agent a brain, deploying it on-chain — now show a checkmark, and an 'I'll do this later' link makes the exit obvious. `[feature, improvement]`
+- **The Pump Visualizer can now render every token as its own coin logo** — The 3D market view has a new Coins style that draws each live token as a crisp, camera-facing logo medallion — the artwork reads instantly instead of wrapping (and distorting) around a sphere — ringed by a tier-coloured glowing edge that still pulses red for fresh mints and green for graduations. A Coins / Orbs toggle in the toolbar (or press C) switches the whole scene instantly without losing your place in the feed, and your choice is remembered next visit. Coins is now the default. We also added real signal to the coin detail panel: the creator's track record (how many coins they've launched and what share actually graduated, with a link to their wallet), how far the coin has retraced from its all-time-high market cap, and — for graduations — the liquidity it migrated with. Every number comes straight from the live on-chain data already on screen. (`/pump-visualizer`) `[feature, improvement]`
- **The trader leaderboard is never empty: live top Solana traders until agents take over** — The leaderboard ranks three.ws agents by a provable, on-chain track record — but until an agent has actually traded in a window, the board had nothing to show. Now, whenever no agent yet has a verified record, the flagship board falls back to the live ranking of the top Solana traders by realized profit (real wallets, real P&L, sourced live from kolscan), each row deep-linked to its on-chain account. The moment an agent earns a record it takes precedence again. Real data throughout — if the live feed is briefly unreachable, the board shows an honest 'be the first' state, never fabricated rows. (`/leaderboard`) `[feature, improvement]`
- **Trading Swarms: pool capital with other agents and split the profits** — A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms. (`/swarms`) `[feature]`
diff --git a/data/changelog.json b/data/changelog.json
index cc7ebeeee..3a92db822 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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-06-26",
+ "title": "The Pump Visualizer can now render every token as its own coin logo",
+ "summary": "The 3D market view has a new Coins style that draws each live token as a crisp, camera-facing logo medallion — the artwork reads instantly instead of wrapping (and distorting) around a sphere — ringed by a tier-coloured glowing edge that still pulses red for fresh mints and green for graduations. A Coins / Orbs toggle in the toolbar (or press C) switches the whole scene instantly without losing your place in the feed, and your choice is remembered next visit. Coins is now the default. We also added real signal to the coin detail panel: the creator's track record (how many coins they've launched and what share actually graduated, with a link to their wallet), how far the coin has retraced from its all-time-high market cap, and — for graduations — the liquidity it migrated with. Every number comes straight from the live on-chain data already on screen.",
+ "tags": ["feature", "improvement"],
+ "link": "/pump-visualizer"
+ },
{
"date": "2026-06-26",
"title": "Agent Activity is now a live trading floor — Conviction Board rail, richer trade detail and a real KPI bar that never shows an empty void",
diff --git a/pages/coin3d.html b/pages/coin3d.html
index fe849dff3..5980aeb93 100644
--- a/pages/coin3d.html
+++ b/pages/coin3d.html
@@ -71,7 +71,10 @@
position: fixed;
left: max(20px, env(safe-area-inset-left));
bottom: max(20px, env(safe-area-inset-bottom));
- width: min(360px, calc(100vw - 40px));
+ width: min(372px, calc(100vw - 40px));
+ max-height: min(86vh, calc(100vh - 40px));
+ overflow-y: auto;
+ overscroll-behavior: contain;
padding: 18px 20px;
background: var(--card);
border: 1px solid var(--border);
@@ -80,6 +83,15 @@
-webkit-backdrop-filter: blur(14px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
animation: rise 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) both;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(120, 140, 220, 0.4) transparent;
+ }
+ #hud::-webkit-scrollbar {
+ width: 6px;
+ }
+ #hud::-webkit-scrollbar-thumb {
+ background: rgba(120, 140, 220, 0.32);
+ border-radius: 3px;
}
@keyframes rise {
from {
@@ -304,15 +316,408 @@
border-radius: 4px;
}
+ /* Category chip + price line in the HUD head */
+ .c3d-cat {
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--muted);
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ padding: 2px 8px;
+ white-space: nowrap;
+ }
+ .hud-price {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ margin: 10px 0 2px;
+ flex-wrap: wrap;
+ }
+ .hud-price .px {
+ font-size: 24px;
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+ }
+ .c3d-change {
+ font-size: 13px;
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+ }
+ .c3d-change.up {
+ color: #44e08a;
+ }
+ .c3d-change.down {
+ color: #ff6b6b;
+ }
+ .c3d-change.flat {
+ color: var(--muted);
+ }
+
+ /* Sparkline */
+ .c3d-spark-wrap {
+ margin: 8px 0 14px;
+ }
+ .c3d-spark {
+ width: 100%;
+ height: 44px;
+ display: block;
+ overflow: visible;
+ }
+ .c3d-spark-empty {
+ height: 44px;
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.04);
+ }
+
+ /* Risk flags */
+ .c3d-risks {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0 0 14px;
+ }
+ .c3d-risk {
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 3px 8px;
+ border-radius: 6px;
+ background: rgba(255, 85, 85, 0.12);
+ color: #ff8f8f;
+ border: 1px solid rgba(255, 85, 85, 0.25);
+ }
+ .c3d-risk.ok {
+ background: rgba(68, 224, 138, 0.12);
+ color: #74e0a8;
+ border-color: rgba(68, 224, 138, 0.25);
+ }
+
+ /* Live trade tape */
+ .c3d-tape {
+ margin: 14px 0 4px;
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ }
+ .c3d-tape-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin: 0 0 8px;
+ }
+ .c3d-tape-title {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--muted);
+ }
+ .c3d-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #44e08a;
+ box-shadow: 0 0 0 0 rgba(68, 224, 138, 0.6);
+ animation: c3dLive 1.6s ease-out infinite;
+ }
+ .c3d-live-dot.stale {
+ background: var(--muted);
+ animation: none;
+ }
+ @keyframes c3dLive {
+ 0% {
+ box-shadow: 0 0 0 0 rgba(68, 224, 138, 0.5);
+ }
+ 70% {
+ box-shadow: 0 0 0 7px rgba(68, 224, 138, 0);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 rgba(68, 224, 138, 0);
+ }
+ }
+ .c3d-tape-flow {
+ font-size: 11px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ color: var(--muted);
+ }
+ .c3d-tape-list {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ max-height: 168px;
+ overflow-y: auto;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(120, 140, 220, 0.4) transparent;
+ }
+ .c3d-tape-list::-webkit-scrollbar {
+ width: 5px;
+ }
+ .c3d-tape-list::-webkit-scrollbar-thumb {
+ background: rgba(120, 140, 220, 0.3);
+ border-radius: 3px;
+ }
+ .c3d-trade {
+ display: grid;
+ grid-template-columns: auto 1fr auto;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 6px;
+ border-radius: 7px;
+ text-decoration: none;
+ color: inherit;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ transition: background 0.12s ease;
+ }
+ .c3d-trade:hover {
+ background: rgba(255, 255, 255, 0.05);
+ }
+ .c3d-trade:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ .c3d-trade.enter {
+ animation: c3dTradeIn 0.4s ease both;
+ }
+ @keyframes c3dTradeIn {
+ from {
+ opacity: 0;
+ transform: translateX(-8px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+ }
+ .c3d-trade .t-side {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+ .c3d-trade.buy .t-side {
+ background: #44e08a;
+ }
+ .c3d-trade.sell .t-side {
+ background: #ff6b6b;
+ }
+ .c3d-trade.buy .t-usd {
+ color: #74e0a8;
+ font-weight: 700;
+ }
+ .c3d-trade.sell .t-usd {
+ color: #ff8f8f;
+ font-weight: 700;
+ }
+ .c3d-trade .t-mid {
+ color: var(--muted);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .c3d-trade .t-time {
+ color: var(--muted);
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .c3d-tape-empty {
+ color: var(--muted);
+ font-size: 12px;
+ padding: 6px 6px 2px;
+ line-height: 1.5;
+ }
+
+ /* Landing (no-mint) state */
+ .c3d-landing {
+ text-align: center;
+ max-width: 540px;
+ width: 100%;
+ animation: rise 0.45s ease both;
+ }
+ .c3d-landing h2 {
+ font-size: 26px;
+ margin: 16px 0 8px;
+ letter-spacing: -0.01em;
+ }
+ .c3d-landing p.lede {
+ color: var(--muted);
+ font-size: 15px;
+ line-height: 1.55;
+ margin: 0 auto 22px;
+ max-width: 440px;
+ }
+ .c3d-search {
+ display: flex;
+ gap: 8px;
+ max-width: 460px;
+ margin: 0 auto 12px;
+ }
+ .c3d-search input {
+ flex: 1;
+ min-width: 0;
+ padding: 11px 14px;
+ font-size: 14px;
+ font-family: inherit;
+ color: var(--fg);
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ outline: none;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+ }
+ .c3d-search input::placeholder {
+ color: var(--muted);
+ }
+ .c3d-search input:focus {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(110, 168, 255, 0.18);
+ }
+ .c3d-search button {
+ padding: 11px 18px;
+ font-size: 14px;
+ font-weight: 700;
+ font-family: inherit;
+ color: #060606;
+ background: var(--accent);
+ border: none;
+ border-radius: 10px;
+ cursor: pointer;
+ transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;
+ }
+ .c3d-search button:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 8px 24px rgba(110, 168, 255, 0.35);
+ }
+ .c3d-search button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ transform: none;
+ box-shadow: none;
+ }
+ .c3d-search-err {
+ color: #ff8f8f;
+ font-size: 12px;
+ min-height: 16px;
+ margin: 0 0 12px;
+ }
+ .c3d-three {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 16px;
+ margin: 0 0 28px;
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--fg);
+ text-decoration: none;
+ background: rgba(110, 168, 255, 0.1);
+ border: 1px solid rgba(110, 168, 255, 0.3);
+ border-radius: 999px;
+ transition: background 0.15s ease, transform 0.12s ease;
+ }
+ .c3d-three:hover {
+ background: rgba(110, 168, 255, 0.18);
+ transform: translateY(-1px);
+ }
+ .c3d-three:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 3px;
+ }
+ .c3d-recent-label {
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--muted);
+ margin: 0 0 12px;
+ }
+ .c3d-recent {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 10px;
+ margin: 0 0 22px;
+ }
+ .c3d-recent-card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 7px;
+ padding: 12px 8px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ text-decoration: none;
+ color: inherit;
+ transition: transform 0.14s ease, border-color 0.14s ease, background 0.14s ease;
+ }
+ .c3d-recent-card:hover {
+ transform: translateY(-3px);
+ border-color: rgba(110, 168, 255, 0.45);
+ background: rgba(110, 168, 255, 0.08);
+ }
+ .c3d-recent-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .c3d-recent-img {
+ width: 46px;
+ height: 46px;
+ border-radius: 50%;
+ object-fit: cover;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--border);
+ }
+ .c3d-recent-img.ph {
+ display: grid;
+ place-items: center;
+ font-size: 16px;
+ font-weight: 700;
+ color: var(--accent);
+ }
+ .c3d-recent-sym {
+ font-size: 12px;
+ font-weight: 700;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .c3d-recent-sk {
+ height: 92px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.05);
+ animation: c3dPulse 1.4s ease-in-out infinite;
+ }
+ .c3d-landing-foot {
+ display: flex;
+ gap: 18px;
+ justify-content: center;
+ flex-wrap: wrap;
+ }
+
@media (max-width: 520px) {
#hud {
width: calc(100vw - 32px);
left: 16px;
bottom: 16px;
+ max-height: 72vh;
}
.hint {
display: none;
}
+ .c3d-recent {
+ grid-template-columns: repeat(3, 1fr);
+ }
+ .c3d-landing h2 {
+ font-size: 22px;
+ }
}
</style>
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index edc5bb189..2cad35f4b 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -861,7 +861,7 @@
</div>
<div class="vz-overlay vz-hint" id="vz-hint" aria-hidden="true">
- <b>Drag</b> to rotate · <b>Scroll</b> to zoom · <b>Click</b> for details · <b>Double-click</b> to open · <b>/</b> to search
+ <b>Drag</b> to rotate · <b>Scroll</b> to zoom · <b>Click</b> for details · <b>Double-click</b> to open · <b>/</b> to search · <b>C</b> coins/orbs
<button type="button" class="dismiss" id="vz-hint-dismiss" aria-label="Dismiss">×</button>
</div>
@@ -995,6 +995,7 @@
const searchInput = document.getElementById('vz-search-input');
const sortBtns = controlsEl.querySelectorAll('.vz-sort button');
const modeBtns = controlsEl.querySelectorAll('.vz-mode button');
+ const styleBtns = controlsEl.querySelectorAll('.vz-style button');
const legendHeadEl = document.querySelector('#vz-legend .head');
const hintEl = document.getElementById('vz-hint');
const hintDismiss = document.getElementById('vz-hint-dismiss');
@@ -1708,9 +1709,87 @@
clearSelection();
loadData();
}
+ } else if (ev.key.toLowerCase() === 'c' && document.activeElement !== searchInput && !ev.metaKey && !ev.ctrlKey) {
+ // Toggle the render style (Coins ⟷ Orbs).
+ setRenderStyle(state.renderStyle === 'coin' ? 'orb' : 'coin');
}
});
+ // ── extra real-data rows: creator track record, distance from ATH,
+ // migration liquidity. Every value traces to data already on the token —
+ // no extra fetch, no placeholders. Rows render only when their data exists.
+ function shortAddr(a) {
+ const s = String(a || '');
+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
+ }
+ function metaRow(key, valueNode) {
+ const row = document.createElement('div');
+ row.className = 'meta-row';
+ const k = document.createElement('span');
+ k.className = 'k';
+ k.textContent = key;
+ row.appendChild(k);
+ if (typeof valueNode === 'string') {
+ const v = document.createElement('span');
+ v.className = 'v';
+ v.innerHTML = valueNode;
+ row.appendChild(v);
+ } else {
+ valueNode.classList.add('v');
+ row.appendChild(valueNode);
+ }
+ return row;
+ }
+ function renderDetailExtra(token) {
+ const host = document.getElementById('vz-detail-extra');
+ if (!host) return;
+ host.innerHTML = '';
+
+ // Creator track record — launches and how many of them graduated. A high
+ // graduation rate is a real credibility signal; a serial-launcher with
+ // zero graduations is a real warning. Both numbers are on the token.
+ const launches = Number(token.creator_launches);
+ if (token.creator && Number.isFinite(launches) && launches > 0) {
+ const graduated = Number(token.creator_graduated) || 0;
+ const rate = Math.round((graduated / launches) * 100);
+ const rateClass = rate >= 30 ? 'good' : rate === 0 ? 'bad' : 'dim';
+ const val = `${launches.toLocaleString()} launch${launches === 1 ? '' : 'es'} · `
+ + `<span class="${rateClass}">${graduated.toLocaleString()} graduated (${rate}%)</span>`;
+ if (isValidMint(token.creator)) {
+ const a = document.createElement('a');
+ a.href = `https://solscan.io/account/${token.creator}`;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
+ a.innerHTML = `${val} <span class="dim">· ${shortAddr(token.creator)} ↗</span>`;
+ host.appendChild(metaRow('Creator', a));
+ } else {
+ host.appendChild(metaRow('Creator', val));
+ }
+ }
+
+ // Distance from all-time-high market cap — how far the coin has retraced.
+ const mc = Number(token.usd_market_cap) || 0;
+ const ath = Number(token.ath_market_cap) || 0;
+ if (mc > 0 && ath > mc * 1.01) {
+ const downPct = Math.round(((ath - mc) / ath) * 100);
+ host.appendChild(metaRow('From ATH', `<span class="bad">−${downPct}%</span> <span class="dim">· ATH ${formatMcap(ath)}</span>`));
+ } else if (mc > 0 && ath > 0 && mc >= ath * 0.99) {
+ host.appendChild(metaRow('From ATH', `<span class="good">at the high</span>`));
+ }
+
+ // Migration liquidity — for graduated coins, how much SOL/USD seeded the pool.
+ if (token.is_migration) {
+ const usd = Number(token.amount_usd) || 0;
+ const sol = Number(token.amount_sol) || 0;
+ if (usd > 0 || sol > 0) {
+ const parts = [];
+ if (usd > 0) parts.push(formatMcap(usd));
+ if (sol > 0) parts.push(`${sol.toLocaleString(undefined, { maximumFractionDigits: 2 })} SOL`);
+ host.appendChild(metaRow('Graduated with', `<span class="good">${parts.join(' · ')}</span>`));
+ }
+ }
+ }
+
// ── detail panel rendering ───────────────────────────────────
function renderDetail(token) {
const avatar = document.getElementById('vz-detail-avatar');
@@ -1726,6 +1805,8 @@
document.getElementById('vz-detail-replies').textContent = token.reply_count != null ? Number(token.reply_count).toLocaleString() : '—';
document.getElementById('vz-detail-age').textContent = formatAge(token.created_timestamp);
+ renderDetailExtra(token);
+
const desc = (token.description || '').trim();
const descEl = document.getElementById('vz-detail-description');
descEl.textContent = desc.length > 800 ? desc.slice(0, 800) + '…' : desc;
@@ -2866,6 +2947,81 @@
});
});
+ // ── Render-style toggle (Coins ⟷ Orbs) ──────────────────────
+ // Rebuild every live mesh in place — same data, same shell positions — so a
+ // style switch is instant and never drops the user's place in the feed.
+ // Preserves any open detail selection across the swap.
+ function rebuildMeshesForStyle() {
+ if (!webglOK) return; // list-view fallback is unaffected by 3D style
+ const snapshots = tokenMeshes.map((e) => ({
+ data: e.data,
+ position: e.mesh.position.clone(),
+ radius: e.radius,
+ isLive: e.isLive,
+ deltaPct: e.deltaPct,
+ visible: e.visible,
+ }));
+ const selMint = selected?.data?.mint || null;
+ const detailWasOpen = detailEl.classList.contains('is-open');
+ for (const e of tokenMeshes.slice()) removeEntry(e);
+
+ for (const s of snapshots) {
+ const { mesh, ring, isLive, tier, cage, rim } = buildTokenMesh(s.data, s.position, s.radius);
+ mesh.scale.setScalar(1);
+ ring.scale.setScalar(1);
+ mesh.visible = s.visible;
+ ring.visible = s.visible;
+ tokensGroup.add(mesh);
+ tokensGroup.add(ring);
+ const entry = {
+ mesh, ring, data: s.data,
+ baseScale: 1, radius: s.radius,
+ isLive,
+ tier, cage, rim,
+ style: state.renderStyle,
+ spawnAt: performance.now() - 1000, // already on-screen → skip pop-in
+ spawned: true,
+ hoverScale: 1,
+ surge: 1,
+ visible: s.visible,
+ label: null,
+ labelOffset: s.radius + 1.6,
+ sonarRings: [],
+ nextSonarAt: 0,
+ deltaPct: s.deltaPct,
+ flashAt: 0,
+ fadeOutAt: 0,
+ };
+ tokenMeshes.push(entry);
+ if (isLive) seedSonarRing(entry);
+ }
+ applyFilterAndRender();
+ if (detailWasOpen && selMint) {
+ const tok = state.all.find((t) => t.mint === selMint);
+ if (tok) selectToken(tok);
+ }
+ }
+
+ function setRenderStyle(style, persist = true) {
+ if (style !== 'coin' && style !== 'orb') return;
+ const changed = state.renderStyle !== style;
+ state.renderStyle = style;
+ styleBtns.forEach((b) => {
+ const on = b.dataset.style === style;
+ b.classList.toggle('is-active', on);
+ b.setAttribute('aria-selected', String(on));
+ });
+ if (persist) { try { localStorage.setItem(RENDER_STYLE_KEY, style); } catch {} }
+ if (changed) rebuildMeshesForStyle();
+ }
+
+ styleBtns.forEach((btn) => {
+ btn.addEventListener('click', () => setRenderStyle(btn.dataset.style));
+ });
+ // Reflect the persisted style on the toggle at boot (no meshes exist yet, so
+ // no rebuild is forced).
+ setRenderStyle(state.renderStyle, false);
+
// Hint dismiss.
hintDismiss.addEventListener('click', () => {
hintEl.classList.add('is-hidden');
diff --git a/public/changelog.json b/public/changelog.json
index 70601ebc1..78f3898fb 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T07:23:48.234Z",
+ "generated_at": "2026-06-26T07:27:08.950Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -243,6 +243,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "The Pump Visualizer can now render every token as its own coin logo",
+ "summary": "The 3D market view has a new Coins style that draws each live token as a crisp, camera-facing logo medallion — the artwork reads instantly instead of wrapping (and distorting) around a sphere — ringed by a tier-coloured glowing edge that still pulses red for fresh mints and green for graduations. A Coins / Orbs toggle in the toolbar (or press C) switches the whole scene instantly without losing your place in the feed, and your choice is remembered next visit. Coins is now the default. We also added real signal to the coin detail panel: the creator's track record (how many coins they've launched and what share actually graduated, with a link to their wallet), how far the coin has retraced from its all-time-high market cap, and — for graduations — the liquidity it migrated with. Every number comes straight from the live on-chain data already on screen.",
+ "link": "/pump-visualizer",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1ebae556c..20112fb64 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -182,6 +182,14 @@
<category>feature</category>
<description>After you create an avatar or agent, the 'what's next' screen no longer shows your character frozen in a stiff T-pose. It now renders a live, gently breathing 3D agent you can spin with a drag — the same idle motion your embeds use — so the moment your agent is ready actually feels ready. A one-time confetti burst celebrates the milestone (and stays out of the way if you prefer reduced motion). For agents, the embed snippet is right there to copy without leaving the page, plus one-tap buttons to copy your agent's public link or share it on X. The steps you've already done — giving your agent a brain, deploying it on-chain — now show a checkmark, and an 'I'll do this later' link makes the exit obvious.</description>
</item>
+ <item>
+ <title>The Pump Visualizer can now render every token as its own coin logo</title>
+ <link>https://three.ws/pump-visualizer</link>
+ <guid isPermaLink="false">2026-06-26:The Pump Visualizer can now render every token as its own coin logo</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The 3D market view has a new Coins style that draws each live token as a crisp, camera-facing logo medallion — the artwork reads instantly instead of wrapping (and distorting) around a sphere — ringed by a tier-coloured glowing edge that still pulses red for fresh mints and green for graduations. A Coins / Orbs toggle in the toolbar (or press C) switches the whole scene instantly without losing your place in the feed, and your choice is remembered next visit. Coins is now the default. We also added real signal to the coin detail panel: the creator's track record (how many coins they've launched and what share actually graduated, with a link to their wallet), how far the coin has retraced from its all-time-high market cap, and — for graduations — the liquidity it migrated with. Every number comes straight from the live on-chain data already on screen.</description>
+ </item>
<item>
<title>The trader leaderboard is never empty: live top Solana traders until agents take over</title>
<link>https://three.ws/leaderboard</link>
diff --git a/public/features.json b/public/features.json
index 2f797f09c..216044ddb 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T07:23:48.210Z",
+ "generated_at": "2026-06-26T07:27:08.734Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/strategy-lab.html b/public/strategy-lab.html
index bf6886f20..f5c18e926 100644
--- a/public/strategy-lab.html
+++ b/public/strategy-lab.html
@@ -5,243 +5,410 @@
<meta charset="utf-8">
<title>Strategy lab · three.ws</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#0b0b0b">
+ <link rel="stylesheet" href="/nav.css">
<style>
- * { box-sizing: border-box; }
:root {
- --fg: #111; --muted: #555; --border: #e5e5e5; --bg: #fafafa;
- --ok-bg: #e7f5e9; --ok-fg: #1b5e20;
- --warn-bg: #fff3cd; --warn-fg: #855008;
- --bad-bg: #fce8e8; --bad-fg: #b71c1c;
- --info-bg: #e3f2fd; --info-fg: #0d47a1;
- --mono: ui-monospace, SFMono-Regular, "JetBrains Mono", monospace;
+ --bg: #0b0b0b; --bg-2: #111111; --panel: #161616; --panel-2: #1d1d1d;
+ --border: #272727; --border-strong: #343434;
+ --text: #f0f2f8; --muted: #8a90a8; --muted-2: #6b7088;
+ --blue: #60a5fa; --green: #4ade80; --red: #f87171; --amber: #f59e0b; --purple: #a78bfa;
+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
+ --ok-bg: color-mix(in srgb, var(--green) 14%, transparent);
+ --warn-bg: color-mix(in srgb, var(--amber) 16%, transparent);
+ --bad-bg: color-mix(in srgb, var(--red) 15%, transparent);
+ --info-bg: color-mix(in srgb, var(--blue) 13%, transparent);
+ --shadow: 0 18px 48px rgba(0,0,0,.45);
}
- body { font: 14px/1.5 system-ui, -apple-system, sans-serif; max-width: 1280px; margin: 1.25rem auto; padding: 0 1rem; color: var(--fg); }
- h1 { font-size: 1.4rem; margin: 0 0 .25rem; }
- h2 { font-size: .95rem; margin: 1.25rem 0 .5rem; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
- .muted { color: var(--muted); }
- .lead { color: var(--muted); margin-bottom: 1rem; max-width: 760px; }
+ html[data-theme='light'] {
+ --bg: #fafafa; --bg-2: #ffffff; --panel: #ffffff; --panel-2: #f4f4f5;
+ --border: #e5e7eb; --border-strong: #d4d4d8;
+ --text: #18181b; --muted: #52525b; --muted-2: #71717a;
+ --blue: #2563eb; --green: #16a34a; --red: #dc2626; --amber: #b45309; --purple: #7c3aed;
+ --shadow: 0 18px 48px rgba(0,0,0,.18);
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }
+ body {
+ font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased; min-height: 100vh;
+ }
+ a { color: var(--blue); text-decoration: none; }
+ a:hover { text-decoration: underline; }
code { font-family: var(--mono); }
+ .wrap { max-width: 1320px; margin: 0 auto; padding: 0 24px 4rem; }
+ @media (max-width: 720px) { .wrap { padding: 0 16px 3rem; } }
+
+ /* ── Hero ─────────────────────────────────────────────── */
+ .hero { padding: 34px 0 14px; display: flex; align-items: flex-start; justify-content: space-between; gap: 22px; flex-wrap: wrap; }
+ .eyebrow { display: inline-flex; align-items: center; gap: 8px; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: var(--amber); font-weight: 600; margin-bottom: 10px; }
+ .eyebrow .pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--amber); box-shadow: 0 0 0 0 rgba(245,158,11,.6); animation: pulse 2s infinite; }
+ @keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(245,158,11,.6); } 50% { box-shadow: 0 0 0 6px rgba(245,158,11,0); } }
+ .hero h1 { font-size: 30px; line-height: 1.12; margin: 0 0 8px; letter-spacing: -.02em; }
+ .hero p.lead { color: var(--muted); margin: 0; font-size: 14.5px; max-width: 680px; }
+ .hero .right { text-align: right; font-family: var(--mono); font-size: 11px; color: var(--muted-2); display: flex; flex-direction: column; gap: 6px; align-items: flex-end; }
+ .kbd-hint { display: inline-flex; gap: 6px; align-items: center; flex-wrap: wrap; justify-content: flex-end; }
+ kbd { font-family: var(--mono); font-size: 10.5px; background: var(--panel-2); border: 1px solid var(--border-strong); border-bottom-width: 2px; border-radius: 5px; padding: 1px 5px; color: var(--text); }
- .layout { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
- @media (max-width: 980px) { .layout { grid-template-columns: 1fr; } }
+ h2 { font-size: 11px; margin: 0 0 .6rem; color: var(--muted); text-transform: uppercase; letter-spacing: .1em; font-weight: 600; }
+ .muted { color: var(--muted); }
- .panel { border: 1px solid var(--border); border-radius: 10px; padding: .9rem 1rem; background: #fff; }
+ .panel { border: 1px solid var(--border); border-radius: 14px; padding: 1rem 1.1rem; background: var(--panel); }
.panel + .panel { margin-top: 1rem; }
+ .layout { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 1rem; margin-top: 1rem; }
+ @media (max-width: 1040px) { .layout { grid-template-columns: 1fr; } }
+
+ /* ── Inputs ───────────────────────────────────────────── */
+ textarea, input, select { font: inherit; padding: .5rem .65rem; border: 1px solid var(--border-strong); border-radius: 8px; background: var(--bg-2); color: var(--text); }
+ textarea:focus, input:focus, select:focus { outline: none; border-color: var(--blue); box-shadow: 0 0 0 3px color-mix(in srgb, var(--blue) 22%, transparent); }
+ textarea { width: 100%; min-height: 340px; font: 12.5px/1.5 var(--mono); resize: vertical; tab-size: 2; }
+ textarea.invalid { border-color: var(--red); box-shadow: 0 0 0 3px color-mix(in srgb, var(--red) 18%, transparent); }
+ select option { background: var(--panel); color: var(--text); }
+
+ button { font: inherit; font-size: 13px; padding: .5rem .85rem; border: 1px solid var(--border-strong); background: var(--panel-2); color: var(--text); border-radius: 8px; cursor: pointer; transition: background .12s, border-color .12s, transform .06s; }
+ button:hover:not(:disabled) { border-color: var(--blue); }
+ button:active:not(:disabled) { transform: translateY(1px); }
+ button:focus-visible { outline: none; box-shadow: 0 0 0 3px color-mix(in srgb, var(--blue) 30%, transparent); }
+ button.primary { background: var(--blue); color: #fff; border-color: var(--blue); }
+ button.primary:hover:not(:disabled) { filter: brightness(1.08); }
+ button.danger { background: transparent; color: var(--red); border-color: color-mix(in srgb, var(--red) 50%, var(--border-strong)); }
+ button.danger:hover:not(:disabled) { background: var(--bad-bg); border-color: var(--red); }
+ button:disabled { opacity: .45; cursor: not-allowed; }
+
+ .actions { display: flex; gap: .5rem; flex-wrap: wrap; margin: .8rem 0 .3rem; align-items: center; }
+
+ /* ── Preset cards ─────────────────────────────────────── */
+ .presets { display: grid; grid-template-columns: repeat(3, 1fr); gap: .5rem; margin-bottom: .75rem; }
+ @media (max-width: 560px) { .presets { grid-template-columns: 1fr; } }
+ .preset-card { text-align: left; padding: .55rem .65rem; border-radius: 10px; display: flex; flex-direction: column; gap: 2px; background: var(--panel-2); border: 1px solid var(--border); }
+ .preset-card.active { border-color: var(--blue); box-shadow: inset 0 0 0 1px var(--blue); }
+ .preset-card .pname { font-weight: 600; font-size: 12.5px; display: flex; align-items: center; gap: 6px; }
+ .preset-card .pdesc { font-size: 10.5px; color: var(--muted); line-height: 1.35; }
+ .risk { width: 7px; height: 7px; border-radius: 50%; flex: none; }
+ .risk.low { background: var(--green); } .risk.med { background: var(--amber); } .risk.high { background: var(--red); }
+
+ /* ── Field palette ────────────────────────────────────── */
+ .palette { margin-top: .65rem; border-top: 1px dashed var(--border); padding-top: .65rem; }
+ .palette .ptitle { font-size: 10.5px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted-2); margin: .35rem 0 .3rem; }
+ .chips { display: flex; flex-wrap: wrap; gap: .35rem; }
+ .chip { font: 11px/1 var(--mono); padding: .3rem .5rem; border-radius: 999px; border: 1px solid var(--border-strong); background: var(--bg-2); color: var(--text); cursor: pointer; display: inline-flex; gap: 5px; align-items: center; }
+ .chip:hover { border-color: var(--blue); background: var(--info-bg); }
+ .chip .dom { color: var(--muted-2); font-size: 9.5px; }
+ details.palette-wrap { margin-top: .65rem; }
+ details.palette-wrap > summary { cursor: pointer; font-size: 11px; color: var(--muted); list-style: none; user-select: none; display: inline-flex; align-items: center; gap: 6px; }
+ details.palette-wrap > summary::-webkit-details-marker { display: none; }
+ details.palette-wrap > summary::before { content: '▸'; transition: transform .12s; display: inline-block; }
+ details.palette-wrap[open] > summary::before { transform: rotate(90deg); }
- textarea, input, select { font: inherit; padding: .45rem .6rem; border: 1px solid var(--border); border-radius: 6px; background: #fff; }
- textarea { width: 100%; min-height: 320px; font: 12px/1.45 var(--mono); resize: vertical; }
- textarea.invalid { border-color: var(--bad-fg); background: #fff8f8; }
- select, input { font-size: 13px; }
-
- .actions { display: flex; gap: .5rem; flex-wrap: wrap; margin: .75rem 0 .25rem; align-items: center; }
- button { font: inherit; padding: .45rem .8rem; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }
- button.primary { background: #111; color: #fff; border-color: #111; }
- button.danger { background: #b71c1c; color: #fff; border-color: #b71c1c; }
- button:disabled { opacity: .5; cursor: wait; }
-
- .preset { font-size: .75rem; padding: .2rem .65rem; border-radius: 999px; }
- .preset:hover { background: #f3f3f3; }
-
- .status { font-size: .8rem; padding: .4rem .6rem; border-radius: 6px; margin-top: .5rem; }
- .status.ok { background: var(--ok-bg); color: var(--ok-fg); }
- .status.bad { background: var(--bad-bg); color: var(--bad-fg); }
- .status.warn { background: var(--warn-bg); color: var(--warn-fg); }
- .status.info { background: var(--info-bg); color: var(--info-fg); }
-
- .issues { margin-top: .5rem; display: flex; flex-direction: column; gap: .35rem; }
- .issue { display: grid; grid-template-columns: auto auto 1fr; gap: .4rem; align-items: start;
- font-size: .78rem; padding: .4rem .55rem; border-radius: 6px; border-left: 3px solid transparent; }
- .issue .badge { text-transform: uppercase; font-size: .6rem; font-weight: 700; letter-spacing: .05em;
- padding: .1rem .35rem; border-radius: 4px; align-self: center; }
- .issue code { font-size: .72rem; opacity: .85; align-self: center; white-space: nowrap; }
- .issue .msg { line-height: 1.4; }
- .issue.error { background: var(--bad-bg); color: var(--bad-fg); border-left-color: var(--bad-fg); }
- .issue.error .badge { background: var(--bad-fg); color: #fff; }
- .issue.warning { background: var(--warn-bg); color: var(--warn-fg); border-left-color: var(--warn-fg); }
- .issue.warning .badge { background: var(--warn-fg); color: #fff; }
- .issue.info { background: var(--info-bg); color: var(--info-fg); border-left-color: var(--info-fg); }
- .issue.info .badge { background: var(--info-fg); color: #fff; }
-
- .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: .5rem; margin: .5rem 0; }
- .metric { border: 1px solid var(--border); border-radius: 8px; padding: .5rem .7rem; background: var(--bg); }
- .metric .v { font-size: 1.3rem; font-weight: 600; line-height: 1.1; }
- .metric .v.pos { color: var(--ok-fg); }
- .metric .v.neg { color: var(--bad-fg); }
- .metric .l { font-size: .7rem; color: var(--muted); margin-top: .15rem; }
-
- table { width: 100%; border-collapse: collapse; font-size: .8rem; }
- th, td { text-align: left; padding: .35rem .5rem; border-bottom: 1px solid #eee; vertical-align: top; }
- th { font-weight: 600; color: var(--muted); font-size: .7rem; text-transform: uppercase; }
+ /* ── Status & issues ──────────────────────────────────── */
+ .status { font-size: 12.5px; padding: .5rem .65rem; border-radius: 8px; margin-top: .65rem; display: flex; align-items: center; gap: .5rem; }
+ .status.ok { background: var(--ok-bg); color: var(--green); } .status.bad { background: var(--bad-bg); color: var(--red); }
+ .status.warn { background: var(--warn-bg); color: var(--amber); } .status.info { background: var(--info-bg); color: var(--blue); }
+ .issues { margin-top: .55rem; display: flex; flex-direction: column; gap: .35rem; }
+ .issue { display: grid; grid-template-columns: auto auto 1fr; gap: .45rem; align-items: start; font-size: 12px; padding: .45rem .55rem; border-radius: 8px; border-left: 3px solid transparent; }
+ .issue .badge { text-transform: uppercase; font-size: 9px; font-weight: 700; letter-spacing: .05em; padding: .12rem .35rem; border-radius: 4px; align-self: center; color: #fff; }
+ .issue code { font-size: 11px; opacity: .9; align-self: center; white-space: nowrap; }
+ .issue.error { background: var(--bad-bg); color: var(--red); border-left-color: var(--red); } .issue.error .badge { background: var(--red); }
+ .issue.warning { background: var(--warn-bg); color: var(--amber); border-left-color: var(--amber); } .issue.warning .badge { background: var(--amber); }
+ .issue.info { background: var(--info-bg); color: var(--blue); border-left-color: var(--blue); } .issue.info .badge { background: var(--blue); }
+
+ .summary-box { margin-top: .6rem; font-size: 12px; color: var(--muted); display: none; flex-direction: column; gap: .3rem; }
+ .summary-box .srow { display: flex; gap: .5rem; }
+ .summary-box .srow b { color: var(--text); font-weight: 600; min-width: 56px; flex: none; }
+ .summary-box code { color: var(--text); }
+
+ .hint { margin-top: .6rem; font-size: 11.5px; color: var(--muted-2); line-height: 1.5; }
+ .hint code { color: var(--muted); }
+
+ /* ── Metrics ──────────────────────────────────────────── */
+ .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: .5rem; margin: .25rem 0 .75rem; }
+ .metric { border: 1px solid var(--border); border-radius: 10px; padding: .55rem .7rem; background: var(--panel-2); }
+ .metric .v { font-size: 1.25rem; font-weight: 650; line-height: 1.1; font-variant-numeric: tabular-nums; }
+ .metric .v.pos { color: var(--green); } .metric .v.neg { color: var(--red); }
+ .metric .l { font-size: 10px; color: var(--muted); margin-top: .2rem; text-transform: uppercase; letter-spacing: .04em; }
+
+ .statgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px,1fr)); gap: .35rem .9rem; font-size: 12px; margin: .25rem 0 .75rem; }
+ .statgrid .row { display: flex; justify-content: space-between; gap: .5rem; padding: .25rem 0; border-bottom: 1px solid var(--border); }
+ .statgrid .row span { color: var(--muted); } .statgrid .row b { font-variant-numeric: tabular-nums; font-weight: 600; }
+
+ /* ── Charts ───────────────────────────────────────────── */
+ .chart-card { border: 1px solid var(--border); border-radius: 10px; padding: .6rem .7rem; background: var(--panel-2); margin-bottom: .75rem; }
+ .chart-card .ctitle { font-size: 10px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted-2); margin-bottom: .4rem; display: flex; justify-content: space-between; }
+ .equity { width: 100%; height: 110px; display: block; }
+ .strip { display: flex; gap: 2px; flex-wrap: wrap; }
+ .strip .cell { width: 13px; height: 13px; border-radius: 3px; background: var(--border-strong); }
+ .strip .cell[data-tip] { cursor: help; }
+
+ /* ── Tables ───────────────────────────────────────────── */
+ .tbl-wrap { overflow-x: auto; }
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
+ th, td { text-align: left; padding: .4rem .55rem; border-bottom: 1px solid var(--border); vertical-align: top; }
+ th { font-weight: 600; color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .04em; white-space: nowrap; }
+ th.sortable { cursor: pointer; user-select: none; }
+ th.sortable:hover { color: var(--text); }
+ th.sortable .arr { opacity: .5; font-size: 9px; }
td.num { text-align: right; font-variant-numeric: tabular-nums; font-family: var(--mono); }
- td .pos { color: var(--ok-fg); } td .neg { color: var(--bad-fg); }
+ td .pos { color: var(--green); } td .neg { color: var(--red); }
+ .reason-chip { font-size: 10px; padding: .1rem .4rem; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--border-strong); color: var(--muted); }
- .log { max-height: 360px; overflow-y: auto; font: 11px/1.55 var(--mono); background: #0f0f0f; color: #d6e1ff; border-radius: 8px; padding: .65rem .8rem; }
- .log .row { padding: .1rem 0; }
+ /* ── Activity log ─────────────────────────────────────── */
+ .log-toolbar { display: flex; gap: .35rem; flex-wrap: wrap; align-items: center; margin-bottom: .5rem; }
+ .fpill { font: 10.5px/1 var(--mono); padding: .28rem .5rem; border-radius: 999px; border: 1px solid var(--border-strong); background: var(--bg-2); color: var(--muted); cursor: pointer; }
+ .fpill.on { background: var(--info-bg); border-color: var(--blue); color: var(--blue); }
+ .fpill .n { opacity: .7; margin-left: 4px; }
+ .log-toolbar .spacer { flex: 1; }
+ .mini { font-size: 10.5px; padding: .28rem .5rem; }
+ .log { max-height: 340px; overflow-y: auto; font: 11px/1.6 var(--mono); background: #0a0a0a; color: #d6e1ff; border-radius: 10px; padding: .65rem .8rem; border: 1px solid var(--border); }
+ html[data-theme='light'] .log { background: #0f1117; }
+ .log .ln { padding: .05rem 0; white-space: pre-wrap; word-break: break-word; }
+ .log .ln .t { color: #4a5269; margin-right: .5rem; }
.log .skip { color: #8c8c8c; } .log .enter { color: #58e891; } .log .exit { color: #ffd54f; }
- .log .error { color: #ff7777; } .log .start { color: #80b8ff; } .log .done { color: #80b8ff; font-weight: 600; }
- .log .tick { color: #4a5269; }
-
- .live-dot { display: inline-flex; align-items: center; gap: .3rem; font-size: .72rem; color: var(--muted); }
- .live-dot::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: #c8c8c8; }
- .live-dot.on::before { background: #43a047; box-shadow: 0 0 0 0 rgba(67,160,71,.5); animation: pulse 1.6s infinite; }
- @keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(67,160,71,.5); } 50% { box-shadow: 0 0 0 5px rgba(67,160,71,0); } }
-
- .row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; margin: .25rem 0; }
- .kv { font-size: .8rem; }
- .kv span { color: var(--muted); margin-right: .35rem; }
- .copy { padding: .1rem .35rem; font-size: .7rem; cursor: pointer; border: 1px solid var(--border); background: #fff; border-radius: 4px; }
- .copy:hover { background: #f3f3f3; }
- .balance { font-size: 1.2rem; font-weight: 600; font-variant-numeric: tabular-nums; }
- .fund-warn { font-size: .75rem; color: var(--warn-fg); margin-top: .35rem; }
-
- .mode-switch { display: inline-flex; border: 1px solid var(--border); border-radius: 6px; overflow: hidden; }
- .mode-switch button { border: none; background: #fff; border-radius: 0; padding: .4rem .7rem; }
- .mode-switch button.active { background: #111; color: #fff; }
-
- .modal-backdrop {
- position: fixed; inset: 0; z-index: 100;
- display: flex; align-items: center; justify-content: center;
- padding: 1rem; background: rgba(15, 15, 15, .55);
- opacity: 0; transition: opacity .14s ease;
- }
+ .log .error { color: #ff7777; } .log .start { color: #80b8ff; } .log .done { color: #80b8ff; font-weight: 600; } .log .tick { color: #4a5269; }
+
+ .live-dot { display: inline-flex; align-items: center; gap: .35rem; font-size: 11px; color: var(--muted); }
+ .live-dot::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--border-strong); }
+ .live-dot.on::before { background: var(--green); animation: blip 1.6s infinite; }
+ @keyframes blip { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--green) 60%, transparent); } 50% { box-shadow: 0 0 0 5px transparent; } }
+
+ /* ── Wallet bar ───────────────────────────────────────── */
+ .row { display: flex; gap: .6rem; align-items: center; flex-wrap: wrap; }
+ .kv { font-size: 12.5px; display: inline-flex; align-items: center; gap: .4rem; }
+ .kv > span.lbl { color: var(--muted); }
+ .copy { padding: .15rem .4rem; font-size: 10px; cursor: pointer; }
+ .balance { font-size: 1.15rem; font-weight: 650; font-variant-numeric: tabular-nums; }
+ .fund-warn { font-size: 11px; color: var(--amber); margin-top: .35rem; }
+ .mode-switch { display: inline-flex; border: 1px solid var(--border-strong); border-radius: 8px; overflow: hidden; }
+ .mode-switch button { border: none; background: transparent; border-radius: 0; padding: .45rem .75rem; }
+ .mode-switch button.active { background: var(--blue); color: #fff; }
+
+ /* ── Allocation bar ───────────────────────────────────── */
+ .alloc { display: flex; height: 8px; border-radius: 999px; overflow: hidden; background: var(--panel-2); margin: .4rem 0 .75rem; }
+ .alloc span { height: 100%; }
+
+ /* ── Skeleton ─────────────────────────────────────────── */
+ .skel { background: linear-gradient(90deg, var(--panel-2) 25%, var(--border) 50%, var(--panel-2) 75%); background-size: 200% 100%; animation: sk 1.2s infinite; border-radius: 6px; }
+ @keyframes sk { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+
+ /* ── Empty states ─────────────────────────────────────── */
+ .empty { text-align: center; padding: 1.6rem 1rem; color: var(--muted); }
+ .empty .ic { font-size: 1.6rem; opacity: .5; }
+ .empty .t { font-weight: 600; color: var(--text); margin: .35rem 0 .2rem; font-size: 13px; }
+ .empty .d { font-size: 12px; max-width: 320px; margin: 0 auto; }
+
+ /* ── Modal ────────────────────────────────────────────── */
+ .modal-backdrop { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; padding: 1rem; background: rgba(0,0,0,.6); opacity: 0; transition: opacity .14s; }
.modal-backdrop.open { opacity: 1; }
- .modal {
- background: #fff; border: 1px solid var(--border); border-radius: 12px;
- width: 100%; max-width: 440px; padding: 1.25rem 1.35rem;
- box-shadow: 0 18px 48px rgba(0, 0, 0, .28);
- transform: translateY(8px) scale(.985); transition: transform .14s ease;
- }
+ .modal { background: var(--panel); border: 1px solid var(--border-strong); border-radius: 14px; width: 100%; max-width: 460px; padding: 1.25rem 1.35rem; box-shadow: var(--shadow); transform: translateY(8px) scale(.985); transition: transform .14s; }
.modal-backdrop.open .modal { transform: none; }
.modal h3 { margin: 0 0 .5rem; font-size: 1.05rem; }
- .modal p { margin: 0 0 .65rem; color: var(--muted); line-height: 1.5; }
- .modal p strong { color: var(--bad-fg); }
+ .modal p { margin: 0 0 .65rem; color: var(--muted); line-height: 1.5; font-size: 13px; }
+ .modal p strong { color: var(--red); }
.modal .modal-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.1rem; }
- .modal button:focus-visible { outline: 2px solid var(--info-fg); outline-offset: 2px; }
+
+ /* ── Toast ────────────────────────────────────────────── */
+ #toasts { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); z-index: 200; display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; }
+ .toast { background: var(--panel); border: 1px solid var(--border-strong); color: var(--text); padding: .55rem .85rem; border-radius: 999px; font-size: 12.5px; box-shadow: var(--shadow); opacity: 0; transform: translateY(8px); transition: opacity .18s, transform .18s; }
+ .toast.show { opacity: 1; transform: none; }
</style>
- <meta name="description" content="Build DCA and subscription strategies that trade on-chain on your behalf.">
+ <meta name="description" content="Build, validate, backtest and run declarative pump.fun trading strategies on real on-chain data.">
<link rel="canonical" href="https://three.ws/strategy-lab">
<meta property="og:type" content="website">
<meta property="og:site_name" content="three.ws">
<meta property="og:title" content="Strategy Lab · three.ws">
- <meta property="og:description" content="Build DCA and subscription strategies that trade on-chain on your behalf.">
+ <meta property="og:description" content="Build, validate, backtest and run declarative pump.fun strategies on real on-chain data.">
<meta property="og:url" content="https://three.ws/strategy-lab">
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Strategy+Lab&amp;d=Build+DCA+and+subscription+strategies+that+trade+on-chain+on+your+behalf.&amp;p=%2Fstrategy-lab">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Strategy+Lab&amp;d=Build%2C+backtest+and+run+pump.fun+strategies+on+real+on-chain+data.&amp;p=%2Fstrategy-lab">
<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="Strategy Lab · three.ws">
- <meta name="twitter:description" content="Build DCA and subscription strategies that trade on-chain on your behalf.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Strategy+Lab&amp;d=Build+DCA+and+subscription+strategies+that+trade+on-chain+on+your+behalf.&amp;p=%2Fstrategy-lab">
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Strategy Lab","description":"Build DCA and subscription strategies that trade on-chain on your behalf.","url":"https://three.ws/strategy-lab","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
-
+ <meta name="twitter:description" content="Build, validate, backtest and run declarative pump.fun strategies on real on-chain data.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Strategy+Lab&amp;d=Build%2C+backtest+and+run+pump.fun+strategies+on+real+on-chain+data.&amp;p=%2Fstrategy-lab">
+ <meta name="twitter:site" content="@trythreews">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Strategy Lab","description":"Build, validate, backtest and run declarative pump.fun strategies on real on-chain data.","url":"https://three.ws/strategy-lab","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="Strategy Lab — three.ws">
- <meta name="twitter:site" content="@trythreews">
</head>
<body>
- <header>
- <div id="nav-container"></div>
- </header>
+ <header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
- <h1>Strategy lab</h1>
- <p class="lead">
- Declarative pump.fun strategies, executed end-to-end. Backtests query the
- live read-only MCP for real holder, curve, and creator data. Live runs
- sign and submit on-chain via your agent's hot wallet.
- </p>
-
- <!-- ── Top bar: agent + wallet ──────────────────────────────────────── -->
- <div class="panel" id="walletPanel">
- <div class="row" style="justify-content:space-between">
- <div class="row" style="margin:0">
- <label class="kv"><span>Agent</span>
- <select id="agentSel"><option value="">— sign in —</option></select>
- </label>
- <label class="kv"><span>Network</span>
- <select id="netSel"><option value="mainnet">mainnet</option><option value="devnet">devnet</option></select>
- </label>
- <button id="provisionBtn" disabled>Provision wallet</button>
+ <main class="wrap">
+ <div class="hero">
+ <div class="left">
+ <div class="eyebrow"><span class="pulse"></span> Strategy lab · live MCP data</div>
+ <h1>Declarative pump.fun strategies, executed end-to-end</h1>
+ <p class="lead">
+ Write a strategy as data. Backtests replay it against real holder, curve, and
+ creator data from the read-only MCP. Live runs sign and submit on-chain through
+ your agent's hot wallet — the same evaluator powers both, so a backtest is a
+ faithful preview of a live run.
+ </p>
</div>
- <div class="row" style="margin:0">
- <div id="walletInfo" class="kv muted">No wallet loaded.</div>
+ <div class="right">
+ <div class="kbd-hint">
+ <kbd>⌘</kbd><kbd>↵</kbd> backtest
+ </div>
+ <div class="kbd-hint">
+ <kbd>⌘</kbd><kbd>⇧</kbd><kbd>↵</kbd> run
+ </div>
+ <div class="kbd-hint">
+ <kbd>⌘</kbd><kbd>S</kbd> validate
+ </div>
</div>
</div>
- <div id="walletStatus" class="status info" style="margin-top:.5rem; display:none"></div>
- </div>
- <div class="layout" style="margin-top:1rem">
- <!-- ── Spec editor ───────────────────────────────────────────────── -->
- <section class="panel">
- <h2>Strategy spec</h2>
- <div style="display:flex; gap:.35rem; flex-wrap:wrap; margin-bottom:.5rem;">
- <button class="preset" data-preset="momentum">Momentum</button>
- <button class="preset" data-preset="snipe">New-token snipe</button>
- <button class="preset" data-preset="mean-revert">Mean revert</button>
- </div>
- <textarea id="spec" spellcheck="false"></textarea>
- <div class="actions">
- <button id="validate">Validate</button>
- <button id="backtest" class="primary">Backtest</button>
- <span style="flex:1"></span>
- <div class="mode-switch">
- <button class="mode active" data-mode="simulate">Simulate</button>
- <button class="mode" data-mode="live">Live (real)</button>
+ <!-- ── Agent + wallet ──────────────────────────────────── -->
+ <div class="panel" id="walletPanel">
+ <div class="row" style="justify-content:space-between">
+ <div class="row">
+ <label class="kv"><span class="lbl">Agent</span>
+ <select id="agentSel"><option value="">— sign in —</option></select>
+ </label>
+ <label class="kv"><span class="lbl">Network</span>
+ <select id="netSel"><option value="mainnet">mainnet</option><option value="devnet">devnet</option></select>
+ </label>
+ <button id="provisionBtn" disabled>Provision wallet</button>
+ </div>
+ <div class="row">
+ <div id="walletInfo" class="kv muted">No wallet loaded.</div>
</div>
- <button id="run" class="primary">Run</button>
- <button id="stop" disabled>Stop</button>
- </div>
- <div id="status" class="status info">Edit the spec and hit Validate.</div>
- <div id="issues" class="issues" style="display:none"></div>
- <div style="margin-top:.5rem; font-size:.75rem;" class="muted">
- Filter &amp; exit paths: <code>holders.total</code>, <code>holders.topHolderPct</code>,
- <code>creator.rugCount</code>, <code>curve.graduationPct</code>, <code>curve.priceSol</code>,
- <code>token.ageSec</code>, <code>token.marketCapSol</code>.
- Exit-only (open position): <code>position.pnlPct</code>, <code>position.ageSec</code>,
- <code>position.amountTokens</code>, <code>position.entryPriceSol</code>.
- Ops: <code>&gt; &gt;= &lt; &lt;= == !=</code>. Validation flags unknown paths,
- impossible thresholds, contradictory filters, and unreachable exit rules.
</div>
- </section>
+ <div id="walletStatus" class="status info" style="display:none"></div>
+ </div>
- <!-- ── Results ───────────────────────────────────────────────────── -->
- <section class="panel">
- <h2>Results <span id="liveDot" class="live-dot" style="margin-left:.5rem"></span></h2>
- <div id="metrics" class="metrics" style="display:none;"></div>
- <div id="resultPanel"><p class="muted">Run a backtest or live session to see results.</p></div>
+ <div class="layout">
+ <!-- ── Spec editor ──────────────────────────────────── -->
+ <section class="panel">
+ <h2>Strategy spec</h2>
+ <div class="presets" id="presets">
+ <button class="preset-card" data-preset="momentum">
+ <span class="pname"><span class="risk med"></span> Momentum</span>
+ <span class="pdesc">Buy strong new launches, take profit at +75%, hard stop at -30%.</span>
+ </button>
+ <button class="preset-card" data-preset="snipe">
+ <span class="pname"><span class="risk high"></span> New-token snipe</span>
+ <span class="pdesc">Small bets on fresh mints; double or 10-minute timeout exit.</span>
+ </button>
+ <button class="preset-card" data-preset="mean-revert">
+ <span class="pname"><span class="risk low"></span> Mean revert</span>
+ <span class="pdesc">Trending coins, scale out at +20% / +40%, cut at -15%.</span>
+ </button>
+ </div>
- <h2 style="margin-top:1rem">Activity</h2>
- <div id="log" class="log"><div class="row muted">— no events yet —</div></div>
- </section>
- </div>
+ <textarea id="spec" spellcheck="false" aria-label="Strategy spec JSON"></textarea>
- <!-- ── Portfolio ────────────────────────────────────────────────────── -->
- <section class="panel" style="margin-top:1rem">
- <div class="row" style="justify-content:space-between; margin:0">
- <h2 style="margin:0">Portfolio</h2>
- <div class="row" style="margin:0">
- <button id="refreshPortfolio">Refresh</button>
- <button id="closeAll" class="danger">Stop & sell all</button>
- </div>
+ <div class="actions">
+ <button id="format" class="mini" title="Pretty-print the JSON">Format</button>
+ <button id="validate">Validate</button>
+ <button id="backtest" class="primary">Backtest</button>
+ <span style="flex:1"></span>
+ <label class="kv"><span class="lbl">Duration</span>
+ <select id="durSel">
+ <option value="30">30s</option>
+ <option value="60" selected>60s</option>
+ <option value="120">2m</option>
+ <option value="300">5m</option>
+ </select>
+ </label>
+ <div class="mode-switch" id="modeSwitch">
+ <button class="mode active" data-mode="simulate">Simulate</button>
+ <button class="mode" data-mode="live">Live</button>
+ </div>
+ <button id="run" class="primary">Run</button>
+ <button id="stop" disabled>Stop</button>
+ </div>
+
+ <div id="status" class="status info">Edit the spec, then validate or backtest.</div>
+ <div id="issues" class="issues" style="display:none"></div>
+ <div id="summaryBox" class="summary-box"></div>
+
+ <details class="palette-wrap" id="paletteWrap" open>
+ <summary>Field palette — click to insert a rule · hover for domain</summary>
+ <div class="palette" id="palette"></div>
+ </details>
+
+ <div class="hint">
+ Operators: <code>&gt; &gt;= &lt; &lt;= == !=</code>.
+ Validation flags unknown paths, impossible thresholds, contradictory filters,
+ and unreachable exit rules. <code>position.*</code> paths are exit-only.
+ </div>
+ </section>
+
+ <!-- ── Results ──────────────────────────────────────── -->
+ <section class="panel">
+ <div class="row" style="justify-content:space-between; align-items:center">
+ <h2 style="margin:0">Results</h2>
+ <div class="row">
+ <span id="liveDot" class="live-dot"></span>
+ <button id="exportBtn" class="mini" style="display:none">Export JSON</button>
+ <button id="copyBtn" class="mini" style="display:none">Copy summary</button>
+ </div>
+ </div>
+ <div id="metrics" class="metrics" style="display:none"></div>
+ <div id="charts"></div>
+ <div id="resultPanel">
+ <div class="empty">
+ <div class="ic">📊</div>
+ <div class="t">No results yet</div>
+ <div class="d">Run a backtest for historical performance, or start a simulated session to watch the strategy trade live.</div>
+ </div>
+ </div>
+
+ <h2 style="margin-top:1.1rem">Activity</h2>
+ <div class="log-toolbar" id="logToolbar">
+ <button class="fpill on" data-f="all">all<span class="n">0</span></button>
+ <button class="fpill" data-f="enter">enter<span class="n">0</span></button>
+ <button class="fpill" data-f="exit">exit<span class="n">0</span></button>
+ <button class="fpill" data-f="skip">skip<span class="n">0</span></button>
+ <button class="fpill" data-f="tick">tick<span class="n">0</span></button>
+ <button class="fpill" data-f="error">error<span class="n">0</span></button>
+ <span class="spacer"></span>
+ <button id="autoscroll" class="fpill on" title="Auto-scroll to newest">⤓ auto</button>
+ <button id="copyLog" class="mini">Copy</button>
+ <button id="clearLog" class="mini">Clear</button>
+ </div>
+ <div id="log" class="log"><div class="ln muted">— no events yet —</div></div>
+ </section>
</div>
- <div id="portfolio"><p class="muted">Pick an agent above to load on-chain holdings.</p></div>
- </section>
- <!-- ── Confirm modal (Stop & sell all) ─────────────────────────────────── -->
+ <!-- ── Portfolio ────────────────────────────────────────── -->
+ <section class="panel" style="margin-top:1rem">
+ <div class="row" style="justify-content:space-between">
+ <h2 style="margin:0">Portfolio</h2>
+ <div class="row">
+ <button id="refreshPortfolio">Refresh</button>
+ <button id="closeAll" class="danger">Stop &amp; sell all</button>
+ </div>
+ </div>
+ <div id="portfolio">
+ <div class="empty">
+ <div class="ic">👛</div>
+ <div class="t">No agent selected</div>
+ <div class="d">Pick an agent above to load its on-chain SOL balance and SPL holdings with live cost-basis PnL.</div>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <!-- ── Confirm modal ────────────────────────────────────────── -->
<div id="confirmModal" class="modal-backdrop" hidden>
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="confirmTitle" aria-describedby="confirmBody">
- <h3 id="confirmTitle">Stop &amp; sell all?</h3>
+ <h3 id="confirmTitle">Confirm</h3>
<p id="confirmBody"></p>
<div class="modal-actions">
<button id="confirmCancel" type="button">Cancel</button>
- <button id="confirmAccept" type="button" class="danger">Stop &amp; sell all</button>
+ <button id="confirmAccept" type="button" class="danger">Confirm</button>
</div>
</div>
</div>
+ <div id="toasts"></div>
+
<script type="module">
+ // ── Presets ─────────────────────────────────────────────────────────────
const PRESETS = {
momentum: {
scan: { kind: 'newTokens', limit: 10 },
@@ -277,78 +444,97 @@
},
};
+ // Field palette metadata — mirrors the DSL METRICS table for editor hints.
+ // Each entry: path, human label, domain string, default predicate to insert.
+ const FIELDS = {
+ filter: [
+ { p: 'holders.total', l: 'holder count', d: '0…∞ int', ins: 'holders.total > 50' },
+ { p: 'holders.topHolderPct', l: 'top-holder %', d: '0…100', ins: 'holders.topHolderPct < 25' },
+ { p: 'creator.rugCount', l: 'creator rugs', d: '0…∞ int', ins: 'creator.rugCount == 0' },
+ { p: 'curve.graduationPct', l: 'graduation %', d: '0…100', ins: 'curve.graduationPct > 50' },
+ { p: 'curve.priceSol', l: 'price (SOL)', d: '0…∞', ins: 'curve.priceSol < 0.0001' },
+ { p: 'token.ageSec', l: 'token age (s)', d: '0…∞', ins: 'token.ageSec < 3600' },
+ { p: 'token.marketCapSol', l: 'mkt cap (SOL)', d: '0…∞', ins: 'token.marketCapSol > 30' },
+ ],
+ exit: [
+ { p: 'position.pnlPct', l: 'position PnL %', d: '-100…∞', ins: 'position.pnlPct > 50', pct: 100 },
+ { p: 'position.ageSec', l: 'position age (s)',d: '0…∞', ins: 'position.ageSec > 600', pct: 100 },
+ { p: 'position.amountTokens', l: 'position size', d: '0…∞', ins: 'position.amountTokens < 1', pct: 100 },
+ { p: 'position.entryPriceSol', l: 'entry price', d: '0…∞', ins: 'position.entryPriceSol > 0.001', pct: 100 },
+ ],
+ };
+
+ // ── Shorthands ──────────────────────────────────────────────────────────
const $ = (id) => document.getElementById(id);
const spec = $('spec'), status = $('status'), log = $('log');
const metrics = $('metrics'), resultPanel = $('resultPanel'), liveDot = $('liveDot');
const agentSel = $('agentSel'), netSel = $('netSel'), provisionBtn = $('provisionBtn');
const walletInfo = $('walletInfo'), walletStatus = $('walletStatus');
+ const issuesEl = $('issues'), summaryBox = $('summaryBox'), charts = $('charts');
- // ── Accessible confirm dialog ─────────────────────────────────────────
- // Promise<boolean>: resolves true on confirm, false on cancel/Escape/backdrop.
- // Focus trap, Escape-to-cancel, focus restored to the trigger on close.
- function confirmDialog({ body, confirmLabel = 'Confirm' }) {
- const backdrop = $('confirmModal');
- const bodyEl = $('confirmBody');
- const accept = $('confirmAccept');
- const cancel = $('confirmCancel');
- bodyEl.innerHTML = body;
- accept.textContent = confirmLabel;
- const lastFocused = document.activeElement;
+ let mode = 'simulate';
+ let activeRun = null;
+ let currentWallet = null; // { address, sol }
+ let lastBacktest = null; // raw backtest data for export
+ let btSort = { key: 'pnlSol', dir: -1 };
+ let portfolioData = null;
+ let pfSort = { key: 'unrealizedPnl', dir: -1 };
+
+ // Log state
+ const logEntries = [];
+ const logCounts = { all: 0, enter: 0, exit: 0, skip: 0, tick: 0, error: 0, start: 0, done: 0 };
+ let logFilter = 'all';
+ let autoscroll = true;
+
+ function escapeHtml(s) { return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]); }
+ function fmt(n, dp = 4) { return Number.isFinite(n) ? n.toFixed(dp) : '—'; }
+ function pct(n) { return Number.isFinite(n) ? n.toFixed(1) + '%' : '—'; }
+ function pn(n) { return n > 0 ? 'pos' : n < 0 ? 'neg' : ''; }
+ function explorerLink(addr, net) { return `https://explorer.solana.com/address/${addr}${net === 'devnet' ? '?cluster=devnet' : ''}`; }
+ function setStatus(msg, kind = 'info') { status.className = 'status ' + kind; status.textContent = msg; }
+ function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }
+ // ── Toasts ──────────────────────────────────────────────────────────────
+ function toast(msg) {
+ const t = document.createElement('div'); t.className = 'toast'; t.textContent = msg;
+ $('toasts').appendChild(t);
+ requestAnimationFrame(() => t.classList.add('show'));
+ setTimeout(() => { t.classList.remove('show'); setTimeout(() => t.remove(), 220); }, 2200);
+ }
+
+ // ── Accessible confirm dialog ───────────────────────────────────────────
+ function confirmDialog({ title = 'Confirm', body, confirmLabel = 'Confirm' }) {
+ const backdrop = $('confirmModal'), bodyEl = $('confirmBody'), titleEl = $('confirmTitle');
+ const accept = $('confirmAccept'), cancel = $('confirmCancel');
+ titleEl.textContent = title; bodyEl.innerHTML = body; accept.textContent = confirmLabel;
+ const lastFocused = document.activeElement;
return new Promise((resolve) => {
const focusable = [cancel, accept];
-
function close(result) {
backdrop.classList.remove('open');
backdrop.removeEventListener('keydown', onKeydown, true);
backdrop.removeEventListener('pointerdown', onBackdrop);
accept.removeEventListener('click', onAccept);
cancel.removeEventListener('click', onCancel);
- const finish = () => {
- backdrop.hidden = true;
- backdrop.removeEventListener('transitionend', finish);
- if (lastFocused && typeof lastFocused.focus === 'function') lastFocused.focus();
- resolve(result);
- };
- // Allow the fade-out transition to play, then hide.
+ const finish = () => { backdrop.hidden = true; backdrop.removeEventListener('transitionend', finish); if (lastFocused?.focus) lastFocused.focus(); resolve(result); };
backdrop.addEventListener('transitionend', finish);
- setTimeout(finish, 200); // fallback if transitionend never fires
+ setTimeout(finish, 200);
}
- const onAccept = () => close(true);
- const onCancel = () => close(false);
+ const onAccept = () => close(true), onCancel = () => close(false);
const onBackdrop = (e) => { if (e.target === backdrop) close(false); };
function onKeydown(e) {
if (e.key === 'Escape') { e.preventDefault(); close(false); return; }
- if (e.key === 'Tab') {
- // Trap focus within the two buttons.
- e.preventDefault();
- const idx = focusable.indexOf(document.activeElement);
- const next = e.shiftKey
- ? focusable[(idx - 1 + focusable.length) % focusable.length]
- : focusable[(idx + 1) % focusable.length];
- next.focus();
- }
+ if (e.key === 'Tab') { e.preventDefault(); const idx = focusable.indexOf(document.activeElement); const next = e.shiftKey ? focusable[(idx - 1 + focusable.length) % focusable.length] : focusable[(idx + 1) % focusable.length]; next.focus(); }
}
-
accept.addEventListener('click', onAccept);
cancel.addEventListener('click', onCancel);
backdrop.addEventListener('pointerdown', onBackdrop);
backdrop.addEventListener('keydown', onKeydown, true);
-
- backdrop.hidden = false;
- // Force reflow so the opacity/transform transition runs from the closed state.
- void backdrop.offsetWidth;
- backdrop.classList.add('open');
- cancel.focus(); // default focus on the non-destructive action
+ backdrop.hidden = false; void backdrop.offsetWidth; backdrop.classList.add('open'); cancel.focus();
});
}
- let mode = 'simulate';
- let activeRun = null;
- let currentWallet = null; // { address, sol }
-
- function setStatus(msg, kind = 'info') { status.className = 'status ' + kind; status.textContent = msg; }
- const issuesEl = $('issues');
+ // ── Issues / summary ────────────────────────────────────────────────────
const ISSUE_ORDER = { error: 0, warning: 1, info: 2 };
function renderIssues(issues) {
if (!issues || !issues.length) { issuesEl.style.display = 'none'; issuesEl.innerHTML = ''; return; }
@@ -361,79 +547,168 @@
<span class="msg">${escapeHtml(i.message || '')}</span>
</div>`).join('');
}
- function setWalletStatus(msg, kind) {
- if (!msg) { walletStatus.style.display = 'none'; return; }
- walletStatus.style.display = ''; walletStatus.className = 'status ' + (kind || 'info'); walletStatus.textContent = msg;
+ function renderSummary(d) {
+ if (!d || (!d.summary && !d.filters?.length && !d.exits?.length)) { summaryBox.style.display = 'none'; return; }
+ const filters = (d.filters || []).map((f) => `<code>${escapeHtml(typeof f === 'string' ? f : JSON.stringify(f))}</code>`).join(' &amp; ') || '<span class="muted">none</span>';
+ const exits = (d.exits || []).map((e) => `<code>${escapeHtml(typeof e === 'string' ? e : (e.if || JSON.stringify(e)))}</code>`).join(' · ') || '<span class="muted">none</span>';
+ summaryBox.style.display = 'flex';
+ summaryBox.innerHTML = `
+ ${d.summary ? `<div class="srow"><b>Plain</b><span>${escapeHtml(d.summary)}</span></div>` : ''}
+ <div class="srow"><b>Enter if</b><span>${filters}</span></div>
+ <div class="srow"><b>Exit when</b><span>${exits}</span></div>`;
}
- function clearLog() { log.innerHTML = ''; }
+
+ // ── Field palette ───────────────────────────────────────────────────────
+ function renderPalette() {
+ const group = (title, items) => `
+ <div class="ptitle">${title}</div>
+ <div class="chips">${items.map((f) => `
+ <button class="chip" data-ins="${escapeHtml(f.ins)}" data-kind="${f.p.startsWith('position.') ? 'exit' : 'filter'}" data-pct="${f.pct || ''}" title="${escapeHtml(f.l)} · domain ${f.d}">
+ ${escapeHtml(f.p)}<span class="dom">${escapeHtml(f.d)}</span>
+ </button>`).join('')}</div>`;
+ $('palette').innerHTML = group('Entry filters', FIELDS.filter) + group('Exit conditions (open position)', FIELDS.exit);
+ $('palette').querySelectorAll('.chip').forEach((c) => c.onclick = () => insertRule(c.dataset.ins, c.dataset.kind, c.dataset.pct));
+ }
+ function insertRule(predicate, kind, pctStr) {
+ let s;
+ try { s = JSON.parse(spec.value); }
+ catch { navigator.clipboard?.writeText(predicate); toast('Spec isn\'t valid JSON — copied snippet to clipboard'); return; }
+ if (kind === 'exit') {
+ s.exit = Array.isArray(s.exit) ? s.exit : [];
+ s.exit.push({ if: predicate, do: { side: 'sell', percent: Number(pctStr) || 100 } });
+ } else {
+ s.filters = Array.isArray(s.filters) ? s.filters : [];
+ if (s.filters.includes(predicate)) { toast('Filter already present'); return; }
+ s.filters.push(predicate);
+ }
+ spec.value = JSON.stringify(s, null, 2);
+ spec.classList.remove('invalid');
+ toast(kind === 'exit' ? `Added exit · ${predicate}` : `Added filter · ${predicate}`);
+ liveValidate();
+ }
+
+ // ── Activity log ────────────────────────────────────────────────────────
+ function logKindClass(kind) { return ['enter', 'exit', 'skip', 'tick', 'error', 'start', 'done'].includes(kind) ? kind : 'skip'; }
+ function bucketOf(kind) { return ['enter', 'exit', 'skip', 'tick', 'error'].includes(kind) ? kind : (kind === 'start' || kind === 'done' ? null : 'skip'); }
+ function clearLog() { logEntries.length = 0; for (const k in logCounts) logCounts[k] = 0; renderLog(); updateLogCounts(); }
function pushLog(kind, text) {
- const row = document.createElement('div'); row.className = 'row ' + kind;
- row.textContent = `${new Date().toLocaleTimeString()} ${text}`;
- log.appendChild(row); log.scrollTop = log.scrollHeight;
+ const entry = { kind: logKindClass(kind), text, ts: new Date().toLocaleTimeString() };
+ logEntries.push(entry);
+ logCounts.all++;
+ const b = bucketOf(entry.kind); if (b) logCounts[b]++;
+ updateLogCounts();
+ if (logFilter === 'all' || entry.kind === logFilter || (logFilter === 'skip' && entry.kind === 'skip')) appendLogRow(entry);
+ }
+ function appendLogRow(e) {
+ if (log.firstChild?.classList?.contains('muted')) log.innerHTML = '';
+ const row = document.createElement('div'); row.className = 'ln ' + e.kind;
+ row.innerHTML = `<span class="t">${e.ts}</span>${escapeHtml(e.text)}`;
+ log.appendChild(row);
+ if (autoscroll) log.scrollTop = log.scrollHeight;
+ }
+ function renderLog() {
+ const rows = logEntries.filter((e) => logFilter === 'all' || e.kind === logFilter);
+ log.innerHTML = rows.length ? rows.map((e) => `<div class="ln ${e.kind}"><span class="t">${e.ts}</span>${escapeHtml(e.text)}</div>`).join('') : '<div class="ln muted">— no events —</div>';
+ if (autoscroll) log.scrollTop = log.scrollHeight;
}
- function loadPreset(name) { spec.value = JSON.stringify(PRESETS[name], null, 2); setStatus(`Loaded preset: ${name}`); }
+ function updateLogCounts() {
+ $('logToolbar').querySelectorAll('.fpill[data-f]').forEach((p) => {
+ const n = p.querySelector('.n'); if (n) n.textContent = logCounts[p.dataset.f] ?? 0;
+ });
+ }
+ $('logToolbar').querySelectorAll('.fpill[data-f]').forEach((p) => p.onclick = () => {
+ logFilter = p.dataset.f;
+ $('logToolbar').querySelectorAll('.fpill[data-f]').forEach((x) => x.classList.toggle('on', x === p));
+ renderLog();
+ });
+ $('autoscroll').onclick = () => { autoscroll = !autoscroll; $('autoscroll').classList.toggle('on', autoscroll); if (autoscroll) log.scrollTop = log.scrollHeight; };
+ $('clearLog').onclick = clearLog;
+ $('copyLog').onclick = () => { navigator.clipboard?.writeText(logEntries.map((e) => `${e.ts} ${e.text}`).join('\n')); toast('Activity copied'); };
+
+ // ── Preset / mode wiring ────────────────────────────────────────────────
+ function loadPreset(name) {
+ spec.value = JSON.stringify(PRESETS[name], null, 2);
+ spec.classList.remove('invalid');
+ $('presets').querySelectorAll('.preset-card').forEach((c) => c.classList.toggle('active', c.dataset.preset === name));
+ setStatus(`Loaded preset: ${name}`, 'info');
+ liveValidate();
+ }
+ $('presets').querySelectorAll('.preset-card').forEach((b) => b.onclick = () => loadPreset(b.dataset.preset));
+ $('modeSwitch').querySelectorAll('.mode').forEach((b) => b.onclick = () => {
+ mode = b.dataset.mode;
+ $('modeSwitch').querySelectorAll('.mode').forEach((x) => x.classList.toggle('active', x === b));
+ });
+ $('format').onclick = () => {
+ try { spec.value = JSON.stringify(JSON.parse(spec.value), null, 2); spec.classList.remove('invalid'); toast('Formatted'); }
+ catch (e) { setStatus('JSON parse error: ' + e.message, 'bad'); spec.classList.add('invalid'); }
+ };
+
function getSpec() {
try { return JSON.parse(spec.value); }
catch (e) { setStatus('JSON parse error: ' + e.message, 'bad'); spec.classList.add('invalid'); throw e; }
}
- function fmt(n, dp = 4) { return Number.isFinite(n) ? n.toFixed(dp) : '—'; }
- function pct(n) { return Number.isFinite(n) ? n.toFixed(1) + '%' : '—'; }
- function pn(n) { return n > 0 ? 'pos' : n < 0 ? 'neg' : ''; }
- function explorerLink(addr, net) { return `https://explorer.solana.com/address/${addr}${net === 'devnet' ? '?cluster=devnet' : ''}`; }
- document.querySelectorAll('.preset').forEach((b) => b.onclick = () => loadPreset(b.dataset.preset));
- document.querySelectorAll('.mode').forEach((b) => b.onclick = () => {
- mode = b.dataset.mode;
- document.querySelectorAll('.mode').forEach((x) => x.classList.toggle('active', x === b));
- });
- loadPreset('momentum');
+ // ── Live validation (debounced, non-blocking) ───────────────────────────
+ const liveValidate = debounce(async () => {
+ let s;
+ try { s = JSON.parse(spec.value); spec.classList.remove('invalid'); }
+ catch (e) { spec.classList.add('invalid'); setStatus('JSON parse error: ' + e.message, 'bad'); renderIssues([]); summaryBox.style.display = 'none'; return; }
+ const r = await fetch('/api/pump/strategy-validate', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy: s, network: netSel.value }),
+ }).then((r) => r.json()).catch(() => null);
+ if (!r) return; // network hiccup — leave last state
+ if (r.error) {
+ const issues = r.issues || r.report?.issues || [{ level: 'error', field: '', message: r.error_description || r.error }];
+ const errCount = issues.filter((i) => i.level === 'error').length || 1;
+ setStatus(`Invalid — ${errCount} error${errCount === 1 ? '' : 's'} to fix`, 'bad');
+ spec.classList.add('invalid'); renderIssues(issues); summaryBox.style.display = 'none';
+ return;
+ }
+ const d = r.data || {};
+ const notes = (d.issues || []).filter((i) => i.level !== 'error');
+ setStatus(`Valid — ${d.filterCount} filter(s), ${d.exitCount} exit rule(s)` + (notes.length ? ` · ${notes.length} note${notes.length === 1 ? '' : 's'}` : ''), notes.length ? 'warn' : 'ok');
+ renderIssues(notes); renderSummary(d);
+ }, 550);
+ spec.addEventListener('input', liveValidate);
+
+ $('validate').onclick = () => liveValidate();
- // ── Agent + wallet bootstrap ───────────────────────────────────────
+ // ── Agent + wallet bootstrap ────────────────────────────────────────────
async function loadAgents() {
const r = await fetch('/api/agents', { credentials: 'include' }).then((r) => r.json()).catch(() => null);
- if (!r?.agents) {
- agentSel.innerHTML = '<option value="">— sign in to load agents —</option>';
- return;
- }
+ if (!r?.agents) { agentSel.innerHTML = '<option value="">— sign in to load agents —</option>'; return; }
agentSel.innerHTML = '<option value="">— select agent —</option>' +
r.agents.map((a) => `<option value="${a.id}">${escapeHtml(a.name || a.id)}</option>`).join('');
- // Auto-select last used.
const saved = localStorage.getItem('strategy-lab:agentId');
if (saved && r.agents.some((a) => a.id === saved)) { agentSel.value = saved; await onAgentChange(); }
}
- function escapeHtml(s) { return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]); }
-
async function onAgentChange() {
const id = agentSel.value;
localStorage.setItem('strategy-lab:agentId', id);
- currentWallet = null;
- walletInfo.innerHTML = '<span class="muted">Loading wallet…</span>';
- setWalletStatus('');
+ currentWallet = null; walletInfo.innerHTML = '<span class="skel" style="display:inline-block;width:120px;height:1rem"></span>'; setWalletStatus('');
provisionBtn.disabled = !id;
if (!id) { walletInfo.textContent = 'No agent selected.'; renderPortfolio(null); return; }
const net = netSel.value;
const r = await fetch(`/api/agents/${id}/solana?network=${net}`, { credentials: 'include' }).then((r) => r.json()).catch(() => null);
if (r?.data?.address) {
currentWallet = { address: r.data.address, sol: r.data.sol ?? 0 };
- renderWalletInfo();
- refreshPortfolio();
+ renderWalletInfo(); refreshPortfolio();
} else {
walletInfo.innerHTML = '<span class="muted">No Solana wallet on this agent.</span>';
- provisionBtn.textContent = 'Provision wallet';
+ provisionBtn.style.display = ''; provisionBtn.textContent = 'Provision wallet';
+ renderPortfolio(null);
}
}
function renderWalletInfo() {
if (!currentWallet) { walletInfo.textContent = 'No wallet.'; return; }
- const { address, sol } = currentWallet;
- const net = netSel.value;
- const fundWarn = (sol < 0.02) ? `<div class="fund-warn">⚠ Balance is below 0.02 SOL — top up before running live trades.</div>` : '';
+ const { address, sol } = currentWallet, net = netSel.value;
+ const fundWarn = (sol < 0.02) ? `<div class="fund-warn">⚠ Below 0.02 SOL — top up before running live.</div>` : '';
walletInfo.innerHTML = `
<span class="balance">${(sol ?? 0).toFixed(4)} SOL</span>
- <a href="${explorerLink(address, net)}" target="_blank" rel="noopener" style="margin-left:.5rem"><code>${address.slice(0, 6)}…${address.slice(-4)}</code></a>
- <button class="copy" data-copy="${address}">copy</button>
- ${fundWarn}
- `;
- walletInfo.querySelectorAll('.copy').forEach((b) => b.onclick = () => navigator.clipboard.writeText(b.dataset.copy));
+ <a href="${explorerLink(address, net)}" target="_blank" rel="noopener"><code>${address.slice(0, 6)}…${address.slice(-4)}</code></a>
+ <button class="copy" data-copy="${address}">copy</button>${fundWarn}`;
+ walletInfo.querySelectorAll('.copy').forEach((b) => b.onclick = () => { navigator.clipboard.writeText(b.dataset.copy); toast('Address copied'); });
provisionBtn.style.display = 'none';
}
provisionBtn.onclick = async () => {
@@ -444,134 +719,233 @@
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
if (r?.data?.address) {
currentWallet = { address: r.data.address, sol: r.data.sol ?? 0 };
- renderWalletInfo();
- setWalletStatus('Wallet provisioned. Send SOL to it before running live.', 'ok');
- refreshPortfolio();
+ renderWalletInfo(); setWalletStatus('Wallet provisioned. Send SOL to it before running live.', 'ok'); refreshPortfolio();
} else {
setWalletStatus('Provision failed: ' + (r?.error_description || r?.error || 'unknown'), 'bad');
provisionBtn.disabled = false; provisionBtn.textContent = 'Provision wallet';
}
};
+ function setWalletStatus(msg, kind) {
+ if (!msg) { walletStatus.style.display = 'none'; return; }
+ walletStatus.style.display = 'flex'; walletStatus.className = 'status ' + (kind || 'info'); walletStatus.textContent = msg;
+ }
agentSel.onchange = onAgentChange;
netSel.onchange = () => { if (agentSel.value) onAgentChange(); };
- // ── Validate / Backtest / Run ──────────────────────────────────────
- $('validate').onclick = async () => {
- spec.classList.remove('invalid'); renderIssues([]);
- let s; try { s = getSpec(); } catch { return; }
- setStatus('Validating…');
- const r = await fetch('/api/pump/strategy-validate', {
- method: 'POST', headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ strategy: s, network: netSel.value }),
- }).then((r) => r.json()).catch((e) => ({ error: e.message }));
- if (r.error) {
- const issues = r.issues || r.report?.issues || [{ level: 'error', field: '', message: r.error_description || r.error }];
- const errCount = issues.filter((i) => i.level === 'error').length || 1;
- setStatus(`Invalid — ${errCount} error${errCount === 1 ? '' : 's'} to fix`, 'bad');
- spec.classList.add('invalid');
- renderIssues(issues);
- return;
- }
- const d = r.data || {};
- const notes = (d.issues || []).filter((i) => i.level !== 'error');
- setStatus(`Valid — ${d.filterCount} filter(s), ${d.exitCount} exit rule(s)` + (notes.length ? ` · ${notes.length} note${notes.length === 1 ? '' : 's'}` : ''), notes.length ? 'warn' : 'ok');
- renderIssues(notes);
- };
-
+ // ── Backtest ────────────────────────────────────────────────────────────
$('backtest').onclick = async () => {
spec.classList.remove('invalid'); renderIssues([]);
let s; try { s = getSpec(); } catch { return; }
- setStatus('Sourcing mints from live MCP…');
+ setStatus('Sourcing mints from live MCP…', 'info');
+ showResultSkeleton();
clearLog(); pushLog('start', '▶ backtest started (real on-chain data)');
+ $('backtest').disabled = true;
const r = await fetch('/api/pump/strategy-backtest', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ strategy: s, network: netSel.value }),
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
+ $('backtest').disabled = false;
if (r.error) {
setStatus('Backtest failed: ' + (r.error_description || r.error), 'bad');
pushLog('error', '! ' + (r.error_description || r.error));
if (r.issues) { spec.classList.add('invalid'); renderIssues(r.issues); }
+ showResultError(r.error_description || r.error);
return;
}
+ lastBacktest = r.data;
renderBacktest(r.data);
- pushLog('done', `✓ ${r.data.tradeCount} trade(s), ROI ${r.data.roiPct.toFixed(1)}%, ${r.data.mintsUsed?.length} mints scanned`);
+ $('exportBtn').style.display = ''; $('copyBtn').style.display = '';
+ pushLog('done', `✓ ${r.data.tradeCount} trade(s), ROI ${r.data.roiPct.toFixed(1)}%, ${r.data.mintsUsed?.length ?? '?'} mints scanned`);
setStatus('Backtest complete', 'ok');
};
+ function computeAnalytics(d) {
+ const t = (d.trades || []).filter((x) => x.action === 'trade');
+ const wins = t.filter((x) => x.pnlSol > 0), losses = t.filter((x) => x.pnlSol < 0);
+ const gp = wins.reduce((a, x) => a + x.pnlSol, 0), gl = Math.abs(losses.reduce((a, x) => a + x.pnlSol, 0));
+ const avgWin = wins.length ? gp / wins.length : 0, avgLoss = losses.length ? gl / losses.length : 0;
+ const winRate = t.length ? wins.length / t.length : 0;
+ const expectancy = t.length ? t.reduce((a, x) => a + x.pnlSol, 0) / t.length : 0;
+ const holds = t.map((x) => x.heldSec).filter((x) => Number.isFinite(x));
+ const avgHold = holds.length ? holds.reduce((a, x) => a + x, 0) / holds.length : null;
+ const best = t.length ? Math.max(...t.map((x) => x.pnlPct)) : null;
+ const worst = t.length ? Math.min(...t.map((x) => x.pnlPct)) : null;
+ return { t, wins: wins.length, losses: losses.length, gp, gl, avgWin, avgLoss, winRate, expectancy, avgHold, best, worst,
+ profitFactor: gl > 0 ? gp / gl : (gp > 0 ? Infinity : 0) };
+ }
+ function fmtDur(sec) {
+ if (sec == null) return '—';
+ if (sec < 60) return Math.round(sec) + 's';
+ if (sec < 3600) return (sec / 60).toFixed(1) + 'm';
+ return (sec / 3600).toFixed(1) + 'h';
+ }
+
function renderBacktest(d) {
+ const a = computeAnalytics(d);
metrics.style.display = '';
metrics.innerHTML = `
<div class="metric"><div class="v ${pn(d.realizedPnlSol)}">${fmt(d.realizedPnlSol)}</div><div class="l">PnL (SOL)</div></div>
<div class="metric"><div class="v ${pn(d.roiPct)}">${pct(d.roiPct)}</div><div class="l">ROI</div></div>
<div class="metric"><div class="v">${pct((d.winRate || 0) * 100)}</div><div class="l">win rate</div></div>
<div class="metric"><div class="v">${d.tradeCount}</div><div class="l">trades</div></div>
- <div class="metric"><div class="v neg">${fmt(d.maxDrawdownSol)}</div><div class="l">max drawdown</div></div>
- <div class="metric"><div class="v">${fmt(d.spent, 3)}</div><div class="l">SOL deployed</div></div>
- `;
- const trades = (d.trades || []).filter((t) => t.action === 'trade');
+ <div class="metric"><div class="v">${a.profitFactor === Infinity ? '∞' : fmt(a.profitFactor, 2)}</div><div class="l">profit factor</div></div>
+ <div class="metric"><div class="v neg">${fmt(d.maxDrawdownSol)}</div><div class="l">max drawdown</div></div>`;
+
+ // Detailed stats
+ const stats = `
+ <div class="statgrid">
+ <div class="row"><span>Expectancy / trade</span><b class="${pn(a.expectancy)}">${fmt(a.expectancy)} SOL</b></div>
+ <div class="row"><span>Avg win</span><b class="pos">${fmt(a.avgWin)} SOL</b></div>
+ <div class="row"><span>Avg loss</span><b class="neg">${fmt(a.avgLoss)} SOL</b></div>
+ <div class="row"><span>Wins / losses</span><b>${a.wins} / ${a.losses}</b></div>
+ <div class="row"><span>Best trade</span><b class="pos">${pct(a.best)}</b></div>
+ <div class="row"><span>Worst trade</span><b class="neg">${pct(a.worst)}</b></div>
+ <div class="row"><span>Avg hold time</span><b>${fmtDur(a.avgHold)}</b></div>
+ <div class="row"><span>SOL deployed</span><b>${fmt(d.spent, 3)}</b></div>
+ </div>`;
+
+ // Equity curve + outcome strip
+ charts.innerHTML = a.t.length ? `
+ <div class="chart-card">
+ <div class="ctitle"><span>Cumulative PnL (SOL)</span><span>${a.t.length} trades</span></div>
+ ${equitySvg(a.t)}
+ </div>
+ <div class="chart-card">
+ <div class="ctitle"><span>Trade outcomes</span><span class="muted">green = win · red = loss</span></div>
+ <div class="strip">${a.t.map((x) => `<div class="cell" style="background:${x.pnlSol > 0 ? 'var(--green)' : x.pnlSol < 0 ? 'var(--red)' : 'var(--border-strong)'}" data-tip="${escapeHtml(String(x.mint).slice(0, 6))} ${pct(x.pnlPct)}" title="${escapeHtml(String(x.mint).slice(0, 8))}… · ${pct(x.pnlPct)}"></div>`).join('')}</div>
+ </div>` : '';
+
const skips = (d.trades || []).filter((t) => t.action !== 'trade');
- resultPanel.innerHTML = `
- <table>
- <thead><tr><th>Mint</th><th class="num">Entry</th><th class="num">Exit</th><th class="num">PnL</th><th class="num">PnL %</th><th>Reason</th></tr></thead>
- <tbody>
- ${trades.map((t) => `
- <tr>
- <td><code>${escapeHtml(t.mint).slice(0, 10)}…</code></td>
- <td class="num">${fmt(t.entryPrice, 8)}</td>
- <td class="num">${fmt(t.exitPrice, 8)}</td>
- <td class="num"><span class="${pn(t.pnlSol)}">${fmt(t.pnlSol)}</span></td>
- <td class="num"><span class="${pn(t.pnlPct)}">${pct(t.pnlPct)}</span></td>
- <td>${typeof t.exitReason === 'string' ? t.exitReason : (t.exitReason?.side || 'eod')}</td>
- </tr>`).join('') || '<tr><td colspan="6" class="muted">— no trades taken —</td></tr>'}
- </tbody>
- </table>
- ${skips.length ? `<p class="muted" style="margin-top:.5rem;font-size:.75rem">${skips.length} mint(s) filtered out before entry.</p>` : ''}
- `;
+ resultPanel.innerHTML = stats + renderTradeTable(a.t) +
+ (skips.length ? `<p class="muted" style="margin-top:.5rem;font-size:11.5px">${skips.length} mint(s) filtered out before entry.</p>` : '');
+ wireTradeSort();
+ }
+
+ function equitySvg(trades) {
+ const W = 600, H = 110, pad = 6;
+ let cum = 0; const pts = trades.map((t) => (cum += t.pnlSol));
+ const max = Math.max(0, ...pts), min = Math.min(0, ...pts), span = (max - min) || 1;
+ const x = (i) => pad + (trades.length <= 1 ? 0 : (i / (trades.length - 1)) * (W - 2 * pad));
+ const y = (v) => pad + (1 - (v - min) / span) * (H - 2 * pad);
+ const zeroY = y(0);
+ const line = pts.map((v, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
+ const area = `M${x(0).toFixed(1)},${zeroY.toFixed(1)} ` + pts.map((v, i) => `L${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ') + ` L${x(pts.length - 1).toFixed(1)},${zeroY.toFixed(1)} Z`;
+ const up = pts[pts.length - 1] >= 0;
+ const col = up ? 'var(--green)' : 'var(--red)';
+ return `<svg class="equity" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Cumulative PnL curve">
+ <line x1="${pad}" y1="${zeroY.toFixed(1)}" x2="${W - pad}" y2="${zeroY.toFixed(1)}" stroke="var(--border-strong)" stroke-width="1" stroke-dasharray="3 3"/>
+ <path d="${area}" fill="${col}" opacity="0.12"/>
+ <path d="${line}" fill="none" stroke="${col}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
+ </svg>`;
+ }
+
+ function renderTradeTable(trades) {
+ const sorted = [...trades].sort((x, y) => {
+ const k = btSort.key; const av = x[k] ?? -Infinity, bv = y[k] ?? -Infinity;
+ if (typeof av === 'string') return btSort.dir * String(av).localeCompare(String(bv));
+ return btSort.dir * (av - bv);
+ });
+ const arrow = (k) => btSort.key === k ? (btSort.dir < 0 ? '▾' : '▴') : '';
+ const th = (k, label, num) => `<th class="sortable${num ? ' num' : ''}" data-k="${k}">${label} <span class="arr">${arrow(k)}</span></th>`;
+ return `<div class="tbl-wrap"><table>
+ <thead><tr>
+ ${th('mint', 'Mint')}
+ ${th('entryPrice', 'Entry', true)}
+ ${th('exitPrice', 'Exit', true)}
+ ${th('pnlSol', 'PnL', true)}
+ ${th('pnlPct', 'PnL %', true)}
+ ${th('heldSec', 'Held', true)}
+ <th>Reason</th>
+ </tr></thead>
+ <tbody>
+ ${sorted.map((t) => `
+ <tr>
+ <td><a href="https://pump.fun/${escapeHtml(t.mint)}" target="_blank" rel="noopener"><code>${escapeHtml(String(t.mint)).slice(0, 10)}…</code></a></td>
+ <td class="num">${fmt(t.entryPrice, 8)}</td>
+ <td class="num">${fmt(t.exitPrice, 8)}</td>
+ <td class="num"><span class="${pn(t.pnlSol)}">${fmt(t.pnlSol)}</span></td>
+ <td class="num"><span class="${pn(t.pnlPct)}">${pct(t.pnlPct)}</span></td>
+ <td class="num">${fmtDur(t.heldSec)}</td>
+ <td><span class="reason-chip">${escapeHtml(typeof t.exitReason === 'string' ? t.exitReason : (t.exitReason?.if || t.exitReason?.do?.side || 'eod'))}</span></td>
+ </tr>`).join('') || '<tr><td colspan="7" class="muted">— no trades taken —</td></tr>'}
+ </tbody>
+ </table></div>`;
}
+ function wireTradeSort() {
+ resultPanel.querySelectorAll('th.sortable').forEach((th) => th.onclick = () => {
+ const k = th.dataset.k;
+ if (btSort.key === k) btSort.dir *= -1; else { btSort.key = k; btSort.dir = -1; }
+ if (lastBacktest) renderBacktest(lastBacktest);
+ });
+ }
+
+ function showResultSkeleton() {
+ metrics.style.display = 'none'; charts.innerHTML = '';
+ resultPanel.innerHTML = `<div style="display:flex;flex-direction:column;gap:.5rem">
+ <div class="skel" style="height:60px"></div><div class="skel" style="height:110px"></div>
+ <div class="skel" style="height:24px"></div><div class="skel" style="height:24px"></div><div class="skel" style="height:24px"></div></div>`;
+ }
+ function showResultError(msg) {
+ metrics.style.display = 'none'; charts.innerHTML = '';
+ resultPanel.innerHTML = `<div class="empty"><div class="ic">⚠️</div><div class="t">Couldn't complete</div><div class="d">${escapeHtml(msg)}</div></div>`;
+ }
+
+ // ── Export / copy ───────────────────────────────────────────────────────
+ $('exportBtn').onclick = () => {
+ if (!lastBacktest) return;
+ const blob = new Blob([JSON.stringify(lastBacktest, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a'); a.href = url; a.download = `strategy-backtest-${Date.now()}.json`; a.click();
+ URL.revokeObjectURL(url); toast('Exported backtest JSON');
+ };
+ $('copyBtn').onclick = () => {
+ if (!lastBacktest) return;
+ const d = lastBacktest, a = computeAnalytics(d);
+ const txt = [
+ `Backtest summary`,
+ `PnL: ${fmt(d.realizedPnlSol)} SOL · ROI ${pct(d.roiPct)}`,
+ `Trades: ${d.tradeCount} · win rate ${pct((d.winRate || 0) * 100)} · profit factor ${a.profitFactor === Infinity ? '∞' : fmt(a.profitFactor, 2)}`,
+ `Expectancy ${fmt(a.expectancy)} SOL · max drawdown ${fmt(d.maxDrawdownSol)} SOL`,
+ `Best ${pct(a.best)} · worst ${pct(a.worst)} · avg hold ${fmtDur(a.avgHold)}`,
+ ].join('\n');
+ navigator.clipboard?.writeText(txt); toast('Summary copied');
+ };
+ // ── Run (simulate / live) ───────────────────────────────────────────────
$('run').onclick = async () => {
spec.classList.remove('invalid'); renderIssues([]);
let s; try { s = getSpec(); } catch { return; }
- const network = netSel.value;
- const agentId = agentSel.value;
+ const network = netSel.value, agentId = agentSel.value;
+ const durationSec = Number($('durSel').value) || 60;
if (mode === 'live') {
if (!agentId) { setStatus('Select an agent first.', 'bad'); return; }
if (!currentWallet) { setStatus('Provision a Solana wallet first.', 'bad'); return; }
- if (currentWallet.sol < 0.02) {
- setStatus('Wallet balance below 0.02 SOL — fund it before going live.', 'bad'); return;
- }
- if (!confirm(`Run LIVE strategy on ${network}?\n\nWallet ${currentWallet.address} will sign real transactions.`)) return;
+ if (currentWallet.sol < 0.02) { setStatus('Wallet balance below 0.02 SOL — fund it before going live.', 'bad'); return; }
+ const ok = await confirmDialog({
+ title: 'Run live strategy?',
+ body: `This signs and submits <strong>real transactions</strong> on ${network} from wallet <code>${currentWallet.address.slice(0, 6)}…${currentWallet.address.slice(-4)}</code> for up to ${durationSec}s. Real SOL will be spent.`,
+ confirmLabel: 'Run live',
+ });
+ if (!ok) return;
}
clearLog();
- pushLog('start', `▶ ${mode === 'live' ? 'LIVE' : 'simulated'} run on ${network}`);
- setStatus(`Streaming ${mode}…`);
- liveDot.classList.add('on');
- $('run').disabled = true; $('stop').disabled = false;
+ pushLog('start', `▶ ${mode === 'live' ? 'LIVE' : 'simulated'} run on ${network} · ${durationSec}s`);
+ setStatus(`Streaming ${mode}…`, 'info'); liveDot.classList.add('on');
+ $('run').disabled = true; $('backtest').disabled = true; $('stop').disabled = false;
const ctrl = new AbortController(); activeRun = ctrl;
try {
const resp = await fetch('/api/pump/strategy-run', {
- method: 'POST', credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- strategy: s,
- durationSec: 60,
- mode,
- network,
- agentId: mode === 'live' ? agentId : undefined,
- }),
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy: s, durationSec, mode, network, agentId: mode === 'live' ? agentId : undefined }),
signal: ctrl.signal,
});
if (!resp.ok) {
let body = null; try { body = JSON.parse(await resp.text()); } catch {}
- if (body?.issues) {
- setStatus(`Run rejected — ${body.error_description || body.error}`, 'bad');
- spec.classList.add('invalid'); renderIssues(body.issues);
- } else {
- setStatus('Run failed: HTTP ' + resp.status + (body?.error_description ? ' — ' + body.error_description : ''), 'bad');
- }
+ if (body?.issues) { setStatus(`Run rejected — ${body.error_description || body.error}`, 'bad'); spec.classList.add('invalid'); renderIssues(body.issues); }
+ else setStatus('Run failed: HTTP ' + resp.status + (body?.error_description ? ' — ' + body.error_description : ''), 'bad');
return;
}
const reader = resp.body.getReader(), dec = new TextDecoder();
@@ -581,10 +955,7 @@
if (done) break;
buf += dec.decode(value, { stream: true });
let idx;
- while ((idx = buf.indexOf('\n\n')) >= 0) {
- const chunk = buf.slice(0, idx); buf = buf.slice(idx + 2);
- handleSse(chunk);
- }
+ while ((idx = buf.indexOf('\n\n')) >= 0) { const chunk = buf.slice(0, idx); buf = buf.slice(idx + 2); handleSse(chunk); }
}
setStatus('Run complete', 'ok');
if (mode === 'live') refreshPortfolio();
@@ -592,7 +963,7 @@
if (e.name !== 'AbortError') setStatus('Stream error: ' + e.message, 'bad');
} finally {
liveDot.classList.remove('on');
- $('run').disabled = false; $('stop').disabled = true; activeRun = null;
+ $('run').disabled = false; $('backtest').disabled = false; $('stop').disabled = true; activeRun = null;
}
};
$('stop').onclick = () => { activeRun?.abort(); pushLog('error', '■ stopped'); };
@@ -600,10 +971,7 @@
function handleSse(chunk) {
const lines = chunk.split('\n');
let event = 'message', data = '';
- for (const l of lines) {
- if (l.startsWith('event: ')) event = l.slice(7);
- else if (l.startsWith('data: ')) data += l.slice(6);
- }
+ for (const l of lines) { if (l.startsWith('event: ')) event = l.slice(7); else if (l.startsWith('data: ')) data += l.slice(6); }
let p; try { p = JSON.parse(data); } catch { return; }
if (event === 'start') pushLog('start', `▶ ${p.mode} · ${p.network} · ${p.durationSec}s${p.walletAddress ? ' · ' + p.walletAddress.slice(0, 6) + '…' : ''}`);
else if (event === 'log') {
@@ -615,42 +983,42 @@
else if (a?.endsWith?.('error')) pushLog('error', `! ${a} ${p.mint || ''}: ${p.error}`);
else pushLog('skip', `${a} ${p.mint || ''}`);
}
- else if (event === 'memory') {/* quiet — already shown via log */}
else if (event === 'done') { pushLog('done', `✓ done · spent ${p.spent.toFixed(3)} SOL · open ${p.openPositions?.length ?? 0}`); renderRunSummary(p); }
else if (event === 'error') pushLog('error', `! ${p.message}`);
}
function renderRunSummary(d) {
- metrics.style.display = '';
+ metrics.style.display = ''; charts.innerHTML = '';
const enters = (d.log || []).filter((l) => l.action === 'enter').length;
const exits = (d.log || []).filter((l) => l.action === 'exit').length;
metrics.innerHTML = `
<div class="metric"><div class="v">${fmt(d.spent, 3)}</div><div class="l">SOL deployed</div></div>
<div class="metric"><div class="v">${d.openPositions?.length ?? 0}</div><div class="l">open positions</div></div>
<div class="metric"><div class="v">${enters}</div><div class="l">entries</div></div>
- <div class="metric"><div class="v">${exits}</div><div class="l">exits</div></div>
- `;
- resultPanel.innerHTML = `<p class="muted">Run complete. Open positions persist across runs and appear in the Portfolio panel.</p>`;
+ <div class="metric"><div class="v">${exits}</div><div class="l">exits</div></div>`;
+ resultPanel.innerHTML = `<div class="empty"><div class="ic">✅</div><div class="t">Session complete</div><div class="d">Open positions persist across runs and appear in the Portfolio panel below.</div></div>`;
}
- // ── Portfolio ──────────────────────────────────────────────────────
+ // ── Portfolio ───────────────────────────────────────────────────────────
async function refreshPortfolio() {
const id = agentSel.value, net = netSel.value;
if (!id) { renderPortfolio(null); return; }
+ $('refreshPortfolio').disabled = true; $('refreshPortfolio').textContent = 'Refreshing…';
const r = await fetch(`/api/pump/portfolio?agentId=${id}&network=${net}`, { credentials: 'include' }).then((r) => r.json()).catch(() => null);
- renderPortfolio(r?.data);
+ $('refreshPortfolio').disabled = false; $('refreshPortfolio').textContent = 'Refresh';
+ portfolioData = r?.data || null;
+ renderPortfolio(portfolioData);
}
$('refreshPortfolio').onclick = refreshPortfolio;
$('closeAll').onclick = async () => {
const id = agentSel.value;
if (!id) { setStatus('Select an agent first.', 'bad'); return; }
- const net = netSel.value;
- const netLabel = net === 'mainnet' ? 'mainnet' : 'devnet';
+ const net = netSel.value, netLabel = net === 'mainnet' ? 'mainnet' : 'devnet';
const ok = await confirmDialog({
+ title: 'Stop & sell all?',
body: `<strong>This stops all activity and sells every position on ${netLabel}.</strong> Any running strategy is aborted and 100% of every SPL holding the wallet owns is sold. This cannot be undone.`,
confirmLabel: 'Stop & sell all',
});
if (!ok) return;
- // Abort any running stream first.
activeRun?.abort();
pushLog('error', '■ STOP — closing all positions');
setStatus('Selling all positions…', 'warn');
@@ -660,7 +1028,7 @@
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
if (r.error) { setStatus('Close-all failed: ' + (r.error_description || r.error), 'bad'); return; }
(r.data?.log || []).forEach((e) => {
- if (e.action === 'sold') pushLog('exit', `× sold ${e.mint} → ${e.sig?.slice(0, 12) ?? ''}…`);
+ if (e.action === 'sold') pushLog('exit', `× sold ${e.mint} → ${e.sig?.slice(0, 12) ?? ''}…`);
else if (e.action === 'sell-error') pushLog('error', `! sell-error ${e.mint}: ${e.error}`);
else pushLog('skip', `${e.action} ${e.mint}`);
});
@@ -669,55 +1037,85 @@
refreshPortfolio();
};
+ const ALLOC_COLORS = ['#60a5fa', '#4ade80', '#f59e0b', '#a78bfa', '#f87171', '#34d399', '#fbbf24', '#818cf8'];
function renderPortfolio(d) {
const el = $('portfolio');
- if (!d) { el.innerHTML = '<p class="muted">Pick an agent above to load on-chain holdings.</p>'; return; }
- // Per-quote subtotals — SOL and USDC are tallied separately so values in
- // different currencies are never summed together.
- const subs = d.subtotals && Object.keys(d.subtotals).length
- ? Object.values(d.subtotals)
- : [];
+ if (!d) { el.innerHTML = `<div class="empty"><div class="ic">👛</div><div class="t">No agent selected</div><div class="d">Pick an agent above to load its on-chain SOL balance and SPL holdings with live cost-basis PnL.</div></div>`; return; }
+ if (!d.holdings?.length) {
+ el.innerHTML = `<div class="metrics" style="margin-top:.5rem"><div class="metric"><div class="v">${(d.sol ?? 0).toFixed(4)} SOL</div><div class="l">wallet balance</div></div></div>
+ <div class="empty"><div class="ic">🌱</div><div class="t">No token holdings</div><div class="d">This wallet holds only SOL. Run a strategy to open positions — they'll show here with live pricing.</div></div>`;
+ return;
+ }
+ const subs = d.subtotals && Object.keys(d.subtotals).length ? Object.values(d.subtotals) : [];
const subCards = subs.map((s) => {
- const dec = s.quoteSymbol === 'SOL' ? 4 : 2;
- const cls = pn(s.unrealizedPnl);
+ const dec = s.quoteSymbol === 'SOL' ? 4 : 2, cls = pn(s.unrealizedPnl);
return `
<div class="metric"><div class="v">${fmt(s.value, dec)} ${s.quoteSymbol}</div><div class="l">value (${s.positions} pos)</div></div>
<div class="metric"><div class="v">${fmt(s.costBasis, dec)} ${s.quoteSymbol}</div><div class="l">${s.quoteSymbol} cost basis</div></div>
<div class="metric"><div class="v ${cls}">${fmt(s.unrealizedPnl, dec)} ${s.quoteSymbol}</div><div class="l">${s.quoteSymbol} PnL (${pct(s.unrealizedPnlPct)})</div></div>`;
}).join('');
+
+ // Allocation bar by value (within each quote currency, fallback proportional).
+ const valued = d.holdings.filter((h) => Number.isFinite(h.valueQuote) && h.valueQuote > 0);
+ const totalVal = valued.reduce((a, h) => a + h.valueQuote, 0);
+ const allocBar = totalVal > 0 ? `<div class="alloc">${valued
+ .sort((a, b) => b.valueQuote - a.valueQuote)
+ .map((h, i) => `<span style="width:${((h.valueQuote / totalVal) * 100).toFixed(2)}%;background:${ALLOC_COLORS[i % ALLOC_COLORS.length]}" title="${escapeHtml(String(h.mint).slice(0, 8))}… · ${((h.valueQuote / totalVal) * 100).toFixed(1)}%"></span>`).join('')}</div>` : '';
+
+ const sorted = [...d.holdings].sort((x, y) => {
+ const k = pfSort.key, av = x[k] ?? -Infinity, bv = y[k] ?? -Infinity;
+ if (typeof av === 'string') return pfSort.dir * String(av).localeCompare(String(bv));
+ return pfSort.dir * (av - bv);
+ });
+ const arrow = (k) => pfSort.key === k ? (pfSort.dir < 0 ? '▾' : '▴') : '';
+ const th = (k, label, num) => `<th class="sortable${num ? ' num' : ''}" data-k="${k}">${label} <span class="arr">${arrow(k)}</span></th>`;
+
el.innerHTML = `
<div class="metrics" style="margin-top:.5rem">
<div class="metric"><div class="v">${(d.sol ?? 0).toFixed(4)} SOL</div><div class="l">wallet balance</div></div>
<div class="metric"><div class="v">${d.holdings.length}</div><div class="l">positions</div></div>
${subCards}
</div>
- <table style="margin-top:.5rem">
- <thead><tr><th>Mint</th><th>Quote</th><th class="num">Amount</th><th class="num">Price</th><th class="num">Value</th><th class="num">Cost</th><th class="num">PnL</th></tr></thead>
+ ${allocBar}
+ <div class="tbl-wrap"><table>
+ <thead><tr>${th('mint', 'Mint')}<th>Quote</th>${th('amount', 'Amount', true)}${th('priceQuote', 'Price', true)}${th('valueQuote', 'Value', true)}${th('costBasis', 'Cost', true)}${th('unrealizedPnl', 'PnL', true)}</tr></thead>
<tbody>
- ${d.holdings.map((h) => {
- const sym = h.quoteSymbol || 'SOL';
- const dec = sym === 'SOL' ? 4 : 2;
- return `
- <tr>
- <td><a href="https://pump.fun/${h.mint}" target="_blank" rel="noopener"><code>${h.mint.slice(0, 8)}…</code></a></td>
- <td>${sym}</td>
+ ${sorted.map((h) => {
+ const sym = h.quoteSymbol || 'SOL', dec = sym === 'SOL' ? 4 : 2;
+ return `<tr>
+ <td><a href="https://pump.fun/${escapeHtml(h.mint)}" target="_blank" rel="noopener"><code>${escapeHtml(String(h.mint)).slice(0, 8)}…</code></a></td>
+ <td>${escapeHtml(sym)}</td>
<td class="num">${fmt(h.amount, 2)}</td>
<td class="num">${fmt(h.priceQuote, 8)}</td>
<td class="num">${h.valueQuote == null ? '—' : `${fmt(h.valueQuote, dec)} ${sym}`}</td>
<td class="num">${h.costBasis == null ? '—' : `${fmt(h.costBasis, dec)} ${sym}`}</td>
<td class="num"><span class="${pn(h.unrealizedPnl)}">${h.unrealizedPnl == null ? '—' : `${fmt(h.unrealizedPnl, dec)} ${sym}`} (${pct(h.unrealizedPnlPct)})</span></td>
</tr>`;
- }).join('') || '<tr><td colspan="7" class="muted">— no token holdings —</td></tr>'}
+ }).join('')}
</tbody>
- </table>
- `;
+ </table></div>`;
+ el.querySelectorAll('th.sortable').forEach((thEl) => thEl.onclick = () => {
+ const k = thEl.dataset.k;
+ if (pfSort.key === k) pfSort.dir *= -1; else { pfSort.key = k; pfSort.dir = -1; }
+ renderPortfolio(portfolioData);
+ });
}
+ // ── Keyboard shortcuts ──────────────────────────────────────────────────
+ document.addEventListener('keydown', (e) => {
+ const meta = e.metaKey || e.ctrlKey;
+ if (meta && e.key === 'Enter') { e.preventDefault(); (e.shiftKey ? $('run') : $('backtest')).click(); }
+ else if (meta && (e.key === 's' || e.key === 'S')) { e.preventDefault(); liveValidate(); }
+ });
+
+ // ── Boot ────────────────────────────────────────────────────────────────
+ renderPalette();
+ loadPreset('momentum');
loadAgents();
</script>
-<div id="footer-container"></div>
-<script src="/footer.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
<script src="/brand.js" defer></script>
</body>
</html>
diff --git a/src/alpha-copilot.css b/src/alpha-copilot.css
index 98c8c0d80..088006f64 100644
--- a/src/alpha-copilot.css
+++ b/src/alpha-copilot.css
@@ -251,7 +251,7 @@
.ac-launches-head { display: flex; align-items: center; justify-content: space-between; padding: var(--space-xs) var(--space-sm) var(--space-sm); }
.ac-launches-head h2 { display: flex; align-items: center; gap: var(--space-xs); font-size: var(--text-md); font-family: var(--font-display); margin: 0; color: var(--ink-bright); }
.ac-launches-count { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); background: var(--surface-2); border-radius: var(--radius-pill); padding: 1px var(--space-xs); }
-.ac-launches-list { display: flex; flex-direction: column; gap: var(--space-sm); max-height: 660px; overflow-y: auto; padding: 0 var(--space-2xs) var(--space-2xs); }
+.ac-launches-list { display: flex; flex-direction: column; gap: var(--space-sm); max-height: 660px; overflow-y: auto; padding: var(--space-sm) var(--space-2xs) var(--space-2xs); }
.ac-launch { position: relative; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); transition: border-color var(--duration-fast), background var(--duration-fast); }
.ac-launch:hover { border-color: var(--wallet-stroke); }
.ac-launch.is-top { border-color: var(--wallet-stroke-strong); background: linear-gradient(180deg, var(--wallet-accent-soft), var(--surface-1)); }
diff --git a/src/alpha-copilot.js b/src/alpha-copilot.js
index 719b8a1d5..27b89da23 100644
--- a/src/alpha-copilot.js
+++ b/src/alpha-copilot.js
@@ -143,12 +143,16 @@ function agentCard(a) {
node.setAttribute('role', 'option');
node.dataset.id = a.id;
const meta = a.featured ? 'Featured' : a.onchain ? esc(a.onchain.network || 'on-chain') : a.chats ? `${a.chats.toLocaleString()} chats` : a.skill ? esc(a.skill.replace(/[-_]/g, ' ')) : 'agent';
+ const fallback = `<span class="ac-agent-initials">${esc(initials(a.name))}</span>`;
node.innerHTML = `
- <span class="ac-agent-av">${a.avatar ? `<img src="${esc(a.avatar)}" alt="" loading="lazy" />` : `<span class="ac-agent-initials">${esc(initials(a.name))}</span>`}</span>
+ <span class="ac-agent-av">${a.avatar ? `<img src="${esc(a.avatar)}" alt="" loading="lazy" />` : fallback}</span>
<span class="ac-agent-info">
<span class="ac-agent-name">${esc(a.name || 'Agent')}</span>
<span class="ac-agent-meta">${meta}</span>
</span>`;
+ // A broken avatar URL falls back to initials rather than the browser's broken-image glyph.
+ const img = node.querySelector('img');
+ if (img) img.addEventListener('error', () => { const host = img.parentElement; if (host) host.innerHTML = fallback; }, { once: true });
node.addEventListener('click', () => loadAgent(a.id));
return node;
}
diff --git a/src/watchlist.css b/src/watchlist.css
index 8f831a879..48c2945e7 100644
--- a/src/watchlist.css
+++ b/src/watchlist.css
@@ -276,3 +276,277 @@ body {
opacity: 0.85;
margin-top: 2px;
}
+.wl-ob-top { display: flex; flex-direction: column; align-items: center; }
+.wl-ob-pillars { display: flex; align-items: flex-end; gap: 2px; height: 14px; margin-top: 4px; }
+.wl-ob-pbar {
+ width: 3px;
+ height: 100%;
+ display: flex;
+ align-items: flex-end;
+ border-radius: 999px;
+ background: rgba(255,255,255,0.1);
+ overflow: hidden;
+}
+.wl-ob-pbar > span { display: block; width: 100%; border-radius: 999px; transition: height var(--duration-base) var(--ease-standard); }
+
+/* ── Conviction delta (24h mover) ─────────────────────────────────────────── */
+
+.wl-delta {
+ position: absolute;
+ top: var(--space-xs);
+ left: var(--space-xs);
+ z-index: 3;
+ font-family: var(--font-mono);
+ font-size: 10.5px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ padding: 3px 7px;
+ border-radius: var(--radius-pill);
+ background: rgba(0,0,0,0.5);
+ border: 1px solid transparent;
+ backdrop-filter: blur(6px);
+ pointer-events: none;
+}
+.wl-delta--up { color: #34d399; border-color: rgba(52,211,153,0.35); }
+.wl-delta--down { color: #f87171; border-color: rgba(248,113,113,0.35); }
+
+/* ── Upgraded-since-last-visit accent ─────────────────────────────────────── */
+
+.wl-card--upgraded { border-color: rgba(192,132,252,0.4); }
+.wl-card--upgraded::before {
+ content: '↑ Upgraded';
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ z-index: 4;
+ font-family: var(--font-mono);
+ font-size: 9px;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: #c084fc;
+ background: var(--bg-0);
+ border: 1px solid rgba(192,132,252,0.4);
+ border-radius: var(--radius-pill);
+ padding: 2px 8px;
+ pointer-events: none;
+}
+
+/* ── Portfolio summary bar ────────────────────────────────────────────────── */
+
+.wl-summary {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr)) 1.4fr;
+ gap: var(--space-md);
+ align-items: center;
+ margin-bottom: var(--space-lg);
+ padding: var(--space-md) var(--space-lg);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: linear-gradient(160deg, var(--surface-2), transparent 60%), var(--surface-1);
+ box-shadow: var(--shadow-1);
+ backdrop-filter: blur(var(--blur-sm));
+}
+.wl-sum-stat { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
+.wl-sum-label {
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-dim);
+ white-space: nowrap;
+}
+.wl-sum-value {
+ font-family: var(--font-mono);
+ font-size: var(--text-xl);
+ font-weight: var(--weight-bold);
+ color: var(--ink-bright);
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+}
+.wl-tierbar {
+ display: flex;
+ gap: 2px;
+ height: 22px;
+ border-radius: var(--radius-sm);
+ overflow: hidden;
+}
+.wl-tierbar-empty { font-size: var(--text-xs); color: var(--ink-dim); align-self: center; }
+.wl-tierseg {
+ display: grid;
+ place-items: center;
+ min-width: 4px;
+ border-radius: 3px;
+ transition: flex var(--duration-base) var(--ease-standard);
+}
+.wl-tierseg-n {
+ font-family: var(--font-mono);
+ font-size: 10px;
+ font-weight: 800;
+ color: rgba(0,0,0,0.7);
+ mix-blend-mode: luminosity;
+}
+
+@media (max-width: 760px) {
+ .wl-summary { grid-template-columns: repeat(2, 1fr); gap: var(--space-sm) var(--space-md); padding: var(--space-md); }
+ .wl-sum-stat--wide { grid-column: 1 / -1; }
+}
+
+/* ── Toolbar ──────────────────────────────────────────────────────────────── */
+
+.wl-toolbar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ margin-bottom: var(--space-lg);
+}
+.wl-tb-search {
+ position: relative;
+ display: flex;
+ align-items: center;
+ flex: 1 1 220px;
+ min-width: 180px;
+}
+.wl-tb-search-ic {
+ position: absolute;
+ left: 11px;
+ width: 15px;
+ height: 15px;
+ color: var(--ink-dim);
+ pointer-events: none;
+}
+.wl-tb-search-in {
+ width: 100%;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 9px 12px 9px 33px;
+ color: var(--ink);
+ font-size: var(--text-sm);
+ font-family: var(--font-body);
+ transition: border-color var(--duration-fast);
+}
+.wl-tb-search-in::placeholder { color: var(--ink-dim); }
+.wl-tb-search-in:focus { outline: none; border-color: var(--stroke-strong); }
+.wl-tb-search-in:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 1px; }
+
+.wl-tb-filters { display: flex; gap: 6px; flex-wrap: wrap; }
+.wl-chip {
+ font-size: var(--text-xs);
+ font-weight: var(--weight-medium);
+ color: var(--ink-dim);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 6px 12px;
+ cursor: pointer;
+ transition: color var(--duration-fast), border-color var(--duration-fast), background var(--duration-fast);
+}
+.wl-chip:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }
+.wl-chip:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 1px; }
+.wl-chip.is-active { color: var(--bg-0); background: var(--accent); border-color: var(--accent); }
+
+.wl-tb-end { display: flex; align-items: center; gap: var(--space-sm); margin-left: auto; }
+.wl-tb-sort { display: inline-flex; align-items: center; gap: var(--space-xs); }
+.wl-tb-sort-label { font-size: var(--text-xs); color: var(--ink-dim); text-transform: uppercase; letter-spacing: 0.06em; }
+.wl-tb-select {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 8px 28px 8px 11px;
+ color: var(--ink);
+ font-size: var(--text-sm);
+ font-family: var(--font-body);
+ cursor: pointer;
+ appearance: none;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2.5'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 9px center;
+ transition: border-color var(--duration-fast);
+}
+.wl-tb-select:hover { border-color: var(--stroke-strong); }
+.wl-tb-select:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 1px; }
+
+.wl-view { display: inline-flex; border: 1px solid var(--stroke); border-radius: var(--radius-md); overflow: hidden; }
+.wl-view-btn {
+ display: grid;
+ place-items: center;
+ width: 34px;
+ height: 34px;
+ background: var(--surface-1);
+ border: none;
+ color: var(--ink-dim);
+ cursor: pointer;
+ transition: color var(--duration-fast), background var(--duration-fast);
+}
+.wl-view-btn + .wl-view-btn { border-left: 1px solid var(--stroke); }
+.wl-view-btn svg { width: 16px; height: 16px; fill: currentColor; }
+.wl-view-btn:hover { color: var(--ink-bright); }
+.wl-view-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: -2px; }
+.wl-view-btn.is-active { color: var(--ink-bright); background: var(--surface-3); }
+
+@media (max-width: 620px) {
+ .wl-tb-end { margin-left: 0; width: 100%; justify-content: space-between; }
+ .wl-tb-sort { flex: 1; }
+ .wl-tb-select { flex: 1; }
+}
+
+/* ── List view ────────────────────────────────────────────────────────────── */
+
+.wl-grid--list { grid-template-columns: 1fr; }
+.wl-grid--list .wl-card { padding: var(--space-sm) var(--space-md); }
+.wl-grid--list .csc-card { flex-direction: row; align-items: center; gap: var(--space-lg); flex-wrap: wrap; }
+.wl-grid--list .csc-card-head { flex: 1 1 220px; min-width: 200px; }
+.wl-grid--list .csc-card-stats { flex: 2 1 320px; grid-template-columns: repeat(3, 1fr); margin: 0; }
+.wl-grid--list .csc-bar { flex: 1 1 100%; order: 9; }
+.wl-grid--list .csc-card-foot { flex: 0 0 auto; }
+.wl-grid--list .wl-oracle-badge { bottom: 50%; transform: translateY(50%); }
+@media (max-width: 640px) {
+ .wl-grid--list .csc-card { flex-direction: column; align-items: stretch; gap: 12px; }
+ .wl-grid--list .wl-oracle-badge { bottom: var(--space-sm); transform: none; }
+}
+
+.wl-hidden { display: none !important; }
+
+/* ── No-match state ───────────────────────────────────────────────────────── */
+
+.wl-nomatch {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: var(--space-md);
+ text-align: center;
+ padding: var(--space-2xl) var(--space-md);
+}
+.wl-nomatch-msg { color: var(--ink-dim); margin: 0; font-size: var(--text-md); }
+
+/* ── Empty-state trending suggestions ─────────────────────────────────────── */
+
+.wl-suggest { margin-top: var(--space-xl); }
+.wl-suggest-head {
+ font-size: var(--text-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-sm);
+}
+.wl-suggest-row { display: flex; gap: var(--space-sm); flex-wrap: wrap; justify-content: center; }
+.wl-suggest-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-medium);
+ color: var(--ink);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ padding: 6px 12px 6px 7px;
+ cursor: pointer;
+ transition: border-color var(--duration-fast), transform var(--duration-fast), background var(--duration-fast);
+}
+.wl-suggest-chip:hover { border-color: var(--stroke-strong); transform: translateY(-1px); background: var(--surface-2); }
+.wl-suggest-chip:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 1px; }
+.wl-suggest-img { width: 20px; height: 20px; border-radius: 50%; object-fit: cover; background: var(--surface-2); }
+.wl-suggest-plus { color: var(--ink-dim); font-weight: var(--weight-bold); }
diff --git a/src/watchlist.js b/src/watchlist.js
index 683591cdc..0df30886b 100644
--- a/src/watchlist.js
+++ b/src/watchlist.js
@@ -1,35 +1,68 @@
// ════════════════════════════════════════════════════════════════════════════
-// /watchlist — the coins a trader is tracking.
+// /watchlist — the coins a trader is tracking, with a live portfolio readout.
//
// Closes the loop opened by the "Watch" button on every coin profile
// (/launches/<mint>): that button writes a mint into localStorage under
// `ld_watchlist`; this page reads it back and renders each as a live status
// card (shared coin-status widget → one /api/pump/coin fetch per coin), linking
-// straight back to the full profile. The list is device-local and private —
-// no account required — and stays in sync across tabs via the storage event.
+// straight back to the Oracle conviction breakdown. The list is device-local
+// and private — no account required — and stays in sync across tabs via the
+// storage event.
+//
+// Beyond the raw list, this page treats the watchlist as a portfolio:
+// · a summary bar aggregates combined market cap, 24h volume, graduated
+// count, average Oracle conviction, and the tier distribution;
+// · a toolbar sorts (added/conviction/mcap/volume/graduation/movers/name),
+// filters by tier, searches by symbol/name/mint, and toggles grid/list;
+// · conviction movers (/api/oracle/movers) surface 24h score swings per coin;
+// · the empty state suggests trending coins to add in one click;
+// · "Share list" copies a self-contained link that recreates the watchlist
+// on any device, and `?add=` links are imported on load.
// ════════════════════════════════════════════════════════════════════════════
-import { mountCoinStatus } from './pump/coin-status-card.js';
+import { mountCoinStatus, formatMcap } from './pump/coin-status-card.js';
const WATCH_KEY = 'ld_watchlist'; // shared with src/launch-detail.js
const LAST_TIERS_KEY = 'wl_last_tiers'; // mint → tier, for upgrade detection
const ALERTS_KEY = 'wl_alerts_on';
+const PREFS_KEY = 'wl_prefs'; // { sort, view, tier }
const TIER_COLOR = { prime: '#c084fc', strong: '#34d399', lean: '#fbbf24', watch: '#94a3b8', avoid: '#f87171' };
+const TIER_LABEL = { prime: 'Prime', strong: 'Strong', lean: 'Lean', watch: 'Watch', avoid: 'Avoid' };
+const TIER_ORDER = ['prime', 'strong', 'lean', 'watch', 'avoid'];
const TIER_RANK = { avoid: 0, watch: 1, lean: 2, strong: 3, prime: 4 };
const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const REFRESH_MS = 90_000;
+const MAX_WATCH = 200;
const feedEl = document.getElementById('wl-feed');
const stateEl = document.getElementById('wl-state');
const countEl = document.getElementById('wl-count');
const clearBtn = document.getElementById('wl-clear');
const alertsBtn = document.getElementById('wl-alerts');
-
-const handles = new Set();
+const shareBtn = document.getElementById('wl-share');
+const summaryEl = document.getElementById('wl-summary');
+const toolbarEl = document.getElementById('wl-toolbar');
+const searchInp = document.getElementById('wl-search');
+const sortSel = document.getElementById('wl-sort');
+const filtersEl = document.getElementById('wl-filters');
+const viewGrid = document.getElementById('wl-view-grid');
+const viewList = document.getElementById('wl-view-list');
+
+// ── live state ─────────────────────────────────────────────────────────────
+// Central stores keyed by mint. Cards mount async, so the summary, sort, and
+// filter all read from these maps as data streams in rather than re-fetching.
+const handles = new Set(); // coin-status destroy handles
+const cardEls = new Map(); // mint → <article>
+const coinData = new Map(); // mint → normalized coin (from widget onData)
+const convData = new Map(); // mint → { score, tier, pillars }
+const moverData = new Map(); // mint → { delta, tierChanged, firstTier }
let refreshTimer = null;
+let sortRaf = 0;
-// ── DOM helper ───────────────────────────────────────────────────────────────
+const prefs = readPrefs();
+
+// ── DOM helpers ──────────────────────────────────────────────────────────────
function el(tag, props = {}, children = []) {
const node = document.createElement(tag);
@@ -37,6 +70,7 @@ function el(tag, props = {}, children = []) {
if (v == null || v === false) continue;
if (k === 'class') node.className = v;
else if (k === 'text') node.textContent = v;
+ else if (k === 'html') node.innerHTML = v;
else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
else node.setAttribute(k, v);
}
@@ -123,7 +157,7 @@ function readList() {
function writeList(list) {
try {
- localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, 200)));
+ localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, MAX_WATCH)));
} catch {
/* storage blocked — non-fatal */
}
@@ -131,10 +165,31 @@ function writeList(list) {
function remove(mint) {
writeList(readList().filter((m) => m !== mint));
+ coinData.delete(mint);
+ convData.delete(mint);
+ moverData.delete(mint);
render();
}
-// ── tier memory ───────────────────────────────────────────────────────────────
+function readPrefs() {
+ const fallback = { sort: 'added', view: 'grid', tier: 'all' };
+ try {
+ const p = JSON.parse(localStorage.getItem(PREFS_KEY) || '{}');
+ return {
+ sort: typeof p.sort === 'string' ? p.sort : fallback.sort,
+ view: p.view === 'list' ? 'list' : 'grid',
+ tier: typeof p.tier === 'string' ? p.tier : fallback.tier,
+ };
+ } catch {
+ return fallback;
+ }
+}
+
+function savePrefs() {
+ try { localStorage.setItem(PREFS_KEY, JSON.stringify(prefs)); } catch { /* non-fatal */ }
+}
+
+// ── tier memory + alerts ────────────────────────────────────────────────────
function readLastTiers() {
try { return JSON.parse(localStorage.getItem(LAST_TIERS_KEY) || '{}'); } catch { return {}; }
@@ -144,10 +199,8 @@ function saveLastTiers(map) {
try { localStorage.setItem(LAST_TIERS_KEY, JSON.stringify(map)); } catch { /* non-fatal */ }
}
-// ── alerts ────────────────────────────────────────────────────────────────────
-
function alertsEnabled() {
- return localStorage.getItem(ALERTS_KEY) === '1' && Notification.permission === 'granted';
+ return localStorage.getItem(ALERTS_KEY) === '1' && typeof Notification !== 'undefined' && Notification.permission === 'granted';
}
function updateAlertsBtn() {
@@ -160,38 +213,39 @@ function updateAlertsBtn() {
}
async function toggleAlerts() {
+ if (typeof Notification === 'undefined') {
+ alertsBtn.textContent = '🔕 Unsupported';
+ setTimeout(() => updateAlertsBtn(), 2400);
+ return;
+ }
if (alertsEnabled()) {
localStorage.setItem(ALERTS_KEY, '0');
updateAlertsBtn();
return;
}
if (Notification.permission === 'denied') {
- // Can't request again — show a tooltip-style message
alertsBtn.textContent = '🔕 Blocked by browser';
setTimeout(() => updateAlertsBtn(), 2400);
return;
}
const perm = await Notification.requestPermission().catch(() => 'denied');
- if (perm === 'granted') {
- localStorage.setItem(ALERTS_KEY, '1');
- }
+ if (perm === 'granted') localStorage.setItem(ALERTS_KEY, '1');
updateAlertsBtn();
}
-function maybeFire(mint, symbol, newTier, oldTier) {
+function maybeFire(mint, newTier, oldTier) {
if (!alertsEnabled()) return;
const oldRank = TIER_RANK[oldTier] ?? -1;
const newRank = TIER_RANK[newTier] ?? -1;
if (newRank <= oldRank) return;
- // Only notify for strong+ upgrades
- if (newRank < TIER_RANK.strong) return;
- const title = `${symbol || mint.slice(0, 8)} → ${newTier} conviction`;
- const body = `Oracle scored this coin ${newTier} on three.ws`;
+ if (newRank < TIER_RANK.strong) return; // only strong+ upgrades
+ const symbol = coinData.get(mint)?.symbol || mint.slice(0, 8);
+ const title = `${symbol} → ${TIER_LABEL[newTier] || newTier} conviction`;
+ const body = `Oracle upgraded this coin to ${newTier} on three.ws`;
try {
const n = new Notification(title, { body, icon: '/favicon-32x32.png', tag: mint });
// Navigate the watchlist tab itself rather than spawning an orphaned new
- // tab — keeps the browser Back button as a reliable return path to the
- // watchlist once the user is done reading the Oracle breakdown.
+ // tab — keeps the browser Back button as a reliable return path.
n.onclick = () => { window.focus(); location.href = `/oracle?mint=${encodeURIComponent(mint)}`; n.close(); };
} catch { /* Notification blocked mid-flight */ }
}
@@ -200,20 +254,16 @@ function maybeFire(mint, symbol, newTier, oldTier) {
function teardown() {
for (const h of handles) {
- try {
- h.destroy();
- } catch {
- /* ignore */
- }
+ try { h.destroy(); } catch { /* ignore */ }
}
handles.clear();
+ cardEls.clear();
}
// ── cards ────────────────────────────────────────────────────────────────────
function watchCard(mint, index) {
- // Primary card link opens Oracle conviction drawer for this coin.
- // Secondary "launch page" link is rendered inside the coin-status-card footer.
+ // Primary card link opens the Oracle conviction breakdown for this coin.
const link = el('a', {
class: 'wl-card-link',
href: `/oracle?mint=${mint}`,
@@ -232,19 +282,34 @@ function watchCard(mint, index) {
remove(mint);
},
});
+ const delta = el('div', { class: 'wl-delta', 'data-delta': mint, hidden: true });
const oracleBadge = el('div', { class: 'wl-oracle-badge', 'data-oracle': mint });
- const card = el('article', { class: 'wl-card', 'data-mint': mint }, [link, oracleBadge, removeBtn, market]);
+ const card = el('article', { class: 'wl-card', 'data-mint': mint }, [link, delta, oracleBadge, removeBtn, market]);
if (!REDUCED_MOTION) {
card.style.animationDelay = `${Math.min(index, 12) * 40}ms`;
card.classList.add('wl-in');
}
- handles.add(mountCoinStatus(market, mint, { variant: 'card', placeholder: mintIdenticon(mint), showBuy: true }));
+ handles.add(
+ mountCoinStatus(market, mint, {
+ variant: 'card',
+ placeholder: mintIdenticon(mint),
+ showBuy: true,
+ oracle: false, // conviction is batch-fetched here; skip the per-card round trip
+ onData: (coin) => {
+ coinData.set(mint, coin);
+ updateSummary();
+ scheduleSortFilter();
+ },
+ }),
+ );
+ cardEls.set(mint, card);
return card;
}
-// ── states ───────────────────────────────────────────────────────────────────
+// ── empty state (with trending suggestions) ─────────────────────────────────
function renderEmpty() {
+ const suggestWrap = el('div', { class: 'wl-suggest', id: 'wl-suggest', hidden: true });
stateEl.replaceChildren(
el('div', { class: 'wl-empty' }, [
el('div', { class: 'wl-empty-glyph', 'aria-hidden': 'true' }, [mintIdenticon('three.ws-watchlist-empty')]),
@@ -254,10 +319,49 @@ function renderEmpty() {
el('a', { class: 'wl-btn wl-btn-primary', href: '/launches', text: 'Explore launches' }),
el('a', { class: 'wl-btn', href: '/oracle', text: 'Open Oracle' }),
]),
+ suggestWrap,
]),
);
+ loadSuggestions(suggestWrap);
+}
+
+// Pull live trending coins so the empty state offers a real first action.
+async function loadSuggestions(wrap) {
+ let coins = [];
+ try {
+ const r = await fetch('/api/pump/trending?limit=8');
+ if (r.ok) {
+ const data = await r.json();
+ coins = (data?.data || []).filter((c) => MINT_RE.test(c?.mint || '')).slice(0, 6);
+ }
+ } catch { /* trending is best-effort garnish on the empty state */ }
+ if (!coins.length || !wrap.isConnected) return;
+
+ const chips = coins.map((c) => {
+ const label = c.symbol ? `$${c.symbol}` : `${c.mint.slice(0, 4)}…`;
+ return el('button', {
+ class: 'wl-suggest-chip',
+ type: 'button',
+ title: `Add ${c.name || label} to your watchlist`,
+ onclick: () => {
+ if (addMint(c.mint) !== 'already') showAddMsg(`Added ${label} — building your list.`, 'ok');
+ },
+ }, [
+ c.logo ? el('img', { class: 'wl-suggest-img', src: c.logo, alt: '', loading: 'lazy' }) : null,
+ el('span', { text: label }),
+ el('span', { class: 'wl-suggest-plus', text: '+', 'aria-hidden': 'true' }),
+ ]);
+ });
+
+ wrap.replaceChildren(
+ el('p', { class: 'wl-suggest-head', text: 'Trending right now — tap to add' }),
+ el('div', { class: 'wl-suggest-row' }, chips),
+ );
+ wrap.hidden = false;
}
+// ── render ───────────────────────────────────────────────────────────────────
+
function render() {
teardown();
feedEl.replaceChildren();
@@ -267,77 +371,354 @@ function render() {
const n = list.length;
countEl.textContent = n ? `${n} coin${n === 1 ? '' : 's'} watched` : '';
clearBtn.hidden = n === 0;
+ if (shareBtn) shareBtn.hidden = n === 0;
+ toolbarEl.hidden = n < 2; // controls only earn their space past one coin
+ summaryEl.hidden = n === 0;
+
+ // Drop cached data for mints no longer watched.
+ for (const m of [...coinData.keys()]) if (!list.includes(m)) coinData.delete(m);
+ for (const m of [...convData.keys()]) if (!list.includes(m)) convData.delete(m);
if (n === 0) {
feedEl.setAttribute('aria-busy', 'false');
renderEmpty();
+ updateSummary();
return;
}
list.forEach((mint, i) => feedEl.appendChild(watchCard(mint, i)));
feedEl.setAttribute('aria-busy', 'false');
-
+ applyView();
+ updateSummary();
enrichWithOracleConviction(list);
+ fetchMovers(list);
+}
+
+// ── summary bar ──────────────────────────────────────────────────────────────
+
+function updateSummary() {
+ if (summaryEl.hidden) return;
+ const list = readList();
+ const coins = list.map((m) => coinData.get(m)).filter(Boolean);
+ const convs = list.map((m) => convData.get(m)).filter((c) => c && c.score != null);
+
+ const sumMcap = coins.reduce((a, c) => a + (c.mcap || 0), 0);
+ const sumVol = coins.reduce((a, c) => a + (c.volume24h || 0), 0);
+ const gradCnt = coins.filter((c) => c.graduated).length;
+ const avgConv = convs.length ? Math.round(convs.reduce((a, c) => a + Number(c.score), 0) / convs.length) : null;
+
+ setText('wl-sum-mcap', coins.length ? formatMcap(sumMcap) : '—');
+ setText('wl-sum-vol', coins.length ? formatMcap(sumVol) : '—');
+ setText('wl-sum-grad', `${gradCnt}/${list.length}`);
+ setText('wl-sum-conv', avgConv != null ? String(avgConv) : '—');
+
+ const convEl = document.getElementById('wl-sum-conv');
+ if (convEl && avgConv != null) convEl.style.color = TIER_COLOR[tierForScore(avgConv)] || '';
+
+ renderTierBar(convs);
+}
+
+function setText(id, text) {
+ const node = document.getElementById(id);
+ if (node) node.textContent = text;
+}
+
+function tierForScore(s) {
+ if (s >= 75) return 'prime';
+ if (s >= 60) return 'strong';
+ if (s >= 45) return 'lean';
+ if (s >= 30) return 'watch';
+ return 'avoid';
+}
+
+function renderTierBar(convs) {
+ const bar = document.getElementById('wl-sum-tiers');
+ if (!bar) return;
+ if (!convs.length) {
+ bar.replaceChildren(el('span', { class: 'wl-tierbar-empty', text: 'Scoring…' }));
+ bar.removeAttribute('aria-label');
+ return;
+ }
+ const counts = {};
+ for (const c of convs) counts[c.tier] = (counts[c.tier] || 0) + 1;
+ const total = convs.length;
+ const segs = [];
+ const labelParts = [];
+ for (const tier of TIER_ORDER) {
+ const cnt = counts[tier] || 0;
+ if (!cnt) continue;
+ labelParts.push(`${cnt} ${tier}`);
+ segs.push(el('span', {
+ class: 'wl-tierseg',
+ style: `flex:${cnt};background:${TIER_COLOR[tier]}`,
+ title: `${cnt} ${TIER_LABEL[tier]}`,
+ }, cnt / total > 0.14 ? [el('span', { class: 'wl-tierseg-n', text: String(cnt) })] : []));
+ }
+ bar.replaceChildren(...segs);
+ bar.setAttribute('aria-label', `Tier distribution: ${labelParts.join(', ')}`);
}
-// Batch-fetch Oracle conviction for all watched mints and paint badges on cards.
+// ── conviction (batch) ──────────────────────────────────────────────────────
+
async function enrichWithOracleConviction(mints) {
if (!mints.length) return;
const chunks = [];
for (let i = 0; i < mints.length; i += 20) chunks.push(mints.slice(i, i + 20));
- let results = {};
+ const results = {};
try {
const responses = await Promise.all(
chunks.map((chunk) =>
fetch(`/api/oracle/batch?mints=${chunk.map(encodeURIComponent).join(',')}&network=mainnet`)
- .then((r) => r.ok ? r.json() : null)
+ .then((r) => (r.ok ? r.json() : null))
.catch(() => null),
),
);
- for (const resp of responses) {
- if (resp?.results) Object.assign(results, resp.results);
- }
+ for (const resp of responses) if (resp?.results) Object.assign(results, resp.results);
} catch { return; }
const lastTiers = readLastTiers();
const nextTiers = { ...lastTiers };
- for (const article of feedEl.querySelectorAll('article[data-mint]')) {
- const mint = article.dataset.mint;
+ for (const mint of mints) {
const data = results[mint];
if (!data || data.score == null) continue;
+ convData.set(mint, data);
+ paintOracleBadge(mint, data);
- let badge = article.querySelector('.wl-oracle-badge');
- if (!badge) {
- badge = document.createElement('div');
- badge.className = 'wl-oracle-badge';
- article.appendChild(badge);
- }
- const color = TIER_COLOR[data.tier] || '#94a3b8';
- badge.innerHTML = `<a class="wl-ob-link" href="/oracle?mint=${encodeURIComponent(mint)}" aria-label="Oracle conviction: ${data.score} ${data.tier || ''}">
- <span class="wl-ob-score" style="color:${color}">${data.score}</span>
- <span class="wl-ob-tier" style="color:${color}">${data.tier || ''}</span>
- </a>`;
-
- // Tier upgrade detection — only alert after first load (lastTiers exists)
const oldTier = lastTiers[mint];
const newTier = data.tier;
- if (oldTier && newTier && oldTier !== newTier) {
- maybeFire(mint, data.symbol || '', newTier, oldTier);
+ const card = cardEls.get(mint);
+ if (oldTier && newTier && (TIER_RANK[newTier] ?? -1) > (TIER_RANK[oldTier] ?? -1)) {
+ maybeFire(mint, newTier, oldTier);
+ if (card) card.classList.add('wl-card--upgraded');
}
if (newTier) nextTiers[mint] = newTier;
}
saveLastTiers(nextTiers);
+ updateSummary();
+ scheduleSortFilter();
}
-function scheduleRefresh() {
- clearTimeout(refreshTimer);
- refreshTimer = setTimeout(async () => {
+function paintOracleBadge(mint, data) {
+ const card = cardEls.get(mint);
+ if (!card) return;
+ const badge = card.querySelector('.wl-oracle-badge');
+ if (!badge) return;
+ const tier = data.tier || 'watch';
+ const color = TIER_COLOR[tier] || '#94a3b8';
+ const p = data.pillars || {};
+ const bars = [
+ ['P', p.pedigree], ['S', p.structure], ['N', p.narrative], ['M', p.momentum],
+ ].filter(([, v]) => v != null);
+ const pillarBars = bars.length
+ ? `<span class="wl-ob-pillars" aria-hidden="true">${bars.map(([k, v]) =>
+ `<span class="wl-ob-pbar" title="${k} ${Math.round(v)}"><span style="height:${Math.max(8, Math.min(100, v))}%;background:${color}"></span></span>`,
+ ).join('')}</span>`
+ : '';
+ badge.innerHTML = `<a class="wl-ob-link" href="/oracle?mint=${encodeURIComponent(mint)}" aria-label="Oracle conviction: ${data.score} ${tier}">
+ <span class="wl-ob-top">
+ <span class="wl-ob-score" style="color:${color}">${data.score}</span>
+ <span class="wl-ob-tier" style="color:${color}">${tier}</span>
+ </span>${pillarBars}
+ </a>`;
+}
+
+// ── conviction movers (24h delta) ───────────────────────────────────────────
+
+async function fetchMovers(mints) {
+ if (!mints.length) return;
+ const watched = new Set(mints);
+ try {
+ const r = await fetch('/api/oracle/movers?direction=all&hours=24&limit=60&network=mainnet');
+ if (!r.ok) return;
+ const data = await r.json();
+ const items = Array.isArray(data?.items) ? data.items : (Array.isArray(data?.movers) ? data.movers : []);
+ for (const it of items) {
+ const mint = it?.mint;
+ if (!mint || !watched.has(mint)) continue;
+ const delta = Number(it.delta);
+ if (!Number.isFinite(delta)) continue;
+ moverData.set(mint, { delta, tierChanged: !!it.tier_changed, firstTier: it.first_tier || null });
+ paintDelta(mint);
+ }
+ } catch { /* movers are an enhancement, not load-bearing */ }
+ scheduleSortFilter();
+}
+
+function paintDelta(mint) {
+ const card = cardEls.get(mint);
+ if (!card) return;
+ const node = card.querySelector('.wl-delta');
+ if (!node) return;
+ const m = moverData.get(mint);
+ if (!m || !m.delta) { node.hidden = true; return; }
+ const up = m.delta > 0;
+ node.className = `wl-delta ${up ? 'wl-delta--up' : 'wl-delta--down'}`;
+ node.title = `Oracle conviction ${up ? 'rose' : 'fell'} ${Math.abs(Math.round(m.delta))} pts in 24h${m.tierChanged ? ` (tier changed from ${m.firstTier})` : ''}`;
+ node.textContent = `${up ? '▲' : '▼'} ${Math.abs(Math.round(m.delta))}`;
+ node.hidden = false;
+}
+
+// ── sort / filter / search ──────────────────────────────────────────────────
+
+function scheduleSortFilter() {
+ if (sortRaf) return;
+ sortRaf = requestAnimationFrame(() => { sortRaf = 0; applySortFilter(); });
+}
+
+function sortValue(mint, mode) {
+ const c = coinData.get(mint);
+ const cv = convData.get(mint);
+ switch (mode) {
+ case 'conviction': return cv?.score ?? -1;
+ case 'mcap': return c?.mcap ?? -1;
+ case 'volume': return c?.volume24h ?? -1;
+ case 'graduation': return c?.graduationPct ?? -1;
+ case 'movers': return moverData.get(mint)?.delta ?? -Infinity;
+ case 'name': return (c?.name || c?.symbol || mint).toLowerCase();
+ default: return 0; // 'added' — keep list order
+ }
+}
+
+function applySortFilter() {
+ const list = readList();
+ if (!list.length) return;
+ const mode = prefs.sort;
+ const q = (searchInp?.value || '').trim().toLowerCase();
+ const tierFilter = prefs.tier;
+
+ // Sort a copy of the list. 'added' preserves list order (newest first).
+ let ordered = list.slice();
+ if (mode !== 'added') {
+ ordered.sort((a, b) => {
+ const va = sortValue(a, mode);
+ const vb = sortValue(b, mode);
+ if (mode === 'name') return String(va).localeCompare(String(vb));
+ return Number(vb) - Number(va); // numeric: descending
+ });
+ }
+
+ let visible = 0;
+ for (const mint of ordered) {
+ const card = cardEls.get(mint);
+ if (!card) continue;
+ feedEl.appendChild(card); // reorder in place
+
+ const c = coinData.get(mint);
+ const cv = convData.get(mint);
+ const matchQ = !q || mint.toLowerCase().includes(q)
+ || (c?.symbol || '').toLowerCase().includes(q)
+ || (c?.name || '').toLowerCase().includes(q);
+ const matchTier = tierFilter === 'all' || cv?.tier === tierFilter;
+ const show = matchQ && matchTier;
+ card.classList.toggle('wl-hidden', !show);
+ if (show) visible++;
+ }
+
+ renderNoMatch(visible === 0, q, tierFilter);
+}
+
+function renderNoMatch(empty, q, tier) {
+ let node = document.getElementById('wl-nomatch');
+ if (!empty) {
+ if (node) node.remove();
+ return;
+ }
+ const reason = q
+ ? `No watched coin matches “${q}”.`
+ : `No watched coin is rated ${TIER_LABEL[tier] || tier} yet.`;
+ const content = [
+ el('p', { class: 'wl-nomatch-msg', text: reason }),
+ el('button', { class: 'wl-btn wl-btn-ghost', type: 'button', text: 'Clear filters', onclick: clearFilters }),
+ ];
+ if (node) {
+ node.replaceChildren(...content);
+ } else {
+ node = el('div', { class: 'wl-nomatch', id: 'wl-nomatch' }, content);
+ stateEl.replaceChildren(node);
+ }
+}
+
+function clearFilters() {
+ if (searchInp) searchInp.value = '';
+ setSort('added');
+ setTierFilter('all');
+}
+
+function setSort(mode) {
+ prefs.sort = mode;
+ savePrefs();
+ if (sortSel && sortSel.value !== mode) sortSel.value = mode;
+ applySortFilter();
+}
+
+function setTierFilter(tier) {
+ prefs.tier = tier;
+ savePrefs();
+ if (filtersEl) {
+ for (const btn of filtersEl.querySelectorAll('.wl-chip')) {
+ const on = btn.dataset.tier === tier;
+ btn.classList.toggle('is-active', on);
+ btn.setAttribute('aria-pressed', String(on));
+ }
+ }
+ applySortFilter();
+}
+
+function applyView() {
+ const list = prefs.view === 'list';
+ feedEl.classList.toggle('wl-grid--list', list);
+ if (viewGrid) { viewGrid.classList.toggle('is-active', !list); viewGrid.setAttribute('aria-pressed', String(!list)); }
+ if (viewList) { viewList.classList.toggle('is-active', list); viewList.setAttribute('aria-pressed', String(list)); }
+}
+
+function setView(view) {
+ prefs.view = view;
+ savePrefs();
+ applyView();
+}
+
+// ── share / import ──────────────────────────────────────────────────────────
+
+async function shareList() {
+ const list = readList();
+ if (!list.length) return;
+ const url = `${location.origin}/watchlist?add=${list.join(',')}`;
+ try {
+ await navigator.clipboard.writeText(url);
+ showAddMsg(`Link copied — opens this ${list.length}-coin watchlist anywhere.`, 'ok');
+ } catch {
+ // Clipboard blocked (insecure context / permission) — fall back to share sheet or prompt.
+ if (navigator.share) {
+ navigator.share({ title: 'My three.ws watchlist', url }).catch(() => {});
+ } else {
+ window.prompt('Copy your watchlist link:', url);
+ }
+ }
+}
+
+// Seed the watchlist from a `?add=mint,mint` link, then strip the param so a
+// refresh doesn't re-import. Returns the count of newly added mints.
+function importFromUrl() {
+ const params = new URLSearchParams(location.search);
+ const raw = params.get('add');
+ if (!raw) return 0;
+ const incoming = raw.split(',').map((m) => m.trim()).filter((m) => MINT_RE.test(m));
+ let added = 0;
+ if (incoming.length) {
const list = readList();
- if (list.length) await enrichWithOracleConviction(list);
- scheduleRefresh();
- }, REFRESH_MS);
+ const have = new Set(list);
+ const fresh = incoming.filter((m) => !have.has(m));
+ if (fresh.length) {
+ writeList([...fresh, ...list]);
+ added = fresh.length;
+ }
+ }
+ params.delete('add');
+ const qs = params.toString();
+ history.replaceState(null, '', location.pathname + (qs ? `?${qs}` : '') + location.hash);
+ return added;
}
// ── ambient field (shared visual language) ──────────────────────────────────
@@ -428,10 +809,8 @@ function startParticleField() {
function parseMintFromInput(raw) {
const s = raw.trim();
- // pump.fun/coin/<mint> or pump.fun/token/<mint>
const urlMatch = s.match(/pump\.fun\/(?:coin|token)\/([1-9A-HJ-NP-Za-km-z]{32,44})/);
if (urlMatch) return urlMatch[1];
- // bare mint address
if (MINT_RE.test(s)) return s;
return null;
}
@@ -445,15 +824,17 @@ function addMint(mint) {
}
function showAddMsg(msg, tone = 'ok') {
- const el = document.getElementById('wl-add-msg');
- if (!el) return;
- el.textContent = msg;
- el.className = `wl-add-msg wl-add-msg-${tone}`;
- el.hidden = false;
- clearTimeout(el._t);
- el._t = setTimeout(() => { el.hidden = true; }, 3500);
+ const node = document.getElementById('wl-add-msg');
+ if (!node) return;
+ node.textContent = msg;
+ node.className = `wl-add-msg wl-add-msg-${tone}`;
+ node.hidden = false;
+ clearTimeout(node._t);
+ node._t = setTimeout(() => { node.hidden = true; }, 3500);
}
+// ── wiring ───────────────────────────────────────────────────────────────────
+
const addForm = document.getElementById('wl-add-form');
const addInput = document.getElementById('wl-add-input');
@@ -468,31 +849,24 @@ if (addForm && addInput) {
}
const result = addMint(mint);
if (result === 'already') {
- showAddMsg(`Already on your watchlist.`, 'warn');
+ showAddMsg('Already on your watchlist.', 'warn');
} else {
- showAddMsg(`Added — scroll down to see it.`, 'ok');
+ showAddMsg('Added — scroll down to see it.', 'ok');
addInput.value = '';
}
});
- // Auto-submit on paste if the pasted value is a complete mint/URL
addInput.addEventListener('paste', (e) => {
const pasted = (e.clipboardData || window.clipboardData)?.getData('text') || '';
const mint = parseMintFromInput(pasted);
if (mint) {
e.preventDefault();
const result = addMint(mint);
- if (result === 'already') {
- showAddMsg('Already on your watchlist.', 'warn');
- } else {
- showAddMsg(`Added — scroll down to see it.`, 'ok');
- }
+ showAddMsg(result === 'already' ? 'Already on your watchlist.' : 'Added — scroll down to see it.', result === 'already' ? 'warn' : 'ok');
}
});
}
-// ── boot ─────────────────────────────────────────────────────────────────────
-
clearBtn.addEventListener('click', () => {
if (!readList().length) return;
writeList([]);
@@ -504,18 +878,58 @@ if (alertsBtn) {
alertsBtn.addEventListener('click', () => toggleAlerts());
}
+if (shareBtn) shareBtn.addEventListener('click', shareList);
+
+if (searchInp) {
+ let t = 0;
+ searchInp.addEventListener('input', () => {
+ clearTimeout(t);
+ t = setTimeout(() => applySortFilter(), 120);
+ });
+}
+if (sortSel) {
+ sortSel.value = prefs.sort;
+ sortSel.addEventListener('change', () => setSort(sortSel.value));
+}
+if (filtersEl) {
+ filtersEl.addEventListener('click', (e) => {
+ const btn = e.target.closest('.wl-chip');
+ if (btn) setTierFilter(btn.dataset.tier);
+ });
+}
+if (viewGrid) viewGrid.addEventListener('click', () => setView('grid'));
+if (viewList) viewList.addEventListener('click', () => setView('list'));
+
// Keep in sync if the user watches/unwatches a coin in another tab.
window.addEventListener('storage', (e) => {
if (e.key === WATCH_KEY) render();
if (e.key === ALERTS_KEY) updateAlertsBtn();
});
-// Pause refresh when tab is hidden, resume on visibility.
+function scheduleRefresh() {
+ clearTimeout(refreshTimer);
+ refreshTimer = setTimeout(async () => {
+ const list = readList();
+ if (list.length) {
+ await enrichWithOracleConviction(list);
+ fetchMovers(list);
+ }
+ scheduleRefresh();
+ }, REFRESH_MS);
+}
+
document.addEventListener('visibilitychange', () => {
if (document.hidden) clearTimeout(refreshTimer);
else scheduleRefresh();
});
+// ── boot ─────────────────────────────────────────────────────────────────────
+
+const imported = importFromUrl();
+// Reflect persisted prefs in the controls before first paint.
+setTierFilter(prefs.tier);
+applyView();
startParticleField();
render();
+if (imported) showAddMsg(`Imported ${imported} coin${imported === 1 ? '' : 's'} from a shared link.`, 'ok');
scheduleRefresh();
diff --git a/verify-trades-tmp.mjs b/verify-trades-tmp.mjs
index 8fd1be5f8..2f99da854 100644
--- a/verify-trades-tmp.mjs
+++ b/verify-trades-tmp.mjs
@@ -1,47 +1,31 @@
-import puppeteer from 'puppeteer';
-
+import { chromium } from 'playwright';
const URL = process.argv[2] || 'http://localhost:3001/trades';
-const browser = await puppeteer.launch({ args: ['--no-sandbox'], headless: 'new' });
-const page = await browser.newPage();
-await page.setViewport({ width: 1440, height: 1000 });
-
+const browser = await chromium.launch({ args: ['--no-sandbox'] });
+const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const errors = [];
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));
-
-await page.goto(URL, { waitUntil: 'networkidle2', timeout: 60000 }).catch((e) => errors.push('GOTO: ' + e.message));
-await new Promise((r) => setTimeout(r, 8000)); // let data + chart + bubblemap settle
-
+await page.goto(URL, { waitUntil: 'networkidle', timeout: 60000 }).catch((e) => errors.push('GOTO: ' + e.message));
+await page.waitForTimeout(9000);
const snap = await page.evaluate(() => {
- const txt = (sel) => document.querySelector(sel)?.textContent?.trim() || null;
- const feedRows = document.querySelectorAll('#ttFeed [data-mint]').length;
- const sections = [...document.querySelectorAll('.dd-card[data-section]')].map((c) => {
- const id = c.dataset.section;
- const b = c.querySelector('.dd-card-b');
- const skel = !!b?.querySelector('.dd-skel');
- const na = !!b?.querySelector('.dd-note--na');
- const filled = b && b.children.length > 0 && !skel;
- return { id, skel, na, filled, len: (b?.textContent || '').length };
- });
- return {
- title: document.title,
- heroSym: txt('.dd-hero-sym'),
- strip: txt('.dd-strip'),
- pulseMints: txt('#ttPulseMints'),
- pulseSol: txt('#ttPulseSol'),
- feedRows,
- hasChartCanvas: !!document.querySelector('.dd-chart canvas'),
- hasBubbleCanvas: !!document.querySelector('.bm-canvas'),
- tapeRows: document.querySelectorAll('.tp-row').length,
- tapeMsg: txt('.tp-msg'),
- sections,
- };
+ const txt = (s) => document.querySelector(s)?.textContent?.trim() || null;
+ const sections = [...document.querySelectorAll('.dd-card[data-section]')].map((c) => {
+ const b = c.querySelector('.dd-card-b');
+ return { id: c.dataset.section, skel: !!b?.querySelector('.dd-skel'), na: !!b?.querySelector('.dd-note--na'), len: (b?.textContent||'').length };
+ });
+ return {
+ heroSym: txt('.dd-hero-sym'), strip: txt('.dd-strip'),
+ pulseMints: txt('#ttPulseMints'), pulseSol: txt('#ttPulseSol'),
+ feedRows: document.querySelectorAll('#ttFeed [data-mint]').length,
+ chartCanvas: !!document.querySelector('.dd-chart canvas'),
+ bubbleCanvas: !!document.querySelector('.bm-canvas'),
+ bubbleEmpty: !!document.querySelector('.bm-empty'),
+ tapeRows: document.querySelectorAll('.tp-row').length,
+ sections,
+ };
});
-
-console.log('URL:', URL);
console.log(JSON.stringify(snap, null, 2));
-console.log('\nCONSOLE ERRORS (' + errors.length + '):');
-errors.slice(0, 25).forEach((e) => console.log(' •', e.slice(0, 200)));
-
+console.log('\nERRORS (' + errors.length + '):');
+errors.slice(0, 20).forEach((e) => console.log(' •', e.slice(0, 200)));
await page.screenshot({ path: '/tmp/claude-1000/-workspaces-three-ws/0a1c2957-b3c5-41d3-8b9b-dcdbdbe28417/scratchpad/trades.png', fullPage: true });
await browser.close();