Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(quests): daily trading quests scored from verified trades, forks, ghost-copies, copy intents and agent wins
nirholased90313bdf86
diff --git a/api/_lib/migrations/20260929121000_trading_quests.sql b/api/_lib/migrations/20260929121000_trading_quests.sqlnew file mode 100644index 000000000..da0fdb5d3--- /dev/null+++ b/api/_lib/migrations/20260929121000_trading_quests.sql@@ -0,0 +1,82 @@+-- Migration: daily trading quests on top of streaks + badges.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260929121000_trading_quests.sql+-- Idempotent.+--+-- Quest progress is computed from events that already prove themselves+-- (copy_executions, agent_sniper_positions, agent_custody_events,+-- pump_agent_trades). Two kinds of event had no durable record, so they get one+-- here in trading_quest_events:+--+-- trade a user-signed pump.fun trade whose signature buy-confirm /+-- sell-confirm verified on-chain. pump_agent_trades only keeps+-- coins launched on three.ws, so a trade of any other coin (most+-- forks) left no trace. One row per signature, first claim wins,+-- and origin = 'fork' when the trade panel was opened by a Fork.+-- ghost_copy the first time a signed-in user ghost-copied a given leader.+-- The replay is stateless, so this row is its only trace; one per+-- (user, leader, network), which is exactly "a new agent".+--+-- trading_quest_completions is the award ledger (XP is its sum). Rows are only+-- ever inserted, so XP never goes down when an underlying row later changes.+--+-- trading_quest_three_rewards is the $THREE payout ledger for a daily clear. It+-- ships DISARMED: api/_lib/quest-rewards.js writes nothing here and moves+-- nothing on-chain unless TRADING_QUEST_THREE_REWARDS is armed (owner gate).++begin;++create table if not exists trading_quest_events (+ id bigserial primary key,+ user_id uuid not null references users(id) on delete cascade,+ kind text not null check (kind in ('trade','ghost_copy')),+ ref text not null, -- trade: tx signature; ghost_copy: leader agent id+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),+ origin text check (origin is null or origin in ('fork')),+ wallet text, -- trade: the signing wallet+ context jsonb,+ created_at timestamptz not null default now()+);++-- A signature is one trade, whoever reports it first.+create unique index if not exists trading_quest_events_trade_uniq+ on trading_quest_events (ref, network)+ where kind = 'trade';+-- The first ghost of a leader wins, so created_at is "when this agent was new to you".+create unique index if not exists trading_quest_events_ghost_uniq+ on trading_quest_events (user_id, ref, network)+ where kind = 'ghost_copy';+create index if not exists trading_quest_events_user_day+ on trading_quest_events (user_id, kind, created_at desc);++create table if not exists trading_quest_completions (+ user_id uuid not null references users(id) on delete cascade,+ day date not null, -- UTC day the quest was completed for+ code text not null, -- quest code, or 'daily_clear'+ xp integer not null check (xp >= 0),+ completed_at timestamptz not null default now(),+ primary key (user_id, day, code)+);+create index if not exists trading_quest_completions_user+ on trading_quest_completions (user_id, day desc);++create table if not exists trading_quest_three_rewards (+ user_id uuid not null references users(id) on delete cascade,+ day date not null,+ amount_atomic numeric not null check (amount_atomic > 0),+ wallet text not null,+ status text not null default 'pending' check (status in ('pending','sent','failed')),+ tx_signature text,+ error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ primary key (user_id, day)+);+create index if not exists trading_quest_three_rewards_day+ on trading_quest_three_rewards (day, status);++comment on table trading_quest_events is+ 'Proof rows for quest events with no other durable trace: verified user-signed trades and first ghost-copies per leader.';+comment on table trading_quest_three_rewards is+ 'Daily-clear $THREE payouts. Empty unless TRADING_QUEST_THREE_REWARDS is armed by the owner.';++commit;diff --git a/api/_lib/quest-rewards.js b/api/_lib/quest-rewards.jsnew file mode 100644index 000000000..3aa5de7f0--- /dev/null+++ b/api/_lib/quest-rewards.js@@ -0,0 +1,203 @@+// $THREE reward for a daily quest clear. SHIPS DISARMED.+// ---------------------------------------------------------------------------+// Paying a reward moves $THREE out of a platform wallet, which is an owner-gated+// spend. So this module is complete (config, eligibility, idempotent ledger,+// daily budget, the on-chain Token-2022 transfer) and inert: until the owner arms+// it, claimDailyClearReward returns `rewards_disarmed` before it reads a row,+// writes a row, loads a key, or opens an RPC connection.+//+// Arming it takes all three of:+// TRADING_QUEST_THREE_REWARDS=on the switch (default off)+// TRADING_QUEST_THREE_REWARD_AMOUNT=<whole $THREE> paid per daily clear, > 0+// TRADING_QUEST_THREE_REWARD_SECRET_KEY_B64=<64-byte secret, base64>+// the funded payout wallet+// and optionally+// TRADING_QUEST_THREE_REWARD_DAILY_BUDGET=<whole $THREE> total paid per UTC day+// (default 20x the amount)+//+// One reward per user per UTC day, only for a day the user actually cleared+// (trading_quest_completions holds the proof), only to a Solana wallet linked to+// the account, only for today or yesterday. The ledger row is claimed before the+// transfer and marked sent or failed after, so a double click never pays twice+// and a failed payout can be retried.++import { sql as defaultSql } from './db.js';++export const THREE_MINT_DEFAULT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+export const THREE_DECIMALS = 6;+const ARM_VALUES = new Set(['on', '1', 'true', 'yes']);+const DAY_MS = 86_400_000;++const utcDay = (at) => new Date(at).toISOString().slice(0, 10);+const fail = (status, code, message, extra = {}) => ({ ok: false, status, code, message, extra });++/**+ * Read the reward switch and its parameters. PURE over the env object passed in.+ * `armed` is true only when the flag is on AND an amount AND a signer are set, so+ * a half-configured deploy stays disarmed rather than failing at payout time.+ */+export function questRewardConfig(env = process.env) {+ const flag = ARM_VALUES.has(String(env.TRADING_QUEST_THREE_REWARDS || '').trim().toLowerCase());+ const amountWhole = Number(env.TRADING_QUEST_THREE_REWARD_AMOUNT);+ const amountOk = Number.isFinite(amountWhole) && amountWhole > 0;+ const budgetRaw = Number(env.TRADING_QUEST_THREE_REWARD_DAILY_BUDGET);+ const budgetWhole = Number.isFinite(budgetRaw) && budgetRaw > 0 ? budgetRaw : amountOk ? amountWhole * 20 : 0;+ const secretB64 = String(env.TRADING_QUEST_THREE_REWARD_SECRET_KEY_B64 || '').trim();+ const hasSigner = secretB64.length > 0;++ let reason = null;+ if (!flag) reason = 'TRADING_QUEST_THREE_REWARDS is off';+ else if (!amountOk) reason = 'TRADING_QUEST_THREE_REWARD_AMOUNT is not set';+ else if (!hasSigner) reason = 'TRADING_QUEST_THREE_REWARD_SECRET_KEY_B64 is not set';++ return {+ armed: reason === null,+ reason,+ amount_whole: amountOk ? amountWhole : 0,+ amount_atomic: amountOk ? toAtomic(amountWhole) : 0n,+ daily_budget_whole: budgetWhole,+ daily_budget_atomic: budgetWhole > 0 ? toAtomic(budgetWhole) : 0n,+ mint: String(env.THREE_TOKEN_MINT || THREE_MINT_DEFAULT).trim(),+ secret_b64: hasSigner ? secretB64 : null,+ };+}++/** Whole $THREE to atomic units (6 decimals), exact for up to 6 decimal places. PURE. */+export function toAtomic(whole) {+ const [i, f = ''] = String(Number(whole).toFixed(THREE_DECIMALS)).split('.');+ return BigInt(i) * 10n ** BigInt(THREE_DECIMALS) + BigInt((f + '000000').slice(0, THREE_DECIMALS));+}++/** What the public quest board may show about rewards: never a key, never a reason string. PURE. */+export function publicRewardInfo(cfg) {+ return cfg.armed ? { armed: true, amount_three: cfg.amount_whole } : { armed: false };+}++/**+ * Send `amountAtomic` $THREE from the configured payout wallet to `wallet`. The+ * mint's owning program is resolved (Token-2022 for $THREE) so the derived ATAs+ * and the transfer instruction target the program that actually owns the mint.+ */+export async function sendThreeOnChain({ wallet, amountAtomic, cfg }) {+ const { Keypair, PublicKey } = await import('@solana/web3.js');+ const {+ getAssociatedTokenAddressSync,+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferCheckedInstruction,+ } = await import('@solana/spl-token');+ const { solanaConnection } = await import('./agent-pumpfun.js');+ const { submitProtected } = await import('./execution-engine.js');+ const { tokenProgramForMint } = await import('./solana-token-program.js');++ const secret = Buffer.from(cfg.secret_b64, 'base64');+ if (secret.length !== 64) throw Object.assign(new Error('payout key is not a 64-byte secret'), { code: 'bad_signer' });+ const payer = Keypair.fromSecretKey(new Uint8Array(secret));+ const mint = new PublicKey(cfg.mint);+ const to = new PublicKey(wallet);+ const connection = solanaConnection('mainnet');+ const programId = await tokenProgramForMint(connection, mint);++ const fromAta = getAssociatedTokenAddressSync(mint, payer.publicKey, false, programId);+ const toAta = getAssociatedTokenAddressSync(mint, to, false, programId);+ const instructions = [+ createAssociatedTokenAccountIdempotentInstruction(payer.publicKey, toAta, to, mint, programId),+ createTransferCheckedInstruction(fromAta, mint, toAta, payer.publicKey, amountAtomic, THREE_DECIMALS, [], programId),+ ];+ const result = await submitProtected({+ network: 'mainnet',+ connection,+ payer,+ instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ return result.signature;+}++/**+ * Claim the $THREE reward for a cleared day.+ *+ * @param {object} p+ * @param {string} p.userId+ * @param {string} p.day YYYY-MM-DD, today or yesterday (UTC).+ * @param {number} [p.now]+ * @param {object} [p.env] defaults to process.env.+ * @param {object} [p.deps] { sql, sendThree } for tests; production uses the real ones.+ */+export async function claimDailyClearReward({ userId, day, now = Date.now(), env = process.env, deps = {} }) {+ const cfg = questRewardConfig(env);+ // The gate. Nothing below this line runs while the switch is off.+ if (!cfg.armed) {+ return fail(409, 'rewards_disarmed', '$THREE quest rewards are not switched on. XP and badges still count.');+ }+ const sql = deps.sql || defaultSql;+ const sendThree = deps.sendThree || sendThreeOnChain;++ const today = utcDay(now);+ const yesterday = utcDay(Date.parse(`${today}T00:00:00.000Z`) - DAY_MS);+ if (day !== today && day !== yesterday) return fail(400, 'invalid_day', 'Rewards can be claimed for today or yesterday only.');++ const [cleared] = await sql`+ select 1 as ok from trading_quest_completions+ where user_id = ${userId} and day = ${day}::date and code = 'daily_clear'+ limit 1+ `;+ if (!cleared) return fail(409, 'not_cleared', 'Clear the daily quests first.');++ const [linked] = await sql`+ select address from user_wallets+ where user_id = ${userId} and chain_type = 'solana'+ order by is_primary desc, created_at asc+ limit 1+ `;+ if (!linked?.address) return fail(409, 'no_wallet', 'Link a Solana wallet to your account to receive $THREE.');++ const [existing] = await sql`+ select status, tx_signature from trading_quest_three_rewards+ where user_id = ${userId} and day = ${day}::date+ limit 1+ `;+ if (existing?.status === 'sent') return { ok: true, status: 'sent', tx_signature: existing.tx_signature, amount_three: cfg.amount_whole };+ if (existing?.status === 'pending') return fail(409, 'in_flight', 'This reward is already being sent.');++ const [{ spent = '0' } = {}] = await sql`+ select coalesce(sum(amount_atomic), 0)::text as spent from trading_quest_three_rewards+ where day = ${day}::date and status in ('pending', 'sent')+ `;+ if (BigInt(String(spent).split('.')[0]) + cfg.amount_atomic > cfg.daily_budget_atomic) {+ return fail(409, 'budget_exhausted', "Today's $THREE reward pool is used up. Your clear and XP still count.");+ }++ // Claim the ledger row before anything moves on-chain.+ const claimed = existing?.status === 'failed'+ ? await sql`+ update trading_quest_three_rewards+ set status = 'pending', wallet = ${linked.address}, amount_atomic = ${cfg.amount_atomic.toString()}, error = null, updated_at = now()+ where user_id = ${userId} and day = ${day}::date and status = 'failed'+ returning user_id+ `+ : await sql`+ insert into trading_quest_three_rewards (user_id, day, amount_atomic, wallet, status)+ values (${userId}, ${day}::date, ${cfg.amount_atomic.toString()}, ${linked.address}, 'pending')+ on conflict do nothing+ returning user_id+ `;+ if (!claimed.length) return fail(409, 'in_flight', 'This reward is already being sent.');++ try {+ const signature = await sendThree({ wallet: linked.address, amountAtomic: cfg.amount_atomic, cfg });+ await sql`+ update trading_quest_three_rewards+ set status = 'sent', tx_signature = ${signature}, updated_at = now()+ where user_id = ${userId} and day = ${day}::date+ `;+ return { ok: true, status: 'sent', tx_signature: signature, amount_three: cfg.amount_whole };+ } catch (err) {+ const message = String(err?.message || 'transfer failed').slice(0, 300);+ await sql`+ update trading_quest_three_rewards+ set status = 'failed', error = ${message}, updated_at = now()+ where user_id = ${userId} and day = ${day}::date+ `;+ return fail(502, 'payout_failed', 'The $THREE transfer did not go through. Try again in a minute.');+ }+}diff --git a/api/_lib/trading-quests.js b/api/_lib/trading-quests.jsnew file mode 100644index 000000000..1edaabeb4--- /dev/null+++ b/api/_lib/trading-quests.js@@ -0,0 +1,367 @@+// Daily trading quests: small, provable goals that reset every UTC midnight.+// ---------------------------------------------------------------------------+// Habit formation on top of streaks + badges (api/_lib/streaks.js). Every quest+// is computed from an event that already proves itself, never from a claim:+//+// trades_3 verified user-signed trades (buy-confirm / sell-confirm check the+// signature on-chain) from a wallet LINKED to the account, plus+// confirmed Co-Pilot trades on an agent the user owns+// fork_trade one of those verified trades opened from a Fork+// ghost_new the first ghost-copy of a leader this user never replayed before+// copy_act a copy intent the user acted on (copy_executions)+// agent_green an agent the user owns closes a LIVE trade in profit (positions ledger)+//+// Clearing any DAILY_CLEAR.need quests in one UTC day is a daily clear. Rewards+// are XP and badges. XP lives in trading_quest_completions as insert-only rows,+// so a total never shrinks when an underlying row later changes. A $THREE reward+// for a daily clear exists in api/_lib/quest-rewards.js and ships DISARMED.+//+// Awards are made when progress is read, for today and yesterday: the proof+// tables are durable, so a day's progress is recomputable after the fact, and+// one day of grace means finishing a quest at 23:59 UTC still counts.++import { sql } from './db.js';+import { unlockBadge, listBadges, BADGES } from './streaks.js';+import { SIMULATED_SIG } from './trade-card.js';+import { isUuid } from './validate.js';++export const QUESTS = Object.freeze([+ {+ code: 'trades_3',+ title: 'Make 3 trades',+ detail: 'Buy or sell any pump.fun coin three times today, signed by a wallet linked to your account, or through the Co-Pilot on an agent you own.',+ target: 3,+ xp: 30,+ cta: { label: 'Open the live trade feed', href: '/trades' },+ },+ {+ code: 'fork_trade',+ title: 'Fork a verified trade',+ detail: 'Tap Fork on a verified trade and sign it from your own wallet at your own size.',+ target: 1,+ xp: 25,+ cta: { label: 'Find a trade to fork', href: '/trades' },+ },+ {+ code: 'ghost_new',+ title: 'Ghost-copy a new agent',+ detail: 'Replay a leader you have never ghost-copied before, with fake money. Nothing is signed.',+ target: 1,+ xp: 15,+ cta: { label: 'Pick a leader', href: '/ghost-copy' },+ },+ {+ code: 'copy_act',+ title: 'Act on a copy intent',+ detail: 'Execute a copy intent from a leader you follow, then mark it copied.',+ target: 1,+ xp: 25,+ cta: { label: 'Open your copy intents', href: '/dashboard/copy' },+ },+ {+ code: 'agent_green',+ title: 'Your agent closes a winner',+ detail: 'An agent you own closes a live trade in profit. Paper trades do not count.',+ target: 1,+ xp: 20,+ cta: { label: 'Tune your trader', href: '/strategy-lab' },+ },+]);++export const DAILY_CLEAR = Object.freeze({ code: 'daily_clear', need: 3, xp: 50 });++const DAY_MS = 86_400_000;+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);++/** The UTC day (YYYY-MM-DD) a timestamp falls on. PURE. */+export function utcDay(at = Date.now()) {+ return new Date(typeof at === 'number' ? at : new Date(at).getTime()).toISOString().slice(0, 10);+}++/** [start, end) of a UTC day as ISO strings. PURE. */+export function dayBounds(day) {+ const start = Date.parse(`${day}T00:00:00.000Z`);+ return { start: new Date(start).toISOString(), end: new Date(start + DAY_MS).toISOString() };+}++/** The day before a UTC day. PURE. */+export function previousDay(day) {+ return utcDay(Date.parse(`${day}T00:00:00.000Z`) - DAY_MS);+}++/**+ * XP needed to REACH a level: 0, 100, 300, 600, 1000, ... (50 * L * (L - 1)).+ * Each level asks for 100 XP more than the last, so early levels come fast and+ * later ones mean something. PURE.+ */+export function xpForLevel(level) {+ const l = Math.max(1, Math.floor(level));+ return 50 * l * (l - 1);+}++/** Level progress for an XP total. PURE. */+export function levelFor(totalXp) {+ const xp = Math.max(0, Math.floor(n(totalXp)));+ let level = 1;+ while (xpForLevel(level + 1) <= xp) level++;+ const floor = xpForLevel(level);+ const next = xpForLevel(level + 1);+ return { total: xp, level, into_level: xp - floor, level_span: next - floor, next_level_at: next };+}++/**+ * Fold a day's raw counts into quest progress. PURE.+ * @param {object} counts { trades, forks, ghosts, acted, green }+ * @param {Set<string>|string[]} [awarded] quest codes already awarded that day.+ */+export function evaluateQuests(counts = {}, awarded = []) {+ const done = new Set(awarded);+ const raw = {+ trades_3: n(counts.trades),+ fork_trade: n(counts.forks),+ ghost_new: n(counts.ghosts),+ copy_act: n(counts.acted),+ agent_green: n(counts.green),+ };+ const quests = QUESTS.map((q) => {+ const progress = Math.min(q.target, raw[q.code]);+ // An award already made stays made, even if a later read counts fewer rows.+ const complete = progress >= q.target || done.has(q.code);+ return { ...q, progress: complete ? q.target : progress, done: complete };+ });+ const doneCount = quests.filter((q) => q.done).length;+ return {+ quests,+ done_count: doneCount,+ cleared: doneCount >= DAILY_CLEAR.need || done.has(DAILY_CLEAR.code),+ };+}++/**+ * Consecutive UTC days with a daily clear, ending today or yesterday (a streak+ * is still alive until a whole day passes without a clear). PURE.+ * @param {string[]} clearDays YYYY-MM-DD strings.+ * @param {string} today+ */+export function clearStreak(clearDays = [], today = utcDay()) {+ const set = new Set(clearDays.map((d) => String(d).slice(0, 10)));+ let cursor = set.has(today) ? today : previousDay(today);+ let current = 0;+ while (set.has(cursor)) {+ current++;+ cursor = previousDay(cursor);+ }+ const sorted = [...set].sort();+ let longest = 0;+ let run = 0;+ let prev = null;+ for (const d of sorted) {+ run = prev && previousDay(d) === prev ? run + 1 : 1;+ if (run > longest) longest = run;+ prev = d;+ }+ return { current, longest };+}++// ── Recording (the two events with no other durable trace) ──────────────────++/**+ * Record a user-signed trade whose signature was verified on-chain. First claim+ * of a signature wins. Never throws: a quest record must not fail a trade.+ */+export async function recordQuestTrade({ userId, signature, network = 'mainnet', wallet, origin = null, direction = null, mint = null }) {+ if (!userId || !signature) return false;+ try {+ const rows = await sql`+ insert into trading_quest_events (user_id, kind, ref, network, origin, wallet, context)+ values (${userId}, 'trade', ${signature}, ${network}, ${origin === 'fork' ? 'fork' : null}, ${wallet || null},+ ${JSON.stringify({ direction, mint })}::jsonb)+ on conflict do nothing+ returning id+ `;+ return rows.length > 0;+ } catch (err) {+ console.warn('[trading-quests] recordQuestTrade skipped:', err?.message);+ return false;+ }+}++/**+ * Record that a signed-in user ghost-copied a leader. Only the first ghost of a+ * given leader is kept, which is exactly what "a new agent" means. The leader+ * must be a public agent with at least one closed round-trip, the same universe+ * the ghost-copy picker offers.+ * @returns {Promise<{ok:boolean, new_agent?:boolean, error?:string}>}+ */+export async function recordGhostQuest({ userId, leaderId, network = 'mainnet', context = null }) {+ if (!userId || !isUuid(leaderId)) return { ok: false, error: 'leader_agent_id must be an agent UUID' };+ const [leader] = await sql`+ select a.id from agent_identities a+ where a.id = ${leaderId} and a.deleted_at is null and a.is_public <> false+ and exists (+ select 1 from agent_sniper_positions p+ where p.agent_id = a.id and p.network = ${network} and p.status = 'closed'+ )+ limit 1+ `;+ if (!leader) return { ok: false, error: 'That leader has no closed trades to ghost-copy.' };+ const rows = await sql`+ insert into trading_quest_events (user_id, kind, ref, network, context)+ values (${userId}, 'ghost_copy', ${leaderId}, ${network}, ${context ? JSON.stringify(context) : null}::jsonb)+ on conflict do nothing+ returning id+ `;+ return { ok: true, new_agent: rows.length > 0 };+}++// ── Progress + awards ────────────────────────────────────────────────────────++/** Raw counts for one user on one UTC day, one round-trip. */+async function dayCounts(userId, day) {+ const { start, end } = dayBounds(day);+ const [row] = await sql`+ with linked as (+ select address from user_wallets where user_id = ${userId} and chain_type = 'solana'+ union+ select wallet_address from users where id = ${userId} and wallet_address is not null+ ),+ trades as (+ select e.ref as sig, e.origin+ from trading_quest_events e+ where e.user_id = ${userId} and e.kind = 'trade'+ and e.created_at >= ${start} and e.created_at < ${end}+ and e.wallet in (select address from linked)+ union+ select t.tx_signature as sig, null as origin+ from pump_agent_trades t+ where t.user_id = ${userId} and t.tx_signature is not null+ and t.created_at >= ${start} and t.created_at < ${end}+ and t.wallet in (select address from linked)+ union+ select c.signature as sig, null as origin+ from agent_custody_events c+ where c.user_id = ${userId} and c.event_type = 'spend' and c.category = 'trade'+ and c.status = 'confirmed' and c.signature is not null+ and c.created_at >= ${start} and c.created_at < ${end}+ )+ select+ (select count(distinct sig) from trades)::int as trades,+ (select count(distinct sig) from trades where origin = 'fork')::int as forks,+ (select count(*) from trading_quest_events g+ where g.user_id = ${userId} and g.kind = 'ghost_copy'+ and g.created_at >= ${start} and g.created_at < ${end})::int as ghosts,+ (select count(*) from copy_executions x+ where x.copier_user_id = ${userId} and x.status = 'acted'+ and x.updated_at >= ${start} and x.updated_at < ${end})::int as acted,+ (select count(*) from agent_sniper_positions p+ join agent_identities a on a.id = p.agent_id+ where a.user_id = ${userId} and p.status = 'closed'+ and p.closed_at >= ${start} and p.closed_at < ${end}+ and p.realized_pnl_lamports > 0+ and p.buy_sig is not null and p.buy_sig <> ${SIMULATED_SIG})::int as green+ `;+ return row || {};+}++async function awardedCodes(userId, day) {+ const rows = await sql`+ select code from trading_quest_completions where user_id = ${userId} and day = ${day}::date+ `;+ return new Set(rows.map((r) => r.code));+}++/** Insert the completions a day newly earned. Returns the codes newly awarded. */+async function awardDay(userId, day, evaluation, alreadyAwarded) {+ const fresh = [];+ for (const q of evaluation.quests) {+ if (!q.done || alreadyAwarded.has(q.code)) continue;+ const rows = await sql`+ insert into trading_quest_completions (user_id, day, code, xp)+ values (${userId}, ${day}::date, ${q.code}, ${q.xp})+ on conflict do nothing+ returning code+ `;+ if (rows.length) fresh.push(q.code);+ }+ if (evaluation.cleared && !alreadyAwarded.has(DAILY_CLEAR.code)) {+ const rows = await sql`+ insert into trading_quest_completions (user_id, day, code, xp)+ values (${userId}, ${day}::date, ${DAILY_CLEAR.code}, ${DAILY_CLEAR.xp})+ on conflict do nothing+ returning code+ `;+ if (rows.length) fresh.push(DAILY_CLEAR.code);+ }+ return fresh;+}++/** Evaluate and award one day. */+async function settleDay(userId, day) {+ const [counts, awarded] = await Promise.all([dayCounts(userId, day), awardedCodes(userId, day)]);+ const evaluation = evaluateQuests(counts, awarded);+ const fresh = await awardDay(userId, day, evaluation, awarded);+ return { day, evaluation, fresh };+}++const QUEST_BADGES = new Set([BADGES.QUEST_FIRST, BADGES.QUEST_CLEAR, BADGES.QUEST_STREAK_7]);++/**+ * A signed-in user's quest board for today. Awards anything newly earned today+ * or yesterday, then reads the XP total, the clear streak, and quest badges.+ */+export async function loadQuestBoard(userId, { now = Date.now() } = {}) {+ const today = utcDay(now);+ const yesterday = previousDay(today);+ const [todayResult, yesterdayResult] = await Promise.all([settleDay(userId, today), settleDay(userId, yesterday)]);++ const [[totals], clearRows] = await Promise.all([+ sql`+ select coalesce(sum(xp), 0)::int as xp,+ count(*) filter (where code <> ${DAILY_CLEAR.code})::int as quests_done+ from trading_quest_completions where user_id = ${userId}+ `,+ sql`+ select day::text as day from trading_quest_completions+ where user_id = ${userId} and code = ${DAILY_CLEAR.code}+ order by day desc limit 400+ `,+ ]);+ const streak = clearStreak(clearRows.map((r) => r.day), today);++ if (n(totals?.quests_done) > 0) await unlockBadge(userId, BADGES.QUEST_FIRST);+ if (clearRows.length > 0) await unlockBadge(userId, BADGES.QUEST_CLEAR);+ if (streak.current >= 7 || streak.longest >= 7) await unlockBadge(userId, BADGES.QUEST_STREAK_7, { longest: streak.longest });+ const badges = (await listBadges(userId)).filter((b) => QUEST_BADGES.has(b.code));++ const ev = todayResult.evaluation;+ return {+ day: today,+ resets_at: dayBounds(today).end,+ quests: ev.quests,+ daily_clear: { need: DAILY_CLEAR.need, xp: DAILY_CLEAR.xp, done_count: ev.done_count, cleared: ev.cleared },+ yesterday: {+ day: yesterday,+ done_count: yesterdayResult.evaluation.done_count,+ cleared: yesterdayResult.evaluation.cleared,+ },+ xp: levelFor(totals?.xp),+ clear_streak: streak,+ badges,+ newly_completed: [+ ...todayResult.fresh.map((code) => ({ day: today, code })),+ ...yesterdayResult.fresh.map((code) => ({ day: yesterday, code })),+ ],+ };+}++/** The quest catalog for a signed-out visitor: real quests, no progress. PURE. */+export function questCatalog(now = Date.now()) {+ const today = utcDay(now);+ return {+ day: today,+ resets_at: dayBounds(today).end,+ quests: QUESTS.map((q) => ({ ...q, progress: null, done: false })),+ daily_clear: { need: DAILY_CLEAR.need, xp: DAILY_CLEAR.xp },+ };+}+diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 797edaa99..5e070c78c 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -68,6 +68,8 @@ import { markPlanLaunched } from '../_lib/agent-token-plan.js';import { randomToken } from '../_lib/crypto.js';import { publishFeedEvent } from '../_lib/feed.js';import { recordDailyActivity } from '../_lib/streaks.js';+import { recordQuestTrade } from '../_lib/trading-quests.js';+import { recordCopyPathStep } from '../_lib/copy-path.js';import { normalizeGatewayURL } from '../../src/ipfs.js';import { buildTokenMetadata } from '../_lib/three-brand.js';import {@@ -597,6 +599,9 @@ const buyConfirmSchema = zusdc_amount: z.number().nonnegative().max(1_000_000).optional(),route: z.enum(['bonding_curve', 'amm']),slippage_bps: z.number().int().min(0).max(5000).optional(),+ // 'fork' when the trade panel was opened by a Fork (src/fork-trade.js). Only+ // labels the verified trade for the daily fork quest; it gates nothing.+ origin: z.enum(['fork']).optional(),}).refine((v) => (v.sol ?? 0) > 0 || (v.usdc_amount ?? 0) > 0, {message: 'sol or usdc_amount required',@@ -671,8 +676,24 @@ async function handleBuyConfirm(req, res) {// this. Fire-and-forget and idempotent per UTC day, exactly like every other// call site: it can never delay or fail the buy that earned it.recordDailyActivity(user.id).catch(() => {});+ } else {+ // A coin launched elsewhere has no pump_agent_trades row, so this verified+ // buy is the proof of step 3 of the first-copy path (api/_lib/copy-path.js).+ recordCopyPathStep(user.id, 'trade', { signature: body.tx_signature }).catch(() => {});}+ // Daily trading quests (api/_lib/trading-quests.js) count every verified trade,+ // on any coin. Fire-and-forget: a quest record can never delay or fail the buy.+ recordQuestTrade({+ userId: user.id,+ signature: body.tx_signature,+ network: body.network,+ wallet: body.wallet_address,+ origin: body.origin ?? null,+ direction: 'buy',+ mint: body.mint,+ }).catch(() => {});+// Surface the buy on the site-wide live activity ticker. The tx is already// verified on-chain above, so this is a real, confirmed purchase. Fire-and-// forget: never let the delight layer delay or fail the buy response.@@ -979,6 +1000,15 @@ async function handleSellConfirm(req, res) {recordDailyActivity(user.id).catch(() => {});}+ recordQuestTrade({+ userId: user.id,+ signature: body.tx_signature,+ network: body.network,+ wallet: body.wallet_address,+ direction: 'sell',+ mint: body.mint,+ }).catch(() => {});+return json(res, 200, {ok: true,tracked: !!mintId,diff --git a/api/quests/claim.js b/api/quests/claim.jsnew file mode 100644index 000000000..3b8255641--- /dev/null+++ b/api/quests/claim.js@@ -0,0 +1,37 @@+// POST /api/quests/claim { day: 'YYYY-MM-DD' }+// ---------------------------------------------------------------------------+// Claim the $THREE reward for a cleared day (today or yesterday, UTC). This is+// the only quest path that can move funds, so it is DISARMED by default: until+// the owner sets TRADING_QUEST_THREE_REWARDS=on with an amount and a funded+// payout key, it answers 409 rewards_disarmed and touches nothing. See+// api/_lib/quest-rewards.js for the full contract.++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { claimDailyClearReward } from '../_lib/quest-rewards.js';++const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer.userId;+ if (session && !(await requireCsrf(req, res, userId))) return;++ const body = await readJson(req).catch(() => null);+ const day = typeof body?.day === 'string' && DAY_RE.test(body.day) ? body.day : null;+ if (!day) return error(res, 400, 'invalid_day', 'day must be YYYY-MM-DD');++ const result = await claimDailyClearReward({ userId, day });+ if (!result.ok) return error(res, result.status, result.code, result.message, result.extra);+ return json(res, 200, result);+});diff --git a/api/quests/event.js b/api/quests/event.jsnew file mode 100644index 000000000..8aece1efc--- /dev/null+++ b/api/quests/event.js@@ -0,0 +1,44 @@+// POST /api/quests/event { kind: 'ghost_copy', leader_agent_id, network?, context? }+// ---------------------------------------------------------------------------+// Records the one quest event the server cannot see on its own: a ghost-copy+// replay. The replay endpoint is public, stateless and CDN-cached, so the page+// reports a finished replay here, signed in. Only the FIRST ghost of a leader+// is kept (that is what "ghost-copy a new agent" means), the leader must be a+// public agent with closed trades, and it is paper-only, so nothing here is+// worth more than XP. The same event completes step 2 of the first-copy path+// (api/_lib/copy-path.js), which had no writer before this.++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { recordGhostQuest } from '../_lib/trading-quests.js';+import { recordCopyPathStep, sanitizeStepContext } from '../_lib/copy-path.js';++const NETWORKS = new Set(['mainnet', 'devnet']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer.userId;+ if (session && !(await requireCsrf(req, res, userId))) return;++ const body = await readJson(req).catch(() => null);+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');+ if (body.kind !== 'ghost_copy') return error(res, 400, 'invalid_kind', "kind must be 'ghost_copy'");++ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';+ const context = sanitizeStepContext('ghost', { ...(body.context || {}), leader_agent_id: body.leader_agent_id });+ const result = await recordGhostQuest({ userId, leaderId: body.leader_agent_id, network, context });+ if (!result.ok) return error(res, 400, 'invalid_leader', result.error);++ if (context) await recordCopyPathStep(userId, 'ghost', context).catch(() => false);+ return json(res, 200, { recorded: true, new_agent: result.new_agent });+});diff --git a/api/quests/index.js b/api/quests/index.jsnew file mode 100644index 000000000..1c355a04c--- /dev/null+++ b/api/quests/index.js@@ -0,0 +1,46 @@+// GET /api/quests+// ---------------------------------------------------------------------------+// Today's trading quests. Signed out: the real quest catalog with no progress,+// so the page can show what there is to do. Signed in: progress computed from+// proof tables (verified trades, forks, first ghost-copies, acted copy intents,+// an owned agent's profitable live closes), with anything newly earned today or+// yesterday awarded on this read, plus XP level, daily-clear streak, and quest+// badges. See api/_lib/trading-quests.js.+//+// `three_rewards.armed` says whether a daily clear also pays $THREE. It is false+// unless the owner switched TRADING_QUEST_THREE_REWARDS on (api/_lib/quest-rewards.js).++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { loadQuestBoard, questCatalog } from '../_lib/trading-quests.js';+import { questRewardConfig, publicRewardInfo } from '../_lib/quest-rewards.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);++ const cfg = questRewardConfig();+ const rewards = publicRewardInfo(cfg);++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id ?? bearer?.userId ?? null;+ res.setHeader?.('cache-control', 'private, no-store');++ if (!userId) return json(res, 200, { signed_in: false, ...questCatalog(), three_rewards: rewards });++ const board = await loadQuestBoard(userId);+ if (cfg.armed) {+ const claims = await sql`+ select day::text as day, status, tx_signature from trading_quest_three_rewards+ where user_id = ${userId} and day in (${board.day}::date, ${board.yesterday.day}::date)+ `;+ rewards.claims = claims;+ }+ return json(res, 200, { signed_in: true, ...board, three_rewards: rewards });+});diff --git a/src/fork-trade.js b/src/fork-trade.jsindex a58958761..ed0df7bc9 100644--- a/src/fork-trade.js+++ b/src/fork-trade.js@@ -143,7 +143,8 @@ export async function openFork(trade, { trigger } = {}) {{ mint: trade.mint, symbol: trade.symbol, name: trade.name, image: trade.image },// elevate: a fork always opens on a page carrying the site nav, which// stacks above the modal's default /play layer.- { mode: 'buy', amount: clampForkSize(trade.size) ?? undefined, elevate: true },+ // origin: labels the verified buy as a fork for the daily fork quest.+ { mode: 'buy', amount: clampForkSize(trade.size) ?? undefined, elevate: true, origin: 'fork' },);return true;} catch {diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex 16146a681..b76b1b499 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -128,7 +128,7 @@ function friendlyTradeError(err, mode = 'buy') {* so a forked trade never leaves the user staring at the previous coin's panel.* Opens in Buy mode; the user can switch to Sell inside the modal.* @param {{mint:string, name?:string, symbol?:string, image?:string}} coin- * @param {{mode?: 'buy'|'sell', amount?: number, elevate?: boolean}} [opts]+ * @param {{mode?: 'buy'|'sell', amount?: number, elevate?: boolean, origin?: 'fork'}} [opts]* `amount` pre-fills the buy input (SOL), which is how a forked trade carries* its size across; `elevate` lifts the modal above a page's sticky site nav.*/@@ -163,6 +163,9 @@ class TradeModal {// Pages with the site nav stack their chrome above this modal's default// layer; they opt into a higher one. See .cc-buy-elevated.this.elevate = !!opts.elevate;+ // 'fork' when a Fork opened this panel. Sent with buy-confirm so the verified+ // trade counts toward the daily fork quest; it changes nothing about the trade.+ this.origin = opts.origin === 'fork' ? 'fork' : null;this._sellMax = false;this.slippageBps = DEFAULT_SLIPPAGE_BPS;this.busy = false;@@ -976,6 +979,7 @@ class TradeModal {// failure here must never read as a failed purchase.const confirmBody = { mint: this.coin.mint, network: NETWORK, tx_signature: sig, wallet_address: walletAddress, route: prep.route, slippage_bps: this.slippageBps };if (isUsdc) confirmBody.usdc_amount = this.amount; else confirmBody.sol = this.amount;+ if (this.origin) confirmBody.origin = this.origin;this._fetchJson('/api/pump/buy-confirm', confirmBody).catch(() => {});this.cta.textContent = `Bought ${this.sym} ✓`;diff --git a/src/ghost-copy.js b/src/ghost-copy.jsindex 5675fb7a9..ae66b4fd4 100644--- a/src/ghost-copy.js+++ b/src/ghost-copy.js@@ -13,6 +13,7 @@// /vaults.import { initFork, forkButton } from './fork-trade.js';+import { apiFetch, noteSession } from './api.js';const leadersEl = document.getElementById('gcLeaders');const resultEl = document.getElementById('gcResult');@@ -364,12 +365,61 @@ async function runGhost() {if (seq !== runSeq) return;if (!r.ok) return renderError(body?.message || `HTTP ${r.status}`);renderResult(body);+ recordGhostQuest(body);} catch (err) {if (seq !== runSeq) return;renderError(err?.message);}}+// ── quest credit ─────────────────────────────────────────────────────────────+// The replay endpoint is public and cached, so it never learns who ran it. For a+// signed-in visitor the page reports the finished replay, which counts toward the+// daily "ghost-copy a new agent" quest (/quests) and the first-copy path. Signed-+// out visitors are checked once and never sent a request that could only 401.++let signedIn = null;+async function isSignedIn() {+ if (signedIn !== null) return signedIn;+ try {+ const r = await fetch('/api/auth/me', { credentials: 'include', headers: { accept: 'application/json' } });+ const d = r.ok ? await r.json() : null;+ signedIn = !!d?.user;+ noteSession(signedIn);+ } catch {+ signedIn = false;+ }+ return signedIn;+}++const reported = new Set();+async function recordGhostQuest(body) {+ const leaderId = body?.leader?.agent_id || state.leader;+ if (!leaderId || reported.has(leaderId)) return;+ reported.add(leaderId);+ if (!(await isSignedIn())) return;+ try {+ await apiFetch('/api/quests/event', {+ method: 'POST',+ allowAnonymous: true,+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({+ kind: 'ghost_copy',+ leader_agent_id: leaderId,+ network: body?.network || 'mainnet',+ context: {+ budget_sol: state.budget,+ window: state.window,+ pnl_sol: body?.summary?.realized_pnl_sol ?? null,+ leader_name: body?.leader?.name || null,+ },+ }),+ });+ } catch {+ // Quest credit is a bonus on top of the replay; a failure here changes nothing on the page.+ }+}+// ── wiring ──────────────────────────────────────────────────────────────────let budgetTimer;diff --git a/tests/quest-rewards.test.js b/tests/quest-rewards.test.jsnew file mode 100644index 000000000..0686aa613--- /dev/null+++ b/tests/quest-rewards.test.js@@ -0,0 +1,164 @@+/**+ * The $THREE daily-clear reward (api/_lib/quest-rewards.js) ships DISARMED.+ *+ * Paying it spends $THREE from a platform wallet, which is an owner-gated action.+ * These tests pin the gate: with the switch off (the default, and every+ * half-configured state) a claim returns before it reads a row, writes a row,+ * or calls the transfer. With it armed, the payout path is idempotent, bounded+ * by a daily budget, and records failures so a retry is possible.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(() => { throw new Error('the default db must never be touched in these tests'); }) }));++const R = await import('../api/_lib/quest-rewards.js');++const USER = 'user-1';+const NOW = Date.UTC(2026, 8, 29, 15);+const TODAY = '2026-09-29';+const ARMED = {+ TRADING_QUEST_THREE_REWARDS: 'on',+ TRADING_QUEST_THREE_REWARD_AMOUNT: '250',+ TRADING_QUEST_THREE_REWARD_SECRET_KEY_B64: Buffer.alloc(64, 7).toString('base64'),+};++function fakeSql(state) {+ const calls = [];+ const sql = (strings, ...values) => {+ const text = strings.join('?');+ calls.push({ text, values });+ if (text.includes('from trading_quest_completions')) return Promise.resolve(state.cleared ? [{ ok: 1 }] : []);+ if (text.includes('from user_wallets')) return Promise.resolve(state.wallet ? [{ address: state.wallet }] : []);+ if (text.includes('select status, tx_signature from trading_quest_three_rewards')) return Promise.resolve(state.existing ? [state.existing] : []);+ if (text.includes('coalesce(sum(amount_atomic)')) return Promise.resolve([{ spent: state.spent || '0' }]);+ if (text.includes('insert into trading_quest_three_rewards')) return Promise.resolve(state.insertLoses ? [] : [{ user_id: USER }]);+ if (text.includes("set status = 'pending'")) return Promise.resolve([{ user_id: USER }]);+ if (text.includes("set status = 'sent'")) { state.sent = values[0]; return Promise.resolve([]); }+ if (text.includes("set status = 'failed'")) { state.failed = values[0]; return Promise.resolve([]); }+ return Promise.resolve([]);+ };+ return { sql, calls };+}++let state;+beforeEach(() => {+ state = { cleared: true, wallet: 'THREEsyntheticWa11et111111111111111111111' };+});++describe('questRewardConfig', () => {+ it('is disarmed by default', () => {+ const cfg = R.questRewardConfig({});+ expect(cfg.armed).toBe(false);+ expect(cfg.reason).toMatch(/TRADING_QUEST_THREE_REWARDS is off/);+ });++ it('stays disarmed when half configured', () => {+ expect(R.questRewardConfig({ TRADING_QUEST_THREE_REWARDS: 'on' }).armed).toBe(false);+ expect(R.questRewardConfig({ TRADING_QUEST_THREE_REWARDS: 'on', TRADING_QUEST_THREE_REWARD_AMOUNT: '10' }).armed).toBe(false);+ expect(R.questRewardConfig({ ...ARMED, TRADING_QUEST_THREE_REWARDS: 'off' }).armed).toBe(false);+ });++ it('arms only with the switch, an amount and a signer, and budgets 20x by default', () => {+ const cfg = R.questRewardConfig(ARMED);+ expect(cfg.armed).toBe(true);+ expect(cfg.amount_atomic).toBe(250_000_000n);+ expect(cfg.daily_budget_whole).toBe(5000);+ expect(cfg.mint).toBe(R.THREE_MINT_DEFAULT);+ });++ it('never exposes the key or the reason publicly', () => {+ expect(R.publicRewardInfo(R.questRewardConfig({}))).toEqual({ armed: false });+ expect(R.publicRewardInfo(R.questRewardConfig(ARMED))).toEqual({ armed: true, amount_three: 250 });+ });++ it('converts whole $THREE to 6-decimal atomic units exactly', () => {+ expect(R.toAtomic(1)).toBe(1_000_000n);+ expect(R.toAtomic(0.000001)).toBe(1n);+ expect(R.toAtomic(12.5)).toBe(12_500_000n);+ });+});++describe('claimDailyClearReward while disarmed', () => {+ it('touches neither the database nor the chain', async () => {+ const { sql, calls } = fakeSql(state);+ const sendThree = vi.fn();+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: {}, deps: { sql, sendThree } });+ expect(r).toMatchObject({ ok: false, status: 409, code: 'rewards_disarmed' });+ expect(calls).toHaveLength(0);+ expect(sendThree).not.toHaveBeenCalled();+ });++ it('falls back to the real env and still refuses, without a db call', async () => {+ const prev = process.env.TRADING_QUEST_THREE_REWARDS;+ delete process.env.TRADING_QUEST_THREE_REWARDS;+ try {+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW });+ expect(r.code).toBe('rewards_disarmed');+ } finally {+ if (prev !== undefined) process.env.TRADING_QUEST_THREE_REWARDS = prev;+ }+ });+});++describe('claimDailyClearReward when armed', () => {+ it('pays the configured amount once to the linked wallet and records the signature', async () => {+ const { sql } = fakeSql(state);+ const sendThree = vi.fn(async () => 'sig-123');+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql, sendThree } });+ expect(r).toEqual({ ok: true, status: 'sent', tx_signature: 'sig-123', amount_three: 250 });+ expect(sendThree).toHaveBeenCalledTimes(1);+ expect(sendThree.mock.calls[0][0]).toMatchObject({ wallet: state.wallet, amountAtomic: 250_000_000n });+ expect(state.sent).toBe('sig-123');+ });++ it('returns the earlier payout instead of paying twice', async () => {+ state.existing = { status: 'sent', tx_signature: 'sig-old' };+ const { sql } = fakeSql(state);+ const sendThree = vi.fn();+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql, sendThree } });+ expect(r).toMatchObject({ ok: true, tx_signature: 'sig-old' });+ expect(sendThree).not.toHaveBeenCalled();+ });++ it('refuses a concurrent claim that lost the ledger race', async () => {+ state.insertLoses = true;+ const { sql } = fakeSql(state);+ const sendThree = vi.fn();+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql, sendThree } });+ expect(r.code).toBe('in_flight');+ expect(sendThree).not.toHaveBeenCalled();+ });++ it('requires the day to be cleared, a linked wallet, and today or yesterday', async () => {+ const sendThree = vi.fn();+ expect((await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql: fakeSql({ ...state, cleared: false }).sql, sendThree } })).code).toBe('not_cleared');+ expect((await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql: fakeSql({ ...state, wallet: null }).sql, sendThree } })).code).toBe('no_wallet');+ expect((await R.claimDailyClearReward({ userId: USER, day: '2026-09-20', now: NOW, env: ARMED, deps: { sql: fakeSql(state).sql, sendThree } })).code).toBe('invalid_day');+ expect((await R.claimDailyClearReward({ userId: USER, day: '2026-09-28', now: NOW, env: ARMED, deps: { sql: fakeSql(state).sql, sendThree: async () => 'sig-y' } })).ok).toBe(true);+ expect(sendThree).not.toHaveBeenCalled();+ });++ it('stops at the daily budget', async () => {+ state.spent = String(5000n * 1_000_000n);+ const { sql } = fakeSql(state);+ const sendThree = vi.fn();+ const r = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql, sendThree } });+ expect(r.code).toBe('budget_exhausted');+ expect(sendThree).not.toHaveBeenCalled();+ });++ it('records a failed transfer so the claim can be retried', async () => {+ const { sql } = fakeSql(state);+ const r = await R.claimDailyClearReward({+ userId: USER, day: TODAY, now: NOW, env: ARMED,+ deps: { sql, sendThree: async () => { throw new Error('blockhash expired'); } },+ });+ expect(r).toMatchObject({ ok: false, status: 502, code: 'payout_failed' });+ expect(state.failed).toBe('blockhash expired');++ state.existing = { status: 'failed' };+ const retry = await R.claimDailyClearReward({ userId: USER, day: TODAY, now: NOW, env: ARMED, deps: { sql: fakeSql(state).sql, sendThree: async () => 'sig-retry' } });+ expect(retry).toMatchObject({ ok: true, tx_signature: 'sig-retry' });+ });+});diff --git a/tests/trading-quests.test.js b/tests/trading-quests.test.jsnew file mode 100644index 000000000..6eacdeee9--- /dev/null+++ b/tests/trading-quests.test.js@@ -0,0 +1,100 @@+/**+ * Daily trading quests (api/_lib/trading-quests.js): the pure scoring that turns+ * a day's proven events into quest progress, the daily clear, the clear streak,+ * and XP levels. Awards are insert-only, so an award already made must stay made+ * even when a later read counts fewer rows.+ */++import { describe, it, expect, vi } from 'vitest';++vi.mock('../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));++const Q = await import('../api/_lib/trading-quests.js');++describe('evaluateQuests', () => {+ it('scores each quest against its target and caps progress at the target', () => {+ const ev = Q.evaluateQuests({ trades: 5, forks: 0, ghosts: 1, acted: 0, green: 0 });+ const byCode = Object.fromEntries(ev.quests.map((q) => [q.code, q]));+ expect(byCode.trades_3).toMatchObject({ progress: 3, done: true });+ expect(byCode.ghost_new).toMatchObject({ progress: 1, done: true });+ expect(byCode.fork_trade).toMatchObject({ progress: 0, done: false });+ expect(ev.done_count).toBe(2);+ expect(ev.cleared).toBe(false);+ });++ it('clears the day at three quests', () => {+ const ev = Q.evaluateQuests({ trades: 3, forks: 1, ghosts: 1 });+ expect(ev.done_count).toBe(3);+ expect(ev.cleared).toBe(true);+ });++ it('keeps an award already made even if the underlying count drops', () => {+ const ev = Q.evaluateQuests({ trades: 1 }, ['trades_3', 'daily_clear']);+ const trades = ev.quests.find((q) => q.code === 'trades_3');+ expect(trades).toMatchObject({ progress: 3, done: true });+ expect(ev.cleared).toBe(true);+ });++ it('treats missing counts as zero', () => {+ const ev = Q.evaluateQuests();+ expect(ev.done_count).toBe(0);+ expect(ev.quests.every((q) => q.progress === 0)).toBe(true);+ });++ it('every quest links somewhere real and pays XP', () => {+ for (const q of Q.QUESTS) {+ expect(q.cta.href).toMatch(/^\//);+ expect(q.xp).toBeGreaterThan(0);+ expect(q.target).toBeGreaterThan(0);+ }+ expect(Q.DAILY_CLEAR.need).toBeLessThanOrEqual(Q.QUESTS.length);+ });+});++describe('UTC day helpers', () => {+ it('bounds a UTC day', () => {+ expect(Q.dayBounds('2026-09-29')).toEqual({ start: '2026-09-29T00:00:00.000Z', end: '2026-09-30T00:00:00.000Z' });+ expect(Q.utcDay(Date.UTC(2026, 8, 29, 23, 59))).toBe('2026-09-29');+ expect(Q.previousDay('2026-03-01')).toBe('2026-02-28');+ });+});++describe('clearStreak', () => {+ it('counts consecutive clears ending today', () => {+ expect(Q.clearStreak(['2026-09-29', '2026-09-28', '2026-09-27', '2026-09-25'], '2026-09-29')).toEqual({ current: 3, longest: 3 });+ });++ it('stays alive through today when the last clear was yesterday', () => {+ expect(Q.clearStreak(['2026-09-28', '2026-09-27'], '2026-09-29').current).toBe(2);+ });++ it('breaks after a whole missed day but remembers the longest run', () => {+ const days = ['2026-09-20', '2026-09-21', '2026-09-22', '2026-09-23', '2026-09-26'];+ expect(Q.clearStreak(days, '2026-09-29')).toEqual({ current: 0, longest: 4 });+ });+});++describe('levelFor', () => {+ it('uses a gently rising curve', () => {+ expect(Q.xpForLevel(1)).toBe(0);+ expect(Q.xpForLevel(2)).toBe(100);+ expect(Q.xpForLevel(3)).toBe(300);+ expect(Q.levelFor(0)).toMatchObject({ level: 1, into_level: 0, level_span: 100, next_level_at: 100 });+ expect(Q.levelFor(99).level).toBe(1);+ expect(Q.levelFor(100).level).toBe(2);+ expect(Q.levelFor(450)).toMatchObject({ level: 3, into_level: 150, level_span: 300 });+ });++ it('never goes negative', () => {+ expect(Q.levelFor(-20)).toMatchObject({ total: 0, level: 1 });+ });+});++describe('questCatalog', () => {+ it('shows the real quests with no progress to a signed-out visitor', () => {+ const c = Q.questCatalog(Date.UTC(2026, 8, 29, 12));+ expect(c.day).toBe('2026-09-29');+ expect(c.resets_at).toBe('2026-09-30T00:00:00.000Z');+ expect(c.quests.every((q) => q.progress === null && q.done === false)).toBe(true);+ });+});