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(duels): ship the trader duels page, API and settlement cron

nirholasf57d3af8d23d
diff --git a/api/_lib/trader-duels.js b/api/_lib/trader-duels.js
index 365263e4c..5d98c5f43 100644
--- a/api/_lib/trader-duels.js
+++ b/api/_lib/trader-duels.js
@@ -223,7 +223,7 @@ export function settleCall(pick, market) {
* Validate a call's shape and stake against a balance. PURE.
* @returns {{ok:true, side:'a'|'b', stake:number} | {ok:false, code:string, message:string}}
*/
-export function validateCall({ side, stake, balance = Infinity } = {}) {
+export function validateCall({ side, stake, balance = null } = {}) {
if (side !== 'a' && side !== 'b') return { ok: false, code: 'invalid_side', message: 'side must be "a" or "b".' };
const s = Number(stake);
if (!Number.isInteger(s) || s < DUEL_RULES.min_stake || s > DUEL_RULES.max_stake) {
@@ -233,7 +233,7 @@ export function validateCall({ side, stake, balance = Infinity } = {}) {
message: `Stake a whole number of points from ${DUEL_RULES.min_stake} to ${DUEL_RULES.max_stake}.`,
};
}
- if (s > n(balance)) {
+ if (balance != null && s > n(balance)) {
return { ok: false, code: 'not_enough_points', message: `You have ${n(balance)} points. Your free allowance tops up at 00:00 UTC.` };
}
return { ok: true, side, stake: s };
diff --git a/api/cron/duels-tick.js b/api/cron/duels-tick.js
new file mode 100644
index 000000000..030d2bb1b
--- /dev/null
+++ b/api/cron/duels-tick.js
@@ -0,0 +1,19 @@
+// GET /api/cron/duels-tick: the trader-duels loop (api/_lib/trader-duels.js).
+//
+// Each tick voids duels whose trader went private or was deleted (refunding
+// every call), resolves duels whose window closed more than the grace period
+// ago from the realized P&L ledger, settles any call a crashed tick left open,
+// and opens duels for the next windows from the rivalry engine. Points only:
+// nothing here can move a token or touch a wallet.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runDuelsTick } from '../_lib/trader-duels.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const result = await runDuelsTick({ network: 'mainnet' });
+ return json(res, 200, { ok: true, ...result });
+});
diff --git a/api/duels/[id].js b/api/duels/[id].js
new file mode 100644
index 000000000..f61ce435a
--- /dev/null
+++ b/api/duels/[id].js
@@ -0,0 +1,58 @@
+// GET /api/duels/:id one duel: both traders' 30-day records,
+// the in-window standing, the crowd, and
+// whether the viewer can call it
+// POST /api/duels/:id { side, stake } make a call (signed in)
+// ---------------------------------------------------------------------------
+// Free to play: a call stakes duel points from the free daily allowance, and
+// points have no cash value. One call per user per duel, locked when the window
+// starts, never on a duel involving an agent the caller owns. See
+// api/_lib/trader-duels.js for the rules and how a duel resolves.
+
+import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
+import { getDuel, placeCall, DUEL_RULES } from '../_lib/trader-duels.js';
+import { duelCaller } from './_auth.js';
+
+/** The duel id is the path segment; route params win over the query string. */
+export function duelIdFromRequest(req) {
+ const fromRoute = req?.query?.id;
+ let raw = typeof fromRoute === 'string' && fromRoute ? fromRoute : '';
+ if (!raw) {
+ const segments = new URL(req?.url || '/', 'http://x').pathname.split('/').filter(Boolean);
+ raw = segments[segments.length - 1] || '';
+ }
+ return isUuid(raw) ? raw.toLowerCase() : null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const id = duelIdFromRequest(req);
+ if (!id) return error(res, 404, 'not_found', 'No such duel.');
+
+ if (req.method === 'GET') {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const caller = await duelCaller(req);
+ const duel = await getDuel(id, { userId: caller?.userId ?? null });
+ if (!duel) return error(res, 404, 'not_found', 'No such duel. It may have been removed, or the link is incomplete.');
+ res.setHeader?.('cache-control', 'private, no-store');
+ return json(res, 200, { duel, rules: DUEL_RULES, t: Date.now() });
+ }
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const caller = await duelCaller(req);
+ if (!caller) return error(res, 401, 'unauthorized', 'Sign in to make a call. It is free.');
+ if (caller.viaSession && !(await requireCsrf(req, res, caller.userId))) return;
+
+ const body = await readJson(req).catch(() => null);
+ if (!body || typeof body !== 'object') return error(res, 400, 'invalid_body', 'Send JSON: { "side": "a" | "b", "stake": number }.');
+
+ const result = await placeCall({ userId: caller.userId, marketId: id, side: body.side, stake: body.stake });
+ if (!result.ok) return error(res, result.status, result.code, result.message);
+ return json(res, 201, { ok: true, call: result.call, balance: result.balance });
+});
diff --git a/api/duels/_auth.js b/api/duels/_auth.js
new file mode 100644
index 000000000..9a2022686
--- /dev/null
+++ b/api/duels/_auth.js
@@ -0,0 +1,11 @@
+// The signed-in caller for /api/duels/*: a session cookie or a bearer token.
+// Returns { userId, viaSession } or null. Never throws.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+
+export async function duelCaller(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, viaSession: true };
+ const bearer = await authenticateBearer(extractBearer(req));
+ return bearer ? { userId: bearer.userId, viaSession: false } : null;
+}
diff --git a/api/duels/index.js b/api/duels/index.js
new file mode 100644
index 000000000..a8f27d668
--- /dev/null
+++ b/api/duels/index.js
@@ -0,0 +1,61 @@
+// GET /api/duels?phase=open|live|settled|all&agent=<agent id>&network=mainnet&limit=30
+// ---------------------------------------------------------------------------
+// Trader duels on the board: head-to-head calls on which of two traders books
+// more realized P&L over a fixed UTC window. Free to play; points have no cash
+// value. Each duel carries both traders, the window, its phase, the crowd's
+// split, and, for a signed-in viewer, their own call. `counts` feeds the tabs
+// and `eligible_traders` explains an empty board. See api/_lib/trader-duels.js.
+
+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import { listDuels, duelCounts, eligibleTraderCount, DUEL_RULES, NETWORKS, PHASES } from '../_lib/trader-duels.js';
+import { duelCaller } from './_auth.js';
+
+const MAX_LIMIT = 60;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) 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 network = params.get('network') || 'mainnet';
+ if (!NETWORKS.has(network)) return error(res, 400, 'invalid_network', 'network must be mainnet or devnet');
+ const phase = params.get('phase') || 'all';
+ if (!PHASES.has(phase)) return error(res, 400, 'invalid_phase', `phase must be one of ${[...PHASES].join(', ')}`);
+ const agent = params.get('agent');
+ if (agent && !isUuid(agent)) return error(res, 400, 'invalid_agent', 'agent must be an agent id');
+ const rawLimit = params.get('limit');
+ let limit = 30;
+ 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 caller = await duelCaller(req);
+ const now = Date.now();
+ const [duels, counts, eligible] = await Promise.all([
+ listDuels({ network, phase, agentId: agent, userId: caller?.userId ?? null, limit, now }),
+ duelCounts({ network, now }),
+ eligibleTraderCount({ network, now }),
+ ]);
+
+ res.setHeader?.('cache-control', 'private, no-store');
+ return json(res, 200, {
+ network,
+ phase,
+ agent: agent || null,
+ signed_in: !!caller,
+ rules: DUEL_RULES,
+ counts,
+ eligible_traders: eligible,
+ duels,
+ t: now,
+ });
+});
diff --git a/api/duels/leaderboard.js b/api/duels/leaderboard.js
new file mode 100644
index 000000000..e35a061ce
--- /dev/null
+++ b/api/duels/leaderboard.js
@@ -0,0 +1,41 @@
+// GET /api/duels/leaderboard?season=YYYY-MM&limit=25
+// ---------------------------------------------------------------------------
+// The season's predictors, ranked by net points from decided calls on duels
+// resolved inside the season (a UTC calendar month; defaults to the current
+// one). Ties break on more correct calls, then fewer calls. Void duels never
+// count. A signed-in viewer outside the top rows still gets their own row as
+// `me`. Points have no cash value.
+
+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { seasonLeaderboard, seasonFor, seasonById } from '../_lib/trader-duels.js';
+import { duelCaller } from './_auth.js';
+
+const MAX_LIMIT = 100;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) 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 rawSeason = params.get('season');
+ const season = rawSeason ? seasonById(rawSeason) : seasonFor();
+ if (!season) return error(res, 400, 'invalid_season', 'season must be YYYY-MM');
+ const rawLimit = params.get('limit');
+ let limit = 25;
+ 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 caller = await duelCaller(req);
+ const board = await seasonLeaderboard({ season, limit, userId: caller?.userId ?? null });
+ res.setHeader?.('cache-control', 'private, no-store');
+ return json(res, 200, { ...board, t: Date.now() });
+});
diff --git a/api/duels/me.js b/api/duels/me.js
new file mode 100644
index 000000000..c2d2262a3
--- /dev/null
+++ b/api/duels/me.js
@@ -0,0 +1,27 @@
+// GET /api/duels/me
+// ---------------------------------------------------------------------------
+// The signed-in predictor: today's free allowance (credited by this read if it
+// has not been yet), points balance, XP level including XP from correct calls,
+// this season's standing, recent calls and duel badges. Signed out, it answers
+// { signed_in: false } with the rules so the page can explain the game.
+// Points have no cash value and cannot be bought, sold, transferred or redeemed.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { loadPredictor, DUEL_RULES } from '../_lib/trader-duels.js';
+import { duelCaller } from './_auth.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ res.setHeader?.('cache-control', 'private, no-store');
+ const caller = await duelCaller(req);
+ if (!caller) return json(res, 200, { signed_in: false, rules: DUEL_RULES });
+
+ const me = await loadPredictor(caller.userId);
+ return json(res, 200, { signed_in: true, rules: DUEL_RULES, ...me });
+});
diff --git a/pages/duels.html b/pages/duels.html
new file mode 100644
index 000000000..44919cfb4
--- /dev/null
+++ b/pages/duels.html
@@ -0,0 +1,116 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot */(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" />
+ <script src="/referral-capture.js"></script>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Trader Duels: call the winner · three.ws</title>
+ <meta name="description" content="Call which of two pump.fun trader agents books more realized profit over a fixed UTC window. Free to play with a daily points allowance; points have no cash value. Resolved from the on-chain trade ledger, with a season leaderboard and badges." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/duels" />
+ <meta property="og:title" content="Trader Duels: call the winner · three.ws" />
+ <meta property="og:description" content="Head-to-head calls on real trader agents, resolved from the on-chain ledger. Free to play; points have no cash value." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Trader+Duels&amp;d=Call+which+trader+books+more+realized+profit.+Free+to+play%2C+resolved+from+the+on-chain+ledger.&amp;p=%2Fduels" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="Trader Duels on three.ws" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Trader Duels: call the winner · three.ws" />
+ <meta name="twitter:description" content="Head-to-head calls on real trader agents, resolved from the on-chain ledger. Free to play; points have no cash value." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Trader+Duels&amp;d=Call+which+trader+books+more+realized+profit.+Free+to+play%2C+resolved+from+the+on-chain+ledger.&amp;p=%2Fduels" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="canonical" href="https://three.ws/duels" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <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/syndicates.css" />
+ <link rel="stylesheet" href="/src/duels.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="sy" aria-labelledby="dx-title">
+ <p class="sy-kicker">Trader duels · skill predictions</p>
+ <h1 id="dx-title" class="sy-title">Call the trader duel</h1>
+ <p class="sy-sub">
+ Two traders who sit next to each other on the board, one fixed UTC window, one question: who books more
+ realized profit? Make your call before the window starts. The result comes straight from the on-chain
+ trade ledger, the same numbers their profiles show.
+ </p>
+ <p class="dx-free"><span aria-hidden="true">●</span> Free to play. Points have no cash value and cannot be bought, sold, transferred or redeemed.</p>
+
+ <div id="dxMe" aria-live="polite">
+ <div class="dx-me" aria-hidden="true">
+ <div class="sy-skel" style="height:104px"></div>
+ <div class="sy-skel" style="height:104px"></div>
+ <div class="sy-skel" style="height:104px"></div>
+ </div>
+ </div>
+
+ <section aria-labelledby="dxBoardTitle">
+ <h2 id="dxBoardTitle" class="sr-only">Duels</h2>
+ <div class="sy-toolbar">
+ <div class="sy-seg" id="dxTabs" role="group" aria-label="Duel status">
+ <button type="button" aria-pressed="true">Open for calls</button>
+ <button type="button" aria-pressed="false">Live</button>
+ <button type="button" aria-pressed="false">Settled</button>
+ </div>
+ <p class="sy-faint" id="dxFilter" style="margin:0;font-size:13px" hidden></p>
+ </div>
+ <div id="dxList" aria-live="polite" aria-busy="true">
+ <ul class="dx-grid" aria-hidden="true">
+ <li><div class="sy-skel" style="height:196px"></div></li>
+ <li><div class="sy-skel" style="height:196px"></div></li>
+ <li><div class="sy-skel" style="height:196px"></div></li>
+ </ul>
+ </div>
+ </section>
+
+ <div class="dx-two sy-section">
+ <section class="sy-panel" id="dxLb" aria-live="polite">
+ <div class="sy-skel" style="height:220px" aria-hidden="true"></div>
+ </section>
+ <section class="sy-panel" id="dxCalls" aria-live="polite">
+ <div class="sy-skel" style="height:220px" aria-hidden="true"></div>
+ </section>
+ </div>
+
+ <section class="sy-section sy-panel" aria-labelledby="dxHowTitle">
+ <h2 id="dxHowTitle" class="sy-h2">How duels work <small><a href="/docs/trader-duels" class="sy-faint">full rules</a></small></h2>
+ <ol class="dx-rules" id="dxRules">
+ <li>Every day you get a free points allowance. Points have no cash value.</li>
+ <li>Pick the trader who books more realized profit over the duel's window.</li>
+ <li>Calls lock when the window starts; the ledger decides the rest.</li>
+ </ol>
+ </section>
+
+ <section class="sy-section" aria-label="Related">
+ <div class="sy-actions">
+ <a class="sy-btn" href="/trade-rooms">Watch live trade rooms</a>
+ <a class="sy-btn" href="/leaderboard">Trader leaderboard</a>
+ <a class="sy-btn" href="/quests">Daily quests</a>
+ <a class="sy-btn" href="/play/arena">The Arena</a>
+ </div>
+ </section>
+ </main>
+
+ <div id="syToast" class="sy-toast" role="status" aria-live="polite"></div>
+
+ <script type="module" src="/src/duels.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/src/duel.js b/src/duel.js
new file mode 100644
index 000000000..9462308ca
--- /dev/null
+++ b/src/duel.js
@@ -0,0 +1,418 @@
+// /duels/:id: one trader duel. Both traders' live records, the in-window race,
+// the crowd, how it resolves, and the call form.
+//
+// Reads GET /api/duels/:id and GET /api/duels/me (points balance; credits the
+// free daily allowance). A call is POST /api/duels/:id { side, stake }. Points
+// have no cash value; nothing here can move a token.
+
+import { apiFetch } from './api.js';
+import { esc, fmtSol, fmtPct, tone, toast, errorMessage, hydrateAvatars, relTime } from './syndicate-shared.js';
+import { ava, crowdBar, phaseChip, windowLabel, pts, until, fmtUtc, VOID_TEXT, FREE_LINE } from './duels-shared.js';
+
+const rootEl = document.getElementById('dxRoot');
+const contentEl = document.getElementById('dxContent');
+const id = (location.pathname.match(/^\/duels\/([0-9a-f-]{36})\/?$/i) || [])[1] || null;
+
+let duel = null;
+let rules = null;
+let me = null;
+let stake = null;
+let side = null;
+let busy = false;
+let lastPhase = null;
+
+async function getJson(path) {
+ const r = await apiFetch(path, { allowAnonymous: true, headers: { accept: 'application/json' } });
+ if (!r.ok) {
+ const { message } = await errorMessage(r, `The server answered ${r.status}.`);
+ const err = new Error(message);
+ err.status = r.status;
+ throw err;
+ }
+ return r.json();
+}
+
+async function load({ quiet = false } = {}) {
+ if (!id) return renderMissing('That duel link is incomplete.');
+ if (!quiet) rootEl.setAttribute('aria-busy', 'true');
+ try {
+ const [d, m] = await Promise.all([
+ getJson(`/api/duels/${id}`),
+ getJson('/api/duels/me').catch(() => null),
+ ]);
+ duel = d.duel;
+ rules = d.rules;
+ me = m;
+ lastPhase = duel.phase;
+ if (stake == null) stake = Math.min(25, Math.max(rules.min_stake, me?.wallet?.balance ?? 25));
+ render();
+ if (me?.wallet?.granted_now && !quiet) toast(`+${me.wallet.daily_allowance} free points for today`);
+ } catch (err) {
+ if (err.status === 404) return renderMissing(err.message);
+ if (quiet) return;
+ contentEl.innerHTML = `
+ <div class="sy-state" role="alert">
+ <h2>This duel did not load</h2>
+ <p>${esc(err.message || 'Check your connection.')} If you already made a call it is safe: calls are stored with the duel and settle on schedule.</p>
+ <button type="button" class="sy-btn primary" id="dxRetry">Try again</button>
+ </div>`;
+ document.getElementById('dxRetry').addEventListener('click', () => load());
+ } finally {
+ rootEl.setAttribute('aria-busy', 'false');
+ }
+}
+
+function renderMissing(message) {
+ document.title = 'Duel not found · three.ws';
+ contentEl.innerHTML = `
+ <div class="sy-state">
+ <h2>Duel not found</h2>
+ <p>${esc(message)} Browse the duels that are open for calls right now.</p>
+ <a class="sy-btn primary" href="/duels">All duels</a>
+ </div>`;
+ rootEl.setAttribute('aria-busy', 'false');
+}
+
+// ── render ──────────────────────────────────────────────────
+
+function render() {
+ const d = duel;
+ document.title = `${d.a.name} vs ${d.b.name} · Trader Duels · three.ws`;
+ const lead = d.phase === 'resolved' ? d.winner : d.standing?.leading || null;
+ contentEl.innerHTML = `
+ <header class="dx-hero">
+ <div class="dx-hero-meta">${phaseChip(d)}<span>${esc(windowLabel(d))}</span></div>
+ <h1><span class="a">${esc(d.a.name)}</span> <span class="sy-faint" style="font-size:.6em">vs</span> <span class="b">${esc(d.b.name)}</span></h1>
+ <p class="dx-question">Who books more realized profit between <b>${esc(fmtUtc(d.window_start))}</b> and <b>${esc(fmtUtc(d.window_end))}</b>?</p>
+ ${d.headline ? `<p class="dx-headline">When this duel opened: ${esc(d.headline)}</p>` : ''}
+ </header>
+
+ <div class="sy-grid">
+ <div style="display:grid;gap:16px;min-width:0">
+ <div class="dx-traders">${traderCard('a', lead)}${traderCard('b', lead)}</div>
+ <section class="sy-panel" aria-labelledby="dxCrowdTitle">
+ <h2 class="sy-h2" id="dxCrowdTitle">The crowd <small>${esc(crowdBar(d).text)}</small></h2>
+ ${crowdBar(d).html}
+ <div style="display:flex;justify-content:space-between;gap:10px;margin-top:8px;font-size:12.5px" class="sy-faint">
+ <span>${esc(d.a.name)}: ${esc(d.crowd.a.calls)} ${d.crowd.a.calls === 1 ? 'call' : 'calls'}, ${esc(pts(d.crowd.a.points))}</span>
+ <span style="text-align:right">${esc(d.b.name)}: ${esc(d.crowd.b.calls)} ${d.crowd.b.calls === 1 ? 'call' : 'calls'}, ${esc(pts(d.crowd.b.points))}</span>
+ </div>
+ </section>
+ ${howItResolves()}
+ </div>
+ <aside class="sy-side" style="display:grid;gap:16px;align-content:start">
+ ${callPanel()}
+ <p class="sy-fine">${esc(FREE_LINE)}</p>
+ </aside>
+ </div>`;
+ hydrateAvatars(contentEl);
+ wireCall();
+}
+
+function spark(series, key) {
+ if (!Array.isArray(series) || series.length < 2) return '';
+ const w = 300;
+ const h = 48;
+ const min = Math.min(0, ...series);
+ const max = Math.max(0, ...series);
+ const span = max - min || 1;
+ const x = (i) => (i * w) / (series.length - 1);
+ const y = (v) => 4 + ((max - v) * (h - 8)) / span;
+ const line = series.map((v, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
+ const last = series[series.length - 1];
+ return `
+ <svg class="dx-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" role="img" aria-label="30-day realized equity curve ending at ${esc(fmtSol(last))}">
+ <line x1="0" x2="${w}" y1="${y(0).toFixed(1)}" y2="${y(0).toFixed(1)}" stroke="var(--sy-line)" stroke-dasharray="3 3" />
+ <path d="${line}" fill="none" stroke="var(--dx-${key})" stroke-width="2" vector-effect="non-scaling-stroke" stroke-linejoin="round" />
+ </svg>`;
+}
+
+function traderCard(key, lead) {
+ const d = duel;
+ const s = d[key];
+ const r = s.record;
+ const st = d.standing?.[key] || null;
+ const isLead = lead === key;
+ const links = s.links
+ ? `<div class="sy-actions"><a class="sy-btn sm" href="${esc(s.links.trade_room)}">Trade room</a><a class="sy-btn sm" href="${esc(s.links.trader)}">Trader profile</a></div>`
+ : '';
+ if (!s.available) {
+ return `
+ <section class="sy-panel dx-trader ${key}" aria-label="${esc(s.name)}">
+ <div class="dx-trader-head">${ava(s.name, s.image, 'dx-ava lg')}<div><h2>${esc(s.name)}</h2><small>No longer public</small></div></div>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0">This trader went private or was removed, so the duel is void and every call is refunded.</p>
+ </section>`;
+ }
+ const board = s.board.rank != null ? `#${esc(s.board.rank)} on the ${esc(rules.board_window)} board when the duel opened` : 'On the trader board';
+ const record = r
+ ? `
+ <dl class="sy-tiles">
+ <div class="sy-tile"><dt>Realized · 30d</dt><dd class="${tone(r.realized_pnl_sol)}">${esc(fmtSol(r.realized_pnl_sol))}</dd>${r.realized_pnl_usd != null ? `<small>$${esc(Math.abs(r.realized_pnl_usd).toLocaleString('en-US', { maximumFractionDigits: 0 }))}</small>` : ''}</div>
+ <div class="sy-tile"><dt>Win rate · 30d</dt><dd>${r.closed ? esc(fmtPct(r.win_rate * 100, { sign: false })) : 'None yet'}</dd><small>${esc(r.wins)} of ${esc(r.closed)} closed</small></div>
+ <div class="sy-tile"><dt>Score</dt><dd>${esc(r.score)}</dd><small>${r.verified ? 'Verified record' : 'Building a record'}</small></div>
+ </dl>
+ ${spark(r.pnl_series, key)}
+ <p class="sy-fine" style="margin-top:8px">${r.last_active_at ? `Last closed a trade ${esc(relTime(r.last_active_at))}` : 'No closed trade in 30 days'}${r.open_positions ? ` · ${esc(r.open_positions)} open now` : ''}</p>`
+ : '<p class="sy-muted" style="font-size:14px">Record unavailable.</p>';
+ return `
+ <section class="sy-panel dx-trader ${key}${isLead ? ' lead' : ''}" aria-label="${esc(s.name)}">
+ <div class="dx-trader-head">${ava(s.name, s.image, 'dx-ava lg')}<div><h2>${esc(s.name)}${isLead ? ` <span class="sy-badge good">${d.phase === 'resolved' ? 'Winner' : 'Leading'}</span>` : ''}</h2><small>${board}</small></div></div>
+ ${record}
+ ${st ? windowBox(st) : ''}
+ ${links}
+ </section>`;
+}
+
+function windowBox(st) {
+ const d = duel;
+ const label = d.phase === 'live' ? 'In this window so far' : d.phase === 'resolving' ? 'In the window (awaiting resolution)' : 'Final, in the window';
+ return `
+ <div class="dx-window">
+ <small style="margin:0 0 4px">${label}</small>
+ <b class="${tone(st.pnl_sol)}">${st.closed ? esc(fmtSol(st.pnl_sol)) : 'No closed trades'}</b>
+ <small>${esc(st.closed)} closed · ${esc(st.wins)} in profit${st.self_dealing_count ? ` · ${esc(st.self_dealing_count)} on own coins not counted` : ''}</small>
+ </div>`;
+}
+
+function howItResolves() {
+ const d = duel;
+ return `
+ <section class="sy-panel" aria-labelledby="dxHowTitle">
+ <h2 class="sy-h2" id="dxHowTitle">How this duel resolves</h2>
+ <ol class="dx-rules">
+ <li><b>Window:</b> ${esc(fmtUtc(d.window_start))} to ${esc(fmtUtc(d.window_end))}. Calls lock at the start.</li>
+ <li><b>Measured about ${esc(fmtUtc(d.resolves_at))}</b> from each trader's round-trips that closed inside the window, on both their sniper and strategy ledgers, using the same math as their <a href="${esc(d.a.links?.trader || '/leaderboard')}">trader profile</a>. Profit on a trader's own coins does not count.</li>
+ <li><b>More realized SOL wins.</b> A trader with no closed trade counts as flat, which beats a loss and loses to a profit.</li>
+ <li><b>Void and refunded</b> if the two are exactly level, if neither closes a trade, or if either trader goes private or is removed.</li>
+ <li><b>A correct call pays ${esc(rules.win_multiplier)}x its stake and ${esc(rules.xp_per_win)} XP.</b> A wrong call keeps nothing.</li>
+ </ol>
+ </section>`;
+}
+
+function callPanel() {
+ const d = duel;
+ const v = d.viewer;
+ const c = d.my_call;
+ const name = (k) => (k === 'a' ? d.a.name : d.b.name);
+
+ if (d.phase === 'resolved' || d.phase === 'void') return resultPanel();
+
+ if (c) {
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">Your call</h2>
+ <p style="font-size:18px;font-weight:800;margin:0 0 6px"><span style="color:var(--dx-${c.side})">${esc(name(c.side))}</span> · ${esc(pts(c.stake))}</p>
+ <p class="dx-payoff">If ${esc(name(c.side))} books more, you get <b>${esc(pts(c.stake * rules.win_multiplier))}</b> back and <b>${esc(rules.xp_per_win)} XP</b>. ${d.phase === 'open' ? `Calls lock in ${esc(until(d.window_start))}.` : 'The window is running; calls are locked.'}</p>
+ <div class="sy-actions" style="margin-top:12px"><a class="sy-btn sm" href="/duels">More duels</a></div>
+ </section>`;
+ }
+
+ if (d.phase !== 'open') {
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">Calls are locked</h2>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0 0 12px">Calls closed when the window started at ${esc(fmtUtc(d.window_start))}. ${d.phase === 'live' ? `The window ends in ${esc(until(d.window_end))}.` : 'The result lands in a few minutes.'}</p>
+ <a class="sy-btn primary" href="/duels">Find an open duel</a>
+ </section>`;
+ }
+
+ if (!v.signed_in) {
+ const next = encodeURIComponent(location.pathname);
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">Make your call</h2>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0 0 12px">Sign in to call this duel. You get ${esc(pts(rules.daily_allowance))} free every day, and it locks in ${esc(until(d.window_start))}.</p>
+ <div class="sy-actions"><a class="sy-btn primary" href="/login?next=${next}">Sign in</a><a class="sy-btn" href="/register?next=${next}">Create an account</a></div>
+ </section>`;
+ }
+
+ if (v.owns_a_trader) {
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">This one is yours</h2>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0 0 12px">You own one of these traders, so you cannot call this duel. Everyone else can; share it and let them back you.</p>
+ <div class="sy-actions"><button type="button" class="sy-btn" id="dxShare">Copy duel link</button><a class="sy-btn" href="/duels">Other duels</a></div>
+ </section>`;
+ }
+
+ if (!d.a.available || !d.b.available) {
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">This duel is being voided</h2>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0">A trader went private, so this duel no longer takes calls and every call is refunded.</p>
+ </section>`;
+ }
+
+ const balance = me?.wallet?.balance ?? 0;
+ const maxStake = Math.min(rules.max_stake, balance);
+ if (maxStake < rules.min_stake) {
+ return `
+ <section class="sy-panel" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">Out of points for today</h2>
+ <p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0 0 12px">You have ${esc(pts(balance))}; a call needs at least ${esc(rules.min_stake)}. Your free ${esc(pts(rules.daily_allowance))} arrive in ${esc(until(me?.wallet?.next_grant_at || d.window_start))}${new Date(me?.wallet?.next_grant_at || 0) < new Date(d.window_start) ? ', before this duel locks' : ''}.</p>
+ <a class="sy-btn" href="/duels">Watch the other duels</a>
+ </section>`;
+ }
+
+ stake = Math.min(Math.max(stake, rules.min_stake), maxStake);
+ const chips = [10, 25, 50, 100].filter((n) => n >= rules.min_stake && n <= rules.max_stake);
+ return `
+ <section class="sy-panel dx-call" aria-labelledby="dxCallTitle">
+ <h2 class="sy-h2" id="dxCallTitle">Make your call <small>locks in ${esc(until(d.window_start))}</small></h2>
+ <form id="dxForm" novalidate>
+ <fieldset>
+ <legend>Who books more realized profit?</legend>
+ <div class="dx-pickers">
+ ${['a', 'b'].map((k) => `
+ <label class="dx-pick ${k}">
+ <input type="radio" name="side" value="${k}" ${side === k ? 'checked' : ''} required />
+ ${ava(d[k].name, d[k].image)}<b>${esc(d[k].name)}</b>
+ </label>`).join('')}
+ </div>
+ </fieldset>
+ <div class="dx-stake">
+ <label class="sy-label" for="dxStakeNum">Stake <span class="sy-faint" style="font-weight:500">${esc(rules.min_stake)} to ${esc(maxStake)} points · you have ${esc(balance)}</span></label>
+ <div class="dx-stake-row">
+ <input type="range" id="dxStakeRange" min="${rules.min_stake}" max="${maxStake}" step="1" value="${stake}" aria-label="Stake in points" />
+ <input type="number" class="sy-input" id="dxStakeNum" min="${rules.min_stake}" max="${maxStake}" step="1" value="${stake}" inputmode="numeric" />
+ </div>
+ <div class="dx-chips" role="group" aria-label="Quick stake">
+ ${chips.map((n) => `<button type="button" data-stake="${n}" aria-pressed="${n === stake}" ${n > maxStake ? 'disabled' : ''}>${n}</button>`).join('')}
+ </div>
+ <p class="dx-payoff" id="dxPayoff"></p>
+ </div>
+ <div class="sy-err" id="dxErr" role="alert" hidden style="margin-top:12px"></div>
+ <button type="submit" class="sy-btn primary" id="dxSubmit" style="width:100%;margin-top:14px">Lock in my call</button>
+ </form>
+ </section>`;
+}
+
+function resultPanel() {
+ const d = duel;
+ const c = d.my_call;
+ const name = (k) => (k === 'a' ? d.a.name : d.b.name);
+ let mine = '<p style="margin-top:10px">You did not call this one.</p>';
+ if (c?.status === 'won') mine = `<p style="margin-top:10px" class="pos"><b>You called it.</b> ${esc(pts(c.payout))} back (${esc(pts(c.payout - c.stake, { sign: true }))}) and ${esc(rules.xp_per_win)} XP.</p>`;
+ else if (c?.status === 'lost') mine = `<p style="margin-top:10px" class="neg">You called ${esc(name(c.side))}. ${esc(pts(-c.stake, { sign: true }))}.</p>`;
+ else if (c?.status === 'refunded') mine = `<p style="margin-top:10px">Your ${esc(pts(c.stake))} were refunded.</p>`;
+ else if (c) mine = '<p style="margin-top:10px">Your call is settling.</p>';
+ const body = d.phase === 'void'
+ ? `<h2>Void</h2><p>${esc(VOID_TEXT[d.void_reason] || 'Every call was refunded.')}</p>`
+ : `<h2><span style="color:var(--dx-${d.winner})">${esc(name(d.winner))}</span> won</h2><p>${esc(name(d.winner))} booked more realized profit in the window. Final numbers are on each trader card, measured ${esc(fmtUtc(d.resolved_at || d.resolves_at))}.</p>`;
+ return `
+ <section class="sy-panel dx-result" aria-live="polite">
+ ${body}
+ ${mine}
+ <div class="sy-actions" style="justify-content:center;margin-top:14px"><a class="sy-btn primary" href="/duels">Next duel</a></div>
+ </section>`;
+}
+
+// ── the call form ───────────────────────────────────────────
+
+function payoffText() {
+ const el = document.getElementById('dxPayoff');
+ if (!el) return;
+ const who = side ? (side === 'a' ? duel.a.name : duel.b.name) : 'your pick';
+ el.innerHTML = `If ${esc(who)} books more: <b>${esc(pts(stake * rules.win_multiplier))}</b> back (${esc(pts(stake * (rules.win_multiplier - 1), { sign: true }))}) and <b>${esc(rules.xp_per_win)} XP</b>. If not, the ${esc(pts(stake))} are gone. Void duels refund.`;
+}
+
+function setStake(v, { from } = {}) {
+ const form = document.getElementById('dxForm');
+ if (!form) return;
+ const range = document.getElementById('dxStakeRange');
+ const num = document.getElementById('dxStakeNum');
+ const max = Number(range.max);
+ const n = Math.round(Number(v));
+ if (!Number.isFinite(n)) return;
+ stake = Math.min(Math.max(n, rules.min_stake), max);
+ if (from !== 'range') range.value = String(stake);
+ if (from !== 'num') num.value = String(stake);
+ for (const b of form.querySelectorAll('[data-stake]')) b.setAttribute('aria-pressed', String(Number(b.dataset.stake) === stake));
+ payoffText();
+}
+
+function wireCall() {
+ document.getElementById('dxShare')?.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(location.href);
+ toast('Duel link copied');
+ } catch {
+ toast('Copy the address bar to share this duel');
+ }
+ });
+ const form = document.getElementById('dxForm');
+ if (!form) return;
+ payoffText();
+ for (const r of form.querySelectorAll('input[name="side"]')) {
+ r.addEventListener('change', () => {
+ side = r.value;
+ payoffText();
+ });
+ }
+ document.getElementById('dxStakeRange').addEventListener('input', (e) => setStake(e.target.value, { from: 'range' }));
+ const num = document.getElementById('dxStakeNum');
+ num.addEventListener('change', (e) => setStake(e.target.value));
+ for (const b of form.querySelectorAll('[data-stake]')) b.addEventListener('click', () => setStake(b.dataset.stake));
+ form.addEventListener('submit', submitCall);
+}
+
+async function submitCall(e) {
+ e.preventDefault();
+ if (busy) return;
+ const errEl = document.getElementById('dxErr');
+ const btn = document.getElementById('dxSubmit');
+ errEl.hidden = true;
+ if (side !== 'a' && side !== 'b') {
+ errEl.textContent = 'Pick the trader you think books more.';
+ errEl.hidden = false;
+ document.querySelector('input[name="side"]')?.focus();
+ return;
+ }
+ busy = true;
+ btn.disabled = true;
+ btn.textContent = 'Locking in…';
+ try {
+ const r = await apiFetch(`/api/duels/${id}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ side, stake }),
+ });
+ if (!r.ok) {
+ const { message } = await errorMessage(r, 'Your call did not go through.');
+ errEl.textContent = message;
+ errEl.hidden = false;
+ if (r.status === 409 || r.status === 403) load({ quiet: true });
+ return;
+ }
+ const out = await r.json();
+ toast(`Call locked: ${side === 'a' ? duel.a.name : duel.b.name}, ${out.call.stake} points. ${out.balance} left.`);
+ await load({ quiet: true });
+ } catch {
+ errEl.textContent = 'Network error. Your call was not placed; try again.';
+ errEl.hidden = false;
+ } finally {
+ busy = false;
+ const b = document.getElementById('dxSubmit');
+ if (b) {
+ b.disabled = false;
+ b.textContent = 'Lock in my call';
+ }
+ }
+}
+
+// Countdowns and the live race stay current: re-render the clock every 30
+// seconds and refetch while the window runs, or when the duel changes phase.
+setInterval(() => {
+ if (!duel || busy) return;
+ const phaseNow = duel.status !== 'open' ? duel.phase
+ : Date.now() < Date.parse(duel.window_start) ? 'open'
+ : Date.now() < Date.parse(duel.window_end) ? 'live' : 'resolving';
+ if (phaseNow !== lastPhase || phaseNow === 'live' || phaseNow === 'resolving') {
+ load({ quiet: true });
+ return;
+ }
+ const chip = contentEl.querySelector('.dx-hero-meta');
+ if (chip) chip.firstElementChild.outerHTML = phaseChip(duel);
+}, 30_000);
+
+load();
diff --git a/src/duels-shared.js b/src/duels-shared.js
new file mode 100644
index 000000000..64fc3c4e2
--- /dev/null
+++ b/src/duels-shared.js
@@ -0,0 +1,116 @@
+// Shared rendering for /duels, /duels/:id and the duels widget on /trader/:id.
+// Every number comes from the API; nothing here computes a result.
+
+import { esc, fmtSol, tone } from './syndicate-shared.js';
+
+export const FREE_LINE = 'Free to play. Points have no cash value and cannot be bought, sold, transferred or redeemed.';
+
+const DATE_FMT = { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' };
+const TIME_FMT = { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' };
+
+export const fmtDay = (iso) => new Date(iso).toLocaleDateString('en-US', DATE_FMT);
+export const fmtUtc = (iso) => `${new Date(iso).toLocaleString('en-US', TIME_FMT)} UTC`;
+
+export function pts(v, { sign = false } = {}) {
+ const n = Math.round(Number(v) || 0);
+ const s = `${Math.abs(n).toLocaleString('en-US')} ${Math.abs(n) === 1 ? 'point' : 'points'}`;
+ if (!sign || n === 0) return n < 0 ? `-${s}` : s;
+ return `${n > 0 ? '+' : '−'}${s}`;
+}
+
+/** "5h 20m", "2d 4h", "12m", from now until an ISO time. */
+export function until(iso, now = Date.now()) {
+ const ms = new Date(iso).getTime() - now;
+ if (ms <= 0) return 'now';
+ const m = Math.floor(ms / 60_000);
+ const d = Math.floor(m / 1440);
+ const h = Math.floor((m % 1440) / 60);
+ if (d > 0) return `${d}d ${h}h`;
+ if (h > 0) return `${h}h ${String(m % 60).padStart(2, '0')}m`;
+ return `${Math.max(1, m)}m`;
+}
+
+export function windowLabel(d) {
+ if (d.window_kind === 'week') return `Week duel · ${fmtDay(d.window_start)} to ${fmtDay(d.window_end)}`;
+ return `24h duel · ${fmtDay(d.window_start)}`;
+}
+
+export const VOID_TEXT = {
+ tie: 'Both traders booked exactly the same realized P&L, so the duel was a tie. Every call was refunded.',
+ no_trades: 'Neither trader closed a trade during the window, so there was nothing to compare. Every call was refunded.',
+ trader_unavailable: 'One of the traders went private or was removed before the duel resolved. Every call was refunded.',
+};
+
+export function phaseChip(d, now = Date.now()) {
+ switch (d.phase) {
+ case 'open': return `<span class="dx-phase open">Open · locks in ${esc(until(d.window_start, now))}</span>`;
+ case 'live': return `<span class="dx-phase live"><span class="dx-live-dot" aria-hidden="true"></span>Live · ends in ${esc(until(d.window_end, now))}</span>`;
+ case 'resolving': return `<span class="dx-phase resolving">Resolving</span>`;
+ case 'resolved': return `<span class="dx-phase resolved">Resolved</span>`;
+ default: return `<span class="dx-phase void">Void · refunded</span>`;
+ }
+}
+
+/** Round avatar with an initial fallback (hydrate with hydrateAvatars from syndicate-shared). */
+export function ava(name, image, cls = 'dx-ava') {
+ const initial = esc((String(name || '?').trim()[0] || '?').toUpperCase());
+ if (image) return `<img class="${cls}" src="${esc(image)}" alt="" loading="lazy" decoding="async" data-initial="${initial}" />`;
+ return `<span class="${cls}" aria-hidden="true">${initial}</span>`;
+}
+
+export function crowdBar(d) {
+ const a = d.crowd.a.points;
+ const b = d.crowd.b.points;
+ const total = a + b;
+ const calls = d.crowd.a.calls + d.crowd.b.calls;
+ const pa = total ? Math.round((a / total) * 100) : 50;
+ const label = total
+ ? `Crowd: ${d.crowd.a.calls} ${d.crowd.a.calls === 1 ? 'call' : 'calls'} on ${d.a.name} (${pa}% of points), ${d.crowd.b.calls} on ${d.b.name} (${100 - pa}%)`
+ : 'No calls yet';
+ return {
+ html: `<div class="dx-crowd${total ? '' : ' empty'}" role="img" aria-label="${esc(label)}"><i class="a" style="width:${pa}%"></i><i class="b" style="width:${100 - pa}%"></i></div>`,
+ text: total ? `${calls} ${calls === 1 ? 'call' : 'calls'} · ${pa}% on ${d.a.name}` : 'No calls yet. Be first.',
+ };
+}
+
+export function myCallChip(d) {
+ const c = d.my_call;
+ if (!c) return '';
+ const who = c.side === 'a' ? d.a.name : d.b.name;
+ if (c.status === 'won') return `<span class="dx-mine won">You called ${esc(who)} · ${esc(pts(c.payout - c.stake, { sign: true }))}</span>`;
+ if (c.status === 'lost') return `<span class="dx-mine lost">You called ${esc(who)} · ${esc(pts(-c.stake, { sign: true }))}</span>`;
+ if (c.status === 'refunded') return `<span class="dx-mine">You called ${esc(who)} · refunded</span>`;
+ return `<span class="dx-mine">Your call: ${esc(who)} · ${esc(pts(c.stake))}</span>`;
+}
+
+function sideLine(d, key) {
+ const s = d[key];
+ const r = d.result?.[key];
+ if ((d.phase === 'resolved' || d.phase === 'void') && r) {
+ return `<span class="${tone(r.pnl_sol)}">${esc(fmtSol(r.pnl_sol))}</span> · ${esc(r.closed)} closed`;
+ }
+ const parts = [];
+ if (s.board.rank != null) parts.push(`#${esc(s.board.rank)}`);
+ if (s.board.realized_pnl_sol != null) parts.push(`<span class="${tone(s.board.realized_pnl_sol)}">${esc(fmtSol(s.board.realized_pnl_sol))}</span> 30d`);
+ return parts.join(' · ') || '30-day record on profile';
+}
+
+/** One duel on the board. */
+export function duelCard(d, now = Date.now()) {
+ const crowd = crowdBar(d);
+ const win = (k) => (d.phase === 'resolved' && d.winner === k ? ' win' : '');
+ const cta = d.phase === 'open' ? (d.my_call ? 'View duel' : 'Make your call') : d.phase === 'live' ? 'Watch the race' : 'See the result';
+ return `
+ <li>
+ <a class="dx-card" href="${esc(d.url)}" aria-label="${esc(`${d.a.name} versus ${d.b.name}, ${windowLabel(d)}`)}">
+ <div class="dx-card-top">${phaseChip(d, now)}<span>${esc(windowLabel(d))}</span></div>
+ <div class="dx-vs">
+ <div class="dx-side a${win('a')}">${ava(d.a.name, d.a.image)}<div><b>${esc(d.a.name)}</b><small>${sideLine(d, 'a')}</small></div></div>
+ <span class="dx-vs-mark" aria-hidden="true">vs</span>
+ <div class="dx-side b${win('b')}">${ava(d.b.name, d.b.image)}<div><b>${esc(d.b.name)}</b><small>${sideLine(d, 'b')}</small></div></div>
+ </div>
+ ${crowd.html}
+ <div class="dx-card-foot"><span>${d.my_call ? myCallChip(d) : esc(crowd.text)}</span><span class="dx-cta">${esc(cta)} →</span></div>
+ </a>
+ </li>`;
+}
diff --git a/src/duels.css b/src/duels.css
new file mode 100644
index 000000000..1428e5034
--- /dev/null
+++ b/src/duels.css
@@ -0,0 +1,162 @@
+/* Trader duels (/duels, /duels/:id). Layered on src/syndicates.css, which owns
+ the palette, buttons, panels, tiles, skeletons and states for both themes. */
+
+:root {
+ --dx-a: #7c5cff;
+ --dx-b: #22d3ee;
+}
+:root[data-theme='light'] {
+ --dx-a: #6d4aff;
+ --dx-b: #0891b2;
+}
+
+.dx-free {
+ display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap;
+ font-size: 12.5px; font-weight: 700; color: var(--sy-green);
+ background: color-mix(in srgb, var(--sy-green) 12%, transparent);
+ border: 1px solid color-mix(in srgb, var(--sy-green) 35%, transparent);
+ padding: 6px 12px; border-radius: 999px; margin: 0 0 18px;
+}
+
+/* ── points bar ──────────────────────────────────────────── */
+.dx-me { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr); margin-bottom: 22px; }
+@media (min-width: 820px) { .dx-me { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
+.dx-stat { display: flex; align-items: center; gap: 14px; min-width: 0; }
+.dx-stat-num { font-size: 30px; font-weight: 900; letter-spacing: -.03em; font-variant-numeric: tabular-nums; line-height: 1; }
+.dx-stat-lbl { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--sy-faint); font-weight: 700; margin-bottom: 6px; }
+.dx-stat small { display: block; color: var(--sy-faint); font-size: 12.5px; margin-top: 6px; line-height: 1.45; }
+.dx-coin {
+ width: 48px; height: 48px; border-radius: 14px; flex: none; display: grid; place-items: center;
+ font-weight: 900; font-size: 15px; color: #fff; background: linear-gradient(135deg, var(--dx-a), var(--dx-b));
+}
+
+/* ── board ───────────────────────────────────────────────── */
+.dx-grid { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); }
+.dx-card {
+ display: flex; flex-direction: column; gap: 14px; height: 100%;
+ background: var(--sy-panel); border: 1px solid var(--sy-line); border-radius: var(--sy-radius);
+ padding: 16px; text-decoration: none; color: inherit;
+ transition: border-color var(--sy-fast), transform var(--sy-fast), background var(--sy-fast);
+ animation: sy-in var(--sy-base) ease both;
+}
+.dx-card:hover { transform: translateY(-2px); border-color: var(--sy-accent); background: var(--sy-panel-2); }
+.dx-card:active { transform: none; }
+.dx-card:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }
+.dx-card-top { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12.5px; color: var(--sy-faint); }
+.dx-vs { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 10px; }
+.dx-side { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.dx-side.b { flex-direction: row-reverse; text-align: right; }
+.dx-side b { display: block; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dx-side small { display: block; font-size: 12px; color: var(--sy-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.dx-side > div { min-width: 0; }
+.dx-side.win b::after { content: ' ✓'; color: var(--sy-green); }
+.dx-vs-mark { font-size: 12px; font-weight: 900; letter-spacing: .1em; color: var(--sy-faint); text-transform: uppercase; }
+.dx-ava { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; flex: none; display: inline-grid; place-items: center; font-weight: 800; font-size: 14px; background: var(--sy-panel-2); border: 2px solid var(--dx-side, var(--sy-accent)); color: var(--dx-side, var(--sy-accent)); }
+.dx-side.a .dx-ava { --dx-side: var(--dx-a); }
+.dx-side.b .dx-ava { --dx-side: var(--dx-b); }
+.dx-ava.lg { width: 64px; height: 64px; font-size: 22px; border-width: 3px; }
+
+.dx-crowd { height: 8px; border-radius: 999px; overflow: hidden; display: flex; background: var(--sy-panel-2); border: 1px solid var(--sy-line); }
+.dx-crowd i { display: block; height: 100%; transition: width 500ms cubic-bezier(.2, .8, .2, 1); }
+.dx-crowd i.a { background: var(--dx-a); }
+.dx-crowd i.b { background: var(--dx-b); }
+.dx-crowd.empty i { background: transparent; }
+.dx-card-foot { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12.5px; color: var(--sy-dim); margin-top: auto; }
+.dx-cta { font-weight: 800; color: var(--sy-accent); white-space: nowrap; }
+.dx-card:hover .dx-cta { color: var(--sy-accent-2); }
+
+.dx-phase { font-size: 11px; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; padding: 4px 9px; border-radius: 999px; white-space: nowrap; }
+.dx-phase.open { background: color-mix(in srgb, var(--sy-green) 16%, transparent); color: var(--sy-green); }
+.dx-phase.live { background: color-mix(in srgb, var(--sy-amber) 18%, transparent); color: var(--sy-amber); }
+.dx-phase.resolving { background: color-mix(in srgb, var(--sy-amber) 12%, transparent); color: var(--sy-amber); }
+.dx-phase.resolved { background: color-mix(in srgb, var(--sy-accent) 16%, transparent); color: var(--sy-accent); }
+.dx-phase.void { background: var(--sy-chip); color: var(--sy-dim); }
+.dx-live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: currentColor; margin-right: 6px; vertical-align: 1px; animation: dx-pulse 1.6s ease-in-out infinite; }
+@keyframes dx-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
+
+.dx-mine { font-size: 11.5px; font-weight: 800; padding: 3px 8px; border-radius: 999px; background: var(--sy-chip); color: var(--sy-text); white-space: nowrap; }
+.dx-mine.won { background: color-mix(in srgb, var(--sy-green) 16%, transparent); color: var(--sy-green); }
+.dx-mine.lost { background: color-mix(in srgb, var(--sy-red) 14%, transparent); color: var(--sy-red); }
+
+/* ── predictor board + calls ─────────────────────────────── */
+.dx-lb { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
+.dx-lb li { display: grid; grid-template-columns: 34px 30px minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 9px 12px; border-radius: 11px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); font-size: 13.5px; }
+.dx-lb li.me { border-color: var(--sy-accent); }
+.dx-lb .rk { font-weight: 900; color: var(--sy-faint); font-variant-numeric: tabular-nums; }
+.dx-lb b { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dx-lb small { color: var(--sy-faint); font-size: 12px; }
+.dx-lb a { text-decoration: none; }
+.dx-lb a:hover b { color: var(--sy-accent-2); }
+.dx-lb .net { font-weight: 800; font-variant-numeric: tabular-nums; white-space: nowrap; }
+.dx-calls { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
+.dx-calls a { display: flex; justify-content: space-between; gap: 10px; align-items: center; text-decoration: none; padding: 10px 12px; border-radius: 11px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); font-size: 13.5px; transition: border-color var(--sy-fast); }
+.dx-calls a:hover { border-color: var(--sy-accent); }
+.dx-calls a:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }
+.dx-calls span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dx-two { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); }
+@media (min-width: 900px) { .dx-two { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); align-items: start; } }
+
+.dx-rules { margin: 0; padding-left: 20px; display: grid; gap: 8px; font-size: 14px; color: var(--sy-dim); line-height: 1.55; }
+.dx-rules b { color: var(--sy-text); }
+
+/* ── detail ──────────────────────────────────────────────── */
+.dx-hero { margin-bottom: 18px; }
+.dx-hero h1 { margin: 6px 0 8px; font-size: clamp(26px, 5vw, 44px); line-height: 1.05; letter-spacing: -.025em; font-weight: 800; overflow-wrap: anywhere; }
+.dx-hero h1 .a { color: var(--dx-a); }
+.dx-hero h1 .b { color: var(--dx-b); }
+.dx-hero-meta { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; font-size: 13px; color: var(--sy-faint); }
+.dx-question { font-size: clamp(15px, 2.2vw, 17px); color: var(--sy-dim); max-width: 70ch; line-height: 1.55; margin: 10px 0 0; }
+.dx-headline { font-size: 13.5px; color: var(--sy-faint); margin: 8px 0 0; }
+.dx-traders { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr); }
+@media (min-width: 760px) { .dx-traders { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } }
+.dx-trader { border-top: 3px solid var(--dx-side); }
+.dx-trader.a { --dx-side: var(--dx-a); }
+.dx-trader.b { --dx-side: var(--dx-b); }
+.dx-trader.lead { box-shadow: 0 0 0 1px var(--dx-side), 0 18px 40px -24px var(--dx-side); }
+.dx-trader-head { display: flex; gap: 14px; align-items: center; margin-bottom: 14px; min-width: 0; }
+.dx-trader-head > div { min-width: 0; }
+.dx-trader-head h2 { margin: 0; font-size: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dx-trader-head small { color: var(--sy-faint); font-size: 12.5px; }
+.dx-window { margin-top: 12px; padding: 12px 14px; border-radius: 12px; background: color-mix(in srgb, var(--dx-side) 8%, var(--sy-panel-2)); border: 1px solid color-mix(in srgb, var(--dx-side) 35%, var(--sy-line)); }
+.dx-window b { font-size: 22px; font-weight: 900; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
+.dx-window small { display: block; color: var(--sy-faint); font-size: 12px; margin-top: 3px; }
+.dx-trader .sy-actions { margin-top: 14px; }
+.dx-spark { width: 100%; height: 48px; display: block; margin-top: 12px; }
+
+.dx-call fieldset { border: 0; margin: 0; padding: 0; min-width: 0; }
+.dx-call legend { font-weight: 800; font-size: 15px; margin-bottom: 10px; padding: 0; }
+.dx-pickers { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; }
+.dx-pick { position: relative; display: flex; align-items: center; gap: 10px; min-width: 0; padding: 12px; border-radius: 12px; border: 2px solid var(--sy-line); background: var(--sy-panel-2); cursor: pointer; transition: border-color var(--sy-fast), background var(--sy-fast), transform var(--sy-fast); }
+.dx-pick:hover { border-color: var(--dx-side); transform: translateY(-1px); }
+.dx-pick.a { --dx-side: var(--dx-a); }
+.dx-pick.b { --dx-side: var(--dx-b); }
+.dx-pick input { position: absolute; opacity: 0; width: 1px; height: 1px; }
+.dx-pick:has(input:checked) { border-color: var(--dx-side); background: color-mix(in srgb, var(--dx-side) 12%, var(--sy-panel-2)); }
+.dx-pick:has(input:focus-visible) { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }
+.dx-pick b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; }
+.dx-stake { display: grid; gap: 10px; margin-top: 16px; }
+.dx-stake-row { display: flex; align-items: center; gap: 12px; }
+.dx-stake-row input[type='range'] { flex: 1; accent-color: var(--sy-accent); min-width: 0; height: 28px; }
+.dx-stake-row input[type='number'] { width: 88px; }
+.dx-chips { display: flex; gap: 6px; flex-wrap: wrap; }
+.dx-chips button { appearance: none; font: inherit; font-size: 12.5px; font-weight: 700; padding: 6px 12px; border-radius: 999px; border: 1px solid var(--sy-line); background: var(--sy-panel-2); color: var(--sy-dim); cursor: pointer; min-height: 32px; transition: border-color var(--sy-fast), color var(--sy-fast); }
+.dx-chips button:hover { border-color: var(--sy-accent); color: var(--sy-text); }
+.dx-chips button:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }
+.dx-chips button[aria-pressed='true'] { border-color: var(--sy-accent); color: var(--sy-text); background: color-mix(in srgb, var(--sy-accent) 14%, var(--sy-panel-2)); }
+.dx-chips button[disabled] { opacity: .45; cursor: not-allowed; }
+.dx-payoff { font-size: 13px; color: var(--sy-dim); line-height: 1.5; }
+.dx-payoff b { color: var(--sy-text); }
+.dx-result { text-align: center; padding: 22px 18px; }
+.dx-result h2 { margin: 0 0 6px; font-size: 22px; }
+.dx-result p { margin: 0 auto; max-width: 60ch; color: var(--sy-dim); font-size: 14px; line-height: 1.55; }
+
+@media (max-width: 520px) {
+ .dx-pickers { grid-template-columns: minmax(0, 1fr); }
+ .dx-lb li { grid-template-columns: 28px 26px minmax(0, 1fr) auto; gap: 8px; padding: 8px 10px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dx-card, .dx-live-dot { animation: none; }
+ .dx-card, .dx-pick, .dx-crowd i { transition: none; }
+ .dx-card:hover, .dx-pick:hover { transform: none; }
+}
diff --git a/src/duels.js b/src/duels.js
new file mode 100644
index 000000000..fb15ca927
--- /dev/null
+++ b/src/duels.js
@@ -0,0 +1,318 @@
+// /duels: the trader-duels board. Call which of two traders books more
+// realized P&L over a fixed UTC window, with free daily points.
+//
+// Reads GET /api/duels (the board, per tab), GET /api/duels/me (points, level,
+// season standing, recent calls, badges; credits today's free allowance) and
+// GET /api/duels/leaderboard (the season's predictors). Points have no cash
+// value; nothing on this page can move a token.
+
+import { apiFetch } from './api.js';
+import { esc, toast, errorMessage, hydrateAvatars } from './syndicate-shared.js';
+import { duelCard, pts, until, fmtUtc, FREE_LINE } from './duels-shared.js';
+
+const listEl = document.getElementById('dxList');
+const meEl = document.getElementById('dxMe');
+const tabsEl = document.getElementById('dxTabs');
+const lbEl = document.getElementById('dxLb');
+const callsEl = document.getElementById('dxCalls');
+const filterEl = document.getElementById('dxFilter');
+const rulesEl = document.getElementById('dxRules');
+
+const DUEL_BADGES = [
+ { code: 'duel_first', label: 'First Call', icon: '🎲', how: 'Make your first call on a trader duel.' },
+ { code: 'duel_hit', label: 'Called It', icon: '📣', how: 'Call a trader duel correctly.' },
+ { code: 'duel_streak_3', label: 'Hot Hand', icon: '🔥', how: 'Call three decided duels in a row correctly.' },
+ { code: 'duel_sharp', label: 'Sharp Caller', icon: '🧠', how: 'Be right on at least 70% of ten or more decided duels.' },
+];
+const TABS = [
+ { key: 'open', label: 'Open for calls' },
+ { key: 'live', label: 'Live' },
+ { key: 'settled', label: 'Settled' },
+];
+
+const params = new URLSearchParams(location.search);
+const agentFilter = /^[0-9a-f-]{36}$/i.test(params.get('agent') || '') ? params.get('agent') : null;
+let phase = TABS.some((t) => t.key === params.get('phase')) ? params.get('phase') : null;
+let board = null;
+let me = null;
+let loadSeq = 0;
+
+function setUrl() {
+ const q = new URLSearchParams();
+ if (phase && phase !== 'open') q.set('phase', phase);
+ if (agentFilter) q.set('agent', agentFilter);
+ const s = q.toString();
+ history.replaceState(null, '', `/duels${s ? `?${s}` : ''}`);
+}
+
+async function getJson(path) {
+ const r = await apiFetch(path, { allowAnonymous: true, headers: { accept: 'application/json' } });
+ if (!r.ok) {
+ const { message } = await errorMessage(r, `The server answered ${r.status}.`);
+ throw new Error(message);
+ }
+ return r.json();
+}
+
+// ── the board ───────────────────────────────────────────────
+
+async function loadBoard() {
+ const seq = ++loadSeq;
+ listEl.setAttribute('aria-busy', 'true');
+ listEl.innerHTML = `<ul class="dx-grid" aria-hidden="true">${'<li><div class="sy-skel" style="height:196px"></div></li>'.repeat(3)}</ul>`;
+ try {
+ const want = phase || 'open';
+ const q = new URLSearchParams({ phase: want });
+ if (agentFilter) q.set('agent', agentFilter);
+ let data = await getJson(`/api/duels?${q}`);
+ // First visit with nothing open: land on whichever tab has something to show.
+ if (!phase && !data.duels.length) {
+ const fallback = data.counts.live ? 'live' : data.counts.settled ? 'settled' : null;
+ if (fallback) {
+ q.set('phase', fallback);
+ data = await getJson(`/api/duels?${q}`);
+ phase = fallback;
+ }
+ }
+ if (seq !== loadSeq) return;
+ phase = phase || 'open';
+ board = data;
+ setUrl();
+ renderTabs();
+ renderBoard();
+ renderRules(data.rules);
+ } catch (err) {
+ if (seq !== loadSeq) return;
+ listEl.innerHTML = `
+ <div class="sy-state" role="alert">
+ <h2>Duels did not load</h2>
+ <p>${esc(err.message || 'Check your connection.')} Calls you already made are safe: they are stored with the duel and settle on schedule.</p>
+ <button type="button" class="sy-btn primary" id="dxRetry">Try again</button>
+ </div>`;
+ document.getElementById('dxRetry').addEventListener('click', loadBoard);
+ } finally {
+ if (seq === loadSeq) listEl.setAttribute('aria-busy', 'false');
+ }
+}
+
+function renderTabs() {
+ const counts = board?.counts || {};
+ tabsEl.innerHTML = TABS.map((t) => `
+ <button type="button" data-tab="${t.key}" aria-pressed="${phase === t.key}">${esc(t.label)}${counts[t.key] ? ` <span class="sy-faint">${esc(counts[t.key])}</span>` : ''}</button>`).join('');
+ for (const b of tabsEl.querySelectorAll('[data-tab]')) {
+ b.addEventListener('click', () => {
+ if (phase === b.dataset.tab) return;
+ phase = b.dataset.tab;
+ loadBoard();
+ });
+ }
+ if (agentFilter && board.duels[0]) {
+ const d = board.duels[0];
+ const name = d.a.agent_id === agentFilter ? d.a.name : d.b.name;
+ filterEl.innerHTML = `Showing duels featuring <b>${esc(name)}</b> · <a href="/duels">show all</a>`;
+ filterEl.hidden = false;
+ } else if (agentFilter) {
+ filterEl.innerHTML = `Showing duels featuring one trader · <a href="/duels">show all</a>`;
+ filterEl.hidden = false;
+ }
+}
+
+function renderBoard() {
+ const now = Date.now();
+ const duels = board.duels || [];
+ if (!duels.length) {
+ listEl.innerHTML = emptyState();
+ return;
+ }
+ listEl.innerHTML = `<ul class="dx-grid" aria-label="${esc(TABS.find((t) => t.key === phase)?.label || 'Duels')}">${duels.map((d) => duelCard(d, now)).join('')}</ul>`;
+ hydrateAvatars(listEl);
+}
+
+function emptyState() {
+ const c = board.counts;
+ const total = c.open + c.live + c.settled;
+ const rules = board.rules;
+ if (agentFilter) {
+ return `
+ <div class="sy-state">
+ <h2>No ${phase === 'open' ? 'open ' : phase === 'live' ? 'live ' : 'settled '}duels for this trader</h2>
+ <p>Duels pair each trader with the one directly next to them on the ${esc(rules.board_window)} board. This trader may be in a duel on another tab, or not paired this window.</p>
+ <div class="sy-actions" style="justify-content:center"><a class="sy-btn primary" href="/duels">See every duel</a><a class="sy-btn" href="/trader/${esc(agentFilter)}">Trader profile</a></div>
+ </div>`;
+ }
+ if (!total) {
+ const need = Math.max(0, 2 - board.eligible_traders);
+ return `
+ <div class="sy-state">
+ <h2>The first duels are warming up</h2>
+ <p>A duel needs two public traders who each closed at least ${esc(rules.board_min_closed)} trades in the last ${esc(rules.board_window)}. ${board.eligible_traders === 1 ? 'One trader qualifies right now' : `${esc(board.eligible_traders)} traders qualify right now`}${need ? `, so ${need === 1 ? 'one more is' : `${need} more are`} needed` : ''}. New duels open every UTC day as soon as the board has a pair.</p>
+ <div class="sy-actions" style="justify-content:center">
+ <a class="sy-btn primary" href="/trade-rooms">Watch live trade rooms</a>
+ <a class="sy-btn" href="/leaderboard">Trader leaderboard</a>
+ <a class="sy-btn" href="/create-agent">Launch a trader</a>
+ </div>
+ </div>`;
+ }
+ if (phase === 'open') {
+ return `
+ <div class="sy-state">
+ <h2>No duels are taking calls right now</h2>
+ <p>Tomorrow's 24-hour duels open at 00:00 UTC, in ${esc(until(nextUtcMidnight()))}. Meanwhile, watch the ${c.live ? `${esc(c.live)} live ${c.live === 1 ? 'duel' : 'duels'}` : 'settled duels'}.</p>
+ <div class="sy-actions" style="justify-content:center"><button type="button" class="sy-btn primary" data-go="${c.live ? 'live' : 'settled'}">${c.live ? 'See live duels' : 'See settled duels'}</button></div>
+ </div>`;
+ }
+ return `
+ <div class="sy-state">
+ <h2>${phase === 'live' ? 'No duel windows are running right now' : 'No duels have settled yet'}</h2>
+ <p>${phase === 'live' ? 'Duels go live when their window starts and calls lock.' : 'A duel settles a few minutes after its window closes, straight from the trade ledger.'}${c.open ? ` ${esc(c.open)} ${c.open === 1 ? 'duel is' : 'duels are'} open for calls.` : ''}</p>
+ ${c.open ? `<div class="sy-actions" style="justify-content:center"><button type="button" class="sy-btn primary" data-go="open">Make a call</button></div>` : ''}
+ </div>`;
+}
+
+listEl.addEventListener('click', (e) => {
+ const go = e.target.closest('[data-go]');
+ if (!go) return;
+ phase = go.dataset.go;
+ loadBoard();
+});
+
+function nextUtcMidnight() {
+ const d = new Date();
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1)).toISOString();
+}
+
+function renderRules(r) {
+ if (!r || rulesEl.dataset.filled) return;
+ rulesEl.dataset.filled = '1';
+ rulesEl.innerHTML = `
+ <li><b>Every day you get ${esc(pts(r.daily_allowance))}, free.</b> They top up at 00:00 UTC. ${esc(FREE_LINE)}</li>
+ <li><b>Pick the trader who books more realized P&L</b> over the duel's window: a 24-hour UTC day, or a Monday-to-Monday week. Stake ${esc(r.min_stake)} to ${esc(r.max_stake)} points, one call per duel.</li>
+ <li><b>Calls lock when the window starts.</b> You cannot call a duel featuring an agent you own.</li>
+ <li><b>Resolved from the trade ledger</b> about ${esc(r.resolve_grace_minutes)} minutes after the window closes: closed round-trips only, the same math as the trader's profile, and profit on a trader's own coins does not count.</li>
+ <li><b>A correct call pays ${esc(r.win_multiplier)}x your stake and ${esc(r.xp_per_win)} XP</b> toward your level on <a href="/quests">Quests</a>. A wrong call keeps nothing.</li>
+ <li><b>Ties, a window where neither trader trades, or a trader who goes private void the duel</b> and refund every call. A trader who sits out while the other trades counts as flat: that beats a loss and loses to a profit.</li>`;
+}
+
+// ── the predictor ───────────────────────────────────────────
+
+async function loadMe() {
+ try {
+ me = await getJson('/api/duels/me');
+ } catch {
+ meEl.innerHTML = `<div class="sy-note" role="status">Your points did not load. The board still works; <button type="button" class="sy-btn sm" id="dxMeRetry">retry</button></div>`;
+ document.getElementById('dxMeRetry').addEventListener('click', loadMe);
+ callsEl.innerHTML = '';
+ return;
+ }
+ renderMe();
+ renderCalls();
+ if (me.wallet?.granted_now) toast(`+${me.wallet.daily_allowance} free points for today`);
+ for (const code of me.newly_unlocked || []) {
+ const b = DUEL_BADGES.find((x) => x.code === code);
+ if (b) toast(`Badge unlocked: ${b.label}`);
+ }
+}
+
+function renderMe() {
+ if (!me.signed_in) {
+ const next = encodeURIComponent(location.pathname + location.search);
+ meEl.innerHTML = `
+ <div class="sy-panel" style="display:flex;flex-wrap:wrap;gap:14px;align-items:center;justify-content:space-between;margin-bottom:22px">
+ <div style="min-width:0;max-width:62ch">
+ <b style="font-size:16px">Sign in to make calls</b>
+ <p class="sy-muted" style="margin:4px 0 0;line-height:1.5">You get ${esc(pts(me.rules.daily_allowance))} free every day. Correct calls earn points, XP and badges. ${esc(FREE_LINE)}</p>
+ </div>
+ <div class="sy-actions"><a class="sy-btn primary" href="/login?next=${next}">Sign in</a><a class="sy-btn" href="/register?next=${next}">Create an account</a></div>
+ </div>`;
+ return;
+ }
+ const s = me.season.standing;
+ meEl.innerHTML = `
+ <div class="dx-me">
+ <section class="sy-panel dx-stat" aria-label="Your points">
+ <span class="dx-coin" aria-hidden="true">pts</span>
+ <div style="min-width:0">
+ <div class="dx-stat-lbl">Your points</div>
+ <div class="dx-stat-num">${esc(me.wallet.balance.toLocaleString('en-US'))}</div>
+ <small>+${esc(me.wallet.daily_allowance)} free in <span data-until="${esc(me.wallet.next_grant_at)}">${esc(until(me.wallet.next_grant_at))}</span></small>
+ </div>
+ </section>
+ <section class="sy-panel dx-stat" aria-label="Your level">
+ <span class="qx-level-num" style="width:48px;height:48px;font-size:20px;border-radius:14px" aria-hidden="true">${esc(me.xp.level)}</span>
+ <div style="min-width:0">
+ <div class="dx-stat-lbl">Level ${esc(me.xp.level)}</div>
+ <div class="qx-bar" role="progressbar" aria-label="Progress to level ${esc(me.xp.level + 1)}" aria-valuemin="0" aria-valuemax="${esc(me.xp.level_span)}" aria-valuenow="${esc(me.xp.into_level)}"><i style="--p:${me.xp.level_span ? Math.round((me.xp.into_level / me.xp.level_span) * 100) : 0}%"></i></div>
+ <small>${esc(me.xp.total)} XP, ${esc(me.xp.from_duels)} from correct calls · <a href="/quests">Quests</a></small>
+ </div>
+ </section>
+ <section class="sy-panel dx-stat" aria-label="Your season">
+ <div style="min-width:0">
+ <div class="dx-stat-lbl">${esc(me.season.label)} season</div>
+ <div class="dx-stat-num">${s ? `#${esc(s.rank)}` : 'Unranked'}</div>
+ <small>${s ? `${esc(pts(s.net, { sign: true }))} · ${esc(s.wins)} of ${esc(s.decided)} calls right` : 'Your first decided call puts you on the board.'}</small>
+ </div>
+ </section>
+ </div>`;
+}
+
+function renderCalls() {
+ const earned = new Set((me.badges || []).map((b) => b.code));
+ const badges = `
+ <h2 class="sy-h2" id="dxBadgesTitle" style="margin-top:18px">Duel badges <small>earned once, kept forever</small></h2>
+ <div class="qx-badges" aria-labelledby="dxBadgesTitle">
+ ${DUEL_BADGES.map((b) => `<span class="qx-badge${earned.has(b.code) ? '' : ' locked'}" title="${esc(b.how)}"><span aria-hidden="true">${b.icon}</span>${esc(b.label)}${earned.has(b.code) ? '' : `<span class="sr-only"> (locked: ${esc(b.how)})</span>`}</span>`).join('')}
+ </div>`;
+ if (!me.signed_in) {
+ callsEl.innerHTML = `<h2 class="sy-h2">Your calls</h2><p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0">Sign in and your calls, results and points history show up here.</p>${badges}`;
+ return;
+ }
+ const calls = me.calls || [];
+ const statusText = (c) => {
+ if (c.status === 'won') return `<span class="pos">${esc(pts(c.net, { sign: true }))}</span>`;
+ if (c.status === 'lost') return `<span class="neg">${esc(pts(c.net, { sign: true }))}</span>`;
+ if (c.status === 'refunded') return '<span class="flat">Refunded</span>';
+ return c.phase === 'open' ? `<span class="sy-faint">Locks ${esc(until(c.window_start))}</span>` : '<span class="sy-faint">In play</span>';
+ };
+ callsEl.innerHTML = `
+ <h2 class="sy-h2">Your calls <small>${calls.length ? `last ${calls.length}` : ''}</small></h2>
+ ${calls.length
+ ? `<ul class="dx-calls">${calls.map((c) => `<li><a href="${esc(c.url)}"><span><b>${esc(c.picked)}</b> <span class="sy-faint">in ${esc(c.label)} · ${esc(pts(c.stake))}</span></span>${statusText(c)}</a></li>`).join('')}</ul>`
+ : '<p class="sy-muted" style="font-size:14px;line-height:1.55;margin:0">No calls yet. Pick a duel above and back the trader you think books more.</p>'}
+ ${badges}`;
+}
+
+// ── season leaderboard ──────────────────────────────────────
+
+async function loadLeaderboard() {
+ try {
+ const data = await getJson('/api/duels/leaderboard?limit=15');
+ const rows = data.leaders || [];
+ const mine = data.me && !rows.some((r) => r.is_me) ? data.me : null;
+ const row = (r) => `
+ <li class="${r.is_me ? 'me' : ''}">
+ <span class="rk">#${esc(r.rank)}</span>
+ ${r.avatar ? `<img class="sy-ava" style="width:30px;height:30px" src="${esc(r.avatar)}" alt="" loading="lazy" data-initial="${esc((r.name[0] || '?').toUpperCase())}" />` : `<span class="sy-ava" style="width:30px;height:30px" aria-hidden="true">${esc((r.name[0] || '?').toUpperCase())}</span>`}
+ ${r.profile ? `<a href="${esc(r.profile)}"><b>${esc(r.name)}${r.is_me ? ' (you)' : ''}</b><small>${esc(r.wins)} of ${esc(r.decided)} right</small></a>` : `<span style="min-width:0"><b>${esc(r.name)}${r.is_me ? ' (you)' : ''}</b><small>${esc(r.wins)} of ${esc(r.decided)} right</small></span>`}
+ <span class="net ${r.net > 0 ? 'pos' : r.net < 0 ? 'neg' : 'flat'}">${esc(pts(r.net, { sign: true }))}</span>
+ </li>`;
+ lbEl.innerHTML = `
+ <h2 class="sy-h2">${esc(data.season.label)} predictors <small>net points from decided calls; resets ${esc(fmtUtc(data.season.end))}</small></h2>
+ ${rows.length
+ ? `<ol class="dx-lb">${rows.map(row).join('')}${mine ? row(mine) : ''}</ol>`
+ : '<div class="sy-chart-empty">No duel has settled this season yet. The first correct call takes the top spot.</div>'}`;
+ hydrateAvatars(lbEl);
+ } catch (err) {
+ lbEl.innerHTML = `<h2 class="sy-h2">Season predictors</h2><div class="sy-err" role="alert">${esc(err.message)} <button type="button" class="sy-btn sm" id="dxLbRetry">Retry</button></div>`;
+ document.getElementById('dxLbRetry').addEventListener('click', loadLeaderboard);
+ }
+}
+
+// Countdowns stay honest without refetching: re-render from the data we have.
+setInterval(() => {
+ if (board) renderBoard();
+ for (const el of document.querySelectorAll('[data-until]')) el.textContent = until(el.dataset.until);
+}, 30_000);
+
+loadBoard();
+loadMe();
+loadLeaderboard();
diff --git a/tests/trader-duels.test.js b/tests/trader-duels.test.js
new file mode 100644
index 000000000..2b1ec9883
--- /dev/null
+++ b/tests/trader-duels.test.js
@@ -0,0 +1,444 @@
+/**
+ * Trader duels (api/_lib/trader-duels.js): the points-only skill-prediction game.
+ *
+ * Pins the pure rules (windows, phases, market generation, resolution with
+ * ties, voids and idle traders, settlement, stake validation, badges, seasons)
+ * and the database paths that enforce them: the abuse rules on a call, a
+ * duel resolved from ledger positions through computeTraderMetrics, and a void
+ * that refunds every stake.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let route = () => [];
+const queries = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join('?') : String(strings);
+ queries.push({ q, values });
+ return Promise.resolve().then(() => route(q, values));
+ },
+ isDbUnavailableError: () => false,
+}));
+
+const unlocked = [];
+vi.mock('../api/_lib/streaks.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return {
+ ...real,
+ unlockBadge: async (userId, code) => {
+ unlocked.push({ userId, code });
+ return true;
+ },
+ listBadges: async () => [],
+ };
+});
+
+const D = await import('../api/_lib/trader-duels.js');
+const { BADGES } = await import('../api/_lib/streaks.js');
+
+const A = '11111111-1111-4111-8111-111111111111';
+const B = '22222222-2222-4222-8222-222222222222';
+const C = '33333333-3333-4333-8333-333333333333';
+const USER = '44444444-4444-4444-8444-444444444444';
+const OWNER_A = '55555555-5555-4555-8555-555555555555';
+const OWNER_B = '66666666-6666-4666-8666-666666666666';
+const MARKET = '77777777-7777-4777-8777-777777777777';
+
+beforeEach(() => {
+ route = () => [];
+ queries.length = 0;
+ unlocked.length = 0;
+});
+
+describe('windows', () => {
+ it('opens a day duel for the next UTC day', () => {
+ const now = Date.parse('2026-09-30T15:20:00Z');
+ const w = D.nextWindow('day', now);
+ expect(new Date(w.start).toISOString()).toBe('2026-10-01T00:00:00.000Z');
+ expect(new Date(w.end).toISOString()).toBe('2026-10-02T00:00:00.000Z');
+ expect(D.windowOpensNow('day', w.start, now)).toBe(true);
+ });
+
+ it('runs a week duel Monday to Monday, always strictly in the future', () => {
+ const wed = D.nextWindow('week', Date.parse('2026-09-30T12:00:00Z'));
+ expect(new Date(wed.start).toISOString()).toBe('2026-10-05T00:00:00.000Z');
+ expect(new Date(wed.end).toISOString()).toBe('2026-10-12T00:00:00.000Z');
+ const mon = D.nextWindow('week', Date.parse('2026-10-05T00:00:01Z'));
+ expect(new Date(mon.start).toISOString()).toBe('2026-10-12T00:00:00.000Z');
+ const sun = D.nextWindow('week', Date.parse('2026-10-04T23:00:00Z'));
+ expect(new Date(sun.start).toISOString()).toBe('2026-10-05T00:00:00.000Z');
+ });
+
+ it('only opens a week duel once the week is at most four days away', () => {
+ const start = Date.parse('2026-10-05T00:00:00Z');
+ expect(D.windowOpensNow('week', start, Date.parse('2026-09-30T12:00:00Z'))).toBe(false);
+ expect(D.windowOpensNow('week', start, Date.parse('2026-10-01T00:05:00Z'))).toBe(true);
+ expect(D.windowOpensNow('week', start, Date.parse('2026-10-05T00:00:00Z'))).toBe(false);
+ });
+
+ it('walks a duel through its phases', () => {
+ const m = { status: 'open', window_start: '2026-10-01T00:00:00Z', window_end: '2026-10-02T00:00:00Z' };
+ expect(D.duelPhase(m, Date.parse('2026-09-30T23:59:59Z'))).toBe('open');
+ expect(D.duelPhase(m, Date.parse('2026-10-01T00:00:00Z'))).toBe('live');
+ expect(D.duelPhase(m, Date.parse('2026-10-02T00:00:00Z'))).toBe('resolving');
+ expect(D.duelPhase({ ...m, status: 'resolved' })).toBe('resolved');
+ expect(D.duelPhase({ ...m, status: 'void' })).toBe('void');
+ expect(D.resolvesAt(m)).toBe('2026-10-02T00:15:00.000Z');
+ });
+});
+
+describe('planDuels (market generation)', () => {
+ const riv = (leader, chaser, kind = 'chase') => ({
+ kind,
+ window: '30d',
+ headline: `${leader} vs ${chaser}`,
+ leader: { agent_id: leader, name: `T-${leader.slice(0, 1)}`, rank: 1, score: 70, closed: 12, win_rate: 0.6, realized_pnl_sol: 1.2 },
+ chaser: { agent_id: chaser, name: `T-${chaser.slice(0, 1)}`, rank: 2, score: 60, closed: 9, win_rate: 0.5, realized_pnl_sol: 0.4 },
+ });
+
+ it('pairs each rivalry leader against the trader directly below', () => {
+ const plan = D.planDuels([riv(A, B), riv(B, C)]);
+ expect(plan).toHaveLength(2);
+ expect(plan[0].a.agent_id).toBe(A);
+ expect(plan[0].b.agent_id).toBe(B);
+ expect(plan[0].context.headline).toBe(`${A} vs ${B}`);
+ expect(plan[0].context.a.rank).toBe(1);
+ });
+
+ it('skips an unavailable trader, a repeated pair in either order, and a self pair', () => {
+ const plan = D.planDuels([riv(A, B), riv(B, A), riv(A, A), riv(B, C)], { excluded: new Set([C]) });
+ expect(plan.map((p) => [p.a.agent_id, p.b.agent_id])).toEqual([[A, B]]);
+ });
+
+ it('caps the number of duels per window', () => {
+ const ids = Array.from({ length: 8 }, (_, i) => `${String(i + 1).repeat(8)}-0000-4000-8000-000000000000`);
+ const rivalries = ids.slice(1).map((id, i) => riv(ids[i], id));
+ expect(D.planDuels(rivalries)).toHaveLength(D.DUEL_RULES.max_per_window);
+ expect(D.planDuels(rivalries, { max: 5 })).toHaveLength(5);
+ });
+
+ it('returns nothing from an empty or missing board', () => {
+ expect(D.planDuels([])).toEqual([]);
+ expect(D.planDuels(undefined)).toEqual([]);
+ });
+});
+
+describe('decideDuel (resolution)', () => {
+ const side = (closed, pnl) => ({ eligible: true, closed, pnl_lamports: String(pnl) });
+
+ it('awards the side that booked more realized P&L', () => {
+ expect(D.decideDuel({ a: side(3, 500_000_000), b: side(4, 200_000_000) })).toEqual({ status: 'resolved', winner: 'a', void_reason: null });
+ expect(D.decideDuel({ a: side(3, -500), b: side(1, -100) }).winner).toBe('b');
+ });
+
+ it('voids a tie and refunds', () => {
+ expect(D.decideDuel({ a: side(2, 1000), b: side(5, 1000) })).toEqual({ status: 'void', winner: null, void_reason: 'tie' });
+ });
+
+ it('voids when neither trader closed a trade in the window', () => {
+ expect(D.decideDuel({ a: side(0, 0), b: side(0, 0) }).void_reason).toBe('no_trades');
+ });
+
+ it('scores an idle trader as flat: beats a loser, loses to a winner', () => {
+ expect(D.decideDuel({ a: side(0, 0), b: side(2, -10) }).winner).toBe('a');
+ expect(D.decideDuel({ a: side(0, 0), b: side(2, 10) }).winner).toBe('b');
+ expect(D.decideDuel({ a: side(3, 0), b: side(0, 0) }).void_reason).toBe('tie');
+ });
+
+ it('voids when either trader is private or deleted, whatever the numbers', () => {
+ expect(D.decideDuel({ a: { ...side(5, 9e9), eligible: false }, b: side(1, 1) }).void_reason).toBe('trader_unavailable');
+ expect(D.decideDuel({ a: side(5, 1), b: { eligible: false } }).void_reason).toBe('trader_unavailable');
+ });
+
+ it('compares lamports exactly, beyond float precision', () => {
+ const r = D.decideDuel({ a: side(1, '9007199254740993'), b: side(1, '9007199254740992') });
+ expect(r.winner).toBe('a');
+ });
+});
+
+describe('settleCall + callNet (points accounting)', () => {
+ const resolved = { status: 'resolved', winner: 'a' };
+
+ it('returns twice the stake on a correct call and nothing on a wrong one', () => {
+ expect(D.settleCall({ side: 'a', stake: 40 }, resolved)).toEqual({ status: 'won', payout: 80 });
+ expect(D.settleCall({ side: 'b', stake: 40 }, resolved)).toEqual({ status: 'lost', payout: 0 });
+ });
+
+ it('refunds the stake on a void duel', () => {
+ expect(D.settleCall({ side: 'b', stake: 25 }, { status: 'void' })).toEqual({ status: 'refunded', payout: 25 });
+ });
+
+ it('leaves a call open while its duel is open', () => {
+ expect(D.settleCall({ side: 'a', stake: 25 }, { status: 'open' })).toEqual({ status: 'open', payout: 0 });
+ });
+
+ it('nets a call the way the season board does', () => {
+ expect(D.callNet({ status: 'won', stake: 30, payout: 60 })).toBe(30);
+ expect(D.callNet({ status: 'lost', stake: 30, payout: 0 })).toBe(-30);
+ expect(D.callNet({ status: 'refunded', stake: 30, payout: 30 })).toBe(0);
+ expect(D.callNet({ status: 'open', stake: 30, payout: 0 })).toBe(0);
+ });
+});
+
+describe('validateCall', () => {
+ it('accepts a whole stake inside the bounds and the balance', () => {
+ expect(D.validateCall({ side: 'a', stake: 10, balance: 100 })).toEqual({ ok: true, side: 'a', stake: 10 });
+ expect(D.validateCall({ side: 'b', stake: '100', balance: 100 })).toEqual({ ok: true, side: 'b', stake: 100 });
+ });
+
+ it('refuses a bad side, a stake out of bounds or fractional, and an overdraft', () => {
+ expect(D.validateCall({ side: 'c', stake: 20 }).code).toBe('invalid_side');
+ expect(D.validateCall({ side: 'a', stake: 9 }).code).toBe('invalid_stake');
+ expect(D.validateCall({ side: 'a', stake: 101 }).code).toBe('invalid_stake');
+ expect(D.validateCall({ side: 'a', stake: 12.5 }).code).toBe('invalid_stake');
+ expect(D.validateCall({ side: 'a', stake: 50, balance: 40 }).code).toBe('not_enough_points');
+ });
+});
+
+describe('duelBadgesFor', () => {
+ const pick = (status, day) => ({ status, settled_at: `2026-10-${String(day).padStart(2, '0')}T01:00:00Z` });
+
+ it('earns First Call on any call, even one still open', () => {
+ expect(D.duelBadgesFor([{ status: 'open', created_at: '2026-10-01T00:00:00Z' }])).toEqual([BADGES.DUEL_FIRST]);
+ expect(D.duelBadgesFor([])).toEqual([]);
+ });
+
+ it('earns Called It on the first correct call', () => {
+ expect(D.duelBadgesFor([pick('lost', 1), pick('won', 2)])).toContain(BADGES.DUEL_HIT);
+ });
+
+ it('needs three correct decided calls in a row for Hot Hand; refunds do not break or extend a run', () => {
+ expect(D.duelBadgesFor([pick('won', 1), pick('won', 2), pick('lost', 3), pick('won', 4)])).not.toContain(BADGES.DUEL_STREAK_3);
+ expect(D.duelBadgesFor([pick('won', 1), pick('refunded', 2), pick('won', 3), pick('won', 4)])).toContain(BADGES.DUEL_STREAK_3);
+ expect(D.duelBadgesFor([pick('won', 3), pick('won', 1), pick('won', 2)])).toContain(BADGES.DUEL_STREAK_3);
+ });
+
+ it('needs ten decided calls at 70% or better for Sharp Caller', () => {
+ const seven = [...Array(7)].map((_, i) => pick('won', i + 1)).concat([pick('lost', 8), pick('lost', 9), pick('lost', 10)]);
+ expect(D.duelBadgesFor(seven)).toContain(BADGES.DUEL_SHARP);
+ const six = [...Array(6)].map((_, i) => pick('won', i + 1)).concat([...Array(4)].map((_, i) => pick('lost', i + 7)));
+ expect(D.duelBadgesFor(six)).not.toContain(BADGES.DUEL_SHARP);
+ expect(D.duelBadgesFor([...Array(9)].map((_, i) => pick('won', i + 1)))).not.toContain(BADGES.DUEL_SHARP);
+ });
+});
+
+describe('seasons', () => {
+ it('is a UTC calendar month', () => {
+ const s = D.seasonFor(Date.parse('2026-10-31T23:59:59Z'));
+ expect(s).toMatchObject({ id: '2026-10', start: '2026-10-01T00:00:00.000Z', end: '2026-11-01T00:00:00.000Z', label: 'October 2026' });
+ expect(D.seasonById('2026-12').end).toBe('2027-01-01T00:00:00.000Z');
+ expect(D.seasonById('2026-13')).toBeNull();
+ expect(D.seasonById('nope')).toBeNull();
+ });
+});
+
+// ── database paths ──────────────────────────────────────────────────────────
+
+const openMarket = (over = {}) => ({
+ id: MARKET,
+ network: 'mainnet',
+ window_kind: 'day',
+ window_start: new Date(Date.now() + 3_600_000).toISOString(),
+ window_end: new Date(Date.now() + 25 * 3_600_000).toISOString(),
+ agent_a: A,
+ agent_b: B,
+ agent_a_name: 'Alpha',
+ agent_b_name: 'Bravo',
+ status: 'open',
+ ...over,
+});
+const agents = (over = {}) => [
+ { id: A, user_id: OWNER_A, name: 'Alpha', is_public: true, deleted_at: null, ...(over.a || {}) },
+ { id: B, user_id: OWNER_B, name: 'Bravo', is_public: true, deleted_at: null, ...(over.b || {}) },
+];
+
+function callRoutes({ market = openMarket(), agentRows = agents(), balance = 100, insert = null } = {}) {
+ return (q) => {
+ if (/from duel_markets where id =/.test(q)) return market ? [market] : [];
+ if (/from agent_identities where id = any/.test(q)) return agentRows;
+ if (/insert into duel_points_ledger \(user_id, kind, amount, day\)/.test(q)) return [];
+ if (/select balance from duel_wallets/.test(q)) return [{ balance }];
+ if (/insert into duel_picks/.test(q)) {
+ if (insert instanceof Error) throw insert;
+ return insert || [{ id: 9, side: 'a', stake: 20, created_at: '2026-09-30T00:00:00Z', balance: balance - 20 }];
+ }
+ return [];
+ };
+}
+
+describe('placeCall (abuse rules)', () => {
+ it('places a call, debits the stake and unlocks First Call', async () => {
+ route = callRoutes();
+ const r = await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 });
+ expect(r.ok).toBe(true);
+ expect(r.balance).toBe(80);
+ expect(r.call).toMatchObject({ side: 'a', stake: 20, status: 'open' });
+ expect(unlocked).toContainEqual({ userId: USER, code: BADGES.DUEL_FIRST });
+ const insert = queries.find((x) => /insert into duel_picks/.test(x.q));
+ // The lock, the owner rule and the availability rule are enforced inside the insert too.
+ expect(insert.q).toMatch(/m\.window_start > now\(\)/);
+ expect(insert.q).toMatch(/a\.user_id = \?/);
+ expect(insert.q).toMatch(/is_public = false/);
+ });
+
+ it('refuses a call on a duel featuring an agent the caller owns', async () => {
+ route = callRoutes({ agentRows: agents({ b: { user_id: USER } }) });
+ const r = await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 });
+ expect(r).toMatchObject({ ok: false, status: 403, code: 'own_agent' });
+ expect(queries.some((x) => /insert into duel_picks/.test(x.q))).toBe(false);
+ });
+
+ it('refuses a call once the window has started', async () => {
+ route = callRoutes({ market: openMarket({ window_start: new Date(Date.now() - 1000).toISOString() }) });
+ const r = await D.placeCall({ userId: USER, marketId: MARKET, side: 'b', stake: 20 });
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'duel_locked' });
+ });
+
+ it('refuses a call when a trader went private or was deleted', async () => {
+ route = callRoutes({ agentRows: agents({ a: { is_public: false } }) });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ code: 'duel_unavailable' });
+ route = callRoutes({ agentRows: agents({ b: { deleted_at: '2026-09-30T00:00:00Z' } }) });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ code: 'duel_unavailable' });
+ });
+
+ it('allows one call per user per duel', async () => {
+ route = callRoutes({ insert: Object.assign(new Error('duplicate key'), { code: '23505' }) });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ status: 409, code: 'already_called' });
+ });
+
+ it('refuses a stake above the balance, before and inside the statement', async () => {
+ route = callRoutes({ balance: 15 });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ code: 'not_enough_points' });
+ route = callRoutes({ insert: Object.assign(new Error('violates check constraint'), { code: '23514' }) });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ code: 'not_enough_points' });
+ });
+
+ it('reports a lock the database clock caught after the pre-check', async () => {
+ route = callRoutes({ insert: [] });
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 20 })).toMatchObject({ code: 'duel_locked' });
+ });
+
+ it('rejects a malformed stake or duel id without touching the database', async () => {
+ expect(await D.placeCall({ userId: USER, marketId: MARKET, side: 'a', stake: 500 })).toMatchObject({ status: 400, code: 'invalid_stake' });
+ expect(await D.placeCall({ userId: USER, marketId: 'nope', side: 'a', stake: 20 })).toMatchObject({ status: 404 });
+ expect(queries).toHaveLength(0);
+ });
+});
+
+describe('resolveDuel (from the ledger)', () => {
+ const closedMarket = openMarket({
+ window_start: '2026-09-28T00:00:00Z',
+ window_end: '2026-09-29T00:00:00Z',
+ });
+ const now = Date.parse('2026-09-29T00:30:00Z');
+ const pos = (pnl, closedAt = '2026-09-28T12:00:00Z', mint = 'THREEsynthetic1111') => ({
+ id: Math.random(), status: 'closed', mint, realized_pnl_lamports: String(pnl), realized_pnl_pct: pnl > 0 ? 10 : -10,
+ entry_quote_lamports: '100000000', opened_at: '2026-09-28T11:00:00Z', closed_at: closedAt,
+ });
+
+ function resolveRoutes({ agentRows = agents(), a = [], b = [], selfDeal = {} } = {}) {
+ const updates = [];
+ return {
+ updates,
+ fn: (q, values) => {
+ if (/from agent_identities where id = any/.test(q)) return agentRows;
+ if (/from agent_sniper_positions p/.test(q)) return values[0] === A ? a : b;
+ if (/from agent_strategy_positions s/.test(q)) return [];
+ if (/from pump_agent_mints/.test(q)) return (selfDeal[values[0]] || []).map((mint) => ({ mint }));
+ if (/update duel_markets set/.test(q)) {
+ updates.push(values);
+ return [{ id: MARKET }];
+ }
+ if (/select distinct user_id from duel_picks/.test(q)) return [{ user_id: USER }];
+ if (/select status, settled_at, created_at from duel_picks/.test(q)) return [{ status: 'won', settled_at: '2026-09-29T00:30:00Z' }];
+ return [];
+ },
+ };
+ }
+
+ it('resolves to the trader with more realized P&L and settles the calls', async () => {
+ const r = resolveRoutes({ a: [pos(300_000_000), pos(-100_000_000)], b: [pos(150_000_000)] });
+ route = r.fn;
+ const out = await D.resolveDuel(closedMarket, { now });
+ expect(out).toMatchObject({ status: 'resolved', winner: 'a' });
+ expect(r.updates[0].slice(0, 3)).toEqual(['resolved', 'a', null]);
+ const result = JSON.parse(r.updates[0][3]);
+ expect(result.a).toMatchObject({ closed: 2, wins: 1, pnl_lamports: '200000000' });
+ expect(result.b).toMatchObject({ closed: 1, pnl_lamports: '150000000' });
+ expect(queries.some((x) => /update duel_picks k set/.test(x.q))).toBe(true);
+ expect(queries.some((x) => /insert into trading_quest_completions/.test(x.q))).toBe(true);
+ expect(unlocked).toContainEqual({ userId: USER, code: BADGES.DUEL_HIT });
+ });
+
+ it('does not credit round-trips on a trader\'s own coin, like the trader card', async () => {
+ const r = resolveRoutes({
+ a: [pos(900_000_000, undefined, 'THREEsyntheticOWN1')],
+ b: [pos(10_000_000)],
+ selfDeal: { [OWNER_A]: ['THREEsyntheticOWN1'] },
+ });
+ route = r.fn;
+ const out = await D.resolveDuel(closedMarket, { now });
+ expect(out.winner).toBe('b');
+ });
+
+ it('voids a tie and a window with no trades on either side', async () => {
+ route = resolveRoutes({ a: [pos(5)], b: [pos(5)] }).fn;
+ expect(await D.resolveDuel(closedMarket, { now })).toMatchObject({ status: 'void', void_reason: 'tie' });
+ route = resolveRoutes().fn;
+ expect(await D.resolveDuel(closedMarket, { now })).toMatchObject({ status: 'void', void_reason: 'no_trades' });
+ });
+
+ it('voids early, before the window closes, when a trader goes private, without measuring', async () => {
+ const r = resolveRoutes({ agentRows: agents({ a: { is_public: false } }) });
+ route = r.fn;
+ const out = await D.resolveDuel(openMarket(), { now: Date.now() });
+ expect(out).toMatchObject({ status: 'void', void_reason: 'trader_unavailable' });
+ expect(queries.some((x) => /agent_sniper_positions/.test(x.q))).toBe(false);
+ // The refund runs through the same settlement statement.
+ expect(queries.some((x) => /update duel_picks k set/.test(x.q))).toBe(true);
+ });
+
+ it('leaves a healthy duel alone until its window closes', async () => {
+ route = resolveRoutes().fn;
+ expect(await D.resolveDuel(openMarket(), { now: Date.now() })).toBeNull();
+ expect(queries.some((x) => /update duel_markets/.test(x.q))).toBe(false);
+ });
+
+ it('does not settle twice when a concurrent tick already flipped the duel', async () => {
+ const r = resolveRoutes({ a: [pos(10)], b: [pos(5)] });
+ route = (q, v) => (/update duel_markets set/.test(q) ? [] : r.fn(q, v));
+ expect(await D.resolveDuel(closedMarket, { now })).toBeNull();
+ expect(queries.some((x) => /update duel_picks k set/.test(x.q))).toBe(false);
+ });
+});
+
+describe('settlement SQL matches settleCall', () => {
+ it('pays the multiplier, refunds voids, and credits XP only for correct calls on resolved duels', async () => {
+ route = () => [];
+ await D.settleDuelPicks(MARKET);
+ const settle = queries.find((x) => /update duel_picks k set/.test(x.q));
+ expect(settle.q).toMatch(/when m\.status = 'void' then 'refunded'/);
+ expect(settle.q).toMatch(/when m\.status = 'void' then k\.stake/);
+ expect(settle.values).toContain(D.DUEL_RULES.win_multiplier);
+ expect(settle.q).toMatch(/on conflict do nothing/);
+ expect(settle.q).toMatch(/k\.status = 'open'/);
+ const xp = queries.find((x) => /insert into trading_quest_completions/.test(x.q));
+ expect(xp.q).toMatch(/k\.status = 'won' and m\.status = 'resolved'/);
+ expect(xp.values).toContain(D.XP_CODE_PREFIX);
+ expect(xp.values).toContain(D.DUEL_RULES.xp_per_win);
+ });
+});
+
+describe('ensureDailyGrant', () => {
+ it('credits the allowance once per UTC day', async () => {
+ route = (q) => (/insert into duel_points_ledger/.test(q) ? [{ balance: 100 }] : []);
+ expect(await D.ensureDailyGrant(USER, Date.parse('2026-09-30T08:00:00Z'))).toEqual({ balance: 100, granted: true });
+ const grant = queries.find((x) => /insert into duel_points_ledger/.test(x.q));
+ expect(grant.values).toContain('2026-09-30');
+ expect(grant.values).toContain(D.DUEL_RULES.daily_allowance);
+
+ route = (q) => (/select balance from duel_wallets/.test(q) ? [{ balance: 40 }] : []);
+ expect(await D.ensureDailyGrant(USER)).toEqual({ balance: 40, granted: false });
+ });
+});