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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(rivalries): pair every trader with the one above them and name what changed
nirholas741663511fdd
diff --git a/api/_lib/rivalries.js b/api/_lib/rivalries.jsnew file mode 100644index 000000000..e895fab4b--- /dev/null+++ b/api/_lib/rivalries.js@@ -0,0 +1,332 @@+/**+ * The rivalry engine: leaderboard deltas turned into matchups.+ *+ * A leaderboard answers "who is ahead". It never answers the question people+ * actually argue about, which is "who just took whose place, and can they hold+ * it". This module derives that from the same ledger the board is computed from,+ * with no new table and no cron: it fetches every public trader's positions once+ * and computes THREE boards from that one fetch through the shared, pure+ * `computeTraderMetrics`:+ *+ * now · the current window, exactly what /api/sniper/leaderboard ranks+ * past · the same window length measured at the lookback cutoff, built from+ * positions that had already closed by then, so it is what the board+ * really said back then rather than a snapshot nobody stored+ * since · only the round-trips closed inside the lookback, which is momentum:+ * who is actually gaining ground right now+ *+ * Rank changes between `now` and `past` are the events; `since` is why. Because+ * the past board is re-derived from close timestamps rather than read from a+ * snapshot table, this works retroactively from day one and cannot drift out of+ * agreement with the live board.+ *+ * The copy is deterministic, not generated. Every clause is a number from the+ * boards above, phrased in the platform's voice: no hype, no prediction, no+ * promise, and never a claim the ledger cannot back. That also makes the strip+ * instant and free to render, which a public surface refreshing every 30 seconds+ * has to be.+ */++import {+ computeTraderMetrics,+ fetchLeaderboardPositions,+ selfDealMintsByUsers,+ mintLaunchTimes,+ cachedSolUsd,+ windowStartIso,+ WINDOWS,+} from './trader-stats.js';++/** Lookback windows the rivalry feed will diff over. */+export const LOOKBACKS = new Map([+ ['1h', 3_600_000],+ ['24h', 86_400_000],+ ['7d', 604_800_000],+]);++const WINDOW_LABEL = { '24h': '24h', '7d': '7d', '30d': '30d', all: 'all-time' };+const LOOKBACK_LABEL = { '1h': 'hour', '24h': '24 hours', '7d': '7 days' };++/** Below this many settled round-trips a "board position" is noise, not a record. */+const MIN_CLOSED = 3;++// ── formatting ──────────────────────────────────────────────────────────────++function digitsFor(abs) {+ return abs >= 100 ? 0 : abs >= 10 ? 1 : abs >= 1 ? 2 : 3;+}++export function fmtSol(n, scale = n) {+ const v = Number(n) || 0;+ // Two amounts compared in one sentence are formatted against the same scale,+ // so a line never reads "+2.00 SOL against +0.500 SOL".+ const digits = digitsFor(Math.abs(Number(scale) || 0));+ return `${v > 0 ? '+' : v < 0 ? '-' : ''}${Math.abs(v).toFixed(digits)} SOL`;+}++/** Gaps are distances, so they never carry a sign. */+export function fmtGap(n) {+ const abs = Math.abs(Number(n) || 0);+ return `${abs.toFixed(digitsFor(abs))} SOL`;+}++// ── board building (pure) ───────────────────────────────────────────────────++/**+ * Group raw board rows by agent. One pass, so the three boards below all read+ * the same objects.+ */+export function groupByAgent(rows) {+ const byAgent = new Map();+ for (const r of rows || []) {+ let g = byAgent.get(r.agent_id);+ if (!g) {+ g = {+ agent_id: r.agent_id,+ user_id: r.agent_user_id,+ name: r.agent_name || 'Unnamed trader',+ image: r.agent_image || r.agent_avatar || null,+ positions: [],+ };+ byAgent.set(r.agent_id, g);+ }+ g.positions.push(r);+ }+ return byAgent;+}++function closedAt(p) {+ const t = Date.parse(p.closed_at);+ return Number.isFinite(t) ? t : null;+}++/**+ * Rank one board out of grouped positions, counting only round-trips that had+ * closed inside [from, to]. Open positions are deliberately excluded from every+ * board here: the composite score is computed from realized history alone, and a+ * position that is open now was open then too, so including it would make the+ * past board disagree with itself.+ */+export function rankBoard(groups, { from = null, to = Date.now(), minClosed = MIN_CLOSED, solUsd = null, selfDealByUser = null, mintCreatedAt = null } = {}) {+ const rows = [];+ for (const g of groups.values()) {+ const inRange = g.positions.filter((p) => {+ if (p.status !== 'closed') return false;+ const t = closedAt(p);+ if (t == null) return false;+ return t <= to && (from == null || t >= from);+ });+ if (inRange.length < minClosed) continue;+ const m = computeTraderMetrics(inRange, {+ solUsd,+ selfDealMints: (selfDealByUser && selfDealByUser.get(g.user_id)) || null,+ mintCreatedAt,+ });+ if (!m.closed_count) continue;+ rows.push({+ agent_id: g.agent_id,+ name: g.name,+ image: g.image,+ score: m.score,+ verified: m.verified,+ closed: m.closed_count,+ wins: m.wins,+ win_rate: m.win_rate,+ realized_pnl_sol: m.realized_pnl_sol,+ realized_pnl_usd: m.realized_pnl_usd,+ best_pnl_pct: m.best_pnl_pct,+ max_drawdown_pct: m.max_drawdown_pct,+ top_coin: m.top_coin,+ top_coins: m.top_coins,+ last_active_at: m.last_active_at,+ });+ }+ rows.sort((a, b) => b.score - a.score || b.realized_pnl_sol - a.realized_pnl_sol);+ return rows.map((r, i) => ({ rank: i + 1, ...r }));+}++// ── the matchups (pure) ─────────────────────────────────────────────────────++/**+ * Coins both traders booked a result on, from each side's top-earning coins.+ * Deliberately narrow: `top_coins` is the per-agent breakdown the profile already+ * shows, so an overlap here is one both profiles can be checked against. An empty+ * list means "no shared coin among their best", never "they never overlapped".+ */+export function sharedCoins(a, b, limit = 2) {+ const bySymbol = new Map();+ for (const c of b.top_coins || []) if (c && c.mint) bySymbol.set(c.mint, c);+ const out = [];+ for (const c of a.top_coins || []) {+ const other = c && c.mint ? bySymbol.get(c.mint) : null;+ if (!other) continue;+ out.push({+ mint: c.mint,+ symbol: c.symbol || other.symbol || null,+ leader_pnl_sol: Number(c.pnl_sol || 0),+ chaser_pnl_sol: Number(other.pnl_sol || 0),+ });+ if (out.length >= limit) break;+ }+ return out;+}++/**+ * The copy. `leader` is whoever is ranked higher right now, `chaser` is the agent+ * one place below. Every sentence is assembled from the numbers on the rivalry+ * object, so a reader can check any of them against the two profiles it links to.+ */+export function rivalryCopy(r) {+ const windowLabel = WINDOW_LABEL[r.window] || r.window;+ const lookbackLabel = LOOKBACK_LABEL[r.lookback] || r.lookback;+ const lead = r.leader, chase = r.chaser;+ const gap = fmtGap(r.gap_sol);++ let headline;+ if (r.kind === 'overtake') {+ headline = `${lead.name} passed ${chase.name} on the ${windowLabel} board.`;+ } else if (r.kind === 'debut') {+ headline = `${lead.name} arrived at number ${lead.rank} on the ${windowLabel} board, above ${chase.name}.`;+ } else if (r.gap_sol > 0) {+ headline = `${chase.name} is ${gap} behind ${lead.name}.`;+ } else if (r.gap_sol < 0) {+ // The board ranks on the composite score, not on P&L, so the trader one place+ // down can be the one holding more SOL. Saying "behind" there would be false;+ // the score gap is the real reason they sit below.+ headline = `${chase.name} has out-earned ${lead.name} by ${gap} and still ranks below.`;+ } else {+ headline = `${chase.name} and ${lead.name} are level on P&L, ${Math.abs(r.gap_score)} apart on score.`;+ }++ const moveL = r.since.leader_pnl_sol, moveC = r.since.chaser_pnl_sol;+ const scale = Math.max(Math.abs(moveL), Math.abs(moveC));+ const sol = (n) => fmtSol(n, scale);+ // A trader who settled nothing inside the lookback has not "booked 0.000 SOL":+ // they were not in the market. Saying it the other way round is the difference+ // between a fact and a number that reads like one.+ let subline;+ if (moveL === 0 && moveC === 0) {+ subline = `Neither has settled a trade in the last ${lookbackLabel}. The gap stands at ${gap}.`;+ } else if (moveC === 0) {+ subline = `${chase.name} has not settled a trade in the last ${lookbackLabel}. ${lead.name} booked ${sol(moveL)}.`;+ } else if (moveL === 0) {+ subline = `${lead.name} has not settled a trade in the last ${lookbackLabel}. ${chase.name} booked ${sol(moveC)}.`;+ } else if (moveC > moveL) {+ subline = `${chase.name} booked ${sol(moveC)} in the last ${lookbackLabel} against ${sol(moveL)}, and is closing.`;+ } else if (moveL > moveC) {+ subline = `${lead.name} booked ${sol(moveL)} in the last ${lookbackLabel} against ${sol(moveC)}, and is pulling away.`;+ } else {+ subline = `Both booked ${sol(moveL)} in the last ${lookbackLabel}. The gap stands at ${gap}.`;+ }++ return { headline, subline };+}++/**+ * Turn three ranked boards into the matchup list. Every trader on the current+ * board is paired with the one directly above them, which is the only rivalry+ * that can change hands on the next settled trade.+ */+export function pairRivalries({ now, past, since, window, lookback, limit = 6 }) {+ const pastRank = new Map((past || []).map((r) => [r.agent_id, r.rank]));+ const sincePnl = new Map((since || []).map((r) => [r.agent_id, r.realized_pnl_sol]));+ const out = [];++ for (let i = 1; i < now.length; i++) {+ const leader = now[i - 1];+ const chaser = now[i];+ const pl = pastRank.get(leader.agent_id) ?? null;+ const pc = pastRank.get(chaser.agent_id) ?? null;++ let kind = 'chase';+ if (pl == null) kind = 'debut';+ else if (pc != null && pl > pc) kind = 'overtake';++ const r = {+ kind,+ window,+ lookback,+ leader: { ...leader, was_rank: pl },+ chaser: { ...chaser, was_rank: pc },+ // Signed, leader minus chaser: negative means the trader one place down+ // holds more realized SOL and sits below on the composite score alone.+ gap_sol: Number((leader.realized_pnl_sol - chaser.realized_pnl_sol).toFixed(6)),+ gap_score: leader.score - chaser.score,+ since: {+ leader_pnl_sol: Number(sincePnl.get(leader.agent_id) || 0),+ chaser_pnl_sol: Number(sincePnl.get(chaser.agent_id) || 0),+ },+ shared_coins: sharedCoins(leader, chaser),+ links: {+ leader_profile: `/trader/${leader.agent_id}`,+ chaser_profile: `/trader/${chaser.agent_id}`,+ ghost_copy_leader: `/ghost-copy?leader=${leader.agent_id}&window=${window}`,+ },+ };+ Object.assign(r, rivalryCopy(r));+ out.push(r);+ }++ // Newsworthiness order: a place that actually changed hands beats a standing+ // gap, and among standing gaps the tightest one is the one worth watching.+ const heat = (r) => {+ if (r.kind === 'overtake') return 3;+ if (r.kind === 'debut') return 2;+ return 1;+ };+ const movement = (r) => Math.abs(r.since.leader_pnl_sol) + Math.abs(r.since.chaser_pnl_sol);+ out.sort((a, b) => heat(b) - heat(a) || movement(b) - movement(a) || Math.abs(a.gap_sol) - Math.abs(b.gap_sol));+ return out.slice(0, limit);+}++// ── the read ────────────────────────────────────────────────────────────────++/**+ * Live rivalries for one network. One position fetch, three boards, no writes.+ */+export async function getRivalries({+ network = 'mainnet', window = '7d', lookback = '24h', limit = 6, now = Date.now(),+} = {}) {+ const win = WINDOWS.has(window) ? window : '7d';+ const back = LOOKBACKS.has(lookback) ? lookback : '24h';+ const cutoff = now - LOOKBACKS.get(back);++ // The past board is the same window length measured at the cutoff, so the+ // fetch has to reach back to whichever of the two window starts is earlier.+ const startNow = windowStartIso(win, now);+ const startPast = windowStartIso(win, cutoff);+ const fetchStart = startNow && startPast ? (Date.parse(startPast) < Date.parse(startNow) ? startPast : startNow) : null;++ const rows = await fetchLeaderboardPositions({ network, start: fetchStart });+ const groups = groupByAgent(rows);+ if (!groups.size) {+ return { network, window: win, lookback: back, sol_usd: null, rivalries: [], board_size: 0, t: now };+ }++ const mints = [...new Set(rows.map((r) => r.mint).filter(Boolean))];+ const [solUsd, selfDealByUser, mintCreatedAt] = await Promise.all([+ cachedSolUsd(),+ selfDealMintsByUsers([...groups.values()].map((g) => g.user_id), network),+ mintLaunchTimes(mints, network),+ ]);+ const shared = { solUsd, selfDealByUser, mintCreatedAt };++ const nowBoard = rankBoard(groups, { from: startNow ? Date.parse(startNow) : null, to: now, ...shared });+ const pastBoard = rankBoard(groups, { from: startPast ? Date.parse(startPast) : null, to: cutoff, ...shared });+ // Momentum is not a track record: a single settled round-trip inside the+ // lookback is exactly the movement this board exists to show, so the+ // three-trade floor that keeps noise off a ranking does not apply here.+ const sinceBoard = rankBoard(groups, { from: cutoff, to: now, minClosed: 1, ...shared });++ return {+ network,+ window: win,+ lookback: back,+ sol_usd: solUsd,+ board_size: nowBoard.length,+ cutoff: new Date(cutoff).toISOString(),+ min_closed: MIN_CLOSED,+ rivalries: pairRivalries({ now: nowBoard, past: pastBoard, since: sinceBoard, window: win, lookback: back, limit }),+ t: now,+ };+}diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.jsindex 855b8d9cc..842ac8ed9 100644--- a/api/_lib/trader-stats.js+++ b/api/_lib/trader-stats.js@@ -514,7 +514,7 @@ export async function fetchTraderPositions({ agentId, network, window = 'all', n/** SOL/USD with a short module cache so a burst of stat requests prices once. */let _solCache = { usd: null, at: 0 };-async function cachedSolUsd() {+export async function cachedSolUsd() {const now = Date.now();if (_solCache.usd != null && now - _solCache.at < 60_000) return _solCache.usd;try {@@ -655,7 +655,7 @@ export async function mintLaunchTimes(mints, network) {}/** Self-deal mint sets for many users at once (leaderboard). Map(userId → Set(mint)). */-async function selfDealMintsByUsers(userIds, network) {+export async function selfDealMintsByUsers(userIds, network) {const byUser = new Map();const ids = [...new Set((userIds || []).filter(Boolean))];if (!ids.length) return byUser;@@ -800,6 +800,48 @@ function buildProjectionComparison(snap, metrics) {* public agents only) so strategy traders rank alongside snipers. Best-effort: an* unmigrated table yields no extra rows rather than failing the whole board.*/+/**+ * Every public agent's positions for one network, board-shaped: the sniper arena+ * ledger plus Strategy Objects, aliased into the one canonical position shape.+ * `start` (ISO) window-bounds CLOSED positions by close time; open positions are+ * always included, because current exposure is "now" regardless of window. Pass+ * `start = null` for the all-time board.+ *+ * Extracted so the leaderboard and the rivalry engine read the same rows through+ * the same joins and the same is_public gate: two boards computed from one fetch+ * can never disagree about who is on them.+ */+export async function fetchLeaderboardPositions({ network, start }) {+ const [rows, strategyRows] = await Promise.all([+ start+ ? sql`+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,+ p.opened_at, p.closed_at,+ p.moonbag_base_amount, p.moonbag_last_value_lamports, p.initials_recovered,+ a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image+ from agent_sniper_positions p+ join agent_identities a on a.id = p.agent_id+ where p.network = ${network} and a.is_public is not false+ and (p.status in ('open','opening','closing') or p.closed_at >= ${start})+ `+ : sql`+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,+ p.opened_at, p.closed_at,+ p.moonbag_base_amount, p.moonbag_last_value_lamports, p.initials_recovered,+ a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image+ from agent_sniper_positions p+ join agent_identities a on a.id = p.agent_id+ where p.network = ${network} and a.is_public is not false+ `,+ fetchStrategyLeaderboardRows({ network, start }),+ ]);+ return strategyRows.length ? [...rows, ...strategyRows] : rows;+}+async function fetchStrategyLeaderboardRows({ network, start }) {try {return start@@ -854,34 +896,7 @@ export async function getLeaderboard({network, window = '30d', limit = 100, sort = 'score', verifiedOnly = false, now = Date.now(),}) {const start = windowStartIso(window, now);- const [rows, strategyRows] = await Promise.all([- start- ? sql`- select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,- p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,- p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,- p.opened_at, p.closed_at,- p.moonbag_base_amount, p.moonbag_last_value_lamports, p.initials_recovered,- a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image- from agent_sniper_positions p- join agent_identities a on a.id = p.agent_id- where p.network = ${network} and a.is_public is not false- and (p.status in ('open','opening','closing') or p.closed_at >= ${start})- `- : sql`- select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,- p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,- p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,- p.opened_at, p.closed_at,- p.moonbag_base_amount, p.moonbag_last_value_lamports, p.initials_recovered,- a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image- from agent_sniper_positions p- join agent_identities a on a.id = p.agent_id- where p.network = ${network} and a.is_public is not false- `,- fetchStrategyLeaderboardRows({ network, start }),- ]);- const allRows = strategyRows.length ? [...rows, ...strategyRows] : rows;+ const allRows = await fetchLeaderboardPositions({ network, start });const solUsd = await cachedSolUsd();const copiers = await activeCopierCounts(network);diff --git a/api/sniper/rivalries.js b/api/sniper/rivalries.jsnew file mode 100644index 000000000..a956e1654--- /dev/null+++ b/api/sniper/rivalries.js@@ -0,0 +1,64 @@+/**+ * Rivalries: who just took whose place on the trader board, and why.+ *+ * GET /api/sniper/rivalries?network=mainnet&window=7d&lookback=24h&limit=6+ *+ * Pairs every trader on the live board with the one directly above them and+ * says what changed since the lookback cutoff: an overtake, a debut, or a+ * standing gap, each with the P&L both sides booked inside the lookback. Derived+ * entirely from `agent_sniper_positions` / `agent_strategy_positions` through the+ * shared trader-stats truth layer, so a matchup can never disagree with the+ * leaderboard or with either trader's profile.+ *+ * Public + IP rate-limited. The on-chain signatures behind every number are+ * public, so the argument about them should be too.+ */++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { WINDOWS } from '../_lib/trader-stats.js';+import { getRivalries, LOOKBACKS } from '../_lib/rivalries.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const MAX_LIMIT = 12;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;++ const rawNetwork = params.get('network');+ if (rawNetwork && !NETWORKS.has(rawNetwork)) {+ return error(res, 400, 'invalid_network', 'network must be mainnet or devnet');+ }+ const rawWindow = params.get('window');+ if (rawWindow && !WINDOWS.has(rawWindow)) {+ return error(res, 400, 'invalid_window', `window must be one of ${[...WINDOWS].join(', ')}`);+ }+ const rawLookback = params.get('lookback');+ if (rawLookback && !LOOKBACKS.has(rawLookback)) {+ return error(res, 400, 'invalid_lookback', `lookback must be one of ${[...LOOKBACKS.keys()].join(', ')}`);+ }+ const rawLimit = params.get('limit');+ let limit = 6;+ if (rawLimit != null && rawLimit !== '') {+ const n = Number(rawLimit);+ if (!Number.isInteger(n) || n < 1 || n > MAX_LIMIT) {+ return error(res, 400, 'invalid_limit', `limit must be an integer between 1 and ${MAX_LIMIT}`);+ }+ limit = n;+ }++ const out = await getRivalries({+ network: rawNetwork || 'mainnet',+ window: rawWindow || '7d',+ lookback: rawLookback || '24h',+ limit,+ });++ return json(res, 200, out, { 'cache-control': 'public, max-age=30, s-maxage=60' });+});diff --git a/docs/rivalries.md b/docs/rivalries.mdnew file mode 100644index 000000000..9812bffb8--- /dev/null+++ b/docs/rivalries.md@@ -0,0 +1,165 @@+# Rivalries: what changed on the trader board++A leaderboard tells you who is ahead. It never tells you the thing people+actually argue about, which is who just took whose place and whether they can+hold it. Rivalries is that layer: it pairs every trader on the board with the+one directly above them and says, in a sentence, what changed since the board+looked different.++Surface: the grudge-match strip under the leaderboard on+[/play/arena](https://three.ws/play/arena)+Endpoint: `GET /api/sniper/rivalries`+Engine: [api/_lib/rivalries.js](../api/_lib/rivalries.js) ·+strip [src/play/rivalries.js](../src/play/rivalries.js) ·+tests [tests/rivalries.test.js](../tests/rivalries.test.js)++## Why it exists++Everything the platform knows about a trader is already public and provable: the+[leaderboard](trading-surfaces.md) ranks them, [/trader/:id](../src/trader.js)+proves the record, and [Trader Wrapped](trader-wrapped.md) recaps a season. What+none of those answer is the question a spectator asks first, which is what just+happened. A place changing hands is the smallest unit of drama a trading board+produces, it happens on its own several times a week, and until now nothing+noticed it.++## Where the numbers come from++One fetch, three boards, no new table and no cron.++The engine reads every public trader's positions once, through the same+`fetchLeaderboardPositions` the leaderboard uses, and runs three passes of the+shared, pure `computeTraderMetrics` over them:++| Board | What it is |+| --- | --- |+| `now` | The current window, exactly what `/api/sniper/leaderboard` ranks. |+| `past` | The same window length measured at the lookback cutoff, built from the round-trips that had already closed by then. |+| `since` | Only the round-trips closed inside the lookback. This is momentum: who is gaining ground right now. |++The `past` board is **re-derived from close timestamps**, not read out of a+snapshot table. That choice is why the feature works retroactively from the day+it shipped, cannot drift out of agreement with the live board, and needs nothing+running in the background to stay true. It also means a rank change is measured+against what the board really said at the cutoff, not against whatever a cron+happened to capture.++Both ranking boards apply a floor of **three settled round-trips**: below that a+"board position" is noise rather than a record. The momentum board deliberately+does not, because a single settled trade inside the lookback is exactly the+movement it exists to show.++Open positions are excluded from every board here. The composite score is+computed from realized history alone, and a position that is open now was open at+the cutoff too, so counting it would let the past board disagree with itself.++## The three kinds of matchup++| Kind | Meaning |+| --- | --- |+| `overtake` | The two traders' order flipped since the cutoff. The one now on top passed the other. |+| `debut` | The higher trader was not on the board at the cutoff at all. |+| `chase` | The order did not change. This is a standing gap. |++Overtakes rank first in the feed, then debuts, then chases; within a kind the+matchup where more money moved during the lookback comes first, and the tightest+gap breaks the tie.++## The copy is derived, not generated++Every headline and subline is assembled from the numbers on the matchup object.+No model writes them. That is a deliberate call and it buys three things: the+strip renders instantly and for free on a public page that refreshes itself, any+sentence can be checked against the two profiles it links to, and no generated+sentence can invent a claim the ledger cannot back.++Two cases the phrasing is careful about, both caught against live production+data before this shipped:++- **The board ranks on the composite score, not on P&L**, so the trader one place+ down can be the one holding more SOL. Calling them "behind" would be false, so+ that matchup reads `X has out-earned Y by 0.021 SOL and still ranks below`.+- **A trader who settled nothing during the lookback did not book zero**, they+ were not in the market. That reads `X has not settled a trade in the last 24+ hours` rather than `X booked 0.000 SOL`, which is a number that looks like a+ fact and is not one.++## The endpoint++```+GET /api/sniper/rivalries?network=mainnet&window=7d&lookback=24h&limit=6+```++| Parameter | Values | Default |+| --- | --- | --- |+| `network` | `mainnet`, `devnet` | `mainnet` |+| `window` | `24h`, `7d`, `30d`, `all` | `7d` |+| `lookback` | `1h`, `24h`, `7d` | `24h` |+| `limit` | 1 to 12 | `6` |++Public, IP rate-limited, cached for 60 seconds at the edge. A bad parameter is+answered as a caller mistake (`400` with `invalid_network`, `invalid_window`,+`invalid_lookback` or `invalid_limit`), never as an empty feed.++```bash+curl -s 'https://three.ws/api/sniper/rivalries?window=7d&lookback=24h&limit=2'+```++```json+{+ "network": "mainnet",+ "window": "7d",+ "lookback": "24h",+ "board_size": 3,+ "cutoff": "2026-09-08T15:04:00.000Z",+ "min_closed": 3,+ "rivalries": [+ {+ "kind": "chase",+ "headline": "Midas Trader is 0.036 SOL behind Moe Money AI.",+ "subline": "Midas Trader has not settled a trade in the last 24 hours. Moe Money AI booked -0.002 SOL.",+ "gap_sol": 0.036347,+ "gap_score": 2,+ "since": { "leader_pnl_sol": -0.002, "chaser_pnl_sol": 0 },+ "shared_coins": [],+ "leader": { "agent_id": "…", "name": "Moe Money AI", "rank": 2, "was_rank": 2, "score": 46, "realized_pnl_sol": -0.014 },+ "chaser": { "agent_id": "…", "name": "Midas Trader", "rank": 3, "was_rank": 3, "score": 44, "realized_pnl_sol": -0.05 },+ "links": {+ "leader_profile": "/trader/…",+ "chaser_profile": "/trader/…",+ "ghost_copy_leader": "/ghost-copy?leader=…&window=7d"+ }+ }+ ]+}+```++`gap_sol` is signed, leader minus chaser. A negative value is the case described+above: the trader one place down holds more realized SOL and sits below on the+composite score alone.++`shared_coins` lists coins that appear in **both** traders' top earners, with what+each side booked on it. It is deliberately narrow: those are the per-coin numbers+both profiles already show, so an overlap here is one a reader can check. An+empty list means no shared coin among their best, never that they never+overlapped.++## On the page++The strip sits under the arena's KPI row, above the board it describes, and shows+up to three matchups: the two traders' faces, the kind as a pill, the headline,+the momentum line, any shared coin, and two links out (the leader's record, and a+[ghost-copy](ghost-copy.md) of them with no money at risk).++Every state is designed, because the strip has to survive an empty board on a+quiet day: one skeleton row while it loads, an honest line naming the settled+round-trip floor when nobody has cleared it yet, and a single amber line with a+retry when the feed cannot be reached. A failed refresh never wipes matchups that+are already on screen.++## Related++- [The trading surfaces](trading-surfaces.md): Radar, Coin Intelligence, Fade Radar, Live Trade Feed, Watchlist, Mission Control+- [Ghost-copy](ghost-copy.md): paper-copy any verified agent over their real closed trades+- [Trader Wrapped](trader-wrapped.md): the season recap, which carries its own nearest-rival slide+- [Fork a trade](fork-trade.md): one tap from any coin to the real trade paneldiff --git a/docs/trading-surfaces.md b/docs/trading-surfaces.mdindex a7edc1e01..53fcf2b2a 100644--- a/docs/trading-surfaces.md+++ b/docs/trading-surfaces.md@@ -25,6 +25,7 @@ On top of that base layer:- **Price history** (candlesticks) comes from Birdeye with GeckoTerminal fallback.- **Live trades** stream over server-sent events from `/api/pump/trades-stream` (PumpPortal websocket, relayed). PumpPortal gates per-coin trade subscriptions behind an API key funded with at least 0.02 SOL; when it refuses one, the socket stays open and simply never delivers, so the relay forwards that refusal as an SSE `notice` event and the tape shows a degraded state instead of a lit "live" lamp over an empty panel. A malformed `mint` is refused up front with `400 invalid_mint`.- **Smart-money pedigree** comes from the proven-wallet ledger (`/api/intel/smart-money`).+- **Rivalries** ([the matchup layer](rivalries.md)) turns the leaderboard's own deltas into what changed: who passed whom, who just arrived, and who is closing. It reads the same closed positions the board is ranked from.One naming trap for API users: `/radar` is served by `api/pump/coin-intel.js` and `/coin-intel` is served by `api/pump/intel.js`. The names look swapped; they are two distinct read models over the same engine.diff --git a/pages/play/arena.html b/pages/play/arena.htmlindex ae69ab9cf..a4137b2d3 100644--- a/pages/play/arena.html+++ b/pages/play/arena.html@@ -131,6 +131,45 @@.as-kpi b.up { color: var(--up); } .as-kpi b.down { color: var(--down); }.as-kpi i { font: 500 10px/1.1 var(--mono); color: var(--faint); font-style: normal; }+ /* grudge matches: what changed on the board, under the numbers that changed */+ .rivalries { border-bottom: 1px solid var(--line); padding: 9px 12px 10px; display: flex; flex-direction: column; gap: 8px; }+ .rv-head { font-size: 9.5px; text-transform: uppercase; letter-spacing: .07em; color: var(--faint); display: flex; gap: 6px; align-items: baseline; }+ .rv-head i { font-style: normal; text-transform: none; letter-spacing: 0; opacity: .75; }+ .rv-row { display: grid; grid-template-columns: 34px 1fr; gap: 9px; align-items: start; }+ .rv-faces { position: relative; display: block; width: 34px; height: 26px; }+ .rv-face { position: absolute; top: 0; width: 22px; height: 22px; border-radius: 7px; object-fit: cover;+ background: radial-gradient(120% 100% at 50% 0%, #1b2233, #0d1018); border: 1px solid var(--line); }+ .rv-face-fb { display: grid; place-items: center; font: 700 10px/1 var(--mono); color: var(--faint); }+ .rv-face.rv-a { left: 0; z-index: 2; border-color: color-mix(in srgb, var(--cyan) 45%, var(--line)); }+ .rv-face.rv-b { left: 12px; z-index: 1; filter: saturate(.7); }+ .rv-body { min-width: 0; }+ .rv-l1 { display: flex; gap: 6px; align-items: baseline; }+ .rv-l1 b { font: 600 12px/1.3 Inter, sans-serif; color: var(--ink); }+ .rv-kind { flex: none; font: 700 8.5px/1.6 var(--mono); text-transform: uppercase; letter-spacing: .06em;+ padding: 0 6px; border-radius: 999px; background: rgba(255,255,255,0.06); color: var(--muted); }+ .rv-kind.overtake { background: color-mix(in srgb, var(--up) 20%, transparent); color: var(--up); }+ .rv-kind.debut { background: color-mix(in srgb, var(--gold) 20%, transparent); color: var(--gold); }+ .rv-kind.chase { background: color-mix(in srgb, var(--cyan) 16%, transparent); color: var(--cyan); }+ .rv-l2 { font-size: 11px; line-height: 1.38; color: var(--muted); margin-top: 2px; }+ .rv-shared { display: block; font: 500 10.5px/1.4 var(--mono); color: var(--faint); margin-top: 3px; }+ .rv-cta { display: flex; gap: 12px; margin-top: 4px; flex-wrap: wrap; }+ .rv-cta a { font-size: 10.5px; color: var(--cyan); text-decoration: none; border-bottom: 1px solid transparent; transition: border-color .15s; }+ .rv-cta a:hover { border-bottom-color: currentColor; }+ .rv-cta a:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; border-radius: 3px; }+ .rv-note { font-size: 11.5px; line-height: 1.45; color: var(--muted); }+ .rv-note.rv-err { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; color: var(--gold); }+ .rv-note.rv-err b { color: var(--gold); font-weight: 600; }+ .rv-retry { padding: 4px 10px; border-radius: 7px; border: 1px solid var(--line); background: rgba(255,255,255,0.04);+ color: var(--ink); font: 600 11px/1 Inter, sans-serif; }+ .rv-retry:hover { border-color: var(--cyan); color: var(--cyan); }+ .rv-skel i { display: block; height: 10px; border-radius: 5px;+ background: linear-gradient(90deg, rgba(255,255,255,0.03) 25%, rgba(255,255,255,0.08) 37%, rgba(255,255,255,0.03) 63%);+ background-size: 400% 100%; animation: sh 1.3s infinite; }+ .rv-skel { grid-template-columns: 34px 1fr; row-gap: 6px; }+ .rv-skel .rv-sk-face { grid-row: 1 / span 2; height: 22px; width: 22px; border-radius: 7px; }+ .rv-skel .rv-sk-l2 { width: 70%; }+ @media (prefers-reduced-motion: reduce) { .rv-skel i { animation: none; } }+/* sort segmented control */.board-tools:empty, .sort-seg[hidden] { display: none; }.board-tools { padding: 9px 12px; border-bottom: 1px solid var(--line); }@@ -408,6 +447,7 @@</div></div><div class="arena-stats" id="arenaStats" hidden></div>+ <section class="rivalries" id="rivalries" aria-label="Grudge matches" hidden></section><div class="board-tools"><div class="sort-seg" id="sortSeg" role="group" aria-label="Sort leaderboard" hidden><button type="button" data-sort="score" aria-pressed="true" data-i18n="play_arena.score">Score</button>diff --git a/src/play/arena.js b/src/play/arena.jsindex 2c4c1c384..66c470b24 100644--- a/src/play/arena.js+++ b/src/play/arena.js@@ -14,6 +14,7 @@ import { createLogger } from '../shared/log.js';import { fetchReputationBatch } from '../shared/agent-reputation.js';import { fetchUnlocks } from '../shared/wallet-access.js';import { evaluateAccessKey, buildAccessContext } from '../shared/wallet-access-rules.js';+import { mountRivalries } from './rivalries.js';const log = createLogger('arena');@@ -156,6 +157,10 @@ function ingest(data) {// picker and the sort toggle respond from the first frame.mountControls();+ // The grudge-match strip reads its own endpoint and owns its own states, so it+ // paints (or says why it cannot) without waiting on the board or the 3D world.+ mountRivalries(document.getElementById('rivalries'), { network: NETWORK, window: '7d', lookback: '24h', limit: 2 });+// The HUD reads the leaderboard API, which owes nothing to the 3D load. Firing// it here means the board (or its error state) paints while the animation// library and the spectator's GLB are still downloading, instead of sitting ondiff --git a/src/play/rivalries.js b/src/play/rivalries.jsnew file mode 100644index 000000000..09a101e5b--- /dev/null+++ b/src/play/rivalries.js@@ -0,0 +1,109 @@+// rivalries.js: the grudge-match strip under the arena leaderboard.+//+// A leaderboard says who is ahead. This strip says what changed: who passed+// whom since the board looked different, who is closing, and who just arrived.+// It reads /api/sniper/rivalries, which derives every matchup from the same+// position ledger the board above it is ranked from, so the two can never+// disagree. Every number rendered here came back from that endpoint; nothing on+// this page computes a standing of its own.+//+// The strip is supplementary, so it never takes space it has not earned: while+// it loads it shows one skeleton row, with nothing to say it says so in one+// line, and a failed fetch degrades to a single amber line with a retry rather+// than an empty box or a hole where a section used to be.++const esc = (s) => String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c]));++const KIND_LABEL = { overtake: 'Passed', debut: 'Debut', chase: 'Chasing' };++/** Two stacked avatars, or the initial when a trader has no image. */+function facePair(a, b) {+ const face = (t, cls) => (t.image+ ? `<img class="rv-face ${cls}" src="${esc(t.image)}" alt="" loading="lazy" decoding="async" />`+ : `<span class="rv-face rv-face-fb ${cls}" aria-hidden="true">${esc((t.name || '?').slice(0, 1).toUpperCase())}</span>`);+ return `<span class="rv-faces">${face(a, 'rv-a')}${face(b, 'rv-b')}</span>`;+}++function rowHtml(r) {+ const kind = KIND_LABEL[r.kind] || 'Chasing';+ const shared = r.shared_coins && r.shared_coins.length ? r.shared_coins[0] : null;+ const sharedLine = shared && shared.symbol+ ? `<span class="rv-shared">Both traded ${esc(shared.symbol)}: ${shared.leader_pnl_sol >= 0 ? '+' : ''}${shared.leader_pnl_sol.toFixed(2)} vs ${shared.chaser_pnl_sol >= 0 ? '+' : ''}${shared.chaser_pnl_sol.toFixed(2)} SOL</span>`+ : '';+ return `+ <div class="rv-row">+ ${facePair(r.leader, r.chaser)}+ <div class="rv-body">+ <div class="rv-l1"><span class="rv-kind ${esc(r.kind)}">${esc(kind)}</span><b>${esc(r.headline)}</b></div>+ <div class="rv-l2">${esc(r.subline)}</div>+ ${sharedLine}+ <div class="rv-cta">+ <a href="${esc(r.links.leader_profile)}">${esc(r.leader.name)}'s record</a>+ <a href="${esc(r.links.ghost_copy_leader)}">Ghost-copy</a>+ </div>+ </div>+ </div>`;+}++/**+ * Mount the strip into `el` and keep it fresh.+ *+ * Returns a handle with `refresh()` and `stop()` so the arena can tie the strip's+ * polling to the page's own lifecycle instead of leaving a timer running behind a+ * hidden tab.+ */+export function mountRivalries(el, { network = 'mainnet', window: win = '7d', lookback = '24h', limit = 2, intervalMs = 90_000 } = {}) {+ if (!el) return { refresh: () => {}, stop: () => {} };+ let timer = null;+ let stopped = false;+ let painted = false;++ const shell = (inner) => { el.innerHTML = inner; el.hidden = false; };++ const skeleton = () => shell(`+ <div class="rv-head">Grudge matches <i>vs the board ${esc(lookback)} ago</i></div>+ <div class="rv-row rv-skel" role="status" aria-label="Loading rivalries"><i class="rv-sk-face"></i><i class="rv-sk-l1"></i><i class="rv-sk-l2"></i></div>`);++ const emptyState = (boardSize, minClosed) => shell(`+ <div class="rv-head">Grudge matches</div>+ <div class="rv-note">${boardSize > 0+ ? `One trader has a settled record on this board. A rivalry needs two, each with at least ${Number(minClosed) || 3} closed round-trips.`+ : `No trader has cleared ${Number(minClosed) || 3} closed round-trips on this board yet. The first one to do it starts the rivalry.`}</div>`);++ const errorState = () => {+ if (painted) return; // keep the last good matchups on screen+ shell(`+ <div class="rv-head">Grudge matches</div>+ <div class="rv-note rv-err"><b>Can't reach the rivalry feed.</b> <button type="button" class="rv-retry">Retry</button></div>`);+ const btn = el.querySelector('.rv-retry');+ if (btn) btn.addEventListener('click', () => { skeleton(); load(); });+ };++ async function load() {+ if (stopped) return;+ try {+ const q = new URLSearchParams({ network, window: win, lookback, limit: String(limit) });+ const res = await fetch(`/api/sniper/rivalries?${q}`, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`http ${res.status}`);+ const data = await res.json();+ if (stopped) return;+ const list = Array.isArray(data.rivalries) ? data.rivalries : [];+ if (!list.length) { painted = false; emptyState(data.board_size, data.min_closed); return; }+ shell(`+ <div class="rv-head">Grudge matches <i>vs the board ${esc(data.lookback)} ago</i></div>+ ${list.map(rowHtml).join('')}`);+ painted = true;+ } catch {+ errorState();+ }+ }++ skeleton();+ load();+ if (intervalMs > 0) timer = setInterval(load, intervalMs);++ return {+ refresh: load,+ stop() { stopped = true; if (timer) clearInterval(timer); timer = null; },+ };+}diff --git a/tests/rivalries.test.js b/tests/rivalries.test.jsnew file mode 100644index 000000000..26c959573--- /dev/null+++ b/tests/rivalries.test.js@@ -0,0 +1,223 @@+/**+ * The rivalry engine, pure logic tests.+ *+ * A matchup is public copy about two named traders, so what has to hold is not+ * that it renders but that it cannot lie: an overtake must be a real change of+ * places measured against the ledger as it stood at the cutoff, a gap must be a+ * distance rather than a signed number, the momentum line must name whoever+ * actually booked more inside the lookback, and a trader with too thin a record+ * must not appear on a board at all.+ */++import { describe, it, expect } from 'vitest';+import {+ groupByAgent, rankBoard, pairRivalries, rivalryCopy, sharedCoins, fmtSol, fmtGap, LOOKBACKS,+} from '../api/_lib/rivalries.js';++const LAM = 1e9;++/** A closed round-trip in the shape both position ledgers normalize to. */+function pos(agent, { id, pnlSol = 0, entry = 1, mint = 'MINTX', symbol = 'TICKER', close, name = 'Trader', image = null }) {+ return {+ id: String(id),+ agent_id: agent,+ agent_user_id: `user-${agent}`,+ agent_name: name,+ agent_avatar: image,+ agent_image: null,+ wallet: `wallet-${agent}`,+ mint,+ symbol,+ name: symbol,+ status: 'closed',+ exit_reason: pnlSol >= 0 ? 'take_profit' : 'stop_loss',+ entry_quote_lamports: String(Math.round(entry * LAM)),+ exit_quote_lamports: String(Math.round((entry + pnlSol) * LAM)),+ last_value_lamports: String(Math.round((entry + pnlSol) * LAM)),+ peak_value_lamports: String(Math.round((entry + Math.max(pnlSol, 0)) * LAM)),+ realized_pnl_lamports: String(Math.round(pnlSol * LAM)),+ realized_pnl_pct: (pnlSol / entry) * 100,+ buy_sig: `buy-${agent}-${id}`,+ sell_sig: `sell-${agent}-${id}`,+ opened_at: close,+ closed_at: close,+ moonbag_base_amount: null,+ moonbag_last_value_lamports: null,+ initials_recovered: null,+ };+}++const T0 = Date.parse('2026-09-01T00:00:00.000Z');+const at = (hoursAgoFromNow, now) => new Date(now - hoursAgoFromNow * 3_600_000).toISOString();++describe('formatting', () => {+ it('signs P&L and never signs a gap', () => {+ expect(fmtSol(1.5)).toBe('+1.50 SOL');+ expect(fmtSol(0.5, 2)).toBe('+0.50 SOL');+ expect(fmtSol(-1.5)).toBe('-1.50 SOL');+ expect(fmtSol(0)).toBe('0.000 SOL');+ expect(fmtGap(-1.5)).toBe('1.50 SOL');+ });++ it('scales precision to the size of the number', () => {+ expect(fmtGap(0.125)).toBe('0.125 SOL');+ expect(fmtGap(12.5)).toBe('12.5 SOL');+ expect(fmtGap(125)).toBe('125 SOL');+ });+});++describe('rankBoard', () => {+ const now = T0;+ const rows = [+ ...[1, 2, 3].map((i) => pos('a', { id: i, pnlSol: 1, close: at(48, now), name: 'Alpha' })),+ ...[1, 2].map((i) => pos('b', { id: i, pnlSol: 5, close: at(48, now), name: 'Beta' })),+ ];++ it('keeps a trader off the board below the settled-trade floor', () => {+ const board = rankBoard(groupByAgent(rows), { to: now });+ expect(board.map((r) => r.agent_id)).toEqual(['a']);+ });++ it('counts a thin record when the caller asks for momentum instead of a ranking', () => {+ const board = rankBoard(groupByAgent(rows), { to: now, minClosed: 1 });+ expect(board.map((r) => r.agent_id).sort()).toEqual(['a', 'b']);+ });++ it('excludes round-trips that closed outside the range', () => {+ const board = rankBoard(groupByAgent(rows), { from: now - 3_600_000, to: now, minClosed: 1 });+ expect(board).toEqual([]);+ });++ it('ranks from 1 with no gaps', () => {+ const board = rankBoard(groupByAgent(rows), { to: now, minClosed: 1 });+ expect(board.map((r) => r.rank)).toEqual([1, 2]);+ });+});++describe('pairRivalries', () => {+ const board = (rows) => rows.map((r, i) => ({ rank: i + 1, top_coins: [], ...r }));+ const nowBoard = board([+ { agent_id: 'a', name: 'Alpha', score: 70, realized_pnl_sol: 9 },+ { agent_id: 'b', name: 'Beta', score: 60, realized_pnl_sol: 6.5 },+ { agent_id: 'c', name: 'Gamma', score: 50, realized_pnl_sol: 2 },+ ]);++ it('calls a change of places an overtake and keeps it first', () => {+ const past = board([+ { agent_id: 'b', name: 'Beta', score: 65, realized_pnl_sol: 6 },+ { agent_id: 'a', name: 'Alpha', score: 55, realized_pnl_sol: 4 },+ { agent_id: 'c', name: 'Gamma', score: 50, realized_pnl_sol: 2 },+ ]);+ const since = board([{ agent_id: 'a', name: 'Alpha', score: 60, realized_pnl_sol: 5 }]);+ const out = pairRivalries({ now: nowBoard, past, since, window: '7d', lookback: '24h' });+ expect(out[0].kind).toBe('overtake');+ expect(out[0].leader.agent_id).toBe('a');+ expect(out[0].chaser.agent_id).toBe('b');+ expect(out[0].headline).toBe('Alpha passed Beta on the 7d board.');+ });++ it('calls an unchanged order a chase and reports the gap unsigned', () => {+ const past = nowBoard;+ const out = pairRivalries({ now: nowBoard, past, since: [], window: '7d', lookback: '24h' });+ const chase = out.find((r) => r.chaser.agent_id === 'b');+ expect(chase.kind).toBe('chase');+ expect(chase.gap_sol).toBeCloseTo(2.5, 6);+ expect(chase.headline).toBe('Beta is 2.50 SOL behind Alpha.');+ });++ it('calls a trader who was not on the past board a debut', () => {+ const past = board([+ { agent_id: 'b', name: 'Beta', score: 60, realized_pnl_sol: 6 },+ { agent_id: 'c', name: 'Gamma', score: 50, realized_pnl_sol: 2 },+ ]);+ const out = pairRivalries({ now: nowBoard, past, since: [], window: '7d', lookback: '24h' });+ expect(out[0].kind).toBe('debut');+ expect(out[0].headline).toBe('Alpha arrived at number 1 on the 7d board, above Beta.');+ });++ it('honours the limit and emits one matchup per adjacent pair', () => {+ const out = pairRivalries({ now: nowBoard, past: nowBoard, since: [], window: '7d', lookback: '24h' });+ expect(out).toHaveLength(2);+ expect(pairRivalries({ now: nowBoard, past: nowBoard, since: [], window: '7d', lookback: '24h', limit: 1 })).toHaveLength(1);+ });++ it('links both profiles and a ghost-copy of the leader', () => {+ const [r] = pairRivalries({ now: nowBoard, past: nowBoard, since: [], window: '7d', lookback: '24h', limit: 1 });+ expect(r.links.leader_profile).toBe('/trader/a');+ expect(r.links.chaser_profile).toBe('/trader/b');+ expect(r.links.ghost_copy_leader).toBe('/ghost-copy?leader=a&window=7d');+ });+});++describe('rivalryCopy momentum line', () => {+ const base = {+ kind: 'chase', window: '7d', lookback: '24h', gap_sol: 2.5,+ leader: { name: 'Alpha', rank: 1 }, chaser: { name: 'Beta', rank: 2 },+ };++ it('names the chaser when the chaser booked more', () => {+ const { subline } = rivalryCopy({ ...base, since: { leader_pnl_sol: 0.5, chaser_pnl_sol: 2 } });+ expect(subline).toBe('Beta booked +2.00 SOL in the last 24 hours against +0.50 SOL, and is closing.');+ });++ it('names the leader when the leader booked more', () => {+ const { subline } = rivalryCopy({ ...base, since: { leader_pnl_sol: 3, chaser_pnl_sol: -1 } });+ expect(subline).toBe('Alpha booked +3.00 SOL in the last 24 hours against -1.00 SOL, and is pulling away.');+ });++ it('says nothing settled rather than implying movement', () => {+ const { subline } = rivalryCopy({ ...base, since: { leader_pnl_sol: 0, chaser_pnl_sol: 0 } });+ expect(subline).toBe('Neither has settled a trade in the last 24 hours. The gap stands at 2.50 SOL.');+ });++ it('never says a trader booked zero when they were not in the market', () => {+ const idle = rivalryCopy({ ...base, since: { leader_pnl_sol: -0.05, chaser_pnl_sol: 0 } });+ expect(idle.subline).toBe('Beta has not settled a trade in the last 24 hours. Alpha booked -0.050 SOL.');+ const other = rivalryCopy({ ...base, since: { leader_pnl_sol: 0, chaser_pnl_sol: 1.2 } });+ expect(other.subline).toBe('Alpha has not settled a trade in the last 24 hours. Beta booked +1.20 SOL.');+ });++ it('does not call a trader "behind" when they hold more SOL than the trader above them', () => {+ const out = rivalryCopy({ ...base, gap_sol: -0.021, gap_score: 4, since: { leader_pnl_sol: 1, chaser_pnl_sol: 1 } });+ expect(out.headline).toBe('Beta has out-earned Alpha by 0.021 SOL and still ranks below.');+ });++ it('calls a dead-level P&L level, and points at the score', () => {+ const out = rivalryCopy({ ...base, gap_sol: 0, gap_score: -3, since: { leader_pnl_sol: 1, chaser_pnl_sol: 1 } });+ expect(out.headline).toBe('Beta and Alpha are level on P&L, 3 apart on score.');+ });++ it('writes neither banned dash character into any line it produces', () => {+ // The repo bans both glyphs everywhere it writes, and this copy is written+ // into a public page, so the ban is asserted rather than assumed. Matched by+ // code point so this test file does not contain the characters it forbids.+ const BANNED = /[\u2014\u2013]/;+ for (const kind of ['overtake', 'debut', 'chase']) {+ const { headline, subline } = rivalryCopy({ ...base, kind, since: { leader_pnl_sol: 1, chaser_pnl_sol: 1 } });+ expect(headline).not.toMatch(BANNED);+ expect(subline).not.toMatch(BANNED);+ }+ });+});++describe('sharedCoins', () => {+ it('reports only coins that appear in both traders top earners', () => {+ const a = { top_coins: [{ mint: 'M1', symbol: 'ONE', pnl_sol: 3 }, { mint: 'M2', symbol: 'TWO', pnl_sol: 1 }] };+ const b = { top_coins: [{ mint: 'M2', symbol: 'TWO', pnl_sol: -0.4 }, { mint: 'M9', symbol: 'NINE', pnl_sol: 2 }] };+ expect(sharedCoins(a, b)).toEqual([+ { mint: 'M2', symbol: 'TWO', leader_pnl_sol: 1, chaser_pnl_sol: -0.4 },+ ]);+ });++ it('returns nothing rather than guessing when there is no overlap', () => {+ expect(sharedCoins({ top_coins: [{ mint: 'M1' }] }, { top_coins: [{ mint: 'M2' }] })).toEqual([]);+ expect(sharedCoins({}, {})).toEqual([]);+ });+});++describe('lookbacks', () => {+ it('exposes the windows the endpoint validates against', () => {+ expect([...LOOKBACKS.keys()]).toEqual(['1h', '24h', '7d']);+ expect(LOOKBACKS.get('24h')).toBe(86_400_000);+ });+});