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(portfolio): live wallet portfolio for any Solana or Ethereum address at /portfolio

nirholas3c6ff4e94e28
diff --git a/STRUCTURE.md b/STRUCTURE.md
index ef8f0b26e..60a4084f0 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -152,6 +152,7 @@ bottom.
| Earned autonomy (sniper fleet) | tier engine [api/_lib/sniper-autonomy.js](api/_lib/sniper-autonomy.js), tier-scaled optimizer [api/_lib/sniper-optimizer.js](api/_lib/sniper-optimizer.js) + cron [api/cron/sniper-optimize.js](api/cron/sniper-optimize.js), tier-weighted portfolio layer [scripts/sniper-evolve.mjs](scripts/sniper-evolve.mjs) + cron [api/cron/sniper-evolve.js](api/cron/sniper-evolve.js), judge knowledge pack [workers/agent-sniper/judge-knowledge.js](workers/agent-sniper/judge-knowledge.js) → [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | A trading arm's own realized record decides how much rope it gets, recomputed every optimizer run: `probation → standard → trusted → autonomous`. The tier scales how far and how fast the optimizer may move a knob, which fields it may touch at all (trusted unlocks the entry universe, the LLM confidence bar, and the take-initials ladder), how much of the fixed fleet budget the evolution loop concentrates on the arm, and how much real evidence the LLM judge is handed before it rules (base rate, learned signal weights, the arm's own record, the realized win-rate table, the model's own calibration). Decided on realized net P&L and average edge, never win rate, so a 36%-hit-rate arm that actually makes money earns room while a 60%-hit-rate arm that loses money does not. Symmetric: an arm that stops paying loses its tier on the next pass. No tier can reach a safety rail (firewall, Mayhem exclusion, price impact, concurrency, loss cap, fleet ceiling) and a bounded stop-loss survives every tier. Tests: [tests/sniper-autonomy.test.js](tests/sniper-autonomy.test.js), [tests/sniper-optimizer.test.js](tests/sniper-optimizer.test.js), [tests/sniper-judge-knowledge.test.js](tests/sniper-judge-knowledge.test.js). See [docs/sniper-autonomy.md](docs/sniper-autonomy.md) |
| Fleet stall diagnosis (why an arm is not trading) | policy [api/_lib/sniper-stall.js](api/_lib/sniper-stall.js), funding invariant [api/_lib/agent-funding-policy.js](api/_lib/agent-funding-policy.js), operational floor `MIN_OPERATIONAL_WALLET_SOL` in [api/_lib/agent-trade-guards.js](api/_lib/agent-trade-guards.js), board field on [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments`, ops page [workers/agent-sniper/alerts.js](workers/agent-sniper/alerts.js) | Live | An armed arm can evaluate every launch and still never buy, because a skipped evaluation writes no row: four arms sat dead for a week behind a bare `0`. Each armed strategy now reports a `stall` code the executor actually enforces (`wallet_dry`, `mcap_band_unreachable`, `mcap_band_tight`, `strict_model_offline`, `size_over_budget`, `kill_switch`, `no_qualifying_launch`), and the two arithmetic deadlocks behind them are gone: an entry clamps to the day's remaining budget instead of sitting out when size drifted above the cap, and the reclaim that pulls idle SOL back to the treasury can no longer take a trading wallet below one complete trade or below the level the auto-funder will instantly restore (the two crons were ping-ponging 0.24 SOL six times in 15 minutes). Tests: [tests/sniper-stall.test.js](tests/sniper-stall.test.js), [tests/economy-sweepback.test.js](tests/economy-sweepback.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md), [docs/economy-master.md](docs/economy-master.md) |
| Autonomous trading experiment | policy [scripts/trading-experiment-setup.mjs](scripts/trading-experiment-setup.mjs), laddered exit [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`decideLadderedExit`), no-Mayhem gate [workers/agent-sniper/mayhem-gate.js](workers/agent-sniper/mayhem-gate.js), journal [workers/agent-sniper/journal.js](workers/agent-sniper/journal.js) → [api/sniper/journal.js](api/sniper/journal.js) | In-repo | One agent, ~10 SOL, newer pump.fun launches ($10k–$100k mcap, no Mayhem). Take-initials-at-2× laddered exit keeps a moon bag (never a 100% exit up), hard stop-loss underneath. Every decision journaled with its reasoning. UI-funded, simulate-first. See [docs/trading-experiment.md](docs/trading-experiment.md) |
+| Wallet Portfolio (any-address viewer) | aggregation [api/_lib/portfolio-overview.js](api/_lib/portfolio-overview.js) (pure, tested in [tests/portfolio-overview.test.js](tests/portfolio-overview.test.js)), endpoint [api/crypto/portfolio.js](api/crypto/portfolio.js) `→ /api/crypto/portfolio`, page [pages/portfolio.html](pages/portfolio.html) + [src/portfolio.js](src/portfolio.js) + [src/portfolio.css](src/portfolio.css) `→ /portfolio` | Live | Live portfolio for any Solana or Ethereum wallet: total value, 24h move with stated coverage, stable/major/token split, top-asset allocation donut, holdings table with dust folding. Solana fully keyless (Helius DAS or public RPC + Jupiter Lite + DexScreener); EVM needs ALCHEMY_API_KEY and 503s honestly without it. Docs: [docs/portfolio.md](docs/portfolio.md). Wiring test: [tests/portfolio-page.test.js](tests/portfolio-page.test.js) |
| Exit Lab (counterfactual exit replay) | kernel [api/_lib/exit-replay.js](api/_lib/exit-replay.js), corpus [api/sniper/exit-lab.js](api/sniper/exit-lab.js) `→ /api/sniper/exit-lab`, page [pages/exit-lab.html](pages/exit-lab.html) + [src/exit-lab.js](src/exit-lab.js) `→ /exit-lab` | Live | Replays every REAL closed sniper position through the live `decideLadderedExit` with the exit rules changed, so the fleet can ask "were our exits right?" about SOL it already spent. The kernel is pure and is imported by BOTH the handler and the browser, so a slider move is instant and server and client can never disagree. Two-phase walk over the recorded path (entry to peak to final quote) mirroring the live partial-sell bookkeeping leg for leg. States its own limits on the page: earlier exits are exact, longer holds are a lower bound, laddered positions are excluded with a stated reason. Grid search is an exact enumeration, flagged as in-sample. Tests: [tests/exit-replay.test.js](tests/exit-replay.test.js), [tests/exit-lab-page.test.js](tests/exit-lab-page.test.js). Docs: [docs/exit-lab.md](docs/exit-lab.md), tutorial [docs/tutorials/find-a-better-exit-policy.md](docs/tutorials/find-a-better-exit-policy.md) |
| Shareable trade card (per closed trade) | model [api/_lib/trade-card.js](api/_lib/trade-card.js), loader [api/_lib/trade-card-store.js](api/_lib/trade-card-store.js), image [api/trade-og.js](api/trade-og.js) `→ /api/trade-og?id=`, page [api/trade-share.js](api/trade-share.js) `→ /trade/<position id>`, share link on every closed row in [src/trader.js](src/trader.js) | Live | The trader-level card answers "is this trader any good?"; this one answers "what just happened?" and is the artifact worth posting the minute a position closes. One closed `agent_sniper_positions` row becomes an SVG 1200x630 card (coin, result with its return multiple, SOL in/out, hold time, exit reason) plus an SSR page carrying per-trade Open Graph / Twitter / Farcaster meta, both legs linked to Solscan, and a one-tap post. Image and page render from ONE pure model, so the picture that unfurls and the page it lands on can never disagree about a number. Honest by construction: a loss renders exactly like a win, a simulate-mode fill is stamped PAPER and never counted as live, and a moon-bag exit says the position was not fully sold. Unknown, still-open or deleted trades fall back rather than break an unfurl. Tests: [tests/trade-card.test.js](tests/trade-card.test.js) |
| Never sell 100% of a winner (moon-bag policy) | rule [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`moonbagExitFraction`, `moonbagAlways`), retained-bag booking [workers/agent-sniper/executor.js](workers/agent-sniper/executor.js), position fields [api/_lib/migrations/20260725100000_sniper_moonbag_always.sql](api/_lib/migrations/20260725100000_sniper_moonbag_always.sql), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | Fleet-wide owner rule: a terminal exit that is IN PROFIT sells down to the moon-bag floor (default 15%) instead of to zero, and the retained tokens ride indefinitely. Once the cost basis is back the remainder is free, so a bag that goes to zero costs nothing and a bag that runs is the whole upside; selling the last slice for a rounding error gives that up. Applies with or without the proactive 2x ladder. A loss exit with the stake still at risk is still a FULL exit and the hard stop-loss is never overridden. The position still books `closed`, so realized P&L and the `max_concurrent_positions` slot are unaffected and a held bag can never stop an arm trading; only the tokens stay behind (`moonbag_base_amount`). Per-strategy opt-out `moonbag_always = false`. Tests: [tests/sniper-laddered-exit.test.js](tests/sniper-laddered-exit.test.js), [tests/trading-experiment-e2e.test.js](tests/trading-experiment-e2e.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md) |
diff --git a/api/_lib/portfolio-overview.js b/api/_lib/portfolio-overview.js
new file mode 100644
index 000000000..25c2f2699
--- /dev/null
+++ b/api/_lib/portfolio-overview.js
@@ -0,0 +1,237 @@
+// Pure aggregation layer for the public wallet portfolio overview
+// (/api/crypto/portfolio). Takes the balance shape produced by
+// api/_lib/balances.js getBalances() plus per-token 24h changes and derives
+// everything the /portfolio page renders: classification summary, top-asset
+// allocation, per-row shares, and an honest aggregate 24h move.
+//
+// Coin-agnostic plumbing: the wallet address is supplied at runtime by the
+// caller, and classification works on token symbols, never on a curated list
+// of promoted projects. Keeping this file pure (no fetch, no env) is what lets
+// tests/portfolio-overview.test.js pin the arithmetic with hand-computed
+// fixtures, mirroring the tests/portfolio.test.js pattern.
+//
+// Honesty rules (same contract as api/_lib/portfolio.js):
+// - A token with no known price keeps usd 0 in totals but is counted in
+// `unpricedCount` and never invents a valuation.
+// - The aggregate 24h change is computed ONLY over rows whose 24h change is
+// known; `coveragePct` states how much of the portfolio that covers, so the
+// UI can say "based on N% of value" instead of implying full coverage.
+
+// Symbol-level classification. Symbols are how every balance provider labels
+// holdings across both chain families, and the same symbol means the same
+// class on either chain. Uppercase-compared.
+export const STABLE_SYMBOLS = new Set([
+ 'USDC', 'USDT', 'DAI', 'USDS', 'USDE', 'FDUSD', 'PYUSD', 'TUSD', 'USDP',
+ 'GUSD', 'FRAX', 'LUSD', 'USDD', 'BUSD', 'EURC', 'USDY', 'USD1', 'USDG',
+ 'SUSD', 'CUSD', 'USDL', 'AUSD',
+]);
+
+// Majors: the chain-native reserve assets and their liquid wrappers/stakes.
+// Holding these is treated as reserve exposure, not memecoin risk, matching
+// the reserve framing in api/_lib/portfolio.js computeRisk().
+export const MAJOR_SYMBOLS = new Set([
+ 'SOL', 'WSOL', 'JITOSOL', 'MSOL', 'BSOL', 'JUPSOL', 'BNSOL', 'INF', 'HSOL',
+ 'ETH', 'WETH', 'STETH', 'WSTETH', 'RETH', 'CBETH', 'WEETH', 'EETH',
+ 'BTC', 'WBTC', 'TBTC', 'CBBTC', 'ZBTC',
+]);
+
+/**
+ * Classify a holding by its symbol.
+ * @param {string|null|undefined} symbol
+ * @returns {'stable'|'major'|'other'}
+ */
+export function classifyToken(symbol) {
+ const s = String(symbol || '').toUpperCase();
+ if (STABLE_SYMBOLS.has(s)) return 'stable';
+ if (MAJOR_SYMBOLS.has(s)) return 'major';
+ return 'other';
+}
+
+// How many named segments the allocation donut carries. Everything past the
+// cap folds into an "Other" bucket: the dataviz palette validates its
+// categorical slots as a set, and more segments than slots would force hue
+// cycling, which is banned.
+export const TOP_ASSET_SLOTS = 5;
+
+// Display rounding for USD figures: cents above $1, six significant digits
+// below so sub-cent token values survive. Same convention as api/crypto/wallet.js.
+function roundUsd(n) {
+ if (!(Number(n) > 0)) return 0;
+ return Number(n) < 1 ? Number(n.toPrecision(6)) : Math.round(n * 100) / 100;
+}
+
+function round2(n) {
+ return Number.isFinite(n) ? Math.round(n * 100) / 100 : 0;
+}
+
+/**
+ * Build the full overview from a getBalances() result.
+ *
+ * @param {object} balances getBalances() shape: { chain, address, native, tokens }
+ * @param {Map<string, number>|null} [changes] per-identifier 24h change in
+ * percent, keyed by mint/contract (and 'native' for the native asset).
+ * Entries here override any change24h already present on a token row, so a
+ * fresher enrichment pass always wins over a null baked into the snapshot.
+ * @param {{ maxRows?: number }} [opts]
+ * @returns {{
+ * totalUsd: number, unpricedCount: number,
+ * change24h: { usd: number, pct: number, coveragePct: number } | null,
+ * summary: Record<'stable'|'major'|'other', { usd: number, pct: number, count: number }>,
+ * topAssets: Array<{ symbol: string, name: string|null, usd: number, pct: number,
+ * slot: number, logo: string|null, id: string|null, count?: number }>,
+ * rows: Array<object>, tokenCount: number, truncated: boolean,
+ * }}
+ */
+export function buildOverview(balances, changes = null, opts = {}) {
+ const maxRows = opts.maxRows ?? 200;
+ const native = balances?.native || null;
+ const tokens = Array.isArray(balances?.tokens) ? balances.tokens : [];
+
+ const rows = [];
+ if (native && Number(native.amount) > 0) {
+ rows.push(shapeRow({
+ id: 'native',
+ symbol: native.symbol || (balances.chain === 'solana' ? 'SOL' : 'ETH'),
+ name: native.name || null,
+ kind: 'native',
+ amount: Number(native.amount) || 0,
+ price: Number(native.price) || 0,
+ usd: Number(native.usd) || 0,
+ change24h: pickChange(changes, 'native', native.change24h),
+ logo: native.logo || null,
+ }));
+ }
+ for (const t of tokens) {
+ const id = t.mint || t.contract || null;
+ rows.push(shapeRow({
+ id,
+ symbol: t.symbol || null,
+ name: t.name || null,
+ kind: 'token',
+ amount: Number(t.amount) || 0,
+ price: Number(t.price) || 0,
+ usd: Number(t.usd) || 0,
+ change24h: pickChange(changes, id, t.change24h),
+ logo: t.logo || null,
+ }));
+ }
+
+ rows.sort((a, b) => (b.usd || 0) - (a.usd || 0));
+
+ const totalUsd = rows.reduce((s, r) => s + (r.usd || 0), 0);
+ const unpricedCount = rows.filter((r) => r.amount > 0 && !(r.price > 0)).length;
+
+ for (const r of rows) {
+ r.sharePct = totalUsd > 0 ? round2(((r.usd || 0) / totalUsd) * 100) : 0;
+ }
+
+ const summary = {
+ stable: { usd: 0, pct: 0, count: 0 },
+ major: { usd: 0, pct: 0, count: 0 },
+ other: { usd: 0, pct: 0, count: 0 },
+ };
+ for (const r of rows) {
+ const bucket = summary[r.class];
+ bucket.usd += r.usd || 0;
+ if (r.amount > 0) bucket.count += 1;
+ }
+ for (const k of Object.keys(summary)) {
+ summary[k].pct = totalUsd > 0 ? round2((summary[k].usd / totalUsd) * 100) : 0;
+ summary[k].usd = roundUsd(summary[k].usd);
+ }
+
+ // Aggregate 24h move, exact per row: a token up c% today was worth
+ // usd / (1 + c/100) a day ago. Summed only over rows with a known change;
+ // coveragePct is the share of portfolio value those rows represent.
+ let deltaUsd = 0;
+ let coveredUsd = 0;
+ for (const r of rows) {
+ if (r.change24h == null || !(r.usd > 0)) continue;
+ const factor = 1 + r.change24h / 100;
+ if (!(factor > 0)) continue;
+ deltaUsd += r.usd - r.usd / factor;
+ coveredUsd += r.usd;
+ }
+ const prevCovered = coveredUsd - deltaUsd;
+ const change24h = coveredUsd > 0 && prevCovered > 0
+ ? {
+ usd: round2(deltaUsd),
+ pct: round2((deltaUsd / prevCovered) * 100),
+ coveragePct: totalUsd > 0 ? round2((coveredUsd / totalUsd) * 100) : 0,
+ }
+ : null;
+
+ // Allocation: merge rows by symbol (the same asset can appear as native +
+ // wrapped, or on several accounts), take the top slots, fold the rest.
+ const bySymbol = new Map();
+ for (const r of rows) {
+ if (!(r.usd > 0)) continue;
+ const key = (r.symbol || r.id || '?').toUpperCase();
+ const agg = bySymbol.get(key);
+ if (agg) {
+ agg.usd += r.usd;
+ } else {
+ bySymbol.set(key, { symbol: r.symbol || key, name: r.name, usd: r.usd, logo: r.logo, id: r.id });
+ }
+ }
+ const ranked = [...bySymbol.values()].sort((a, b) => b.usd - a.usd);
+ const topAssets = ranked.slice(0, TOP_ASSET_SLOTS).map((a, i) => ({
+ symbol: a.symbol,
+ name: a.name || null,
+ usd: roundUsd(a.usd),
+ pct: totalUsd > 0 ? round2((a.usd / totalUsd) * 100) : 0,
+ slot: i + 1,
+ logo: a.logo || null,
+ id: a.id || null,
+ }));
+ const rest = ranked.slice(TOP_ASSET_SLOTS);
+ if (rest.length > 0) {
+ const restUsd = rest.reduce((s, a) => s + a.usd, 0);
+ topAssets.push({
+ symbol: 'Other',
+ name: null,
+ usd: roundUsd(restUsd),
+ pct: totalUsd > 0 ? round2((restUsd / totalUsd) * 100) : 0,
+ slot: 0,
+ logo: null,
+ id: null,
+ count: rest.length,
+ });
+ }
+
+ const truncated = rows.length > maxRows;
+ return {
+ totalUsd: roundUsd(totalUsd),
+ unpricedCount,
+ change24h,
+ summary,
+ topAssets,
+ rows: rows.slice(0, maxRows).map((r) => ({ ...r, usd: r.price > 0 ? roundUsd(r.usd) : null })),
+ tokenCount: rows.length,
+ truncated,
+ };
+}
+
+function pickChange(changes, id, baked) {
+ if (changes && id != null && changes.has(id)) {
+ const v = changes.get(id);
+ return Number.isFinite(v) ? round2(v) : null;
+ }
+ return Number.isFinite(baked) ? round2(baked) : null;
+}
+
+function shapeRow({ id, symbol, name, kind, amount, price, usd, change24h, logo }) {
+ return {
+ id,
+ symbol,
+ name,
+ kind,
+ class: classifyToken(symbol),
+ amount,
+ price: price > 0 ? price : null,
+ usd,
+ change24h,
+ logo,
+ sharePct: 0,
+ };
+}
diff --git a/api/crypto/portfolio.js b/api/crypto/portfolio.js
new file mode 100644
index 000000000..0a99982d0
--- /dev/null
+++ b/api/crypto/portfolio.js
@@ -0,0 +1,190 @@
+// GET /api/crypto/portfolio - free, keyless portfolio overview for any wallet.
+//
+// The /portfolio page's data source, and part of the free crypto-data endpoint
+// family (same conventions as api/crypto/wallet.js). One call returns what a
+// portfolio view needs beyond raw balances: stable/major/other classification,
+// top-asset allocation with palette slots, per-row portfolio share, per-token
+// 24h price change, and an honest aggregate 24h move with its coverage stated.
+//
+// Chains: Solana first (fully keyless: Helius DAS when a key is present, public
+// RPC walk otherwise, Jupiter Lite + pump.fun curve prices), Ethereum via the
+// same getBalances() EVM path (needs ALCHEMY_API_KEY, degrades to 503).
+//
+// 24h changes: the EVM path already carries CoinGecko 24h changes per token.
+// Solana balances carry none, so this handler enriches the top holdings from
+// DexScreener's batch endpoint (30 mints per call, keyless) and SOL itself from
+// the multi-provider sol-price failover. Tokens beyond the enrichment cap keep
+// change24h null and the aggregate reports its actual coverage; nothing is
+// extrapolated.
+
+import { cors, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getBalances, heliusHealth } from '../_lib/balances.js';
+import { isValidAddressForChain } from '../_lib/splits.js';
+import { solChange24hPct } from '../_lib/sol-price.js';
+import { cacheWrap } from '../_lib/cache.js';
+import { buildOverview } from '../_lib/portfolio-overview.js';
+
+const CHAIN_ALIASES = {
+ solana: 'solana',
+ sol: 'solana',
+ ethereum: 'evm',
+ eth: 'evm',
+ evm: 'evm',
+ mainnet: 'evm',
+};
+
+// DexScreener batches up to 30 token addresses per request. Two batches cover
+// the top 60 holdings by value; beyond that is dust whose 24h move cannot
+// meaningfully shift the aggregate, and coveragePct reports the gap honestly.
+const DEXSCREENER_TOKENS = 'https://api.dexscreener.com/latest/dex/tokens/';
+const CHANGE_BATCH = 30;
+const CHANGE_BATCHES_MAX = 2;
+
+const OVERVIEW_TTL_S = 60;
+
+// Wrapped SOL tracks native SOL; pricing it off its own (thinner) pairs would
+// let the two report different moves for the same asset.
+const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+
+async function fetchSolanaChanges(tokens) {
+ const changes = new Map();
+
+ const [solPct, batchResults] = await Promise.all([
+ solChange24hPct().catch(() => null),
+ fetchDexScreenerChanges(tokens),
+ ]);
+ if (Number.isFinite(solPct)) {
+ changes.set('native', solPct);
+ changes.set(WSOL_MINT, solPct);
+ }
+ for (const [mint, pct] of batchResults) {
+ if (!changes.has(mint)) changes.set(mint, pct);
+ }
+ return changes;
+}
+
+async function fetchDexScreenerChanges(tokens) {
+ const mints = tokens
+ .filter((t) => t.mint && t.mint !== WSOL_MINT && Number(t.usd) > 0)
+ .sort((a, b) => (b.usd || 0) - (a.usd || 0))
+ .slice(0, CHANGE_BATCH * CHANGE_BATCHES_MAX)
+ .map((t) => t.mint);
+ if (!mints.length) return new Map();
+
+ const batches = [];
+ for (let i = 0; i < mints.length; i += CHANGE_BATCH) {
+ batches.push(mints.slice(i, i + CHANGE_BATCH));
+ }
+ const settled = await Promise.allSettled(batches.map(async (batch) => {
+ const r = await fetch(`${DEXSCREENER_TOKENS}${batch.map(encodeURIComponent).join(',')}`, {
+ headers: { Accept: 'application/json' },
+ signal: AbortSignal.timeout(6000),
+ });
+ if (!r.ok) return [];
+ const data = await r.json().catch(() => null);
+ return Array.isArray(data?.pairs) ? data.pairs : [];
+ }));
+
+ // A mint can be either side of many pairs; keep the change from its
+ // deepest-liquidity pair, the same pick rule as api/_lib/token-market.js.
+ const best = new Map();
+ const wanted = new Set(mints);
+ for (const res of settled) {
+ if (res.status !== 'fulfilled') continue;
+ for (const p of res.value) {
+ const liq = p?.liquidity?.usd ?? 0;
+ for (const side of [p?.baseToken, p?.quoteToken]) {
+ const addr = side?.address;
+ if (!addr || !wanted.has(addr)) continue;
+ const prev = best.get(addr);
+ if (!prev || liq > prev.liq) {
+ const pct = Number(p?.priceChange?.h24);
+ best.set(addr, { liq, pct: Number.isFinite(pct) ? pct : null });
+ }
+ }
+ }
+ }
+ const changes = new Map();
+ for (const [mint, { pct }] of best) {
+ if (pct != null) changes.set(mint, pct);
+ }
+ return changes;
+}
+
+function sourcesFor(chain) {
+ if (chain === 'solana') {
+ const h = heliusHealth();
+ const balanceSource = h.configured && h.available ? 'helius-das' : 'solana-rpc';
+ return [balanceSource, 'jupiter-lite', 'dexscreener'];
+ }
+ return ['alchemy', 'coingecko'];
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const ip = clientIp(req);
+ const [ipRl, globalRl] = await Promise.all([limits.cryptoDataIp(ip), limits.cryptoDataGlobal()]);
+ if (!ipRl.success || !globalRl.success) {
+ return error(res, 429, 'rate_limited', 'too many requests - slow down and retry shortly', {
+ retryAfter: 60,
+ });
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const address = (url.searchParams.get('address') || '').trim();
+ const rawChain = (url.searchParams.get('chain') || 'solana').trim().toLowerCase();
+
+ if (!address) {
+ return error(res, 400, 'missing_address', 'pass ?address=<wallet> (a Solana or EVM address)', {
+ example: '/api/crypto/portfolio?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',
+ });
+ }
+ const chain = CHAIN_ALIASES[rawChain];
+ if (!chain) {
+ return error(res, 400, 'unsupported_chain', `chain "${rawChain}" is not supported`, {
+ supported: ['solana', 'ethereum'],
+ });
+ }
+ if (!isValidAddressForChain(address, chain)) {
+ return error(res, 400, 'invalid_address', `not a valid ${chain === 'solana' ? 'Solana' : 'EVM'} address`, {
+ example: '/api/crypto/portfolio?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=solana',
+ });
+ }
+
+ let body;
+ try {
+ body = await cacheWrap(`pfovw:${chain}:${address}`, OVERVIEW_TTL_S, async () => {
+ const balances = await getBalances({ chain, address });
+ const changes = chain === 'solana'
+ ? await fetchSolanaChanges(balances.tokens || [])
+ : null;
+ const overview = buildOverview(balances, changes);
+ return {
+ address,
+ chain: chain === 'solana' ? 'solana' : 'ethereum',
+ ...overview,
+ ...(balances.stale ? { stale: true } : {}),
+ ts: new Date().toISOString(),
+ sources: sourcesFor(chain),
+ };
+ });
+ } catch (err) {
+ if (err?.code === 'not_configured') {
+ return error(res, 503, 'not_configured', 'this chain requires a provider key that is not set on this deployment - Solana works keyless', {
+ chain: rawChain,
+ });
+ }
+ res.setHeader('retry-after', '15');
+ return error(res, 503, 'upstream_unavailable', 'wallet data source is temporarily unavailable - retry shortly', {
+ retryAfter: 15,
+ });
+ }
+
+ res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(body));
+});
diff --git a/data/pages.json b/data/pages.json
index 6804f3d3f..8da8991dc 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1267,6 +1267,14 @@
"changefreq": "always",
"added": "2026-06-27"
},
+ {
+ "path": "/portfolio",
+ "title": "Wallet Portfolio",
+ "description": "A live portfolio view for any Solana or Ethereum wallet: total value, 24h move with honest coverage, stablecoin/major/token breakdown, top-asset allocation, and every holding priced in real time. Free, keyless, deep-linkable, no account.",
+ "priority": 0.8,
+ "changefreq": "always",
+ "added": "2026-08-06"
+ },
{
"path": "/launcher",
"title": "Memetic Launcher",
@@ -4821,6 +4829,14 @@
"priority": 0.6,
"changefreq": "monthly",
"added": "2026-08-02"
+ },
+ {
+ "path": "/docs/portfolio",
+ "title": "Docs · Wallet Portfolio",
+ "description": "How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-08-06"
}
]
},
diff --git a/docs/portfolio.md b/docs/portfolio.md
new file mode 100644
index 000000000..9a628afd8
--- /dev/null
+++ b/docs/portfolio.md
@@ -0,0 +1,104 @@
+# Wallet Portfolio
+
+**Live surface: [three.ws/portfolio](https://three.ws/portfolio)**
+
+Paste any Solana or Ethereum address and get a live portfolio: total value, the
+24h move, a stablecoin/major/token breakdown, top-asset allocation, and every
+holding priced in real time. Free, keyless, no account, and every portfolio has
+a shareable URL.
+
+---
+
+## What the page shows
+
+Top to bottom:
+
+- **Value card**: total USD value, a 24h change pill (absolute and percent), and
+ the address with copy, explorer, and share-link actions.
+- **Summary cards**: holdings split three ways. *Stablecoins* (USDC, USDT, DAI
+ and the rest of the recognized set), *Majors* (SOL, ETH, BTC and their liquid
+ wrappers and stakes: jitoSOL, mSOL, wstETH, WBTC, ...), and *Tokens*
+ (everything else). Reserve next to open risk, at a glance.
+- **Allocation donut**: the top 5 assets by value plus an "Other" fold, with a
+ legend carrying exact percentages and values. Hover or focus a segment for
+ detail.
+- **Holdings table**: every position with its portfolio share, amount, live
+ price, 24h change, and value. Balances under 1% are folded behind a
+ "show all" banner so a dust-filled wallet stays readable.
+
+Deep links work: `/portfolio?address=<wallet>&chain=solana` renders the same
+live view for anyone who opens it.
+
+## Where the numbers come from
+
+The page calls one endpoint:
+
+```
+GET /api/crypto/portfolio?address=<wallet>&chain=solana|ethereum
+```
+
+which builds on the same balance layer as
+[`/api/crypto/wallet`](crypto-api.md) ([`api/_lib/balances.js`](../api/_lib/balances.js)):
+
+- **Solana** (fully keyless): Helius DAS when a key is configured, public RPC
+ otherwise; prices from Jupiter Lite with a pump.fun bonding-curve fallback;
+ per-token 24h changes from DexScreener's batch endpoint; SOL's own 24h move
+ from a multi-provider failover.
+- **Ethereum**: Alchemy balances with CoinGecko prices and 24h changes. Requires
+ a provider key on the deployment; without one the endpoint returns an honest
+ `503 not_configured`, never fabricated data.
+
+Classification and aggregation are pure functions in
+[`api/_lib/portfolio-overview.js`](../api/_lib/portfolio-overview.js), unit-tested
+with hand-computed fixtures in
+[`tests/portfolio-overview.test.js`](../tests/portfolio-overview.test.js).
+
+## Honesty rules
+
+The same contract as the rest of the platform's money surfaces:
+
+- A token with no price route is listed with its amount and marked *unpriced*.
+ It is never given an invented valuation and never silently dropped.
+- The aggregate 24h move is computed only over holdings whose price history is
+ known, and the response states the exact share of value that covers
+ (`change24h.coveragePct`). The UI repeats it: "past 24h, based on N% of value".
+- If every live source fails, the endpoint serves the wallet's last confirmed
+ snapshot flagged `stale: true`, and the page shows a banner saying so.
+
+## Response shape
+
+```json
+{
+ "address": "…",
+ "chain": "solana",
+ "totalUsd": 1234.56,
+ "unpricedCount": 2,
+ "change24h": { "usd": 31.2, "pct": 2.59, "coveragePct": 97.4 },
+ "summary": {
+ "stable": { "usd": 200, "pct": 16.2, "count": 1 },
+ "major": { "usd": 800, "pct": 64.8, "count": 2 },
+ "other": { "usd": 234.56, "pct": 19, "count": 5 }
+ },
+ "topAssets": [
+ { "symbol": "SOL", "usd": 800, "pct": 64.8, "slot": 1, "logo": "…", "id": "native" }
+ ],
+ "rows": [
+ { "id": "…", "symbol": "SOL", "kind": "native", "class": "major", "amount": 4.2, "price": 190.4, "usd": 800, "change24h": 2.1, "sharePct": 64.8 }
+ ],
+ "tokenCount": 8,
+ "truncated": false,
+ "ts": "2026-08-06T20:00:00.000Z",
+ "sources": ["helius-das", "jupiter-lite", "dexscreener"]
+}
+```
+
+Rows are capped at the top 200 by value (`truncated: true` flags the rest), and
+responses are cached for about a minute per wallet.
+
+## Related surfaces
+
+- [`/wallet`](user-wallet.md): your own custodial three.ws wallet.
+- `/agent-wallet`: the agent wallet hub, whose Portfolio tab covers an agent's
+ holdings with FIFO cost basis and PnL attribution.
+- [`/api/crypto/wallet`](crypto-api.md): the raw balances endpoint this page
+ builds on, for agents and scripts.
diff --git a/pages/portfolio.html b/pages/portfolio.html
new file mode 100644
index 000000000..76552f8bd
--- /dev/null
+++ b/pages/portfolio.html
@@ -0,0 +1,215 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Wallet Portfolio · three.ws</title>
+ <meta
+ name="description"
+ content="A live portfolio view for any Solana or Ethereum wallet: total value, 24h move, stable/major/token breakdown, allocation, and every holding priced in real time. Free, keyless, no account."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/portfolio" />
+ <meta property="og:title" content="Wallet Portfolio · three.ws" />
+ <meta
+ property="og:description"
+ content="Paste any Solana or Ethereum address and get a live portfolio: total value, 24h move, allocation, and every holding priced in real time."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Wallet+Portfolio&amp;d=A+live+portfolio+view+for+any+Solana+or+Ethereum+wallet%3A+total+value%2C+24h+move+with+honest+coverage%2C+stablecoin%2Fmajor%2Ftoken+breakdown%2C+top-asset+allocation&amp;p=%2Fportfolio" />
+ <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:site" content="@trythreews" />
+ <meta name="twitter:title" content="Wallet Portfolio · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Paste any Solana or Ethereum address and get a live portfolio: total value, 24h move, allocation, and every holding priced in real time."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Wallet+Portfolio&amp;d=A+live+portfolio+view+for+any+Solana+or+Ethereum+wallet%3A+total+value%2C+24h+move+with+honest+coverage%2C+stablecoin%2Fmajor%2Ftoken+breakdown%2C+top-asset+allocation&amp;p=%2Fportfolio" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/coin-pages.css" />
+ <link rel="stylesheet" href="/src/portfolio.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/portfolio" />
+ <script type="application/ld+json">
+ {"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Wallet Portfolio","applicationCategory":"FinanceApplication","operatingSystem":"Any","description":"A live portfolio view for any Solana or Ethereum wallet: total value, 24h move, allocation, and every holding priced in real time.","url":"https://three.ws/portfolio","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Wallet Portfolio","item":"https://three.ws/portfolio"}]}]}
+ </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="Wallet Portfolio · three.ws" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="pf-shell cv-container">
+ <section class="pf-hero">
+ <p class="pf-kicker"><span class="pf-live-dot" aria-hidden="true"></span> Live prices · any wallet</p>
+ <h1 class="pf-title">Wallet <em>Portfolio</em></h1>
+ <p class="pf-sub">
+ Paste any <strong>Solana</strong> or <strong>Ethereum</strong> address and get a live portfolio:
+ total value, 24h move, allocation, and every holding priced in real time. Free, keyless, no account.
+ </p>
+ <form class="pf-form" id="pf-form" role="search" aria-label="Look up a wallet">
+ <label class="pf-visually-hidden" for="pf-address">Wallet address</label>
+ <input
+ id="pf-address"
+ class="pf-input"
+ type="text"
+ inputmode="text"
+ autocomplete="off"
+ spellcheck="false"
+ placeholder="Wallet address (Solana or 0x…)"
+ aria-describedby="pf-form-hint"
+ />
+ <label class="pf-visually-hidden" for="pf-chain">Chain</label>
+ <select id="pf-chain" class="pf-select" aria-label="Chain">
+ <option value="solana" selected>Solana</option>
+ <option value="ethereum">Ethereum</option>
+ </select>
+ <button type="submit" class="pf-go" id="pf-go">View portfolio</button>
+ </form>
+ <p class="pf-form-hint" id="pf-form-hint">Press <kbd>/</kbd> to focus. The chain is detected from the address automatically.</p>
+ <div class="pf-recent" id="pf-recent" hidden>
+ <span class="pf-recent-label">Recent:</span>
+ <span id="pf-recent-list"></span>
+ </div>
+ </section>
+
+ <section class="pf-intro" id="pf-intro">
+ <div class="pf-intro-grid">
+ <div class="pf-intro-card">
+ <h2>Every holding, priced</h2>
+ <p>Native balance and every token in the wallet, valued live. Tokens with no route to a price are listed honestly as unpriced, never guessed.</p>
+ </div>
+ <div class="pf-intro-card">
+ <h2>Reserve vs. risk</h2>
+ <p>Holdings are split into stablecoins, majors (SOL, ETH, BTC and their liquid stakes), and everything else, so you can see dry powder next to open risk.</p>
+ </div>
+ <div class="pf-intro-card">
+ <h2>Deep-linkable</h2>
+ <p>Every portfolio has a URL. Share the link and anyone sees the same live view, straight from the chain.</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="pf-report" id="pf-report" hidden aria-live="polite">
+ <div class="pf-stale" id="pf-stale" hidden>
+ Live sources are unreachable right now. Showing this wallet's last confirmed snapshot.
+ </div>
+
+ <div class="pf-value-card">
+ <div class="pf-value-main">
+ <div class="pf-addr-row">
+ <span class="pf-addr" id="pf-addr" title=""></span>
+ <span class="pf-chain-tag" id="pf-chain-tag"></span>
+ <button type="button" class="pf-chip-btn" id="pf-copy-addr" aria-label="Copy address">Copy</button>
+ <a class="pf-chip-btn" id="pf-explorer" href="#" target="_blank" rel="noopener noreferrer">Explorer</a>
+ <button type="button" class="pf-chip-btn" id="pf-share" aria-label="Copy link to this portfolio">Share</button>
+ </div>
+ <p class="pf-total-label">Total value</p>
+ <p class="pf-total" id="pf-total">$0.00</p>
+ <div class="pf-change-row">
+ <span class="pf-change-pill" id="pf-change" hidden></span>
+ <span class="pf-change-note" id="pf-change-note" hidden></span>
+ </div>
+ </div>
+ <div class="pf-value-side">
+ <dl class="pf-summary" id="pf-summary">
+ <div class="pf-sum-card" data-class="stable">
+ <dt>Stablecoins</dt>
+ <dd id="pf-sum-stable">$0</dd>
+ <span class="pf-sum-sub" id="pf-sum-stable-sub"></span>
+ </div>
+ <div class="pf-sum-card" data-class="major">
+ <dt>Majors</dt>
+ <dd id="pf-sum-major">$0</dd>
+ <span class="pf-sum-sub" id="pf-sum-major-sub"></span>
+ </div>
+ <div class="pf-sum-card" data-class="other">
+ <dt>Tokens</dt>
+ <dd id="pf-sum-other">$0</dd>
+ <span class="pf-sum-sub" id="pf-sum-other-sub"></span>
+ </div>
+ </dl>
+ </div>
+ </div>
+
+ <div class="pf-columns">
+ <section class="pf-card pf-alloc-card" aria-label="Allocation">
+ <div class="pf-card-h">Allocation <small id="pf-alloc-sub"></small></div>
+ <div class="pf-alloc-body">
+ <div class="pf-donut-wrap">
+ <svg id="pf-donut" viewBox="0 0 120 120" role="img" aria-label="Portfolio allocation donut chart" width="180" height="180"></svg>
+ <div class="pf-donut-center" id="pf-donut-center" aria-hidden="true"></div>
+ </div>
+ <ul class="pf-legend" id="pf-legend"></ul>
+ </div>
+ </section>
+ <section class="pf-card pf-meta-card" aria-label="About this data">
+ <div class="pf-card-h">Data</div>
+ <dl class="pf-meta" id="pf-meta"></dl>
+ <p class="pf-fineprint">
+ Balances and prices are read live per request and cached for about a minute.
+ The 24h move covers the share of value with known price history; the coverage is stated, never assumed.
+ Unpriced tokens keep their amounts and are excluded from totals.
+ </p>
+ </section>
+ </div>
+
+ <section class="pf-card pf-holdings-card" aria-label="Holdings">
+ <div class="pf-card-h">
+ Holdings <small id="pf-holdings-count"></small>
+ <label class="pf-toggle"><input type="checkbox" id="pf-show-small" /> Show balances under 1%</label>
+ </div>
+ <div class="pf-table-wrap">
+ <table class="pf-table" id="pf-table">
+ <thead>
+ <tr>
+ <th scope="col">Asset</th>
+ <th scope="col">Share</th>
+ <th scope="col">Amount</th>
+ <th scope="col">Price</th>
+ <th scope="col">24h</th>
+ <th scope="col">Value</th>
+ </tr>
+ </thead>
+ <tbody id="pf-rows"></tbody>
+ </table>
+ </div>
+ <button type="button" class="pf-small-banner" id="pf-small-banner" hidden></button>
+ </section>
+ </section>
+
+ <section class="pf-state" id="pf-loading" hidden aria-label="Loading portfolio">
+ <div class="pf-skel pf-skel-value"><span class="a"></span><span class="b"></span><span class="c"></span></div>
+ <div class="pf-skel pf-skel-table"><span class="c"></span><span class="c"></span><span class="c"></span><span class="c"></span><span class="c"></span></div>
+ </section>
+
+ <section class="pf-state pf-error" id="pf-error" hidden>
+ <h2 id="pf-error-title">Could not load this wallet</h2>
+ <p id="pf-error-body"></p>
+ <button type="button" class="pf-go" id="pf-retry">Retry</button>
+ </section>
+
+ <section class="pf-state pf-empty" id="pf-empty" hidden>
+ <h2>This wallet is empty</h2>
+ <p>No native balance and no tokens found at this address on <span id="pf-empty-chain"></span>. If you expected holdings here, check the address and chain, or try the other chain.</p>
+ </section>
+ </main>
+
+ <script type="module" src="/src/portfolio.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/nav-data.js b/public/nav-data.js
index 3583411b2..96b4541e6 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -335,6 +335,13 @@ export const NAV_GROUPS = [
href: '/deployments',
desc: 'Live cross-chain feed of every agent registered on the ERC-8004 Identity Registry, as it lands on-chain',
},
+ {
+ title: 'Wallet Portfolio',
+ href: '/portfolio',
+ badge: 'New',
+ badgeTone: 'new',
+ desc: 'Live portfolio for any Solana or Ethereum wallet: total value, 24h move, allocation & every holding priced',
+ },
{
title: 'Minted 3D Assets',
href: '/minted',
diff --git a/src/portfolio.css b/src/portfolio.css
new file mode 100644
index 000000000..f48b36f67
--- /dev/null
+++ b/src/portfolio.css
@@ -0,0 +1,730 @@
+/* /portfolio: live wallet portfolio viewer. Builds on the shared markets layer
+ * (src/coin-pages.css, --cv-*) for surfaces/type and on public/tokens.css for
+ * motion and focus floors. Chart series colors are the dataviz-validated
+ * categorical palette (5 slots + neutral Other), stepped per theme; slots are
+ * assigned by rank order server-side and never cycled. */
+
+.pf-shell {
+ --pf-series-1: #3987e5;
+ --pf-series-2: #d95926;
+ --pf-series-3: #199e70;
+ --pf-series-4: #c98500;
+ --pf-series-5: #d55181;
+ --pf-series-other: #6b7280;
+ --pf-up: var(--cv-green, #16a34a);
+ --pf-down: var(--cv-red, #dc2626);
+ padding-top: calc(var(--header-h, 64px) + 2rem);
+ padding-bottom: 4rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1.75rem;
+ font-family: var(--cv-font-sans, 'Inter', system-ui, sans-serif);
+ color: var(--cv-text, #fafafa);
+}
+:root[data-theme='light'] .pf-shell {
+ --pf-series-1: #2a78d6;
+ --pf-series-2: #eb6834;
+ --pf-series-3: #1baf7a;
+ --pf-series-4: #eda100;
+ --pf-series-5: #e87ba4;
+ --pf-series-other: #9ca3af;
+}
+
+.pf-visually-hidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+/* ---------------- Hero + lookup form ---------------- */
+
+.pf-hero { max-width: 46rem; }
+.pf-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.72rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--cv-text-3, #64748b);
+ margin: 0 0 0.6rem;
+}
+.pf-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--pf-up);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--pf-up) 55%, transparent);
+ animation: pf-pulse 2s ease-out infinite;
+}
+@keyframes pf-pulse {
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--pf-up) 50%, transparent); }
+ 70% { box-shadow: 0 0 0 6px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+.pf-title {
+ font-family: var(--cv-font-serif, 'Space Grotesk', sans-serif);
+ font-size: clamp(2rem, 5.5vw, 3rem);
+ line-height: 1.05;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.75rem;
+}
+.pf-title em {
+ font-style: normal;
+ color: var(--cv-accent, #60a5fa);
+}
+.pf-sub {
+ color: var(--cv-text-2, #a1a1aa);
+ line-height: 1.6;
+ margin: 0 0 1.4rem;
+}
+
+.pf-form {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+.pf-input {
+ flex: 1 1 20rem;
+ min-width: 0;
+ font: inherit;
+ font-family: var(--cv-font-mono, ui-monospace, monospace);
+ font-size: 0.85rem;
+ color: var(--cv-text, #fafafa);
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.65rem 0.85rem;
+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-input:hover { border-color: var(--cv-border-hover, #3f3f46); }
+.pf-input:focus-visible {
+ outline: none;
+ border-color: var(--cv-accent, #60a5fa);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--cv-accent, #60a5fa) 25%, transparent);
+}
+.pf-select {
+ font: inherit;
+ font-size: 0.85rem;
+ color: var(--cv-text, #fafafa);
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.65rem 0.85rem;
+ cursor: pointer;
+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-select:hover { border-color: var(--cv-border-hover, #3f3f46); }
+.pf-go {
+ font: inherit;
+ font-size: 0.85rem;
+ font-weight: 600;
+ color: #fff;
+ background: var(--cv-accent, #3b82f6);
+ border: none;
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.65rem 1.1rem;
+ cursor: pointer;
+ transition:
+ background var(--duration-fast, 140ms) var(--ease-standard, ease),
+ transform var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-go:hover { background: var(--cv-accent-hover, #2563eb); }
+.pf-go:active { transform: translateY(1px); }
+.pf-form-hint {
+ font-size: 0.75rem;
+ color: var(--cv-text-3, #64748b);
+ margin: 0.6rem 0 0;
+}
+.pf-form-hint kbd {
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.7rem;
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: 4px;
+ padding: 0.05rem 0.35rem;
+ background: var(--cv-surface-2, #131316);
+}
+
+.pf-recent {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ margin-top: 0.9rem;
+ font-size: 0.78rem;
+}
+.pf-recent-label { color: var(--cv-text-3, #64748b); }
+.pf-recent-chip {
+ font: inherit;
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.72rem;
+ color: var(--cv-text-2, #a1a1aa);
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: 999px;
+ padding: 0.25rem 0.7rem;
+ cursor: pointer;
+ transition:
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease),
+ color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-recent-chip:hover {
+ border-color: var(--cv-accent, #60a5fa);
+ color: var(--cv-text, #fafafa);
+}
+
+/* ---------------- Intro (pre-lookup state) ---------------- */
+
+.pf-intro-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
+ gap: 0.9rem;
+}
+.pf-intro-card {
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-lg, 10px);
+ padding: 1.1rem 1.2rem;
+ transition:
+ transform var(--duration-fast, 140ms) var(--ease-standard, ease),
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-intro-card:hover {
+ transform: translateY(-2px);
+ border-color: var(--cv-border-hover, #3f3f46);
+}
+.pf-intro-card h2 {
+ font-size: 0.95rem;
+ margin: 0 0 0.4rem;
+}
+.pf-intro-card p {
+ font-size: 0.82rem;
+ color: var(--cv-text-2, #a1a1aa);
+ line-height: 1.55;
+ margin: 0;
+}
+
+/* ---------------- Report ---------------- */
+
+.pf-report {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+.pf-report.pf-enter > * {
+ animation: pf-rise 0.45s var(--ease-out, cubic-bezier(0.2, 0.7, 0.2, 1)) both;
+}
+.pf-report.pf-enter > *:nth-child(2) { animation-delay: 0.06s; }
+.pf-report.pf-enter > *:nth-child(3) { animation-delay: 0.12s; }
+.pf-report.pf-enter > *:nth-child(4) { animation-delay: 0.18s; }
+@keyframes pf-rise {
+ from { opacity: 0; transform: translateY(10px); }
+ to { opacity: 1; transform: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .pf-report.pf-enter > * { animation: none; }
+ .pf-live-dot { animation: none; }
+}
+
+.pf-stale {
+ font-size: 0.8rem;
+ color: var(--warn, #fbbf24);
+ background: color-mix(in srgb, var(--warn, #fbbf24) 10%, transparent);
+ border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 35%, transparent);
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.6rem 0.9rem;
+}
+
+.pf-value-card {
+ display: flex;
+ gap: 1.5rem;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-xl, 12px);
+ padding: 1.4rem 1.5rem;
+}
+.pf-value-main { min-width: 0; }
+.pf-addr-row {
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.9rem;
+}
+.pf-addr {
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.78rem;
+ color: var(--cv-text-2, #a1a1aa);
+}
+.pf-chain-tag {
+ font-size: 0.66rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--cv-accent, #60a5fa);
+ border: 1px solid color-mix(in srgb, var(--cv-accent, #60a5fa) 40%, transparent);
+ border-radius: 999px;
+ padding: 0.1rem 0.5rem;
+}
+.pf-chip-btn {
+ font: inherit;
+ font-size: 0.7rem;
+ color: var(--cv-text-3, #64748b);
+ background: none;
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: 999px;
+ padding: 0.15rem 0.6rem;
+ cursor: pointer;
+ text-decoration: none;
+ transition:
+ color var(--duration-fast, 140ms) var(--ease-standard, ease),
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-chip-btn:hover {
+ color: var(--cv-text, #fafafa);
+ border-color: var(--cv-border-hover, #3f3f46);
+}
+.pf-chip-btn.pf-chip-ok {
+ color: var(--pf-up);
+ border-color: color-mix(in srgb, var(--pf-up) 45%, transparent);
+}
+.pf-total-label {
+ font-size: 0.72rem;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--cv-text-3, #64748b);
+ margin: 0;
+}
+.pf-total {
+ font-size: clamp(2.1rem, 6vw, 2.9rem);
+ font-weight: 750;
+ letter-spacing: -0.02em;
+ line-height: 1.05;
+ margin: 0.25rem 0 0;
+ font-variant-numeric: tabular-nums;
+}
+.pf-change-row {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ flex-wrap: wrap;
+ margin-top: 0.6rem;
+}
+.pf-change-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.8rem;
+ font-weight: 600;
+ border-radius: 999px;
+ padding: 0.25rem 0.7rem;
+ font-variant-numeric: tabular-nums;
+}
+.pf-change-pill.up { color: var(--pf-up); background: var(--cv-green-soft, rgba(34, 197, 94, 0.1)); }
+.pf-change-pill.down { color: var(--pf-down); background: var(--cv-red-soft, rgba(239, 68, 68, 0.1)); }
+.pf-change-note {
+ font-size: 0.72rem;
+ color: var(--cv-text-3, #64748b);
+}
+
+.pf-summary {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(7rem, 1fr));
+ gap: 0.7rem;
+ margin: 0;
+}
+.pf-sum-card {
+ position: relative;
+ background: var(--cv-surface-3, #1c1c21);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.8rem 0.9rem 0.8rem 1.05rem;
+ overflow: hidden;
+ transition:
+ transform var(--duration-fast, 140ms) var(--ease-standard, ease),
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-sum-card:hover {
+ transform: translateY(-2px);
+ border-color: var(--cv-border-hover, #3f3f46);
+}
+.pf-sum-card::before {
+ content: '';
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 3px;
+ background: var(--pf-series-other);
+ opacity: 0.85;
+}
+.pf-sum-card[data-class='stable']::before { background: var(--pf-series-3); }
+.pf-sum-card[data-class='major']::before { background: var(--pf-series-1); }
+.pf-sum-card[data-class='other']::before { background: var(--pf-series-2); }
+.pf-sum-card dt {
+ font-size: 0.68rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--cv-text-3, #64748b);
+}
+.pf-sum-card dd {
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 1.05rem;
+ font-weight: 700;
+ margin: 0.25rem 0 0;
+ font-variant-numeric: tabular-nums;
+}
+.pf-sum-sub {
+ display: block;
+ font-size: 0.68rem;
+ color: var(--cv-text-3, #64748b);
+ margin-top: 0.15rem;
+ font-variant-numeric: tabular-nums;
+}
+
+/* ---------------- Cards / columns ---------------- */
+
+.pf-columns {
+ display: grid;
+ grid-template-columns: minmax(0, 3fr) minmax(0, 2fr);
+ gap: 1rem;
+}
+@media (max-width: 860px) {
+ .pf-columns { grid-template-columns: 1fr; }
+ .pf-summary { grid-template-columns: repeat(auto-fit, minmax(7rem, 1fr)); width: 100%; }
+ .pf-value-card { flex-direction: column; }
+}
+.pf-card {
+ background: var(--cv-surface-2, #131316);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-xl, 12px);
+ padding: 1.1rem 1.25rem;
+}
+.pf-card-h {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5rem;
+ font-size: 0.85rem;
+ font-weight: 650;
+ margin-bottom: 0.9rem;
+}
+.pf-card-h small {
+ font-size: 0.7rem;
+ font-weight: 400;
+ color: var(--cv-text-3, #64748b);
+}
+.pf-toggle {
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ font-size: 0.72rem;
+ font-weight: 400;
+ color: var(--cv-text-3, #64748b);
+ cursor: pointer;
+ user-select: none;
+}
+.pf-toggle input { accent-color: var(--cv-accent, #3b82f6); cursor: pointer; }
+
+/* ---------------- Donut + legend ---------------- */
+
+.pf-alloc-body {
+ display: flex;
+ align-items: center;
+ gap: 1.4rem;
+ flex-wrap: wrap;
+}
+.pf-donut-wrap { position: relative; flex: 0 0 auto; }
+.pf-donut-center {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ pointer-events: none;
+}
+.pf-donut-center b {
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.95rem;
+ font-variant-numeric: tabular-nums;
+}
+.pf-donut-center span {
+ font-size: 0.62rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--cv-text-3, #64748b);
+}
+#pf-donut path {
+ transition: opacity var(--duration-fast, 140ms) var(--ease-standard, ease);
+ cursor: pointer;
+}
+#pf-donut.pf-donut-focus path { opacity: 0.35; }
+#pf-donut.pf-donut-focus path.pf-seg-active { opacity: 1; }
+.pf-legend {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+ flex: 1 1 12rem;
+ min-width: 0;
+}
+.pf-legend li {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto auto;
+ align-items: center;
+ gap: 0.55rem;
+ font-size: 0.8rem;
+ padding: 0.25rem 0.4rem;
+ border-radius: var(--cv-radius-sm, 4px);
+ transition: background var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-legend li:hover { background: var(--cv-surface-3, #1c1c21); }
+.pf-legend i {
+ width: 10px;
+ height: 10px;
+ border-radius: 3px;
+ background: var(--c, var(--pf-series-other));
+ flex: none;
+}
+.pf-legend .sym {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-weight: 600;
+}
+.pf-legend .pct,
+.pf-legend .val {
+ font-family: var(--cv-font-mono, monospace);
+ font-size: 0.75rem;
+ color: var(--cv-text-2, #a1a1aa);
+ font-variant-numeric: tabular-nums;
+}
+
+.pf-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ margin: 0;
+}
+.pf-meta > div {
+ display: flex;
+ justify-content: space-between;
+ gap: 1rem;
+ font-size: 0.78rem;
+ border-bottom: 1px solid var(--cv-border, #27272a);
+ padding-bottom: 0.5rem;
+}
+.pf-meta > div:last-child { border-bottom: none; }
+.pf-meta dt { color: var(--cv-text-3, #64748b); }
+.pf-meta dd {
+ margin: 0;
+ font-family: var(--cv-font-mono, monospace);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+.pf-fineprint {
+ font-size: 0.72rem;
+ color: var(--cv-text-3, #64748b);
+ line-height: 1.55;
+ margin: 0.9rem 0 0;
+}
+
+/* ---------------- Holdings table ---------------- */
+
+.pf-table-wrap { overflow-x: auto; }
+.pf-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.82rem;
+}
+.pf-table th {
+ text-align: right;
+ font-weight: 500;
+ font-size: 0.68rem;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--cv-text-3, #64748b);
+ padding: 0 0 0.6rem;
+ border-bottom: 1px solid var(--cv-border, #27272a);
+}
+.pf-table th:first-child,
+.pf-table th:nth-child(2) { text-align: left; }
+.pf-table td {
+ text-align: right;
+ padding: 0.6rem 0;
+ border-bottom: 1px solid var(--cv-border, #27272a);
+ font-family: var(--cv-font-mono, monospace);
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+}
+.pf-table td + td,
+.pf-table th + th { padding-left: 1rem; }
+.pf-table td:first-child {
+ text-align: left;
+ font-family: inherit;
+ white-space: normal;
+}
+.pf-table td:nth-child(2) { text-align: left; min-width: 7.5rem; }
+.pf-table tbody tr:last-child td { border-bottom: none; }
+.pf-table tbody tr {
+ transition: background var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-table tbody tr:hover td { background: var(--cv-surface-3, #1c1c21); }
+.pf-asset {
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ min-width: 0;
+}
+.pf-asset img,
+.pf-asset .ph {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ flex: none;
+ background: var(--cv-surface-3, #1c1c21);
+ object-fit: cover;
+}
+.pf-asset .ph {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 0.55rem;
+ font-family: var(--cv-font-mono, monospace);
+ color: var(--cv-text-3, #64748b);
+}
+.pf-asset .sym {
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 11rem;
+}
+.pf-asset .name {
+ display: block;
+ font-size: 0.68rem;
+ color: var(--cv-text-3, #64748b);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 11rem;
+}
+.pf-badge {
+ font-size: 0.6rem;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--cv-text-3, #64748b);
+ border: 1px solid var(--cv-border, #27272a);
+ border-radius: 999px;
+ padding: 0.05rem 0.4rem;
+ margin-left: 0.4rem;
+ vertical-align: middle;
+}
+.pf-share-bar {
+ display: block;
+ height: 6px;
+ width: 100%;
+ max-width: 8rem;
+ border-radius: 999px;
+ background: var(--cv-surface-3, #1c1c21);
+ overflow: hidden;
+}
+.pf-share-bar > span {
+ display: block;
+ height: 100%;
+ border-radius: inherit;
+ background: var(--c, var(--pf-series-other));
+ min-width: 2px;
+}
+.pf-share-pct {
+ display: block;
+ font-size: 0.66rem;
+ color: var(--cv-text-3, #64748b);
+ margin-top: 0.2rem;
+ font-family: var(--cv-font-mono, monospace);
+ font-variant-numeric: tabular-nums;
+}
+.pf-chg.up { color: var(--pf-up); }
+.pf-chg.down { color: var(--pf-down); }
+.pf-chg.na { color: var(--cv-text-3, #64748b); }
+.pf-val { font-weight: 600; }
+.pf-muted { color: var(--cv-text-3, #64748b); }
+
+.pf-small-banner {
+ display: block;
+ width: 100%;
+ font: inherit;
+ font-size: 0.75rem;
+ color: var(--cv-text-2, #a1a1aa);
+ background: var(--cv-surface-3, #1c1c21);
+ border: 1px dashed var(--cv-border, #27272a);
+ border-radius: var(--cv-radius-md, 8px);
+ padding: 0.55rem 0.9rem;
+ margin-top: 0.8rem;
+ cursor: pointer;
+ transition:
+ color var(--duration-fast, 140ms) var(--ease-standard, ease),
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.pf-small-banner:hover {
+ color: var(--cv-text, #fafafa);
+ border-color: var(--cv-border-hover, #3f3f46);
+}
+
+/* ---------------- Chart tooltip ---------------- */
+
+.pf-tip {
+ position: fixed;
+ z-index: 40;
+ pointer-events: none;
+ background: var(--cv-surface-3, #1c1c21);
+ border: 1px solid var(--cv-border-hover, #3f3f46);
+ border-radius: var(--cv-radius-md, 8px);
+ box-shadow: var(--cv-shadow-dropdown, 0 4px 24px -4px rgb(0 0 0 / 0.4));
+ padding: 0.45rem 0.7rem;
+ font-size: 0.75rem;
+ max-width: 16rem;
+}
+.pf-tip b { font-family: var(--cv-font-mono, monospace); }
+.pf-tip .sub { color: var(--cv-text-3, #64748b); }
+
+/* ---------------- States ---------------- */
+
+.pf-state { max-width: 40rem; }
+.pf-error h2,
+.pf-empty h2 { font-size: 1.1rem; margin: 0 0 0.5rem; }
+.pf-error p,
+.pf-empty p {
+ color: var(--cv-text-2, #a1a1aa);
+ line-height: 1.6;
+ margin: 0 0 1rem;
+}
+
+.pf-skel span {
+ display: block;
+ background: var(--cv-surface-3, #1c1c21);
+ border-radius: var(--cv-radius-sm, 4px);
+ animation: pf-skel 1.4s ease-in-out infinite;
+}
+.pf-skel .a { height: 34px; width: 44%; margin-bottom: 0.7rem; }
+.pf-skel .b { height: 14px; width: 26%; margin-bottom: 1.4rem; }
+.pf-skel .c { height: 18px; width: 100%; margin-bottom: 0.7rem; }
+@keyframes pf-skel {
+ 0%, 100% { opacity: 0.55; }
+ 50% { opacity: 1; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .pf-skel span { animation: none; }
+}
diff --git a/src/portfolio.js b/src/portfolio.js
new file mode 100644
index 000000000..ee2d22f00
--- /dev/null
+++ b/src/portfolio.js
@@ -0,0 +1,489 @@
+// /portfolio: live portfolio viewer for any Solana or Ethereum wallet.
+//
+// Data flow: address (form input, ?address= deep link, or a recent-wallet chip)
+// -> GET /api/crypto/portfolio?address=&chain= (api/crypto/portfolio.js, built
+// on api/_lib/balances.js + api/_lib/portfolio-overview.js) -> hero value card,
+// stable/major/token summary, allocation donut, holdings table. Series colors
+// are the dataviz-validated categorical slots defined in src/portfolio.css;
+// the server assigns slot ranks, the CSS supplies the theme-stepped hex.
+
+import { updateValue, enterStagger } from './ui-juice.js';
+import { formatUsd, formatPrice, formatPercent, formatSupply, timeAgo, escapeHtml } from './shared/coin-format.js';
+import { createLogger } from './shared/log.js';
+
+const log = createLogger('portfolio');
+const $ = (id) => document.getElementById(id);
+
+const RECENT_KEY = 'twx_portfolio_recent';
+const RECENT_MAX = 5;
+const SMALL_SHARE_PCT = 1;
+
+const EXPLORERS = {
+ solana: (a) => `https://solscan.io/account/${a}`,
+ ethereum: (a) => `https://etherscan.io/address/${a}`,
+};
+
+const state = {
+ address: '',
+ chain: 'solana',
+ data: null,
+ showSmall: false,
+ loading: false,
+};
+
+/* ---------------- address helpers ---------------- */
+
+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
+const SOLANA_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+function detectChain(address) {
+ if (EVM_RE.test(address)) return 'ethereum';
+ if (SOLANA_RE.test(address)) return 'solana';
+ return null;
+}
+
+function shortAddr(a) {
+ return a.length > 13 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
+}
+
+function loadRecent() {
+ try {
+ const list = JSON.parse(localStorage.getItem(RECENT_KEY) || '[]');
+ return Array.isArray(list) ? list.filter((r) => r && detectChain(r.address)) : [];
+ } catch {
+ return [];
+ }
+}
+
+function saveRecent(address, chain) {
+ const list = loadRecent().filter((r) => r.address !== address);
+ list.unshift({ address, chain });
+ try {
+ localStorage.setItem(RECENT_KEY, JSON.stringify(list.slice(0, RECENT_MAX)));
+ } catch {
+ /* storage full or blocked: recents are a convenience, not state */
+ }
+ renderRecent();
+}
+
+function renderRecent() {
+ const list = loadRecent();
+ const wrap = $('pf-recent');
+ if (!list.length) {
+ wrap.hidden = true;
+ return;
+ }
+ wrap.hidden = false;
+ $('pf-recent-list').innerHTML = list
+ .map(
+ (r) =>
+ `<button type="button" class="pf-recent-chip" data-address="${escapeHtml(r.address)}" data-chain="${escapeHtml(r.chain)}" title="${escapeHtml(r.address)}">${escapeHtml(shortAddr(r.address))}</button>`,
+ )
+ .join(' ');
+}
+
+/* ---------------- view switching ---------------- */
+
+function show(view) {
+ $('pf-intro').hidden = view !== 'intro';
+ $('pf-report').hidden = view !== 'report';
+ $('pf-loading').hidden = view !== 'loading';
+ $('pf-error').hidden = view !== 'error';
+ $('pf-empty').hidden = view !== 'empty';
+}
+
+/* ---------------- data ---------------- */
+
+async function lookup(address, chain, { push = true } = {}) {
+ if (state.loading) return;
+ state.loading = true;
+ state.address = address;
+ state.chain = chain;
+ $('pf-address').value = address;
+ $('pf-chain').value = chain;
+ show('loading');
+
+ if (push) {
+ const q = new URLSearchParams({ address, chain });
+ history.replaceState(null, '', `/portfolio?${q}`);
+ }
+
+ try {
+ const res = await fetch(`/api/crypto/portfolio?address=${encodeURIComponent(address)}&chain=${chain}`, {
+ headers: { accept: 'application/json' },
+ });
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ renderError(res.status, body);
+ return;
+ }
+ state.data = body;
+ saveRecent(address, chain);
+ if (!body.rows.length) {
+ $('pf-empty-chain').textContent = body.chain === 'solana' ? 'Solana' : 'Ethereum';
+ show('empty');
+ return;
+ }
+ renderReport(body);
+ show('report');
+ } catch (err) {
+ log.warn('lookup failed', err);
+ renderError(0, null);
+ } finally {
+ state.loading = false;
+ }
+}
+
+function renderError(status, body) {
+ const title = $('pf-error-title');
+ const msg = $('pf-error-body');
+ if (status === 400) {
+ title.textContent = 'That address does not look right';
+ msg.textContent = body?.error?.message || body?.message || 'Check the address and chain, then try again.';
+ } else if (status === 429) {
+ title.textContent = 'Slow down a moment';
+ msg.textContent = 'Too many lookups in a short burst. Wait a few seconds and retry.';
+ } else if (status === 503) {
+ title.textContent = 'Data source unavailable';
+ msg.textContent = body?.error?.message || body?.message || 'The balance sources for this chain are unreachable right now. Retry shortly.';
+ } else {
+ title.textContent = 'Could not load this wallet';
+ msg.textContent = 'The request failed before reaching the data sources. Check your connection and retry.';
+ }
+ show('error');
+}
+
+/* ---------------- report rendering ---------------- */
+
+function renderReport(d) {
+ const report = $('pf-report');
+ report.classList.remove('pf-enter');
+ void report.offsetWidth;
+ report.classList.add('pf-enter');
+
+ $('pf-stale').hidden = !d.stale;
+
+ const addrEl = $('pf-addr');
+ addrEl.textContent = shortAddr(d.address);
+ addrEl.title = d.address;
+ $('pf-chain-tag').textContent = d.chain;
+ $('pf-explorer').href = EXPLORERS[d.chain](d.address);
+
+ updateValue($('pf-total'), d.totalUsd, (v) => formatUsd(v));
+
+ const pill = $('pf-change');
+ const note = $('pf-change-note');
+ if (d.change24h) {
+ const up = d.change24h.usd >= 0;
+ pill.hidden = false;
+ pill.className = `pf-change-pill ${up ? 'up' : 'down'}`;
+ pill.innerHTML = `<span aria-hidden="true">${up ? '▲' : '▼'}</span> ${escapeHtml(formatUsd(Math.abs(d.change24h.usd)))} (${escapeHtml(formatPercent(d.change24h.pct))}) <span class="pf-visually-hidden">${up ? 'up' : 'down'} in the last 24 hours</span>`;
+ note.hidden = false;
+ note.textContent =
+ d.change24h.coveragePct >= 99.5
+ ? 'past 24h'
+ : `past 24h, based on ${d.change24h.coveragePct}% of value`;
+ } else {
+ pill.hidden = true;
+ note.hidden = false;
+ note.textContent = 'No 24h price history is available for these holdings.';
+ }
+
+ for (const key of ['stable', 'major', 'other']) {
+ const s = d.summary[key];
+ $(`pf-sum-${key}`).textContent = formatUsd(s.usd);
+ $(`pf-sum-${key}-sub`).textContent = s.count
+ ? `${s.pct}% · ${s.count} asset${s.count === 1 ? '' : 's'}`
+ : 'none held';
+ }
+
+ renderDonut(d);
+ renderMeta(d);
+ renderTable(d);
+
+ enterStagger($('pf-rows').querySelectorAll('tr'));
+}
+
+/* ---------------- donut ---------------- */
+
+function segColor(slot) {
+ return slot === 0 ? 'var(--pf-series-other)' : `var(--pf-series-${slot})`;
+}
+
+function arcPath(cx, cy, rOuter, rInner, a0, a1) {
+ const large = a1 - a0 > Math.PI ? 1 : 0;
+ const p = (r, a) => `${cx + r * Math.cos(a)} ${cy + r * Math.sin(a)}`;
+ return [
+ `M ${p(rOuter, a0)}`,
+ `A ${rOuter} ${rOuter} 0 ${large} 1 ${p(rOuter, a1)}`,
+ `L ${p(rInner, a1)}`,
+ `A ${rInner} ${rInner} 0 ${large} 0 ${p(rInner, a0)}`,
+ 'Z',
+ ].join(' ');
+}
+
+function renderDonut(d) {
+ const svg = $('pf-donut');
+ const assets = d.topAssets;
+ $('pf-alloc-sub').textContent = `top ${Math.min(assets.length, 5)} of ${d.tokenCount} holdings`;
+
+ const total = assets.reduce((s, a) => s + a.usd, 0);
+ if (!(total > 0)) {
+ svg.innerHTML = '';
+ $('pf-legend').innerHTML = '<li class="pf-muted">Nothing priced yet.</li>';
+ $('pf-donut-center').innerHTML = '';
+ return;
+ }
+
+ let angle = -Math.PI / 2;
+ const paths = assets.map((a, i) => {
+ const sweep = (a.usd / total) * Math.PI * 2;
+ const path = arcPath(60, 60, 56, 36, angle, angle + sweep);
+ angle += sweep;
+ return `<path d="${path}" style="fill:${segColor(a.slot)}" stroke="var(--cv-surface-2, #131316)" stroke-width="2" data-i="${i}" tabindex="0" role="img" aria-label="${escapeHtml(a.symbol)}: ${a.pct}% (${escapeHtml(formatUsd(a.usd))})"></path>`;
+ });
+ svg.innerHTML = paths.join('');
+ svg.setAttribute(
+ 'aria-label',
+ `Portfolio allocation: ${assets.map((a) => `${a.symbol} ${a.pct}%`).join(', ')}`,
+ );
+
+ $('pf-donut-center').innerHTML = `<b>${escapeHtml(formatUsd(d.totalUsd))}</b><span>total</span>`;
+
+ $('pf-legend').innerHTML = assets
+ .map(
+ (a) => `<li>
+ <i style="--c:${segColor(a.slot)}" aria-hidden="true"></i>
+ <span class="sym">${escapeHtml(a.symbol)}${a.slot === 0 && a.count ? ` <span class="pf-muted">(${a.count})</span>` : ''}</span>
+ <span class="pct">${a.pct}%</span>
+ <span class="val">${escapeHtml(formatUsd(a.usd))}</span>
+ </li>`,
+ )
+ .join('');
+
+ wireDonutHover(svg, assets);
+}
+
+let tipEl = null;
+function tip() {
+ if (!tipEl) {
+ tipEl = document.createElement('div');
+ tipEl.className = 'pf-tip';
+ tipEl.hidden = true;
+ document.body.appendChild(tipEl);
+ }
+ return tipEl;
+}
+
+function wireDonutHover(svg, assets) {
+ const t = tip();
+ const showTip = (seg, x, y) => {
+ const a = assets[Number(seg.dataset.i)];
+ if (!a) return;
+ svg.classList.add('pf-donut-focus');
+ svg.querySelectorAll('path').forEach((p) => p.classList.toggle('pf-seg-active', p === seg));
+ t.innerHTML = `<b>${escapeHtml(a.symbol)}</b> ${a.pct}%<br /><span class="sub">${escapeHtml(formatUsd(a.usd))}</span>`;
+ t.hidden = false;
+ const pad = 12;
+ t.style.left = `${Math.min(x + pad, window.innerWidth - t.offsetWidth - pad)}px`;
+ t.style.top = `${Math.max(y - t.offsetHeight - pad, pad)}px`;
+ };
+ const hideTip = () => {
+ svg.classList.remove('pf-donut-focus');
+ svg.querySelectorAll('path').forEach((p) => p.classList.remove('pf-seg-active'));
+ t.hidden = true;
+ };
+ svg.onmousemove = (e) => {
+ const seg = e.target.closest('path');
+ if (seg) showTip(seg, e.clientX, e.clientY);
+ else hideTip();
+ };
+ svg.onmouseleave = hideTip;
+ svg.onfocusin = (e) => {
+ const seg = e.target.closest('path');
+ if (!seg) return;
+ const r = seg.getBoundingClientRect();
+ showTip(seg, r.left + r.width / 2, r.top);
+ };
+ svg.onfocusout = hideTip;
+}
+
+/* ---------------- meta + table ---------------- */
+
+function renderMeta(d) {
+ const rows = [
+ ['Chain', d.chain === 'solana' ? 'Solana' : 'Ethereum'],
+ ['Holdings', String(d.tokenCount)],
+ ['Unpriced', d.unpricedCount ? `${d.unpricedCount} token${d.unpricedCount === 1 ? '' : 's'}` : 'none'],
+ ['24h coverage', d.change24h ? `${d.change24h.coveragePct}% of value` : 'unavailable'],
+ ['Updated', timeAgo(d.ts) || 'just now'],
+ ['Sources', d.sources.join(', ')],
+ ];
+ if (d.truncated) rows.splice(2, 0, ['Shown', `top ${d.rows.length} by value`]);
+ $('pf-meta').innerHTML = rows
+ .map(([k, v]) => `<div><dt>${escapeHtml(k)}</dt><dd>${escapeHtml(v)}</dd></div>`)
+ .join('');
+}
+
+function slotForSymbol(d, symbol) {
+ const hit = d.topAssets.find((a) => a.slot > 0 && a.symbol === symbol);
+ return hit ? hit.slot : 0;
+}
+
+function renderTable(d) {
+ const all = d.rows;
+ const visible = state.showSmall ? all : all.filter((r) => r.sharePct >= SMALL_SHARE_PCT || r.kind === 'native');
+ const hiddenCount = all.length - visible.length;
+
+ $('pf-holdings-count').textContent = `${visible.length} of ${d.tokenCount}`;
+ $('pf-rows').innerHTML = visible.map((r) => rowHtml(d, r)).join('');
+
+ const banner = $('pf-small-banner');
+ if (!state.showSmall && hiddenCount > 0) {
+ banner.hidden = false;
+ banner.textContent = `${hiddenCount} balance${hiddenCount === 1 ? '' : 's'} under ${SMALL_SHARE_PCT}% hidden · show all`;
+ } else {
+ banner.hidden = true;
+ }
+}
+
+function rowHtml(d, r) {
+ const slot = slotForSymbol(d, r.symbol);
+ const sym = r.symbol || (r.id ? `${r.id.slice(0, 6)}…` : '?');
+ const logo = r.logo
+ ? `<img src="${escapeHtml(r.logo)}" alt="" loading="lazy" data-ph="${escapeHtml(sym.slice(0, 3))}" />`
+ : `<span class="ph">${escapeHtml(sym.slice(0, 3))}</span>`;
+ const chg =
+ r.change24h == null
+ ? '<span class="pf-chg na">n/a</span>'
+ : `<span class="pf-chg ${r.change24h >= 0 ? 'up' : 'down'}">${escapeHtml(formatPercent(r.change24h))}</span>`;
+ const price = r.price == null ? '<span class="pf-muted">unpriced</span>' : escapeHtml(formatPrice(r.price));
+ const value = r.usd == null ? '<span class="pf-muted">n/a</span>' : escapeHtml(formatUsd(r.usd));
+ return `<tr>
+ <td>
+ <span class="pf-asset">
+ ${logo}
+ <span>
+ <span class="sym">${escapeHtml(sym)}${r.kind === 'native' ? '<span class="pf-badge">native</span>' : ''}</span>
+ ${r.name ? `<span class="name">${escapeHtml(r.name)}</span>` : ''}
+ </span>
+ </span>
+ </td>
+ <td>
+ <span class="pf-share-bar"><span style="--c:${segColor(slot)};width:${Math.max(r.sharePct, 0.5)}%"></span></span>
+ <span class="pf-share-pct">${r.sharePct}%</span>
+ </td>
+ <td>${escapeHtml(formatSupply(r.amount))}</td>
+ <td>${price}</td>
+ <td>${chg}</td>
+ <td class="pf-val">${value}</td>
+ </tr>`;
+}
+
+/* ---------------- wiring ---------------- */
+
+function submit(raw) {
+ const address = raw.trim();
+ if (!address) {
+ $('pf-address').focus();
+ return;
+ }
+ const detected = detectChain(address);
+ if (!detected) {
+ renderError(400, { message: 'Not a valid Solana or Ethereum address.' });
+ return;
+ }
+ lookup(address, detected);
+}
+
+function init() {
+ renderRecent();
+
+ // Broken token logos collapse to a monogram placeholder. Error events do not
+ // bubble, so this listens in the capture phase over the whole table body.
+ $('pf-rows').addEventListener(
+ 'error',
+ (e) => {
+ const img = e.target;
+ if (img?.tagName !== 'IMG') return;
+ const ph = document.createElement('span');
+ ph.className = 'ph';
+ ph.textContent = img.dataset.ph || '?';
+ img.replaceWith(ph);
+ },
+ true,
+ );
+
+ $('pf-form').addEventListener('submit', (e) => {
+ e.preventDefault();
+ submit($('pf-address').value);
+ });
+
+ // The select is a manual override for the rare address shape that is valid
+ // on both families; typing an address re-detects on submit.
+ $('pf-chain').addEventListener('change', () => {
+ const address = $('pf-address').value.trim();
+ if (address && detectChain(address)) lookup(address, $('pf-chain').value);
+ });
+
+ $('pf-recent').addEventListener('click', (e) => {
+ const chip = e.target.closest('.pf-recent-chip');
+ if (chip) lookup(chip.dataset.address, chip.dataset.chain);
+ });
+
+ $('pf-retry').addEventListener('click', () => {
+ if (state.address) lookup(state.address, state.chain);
+ else show('intro');
+ });
+
+ $('pf-show-small').addEventListener('change', (e) => {
+ state.showSmall = e.target.checked;
+ if (state.data) renderTable(state.data);
+ });
+ $('pf-small-banner').addEventListener('click', () => {
+ state.showSmall = true;
+ $('pf-show-small').checked = true;
+ if (state.data) renderTable(state.data);
+ });
+
+ $('pf-copy-addr').addEventListener('click', async () => {
+ if (!state.data) return;
+ await copyWithFeedback($('pf-copy-addr'), state.data.address, 'Copied');
+ });
+ $('pf-share').addEventListener('click', async () => {
+ await copyWithFeedback($('pf-share'), location.href, 'Link copied');
+ });
+
+ document.addEventListener('keydown', (e) => {
+ if (e.key === '/' && !/^(input|textarea|select)$/i.test(document.activeElement?.tagName || '')) {
+ e.preventDefault();
+ $('pf-address').focus();
+ }
+ });
+
+ const params = new URLSearchParams(location.search);
+ const address = (params.get('address') || '').trim();
+ if (address && detectChain(address)) {
+ const chain = ['solana', 'ethereum'].includes(params.get('chain')) ? params.get('chain') : detectChain(address);
+ lookup(address, chain, { push: false });
+ } else {
+ show('intro');
+ }
+}
+
+async function copyWithFeedback(btn, text, doneLabel) {
+ const original = btn.textContent;
+ try {
+ await navigator.clipboard.writeText(text);
+ btn.textContent = doneLabel;
+ btn.classList.add('pf-chip-ok');
+ } catch {
+ btn.textContent = 'Copy failed';
+ }
+ setTimeout(() => {
+ btn.textContent = original;
+ btn.classList.remove('pf-chip-ok');
+ }, 1600);
+}
+
+init();
diff --git a/tests/portfolio-overview.test.js b/tests/portfolio-overview.test.js
new file mode 100644
index 000000000..5bfcafb1b
--- /dev/null
+++ b/tests/portfolio-overview.test.js
@@ -0,0 +1,187 @@
+// api/_lib/portfolio-overview.js is the pure arithmetic behind
+// /api/crypto/portfolio and the /portfolio page. Same testing philosophy as
+// tests/portfolio.test.js: hand-computed fixtures, no network, no mocks of
+// upstreams (there are none to mock; the module is pure by design).
+
+import { describe, it, expect } from 'vitest';
+import {
+ classifyToken,
+ buildOverview,
+ STABLE_SYMBOLS,
+ MAJOR_SYMBOLS,
+ TOP_ASSET_SLOTS,
+} from '../api/_lib/portfolio-overview.js';
+
+describe('classifyToken', () => {
+ it('classifies stables, majors, and everything else', () => {
+ expect(classifyToken('USDC')).toBe('stable');
+ expect(classifyToken('usdt')).toBe('stable');
+ expect(classifyToken('SOL')).toBe('major');
+ expect(classifyToken('jitoSOL')).toBe('major');
+ expect(classifyToken('WETH')).toBe('major');
+ expect(classifyToken('BONK')).toBe('other');
+ expect(classifyToken('')).toBe('other');
+ expect(classifyToken(null)).toBe('other');
+ });
+
+ it('keeps the stable and major sets disjoint', () => {
+ for (const s of STABLE_SYMBOLS) expect(MAJOR_SYMBOLS.has(s)).toBe(false);
+ });
+});
+
+// 2 SOL @ $200 (+5%), 100 USDC @ $1 (0%), 1000 MEME @ $0.05 (-10%),
+// and 5 DUST with no price.
+const FIXTURE = {
+ chain: 'solana',
+ address: 'WaLLetAddr',
+ native: { symbol: 'SOL', name: 'Solana', amount: 2, price: 200, usd: 400, change24h: null },
+ tokens: [
+ { mint: 'UsdcMint', symbol: 'USDC', name: 'USD Coin', amount: 100, price: 1, usd: 100, change24h: null },
+ { mint: 'MemeMint', symbol: 'MEME', name: 'Meme Token', amount: 1000, price: 0.05, usd: 50, change24h: null },
+ { mint: 'DustMint', symbol: 'DUST', name: 'Dust', amount: 5, price: 0, usd: 0, change24h: null },
+ ],
+};
+
+const CHANGES = new Map([
+ ['native', 5],
+ ['UsdcMint', 0],
+ ['MemeMint', -10],
+]);
+
+describe('buildOverview', () => {
+ it('totals, classifies, and ranks the fixture wallet', () => {
+ const o = buildOverview(FIXTURE, CHANGES);
+
+ expect(o.totalUsd).toBe(550);
+ expect(o.tokenCount).toBe(4);
+ expect(o.truncated).toBe(false);
+ expect(o.unpricedCount).toBe(1);
+
+ expect(o.summary.major).toEqual({ usd: 400, pct: 72.73, count: 1 });
+ expect(o.summary.stable).toEqual({ usd: 100, pct: 18.18, count: 1 });
+ // DUST counts as a held position even though it has no price.
+ expect(o.summary.other).toEqual({ usd: 50, pct: 9.09, count: 2 });
+
+ // Rows sorted by value descending; native first by value here.
+ expect(o.rows.map((r) => r.symbol)).toEqual(['SOL', 'USDC', 'MEME', 'DUST']);
+ expect(o.rows[0].kind).toBe('native');
+ expect(o.rows[0].sharePct).toBe(72.73);
+ // Unpriced rows surface usd: null, never a fake zero valuation.
+ expect(o.rows[3].price).toBe(null);
+ expect(o.rows[3].usd).toBe(null);
+ });
+
+ it('computes the exact 24h move over covered value only', () => {
+ const o = buildOverview(FIXTURE, CHANGES);
+
+ // SOL: 400 - 400/1.05 = 19.047619; MEME: 50 - 50/0.9 = -5.555556;
+ // USDC: 0. Delta = 13.492063, previous covered value = 536.507937.
+ expect(o.change24h.usd).toBe(13.49);
+ expect(o.change24h.pct).toBe(2.51);
+ expect(o.change24h.coveragePct).toBe(100);
+ });
+
+ it('reports partial coverage when some tokens have no change data', () => {
+ const partial = new Map([['native', 5]]);
+ const o = buildOverview(FIXTURE, partial);
+ // Only SOL (400 of 550) is covered.
+ expect(o.change24h.coveragePct).toBe(72.73);
+ expect(o.change24h.usd).toBe(19.05);
+ });
+
+ it('returns change24h null when nothing is covered', () => {
+ const o = buildOverview(FIXTURE, new Map());
+ expect(o.change24h).toBe(null);
+ });
+
+ it('ignores a -100% change instead of dividing by zero', () => {
+ const o = buildOverview(FIXTURE, new Map([['MemeMint', -100]]));
+ expect(o.change24h).toBe(null);
+ });
+
+ it('prefers the enrichment map over a change baked into the snapshot', () => {
+ const baked = {
+ ...FIXTURE,
+ tokens: [{ mint: 'UsdcMint', symbol: 'USDC', name: 'USD Coin', amount: 100, price: 1, usd: 100, change24h: 9 }],
+ };
+ const o = buildOverview(baked, new Map([['UsdcMint', 1]]));
+ const usdc = o.rows.find((r) => r.symbol === 'USDC');
+ expect(usdc.change24h).toBe(1);
+ });
+
+ it('keeps a baked change when the map has no entry', () => {
+ const baked = {
+ ...FIXTURE,
+ tokens: [{ mint: 'UsdcMint', symbol: 'USDC', name: 'USD Coin', amount: 100, price: 1, usd: 100, change24h: 9 }],
+ };
+ const o = buildOverview(baked, null);
+ expect(o.rows.find((r) => r.symbol === 'USDC').change24h).toBe(9);
+ });
+
+ it('folds allocation past the slot cap into Other', () => {
+ const many = {
+ chain: 'solana',
+ address: 'W',
+ native: { symbol: 'SOL', amount: 1, price: 100, usd: 100 },
+ tokens: Array.from({ length: 7 }, (_, i) => ({
+ mint: `M${i}`,
+ symbol: `TK${i}`,
+ name: `Token ${i}`,
+ amount: 1,
+ price: 50 - i,
+ usd: 50 - i,
+ })),
+ };
+ const o = buildOverview(many, null);
+ expect(o.topAssets).toHaveLength(TOP_ASSET_SLOTS + 1);
+ const other = o.topAssets.at(-1);
+ expect(other.symbol).toBe('Other');
+ expect(other.slot).toBe(0);
+ expect(other.count).toBe(3);
+ // Slots are assigned in rank order, never cycled.
+ expect(o.topAssets.slice(0, TOP_ASSET_SLOTS).map((a) => a.slot)).toEqual([1, 2, 3, 4, 5]);
+ // Percentages of named slots + Other account for the whole portfolio.
+ const pctSum = o.topAssets.reduce((s, a) => s + a.pct, 0);
+ expect(pctSum).toBeGreaterThan(99.9);
+ expect(pctSum).toBeLessThan(100.1);
+ });
+
+ it('merges the same symbol across positions in the allocation', () => {
+ const dup = {
+ chain: 'evm',
+ address: '0xW',
+ native: { symbol: 'ETH', amount: 1, price: 3000, usd: 3000 },
+ tokens: [
+ { contract: '0xA', symbol: 'AAA', amount: 10, price: 10, usd: 100 },
+ { contract: '0xB', symbol: 'AAA', amount: 5, price: 10, usd: 50 },
+ ],
+ };
+ const o = buildOverview(dup, null);
+ const aaa = o.topAssets.find((a) => a.symbol === 'AAA');
+ expect(aaa.usd).toBe(150);
+ expect(o.topAssets).toHaveLength(2);
+ });
+
+ it('caps rows at maxRows and flags truncation', () => {
+ const big = {
+ chain: 'solana',
+ address: 'W',
+ native: { symbol: 'SOL', amount: 1, price: 100, usd: 100 },
+ tokens: Array.from({ length: 250 }, (_, i) => ({
+ mint: `M${i}`, symbol: `T${i}`, amount: 1, price: 1, usd: 1,
+ })),
+ };
+ const o = buildOverview(big, null);
+ expect(o.rows).toHaveLength(200);
+ expect(o.tokenCount).toBe(251);
+ expect(o.truncated).toBe(true);
+ });
+
+ it('handles an empty wallet without inventing anything', () => {
+ const o = buildOverview({ chain: 'solana', address: 'W', native: { symbol: 'SOL', amount: 0, price: 200, usd: 0 }, tokens: [] }, null);
+ expect(o.totalUsd).toBe(0);
+ expect(o.rows).toEqual([]);
+ expect(o.change24h).toBe(null);
+ expect(o.topAssets).toEqual([]);
+ });
+});
diff --git a/tests/portfolio-page.test.js b/tests/portfolio-page.test.js
new file mode 100644
index 000000000..af3eeeb5c
--- /dev/null
+++ b/tests/portfolio-page.test.js
@@ -0,0 +1,182 @@
+// /portfolio page wiring.
+//
+// A page can be built, styled and correct and still be unreachable. These pin
+// the connections that have silently broken before: the route table, the vite
+// entry, the sitemap record, the nav link, the API handler, and every href on
+// the page resolving to something that actually exists. Modeled on
+// tests/exit-lab-page.test.js.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const read = (p) => readFileSync(resolve(ROOT, p), 'utf8');
+
+const html = read('pages/portfolio.html');
+const js = read('src/portfolio.js');
+const css = read('src/portfolio.css');
+const vercel = JSON.parse(read('vercel.json'));
+const viteConfig = read('vite.config.js');
+const pages = JSON.parse(read('data/pages.json'));
+const navData = read('public/nav-data.js');
+
+function pagePaths() {
+ const out = new Set();
+ const walk = (node) => {
+ if (Array.isArray(node)) return node.forEach(walk);
+ if (!node || typeof node !== 'object') return;
+ if (typeof node.path === 'string') out.add(node.path);
+ Object.values(node).forEach(walk);
+ };
+ walk(pages);
+ return out;
+}
+
+describe('routing', () => {
+ it('serves /portfolio from the route table', () => {
+ const route = vercel.routes.find((r) => r.src === '/portfolio/?');
+ expect(route).toBeDefined();
+ expect(route.dest).toBe('/portfolio.html');
+ });
+
+ it('declares the page route before the filesystem phase', () => {
+ const pageIdx = vercel.routes.findIndex((r) => r.src === '/portfolio/?');
+ const fsIdx = vercel.routes.findIndex((r) => r.handle === 'filesystem');
+ expect(pageIdx).toBeGreaterThan(-1);
+ expect(fsIdx).toBeGreaterThan(pageIdx);
+ });
+
+ it('has its API handler on disk where filesystem routing resolves it', () => {
+ // /api/crypto/portfolio has no explicit vercel route on purpose: the
+ // server's Vercel-parity filesystem routing maps it straight to this file.
+ expect(existsSync(resolve(ROOT, 'api/crypto/portfolio.js'))).toBe(true);
+ });
+
+ it('is not shadowed by an explicit /api/crypto/portfolio route pointing elsewhere', () => {
+ const explicit = vercel.routes.filter(
+ (r) => typeof r.src === 'string' && r.src.includes('/api/crypto/portfolio'),
+ );
+ for (const r of explicit) expect(r.dest).toBe('/api/crypto/portfolio.js');
+ });
+
+ it('is a build entry, so the static HTML is actually emitted', () => {
+ expect(viteConfig).toContain("portfolio: resolve(__dirname, 'pages/portfolio.html')");
+ });
+
+ it('resolves in the dev server route map', () => {
+ expect(viteConfig).toContain("'/portfolio': resolve(root, 'pages/portfolio.html')");
+ expect(viteConfig).toContain("'/portfolio/': resolve(root, 'pages/portfolio.html')");
+ });
+});
+
+describe('discovery', () => {
+ it('is declared in data/pages.json, which feeds the sitemap and llms.txt', () => {
+ expect(pagePaths().has('/portfolio')).toBe(true);
+ });
+
+ it('ships its docs page, registered so audit:docs passes', () => {
+ expect(existsSync(resolve(ROOT, 'docs/portfolio.md'))).toBe(true);
+ expect(pagePaths().has('/docs/portfolio')).toBe(true);
+ });
+
+ it('is linked from the site nav', () => {
+ expect(navData).toContain("href: '/portfolio'");
+ });
+
+ it('declares a canonical URL and an OG image', () => {
+ expect(html).toContain('<link rel="canonical" href="https://three.ws/portfolio" />');
+ expect(html).toContain('og:image');
+ });
+});
+
+describe('page structure', () => {
+ it('mounts every element the hydration script writes into', () => {
+ const ids = [...js.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map((m) => m[1]);
+ expect(ids.length).toBeGreaterThan(10);
+ for (const id of new Set(ids)) {
+ // Dynamic summary-card ids are still static in the page markup.
+ if (id.startsWith('pf-sum-')) continue;
+ expect(html, `#${id} is written to but not present in the page`).toContain(`id="${id}"`);
+ }
+ });
+
+ it('mounts the summary cards for every classification bucket', () => {
+ for (const key of ['stable', 'major', 'other']) {
+ expect(html).toContain(`id="pf-sum-${key}"`);
+ expect(html).toContain(`id="pf-sum-${key}-sub"`);
+ }
+ });
+
+ it('loads its own stylesheet, the shared markets layer, and its module', () => {
+ expect(html).toContain('/src/coin-pages.css');
+ expect(html).toContain('/src/portfolio.css');
+ expect(html).toContain('/src/portfolio.js');
+ });
+
+ it('every internal href resolves to a declared page or a docs path', () => {
+ const hrefs = [...html.matchAll(/href="(\/[^"#]*)"/g)]
+ .map((m) => m[1])
+ .filter((h) => !h.startsWith('/src/') && !h.startsWith('/api/'));
+ const known = pagePaths();
+ for (const href of new Set(hrefs)) {
+ if (href === '/') continue;
+ if (/\.(css|js|ico|svg|png|webmanifest)$/.test(href)) continue;
+ const ok = known.has(href) || known.has(href.replace(/\/$/, '')) || href.startsWith('/docs/');
+ expect(ok, `${href} is linked from /portfolio but matches no route`).toBe(true);
+ }
+ });
+
+ it('designs a loading, an empty and an error state', () => {
+ expect(html).toContain('id="pf-loading"');
+ expect(html).toContain('id="pf-empty"');
+ expect(html).toContain('id="pf-error"');
+ expect(js).toContain("show('empty')");
+ expect(js).toContain("show('error')");
+ expect(js).toContain("show('loading')");
+ });
+
+ it('respects a reduced-motion preference', () => {
+ expect(css).toContain('@media (prefers-reduced-motion: reduce)');
+ });
+
+ it('scrolls the holdings table inside its own container rather than the page body', () => {
+ expect(css).toMatch(/\.pf-table-wrap\s*\{[^}]*overflow-x:\s*auto/);
+ });
+
+ it('uses no inline event handlers (CSP + audit:inline-handlers)', () => {
+ expect(html).not.toMatch(/\son(error|click|load|mouseover)=/i);
+ expect(js).not.toMatch(/\bonerror="/);
+ });
+});
+
+describe('honesty', () => {
+ it('ships no sample or seed portfolio', () => {
+ expect(js).not.toMatch(/const\s+(sample|demo|fake|mock)[A-Za-z]*\s*=\s*\[/i);
+ });
+
+ it('reads holdings from the real endpoint', () => {
+ expect(js).toContain('/api/crypto/portfolio');
+ });
+
+ it('states 24h coverage instead of implying complete data', () => {
+ expect(js).toContain('coveragePct');
+ expect(js).toMatch(/based on .*% of value/);
+ });
+
+ it('surfaces the stale-snapshot banner path', () => {
+ expect(html).toContain('id="pf-stale"');
+ expect(js).toContain('pf-stale');
+ });
+
+ it('uses no banned dash characters', () => {
+ for (const [name, src] of [
+ ['pages/portfolio.html', html],
+ ['src/portfolio.js', js],
+ ['src/portfolio.css', css],
+ ]) {
+ expect(src, `${name} contains a banned dash`).not.toMatch(/[\u2014\u2013]/);
+ }
+ });
+});
diff --git a/vercel.json b/vercel.json
index 311e4607d..f73861282 100644
--- a/vercel.json
+++ b/vercel.json
@@ -918,6 +918,10 @@
"src": "/deployments/?",
"dest": "/deployments.html"
},
+ {
+ "src": "/portfolio/?",
+ "dest": "/portfolio.html"
+ },
{
"src": "/launcher/?",
"dest": "/launcher.html"
diff --git a/vite.config.js b/vite.config.js
index 31ed607e5..7bf0285d5 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -482,6 +482,7 @@ const appConfig = {
fits: resolve(__dirname, 'pages/fits.html'),
viability: resolve(__dirname, 'pages/viability.html'),
deployments: resolve(__dirname, 'pages/deployments.html'),
+ portfolio: resolve(__dirname, 'pages/portfolio.html'),
launcher: resolve(__dirname, 'pages/launcher.html'),
'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),
model: resolve(__dirname, 'pages/model.html'),
@@ -1128,6 +1129,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/viability/': resolve(root, 'pages/viability.html'),
'/deployments': resolve(root, 'pages/deployments.html'),
'/deployments/': resolve(root, 'pages/deployments.html'),
+ '/portfolio': resolve(root, 'pages/portfolio.html'),
+ '/portfolio/': resolve(root, 'pages/portfolio.html'),
'/launcher': resolve(root, 'pages/launcher.html'),
'/launcher/': resolve(root, 'pages/launcher.html'),
'/clash': resolve(root, 'pages/clash.html'),