// THE DRAFT ENGINE. Pure functions: no I/O, no Date.now(). Every function takes `now` (ms) and the data it needs, so the weekly // draft is deterministic and unit-tested with a mocked clock (qa/unit.test.cjs). server.js feeds it the store and the tank adapter. // // The rules (Marty 2026-11-14, project-5xyourteam-draft): // - Every coach (holds a position) gets a draft spot every week. Each Monday the coaches draft from that week's pool, in rounds. // - Draft order is EARNED: most of LAST week's picks "started" (switched on payouts or bought) picks first. Ties: more started // picks ever, then the earlier first position (seniority), then a fixed shuffle of (week, coach) so nobody is always last. // - A pick is an ADOPTION under the holding-tank rules: never anyone locked on a network contract or already sponsored, never a // person adopted twice already (max 2 per person, lifetime, every pick counts), never spam / throwaway, never inside the 24-hour // sign-up grace, never someone already on a team. // - A coach in the draft room (the board pinged recently) gets the clock (pickSeconds); a coach who is away is auto-picked at once: // the first available person on their own queue, else the best available by the scouting score. A coach with a full team // (maxOpen open picks) is skipped for that slot. // - An unconverted pick returns to the pool after returnDays. A person whose adoption count has reached the limit stays with the // coach instead (never back to nobody: the IAP sweep rule). A converted pick (started) stays for good. 'use strict'; const TIERS = ['rookie', 'starter', 'pro', 'allstar', 'hof']; const TIER_NAME = { rookie: 'Rookie', starter: 'Starter', pro: 'Pro', allstar: 'All-Star', hof: 'Hall of Fame' }; const DAY = 86400000; // ---- milestones -> card tier. m = { wallet, payouts, purchase, ownTeam } as timestamps (0/absent = not yet) ---- function tierOf(m) { m = m || {}; if (m.ownTeam) return 'hof'; // holds a 5xYourTeam position of their own: they coach a team now if (m.purchase) return 'allstar'; // first purchase on the network if (m.payouts) return 'pro'; // switched on payouts if (m.wallet) return 'starter'; // linked a wallet return 'rookie'; // drafted } const tierRank = t => TIERS.indexOf(t); const tierAt = (m, t) => ({ hof: m.ownTeam, allstar: m.purchase, pro: m.payouts, starter: m.wallet }[t] || 0); // "started" = the conversion the draft order and Best Coach count: payouts switched on or a purchase const started = m => !!(m && (m.payouts || m.purchase)); const startedAt = m => { if (!m) return 0; const t = [m.payouts, m.purchase].filter(Boolean); return t.length ? Math.min(...t) : 0; }; // ---- scouting score (only real fields; a missing field adds nothing) ---- function score(c, now) { let s = 0; if (c.wallet) s += 30; if (c.games && Number(c.games.plays) > 0) s += Math.min(40, Number(c.games.plays)); const seen = Number(c.lastSeen) || 0; if (seen) { const age = now - seen; s += age < DAY ? 25 : age < 3 * DAY ? 12 : age < 7 * DAY ? 5 : 0; } if ((c.surfWei && BigInt(c.surfWei) > 0n) || Number(c.surfCredits) > 0) s += 10; // InstantAdPay reports surfing as ad credits earned if (c.games && c.games.earnedWei && BigInt(c.games.earnedWei) > 0n) s += 10; return s; } // how many adoptions a person has had: every pick here counts, plus the network's count from elsewhere (the tank's own record) const adoptionCount = (c, picks) => (Number(c.adoptions) || 0) + picks.filter(p => p.person === c.id && p.status !== 'void').length; const OPEN = ['open']; // why a tank candidate cannot be drafted right now (null = draftable) function blocked(c, picks, rules, now) { if (!c || !c.id) return 'unknown'; if (c.locked) return 'locked'; // locked on a network contract: never offered if (c.sponsored) return 'sponsored'; // the hub knows a sponsor for them if (c.spam || c.throwaway) return 'spam'; // spam / throwaway addresses are skipped if (c.joinedAt && now - c.joinedAt < rules.graceHours * 3600000) return 'grace'; if (picks.some(p => p.person === c.id && OPEN.includes(p.status))) return 'taken'; if (picks.some(p => p.person === c.id && ['done', 'kept'].includes(p.status))) return 'taken'; if (adoptionCount(c, picks) >= rules.maxAdoptions) return 'adopted-twice'; return null; } // the draftable pool, best scouting score first (ties: newest sign-in, then id, so the order is fixed) function pool(cands, picks, rules, now) { return (cands || []).filter(c => !blocked(c, picks, rules, now)) .map(c => Object.assign({}, c, { score: score(c, now) })) .sort((a, b) => b.score - a.score || (Number(b.lastSeen) || 0) - (Number(a.lastSeen) || 0) || String(a.id).localeCompare(String(b.id))); } // ---- draft order ---- function fnv(s) { let h = 0x811c9dc5; for (const ch of String(s)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 0x01000193) >>> 0; } return h; } // coaches: [{ address, username, since }]; picks carry week, coach, m (milestones). prevWeek = last week's Monday date. function standings(coaches, picks, week, prevWeek) { return coaches.map(c => { const mine = picks.filter(p => p.coach === c.address); return { address: c.address, username: c.username || null, since: c.since || 0, lastWeek: mine.filter(p => p.week === prevWeek && started(p.m)).length, lifetime: mine.filter(p => started(p.m)).length, tie: fnv(week + '|' + c.address) }; }).sort((a, b) => b.lastWeek - a.lastWeek || b.lifetime - a.lifetime || (a.since || Infinity) - (b.since || Infinity) || a.tie - b.tie); } // a new draft: straight rounds (the earned order every round) function newDraft(o) { const slots = []; for (let r = 1; r <= o.rounds; r++) o.order.forEach((coach, i) => slots.push({ round: r, n: i + 1, coach })); return { week: o.week, at: o.at, rounds: o.rounds, order: o.order.slice(), standings: o.standings || null, slots, made: [], taken: [], unavailable: [], status: o.order.length ? 'live' : 'done', clockAt: o.at, doneAt: o.order.length ? null : o.at, poolSize: o.poolSize || 0 }; } const slotLabel = s => s.round + '.' + s.n; const current = d => (d && d.status === 'live' ? d.slots[d.made.length] || null : null); // ctx: { pool: [ids, best first], present(addr) -> bool, queue(addr) -> [ids], openCount(addr) -> n, rules: { maxOpen }, pickSeconds } // -> { type: 'wait', until } | { type: 'auto', slot, coach, person } | { type: 'skip', slot, why } | { type: 'done', why } function nextAction(d, ctx, now) { if (!d || d.status !== 'live') return { type: 'done', why: 'not live' }; const i = d.made.length; if (i >= d.slots.length) return { type: 'done', why: 'all rounds made' }; const gone = new Set(d.taken.concat(d.unavailable)); const avail = ctx.pool.filter(id => !gone.has(id)); if (!avail.length) return { type: 'done', why: 'pool empty' }; const slot = d.slots[i]; if (ctx.openCount(slot.coach) >= ctx.rules.maxOpen) return { type: 'skip', slot, why: 'team full' }; const until = d.clockAt + ctx.pickSeconds * 1000; if (ctx.present(slot.coach) && now < until) return { type: 'wait', until }; const q = (ctx.queue(slot.coach) || []).find(id => avail.includes(id)); return { type: 'auto', slot, coach: slot.coach, person: q || avail[0], fromQueue: !!q }; } // a coach on the clock picks by hand -> the same action shape, or { error } function manual(d, coach, person, ctx, now) { const slot = current(d); if (!slot) return { error: 'The draft is not live.' }; if (slot.coach !== coach) return { error: 'You are not on the clock.' }; const gone = new Set(d.taken.concat(d.unavailable)); if (gone.has(person) || !ctx.pool.includes(person)) return { error: 'That player is no longer available.' }; if (ctx.openCount(coach) >= ctx.rules.maxOpen) return { error: 'Your team is full this week.' }; return { type: 'pick', slot, coach, person, manual: true }; } // record what happened for the current slot (the adoption already went through, or was refused) function record(d, act, res, now) { if (act.type === 'skip') { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.slot.coach, skipped: act.why, at: now }); d.clockAt = now; } else if (res && res.ok) { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.coach, person: act.person, auto: act.type === 'auto', fromQueue: !!act.fromQueue, pickId: res.pickId || null, at: now }); d.taken.push(act.person); d.clockAt = now; } else if (res && res.skip) { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.coach, skipped: res.skip, at: now }); d.clockAt = now; } // the tank refused the COACH (no account there, full, ...): the slot passes, nobody is burned else { d.unavailable.push(act.person); } // the tank refused this person (locked a moment ago, adopted elsewhere): the same coach chooses again return d; } function finish(d, why, now) { d.status = 'done'; d.doneAt = now; d.why = why; return d; } // run every decision due at `now`; adopt(act) -> { ok, pickId } | { error } (may be async). Returns the draft (mutated). async function run(d, ctx, adopt, now, maxSteps) { for (let n = 0; n < (maxSteps || 10000); n++) { const a = nextAction(d, ctx, now); if (a.type === 'wait') return d; if (a.type === 'done') { if (d.status === 'live') finish(d, a.why, now); return d; } if (a.type === 'skip') { record(d, a, null, now); continue; } const res = await adopt(a); if (res && res.wait) return d; // the tank did not answer: nothing recorded, the next tick tries the same slot again record(d, a, res, now); } return d; } // ---- pick returns (the rolling pool) ---- // statusOf(person) -> fresh milestones (or null when the network cannot say: then nothing changes). Returns the changes to apply. function sweep(picks, statusOf, rules, now) { const out = []; for (const p of picks) { if (p.status !== 'open') continue; const m = statusOf(p.person); if (!m) continue; if (started(m)) { out.push({ pick: p, set: { status: 'done', m, tier: tierOf(m), doneAt: now } }); continue; } if (now < p.expires) { if (JSON.stringify(m) !== JSON.stringify(p.m)) out.push({ pick: p, set: { m, tier: tierOf(m) } }); continue; } // the window ended unconverted: back to the pool, unless this person has had their adoptions (then they stay with this coach) const count = (Number(m.adoptions) || 0) + picks.filter(x => x.person === p.person && x.status !== 'void').length; if (count >= rules.maxAdoptions) out.push({ pick: p, set: { status: 'kept', m, tier: tierOf(m), keptAt: now } }); else out.push({ pick: p, set: { status: 'returned', m, tier: tierOf(m), returnedAt: now }, release: true }); } return out; } // may this coach release a pick now? (the IAP churn rule: not inside the hold) function canRelease(p, rules, now) { if (p.status !== 'open') return 'That pick is not open.'; if (now - p.at < rules.holdHours * 3600000) return 'You picked them less than ' + rules.holdHours + ' hours ago. Give them a little time first.'; return null; } // ---- boards ---- // Best Coach: picks that STARTED inside the week [from, to), per coach. Ties: who got there first, then username. function bestCoach(picks, from, to, nameOf) { const by = new Map(); for (const p of picks) { const t = startedAt(p.m); if (!t || t < from || t >= to) continue; const x = by.get(p.coach) || { coach: p.coach, started: 0, lastAt: 0 }; x.started++; x.lastAt = Math.max(x.lastAt, t); by.set(p.coach, x); } return [...by.values()].map(x => Object.assign(x, { username: nameOf ? nameOf(x.coach) : null })) .sort((a, b) => b.started - a.started || a.lastAt - b.lastAt || String(a.username || a.coach).localeCompare(String(b.username || b.coach))) .map((x, i) => Object.assign(x, { rank: i + 1 })); } // Rookie of the Week: of the picks made that week, the one that climbed highest; ties: reached it first, then the pick id function rookie(picks, week) { const l = picks.filter(p => p.week === week && p.status !== 'void').map(p => ({ p, t: tierOf(p.m) })).filter(x => x.t !== 'rookie'); l.sort((a, b) => tierRank(b.t) - tierRank(a.t) || tierAt(a.p.m, a.t) - tierAt(b.p.m, b.t) || a.p.id - b.p.id); return l.length ? { pick: l[0].p, tier: l[0].t } : null; } // the week's pot split into places (percentages of the pot; dust stays in the pot wallet) function potShares(potWei, split, board) { const pot = BigInt(potWei || 0); return split.slice(0, board.length).map((pct, i) => ({ rank: i + 1, coach: board[i].coach, username: board[i].username, pct, wei: (pot * BigInt(Math.round(pct * 100)) / 10000n).toString() })); } // ---- coaching: who to help first, and what to say ---- const STEPS = [['signedIn', 'Signed in'], ['username', 'Username'], ['wallet', 'Wallet linked'], ['payouts', 'Payouts on'], ['purchase', 'First purchase']]; function steps(m) { m = m || {}; const done = { signedIn: !!m.lastSeen, username: !!m.username, wallet: !!m.wallet, payouts: !!m.payouts, purchase: !!m.purchase }; const next = STEPS.find(s => !done[s[0]]); return STEPS.map(s => ({ key: s[0], label: s[1], done: done[s[0]], next: !!next && next[0] === s[0] })); } function helpList(picks, now) { return picks.filter(p => p.status === 'open').map(p => { const m = p.m || {}; const left = p.expires - now; const quiet = m.lastSeen ? now - m.lastSeen : Infinity; let why, say, urgency; if (left < DAY) { why = 'Back to the pool in ' + (left < 3600000 ? 'under an hour' : Math.ceil(left / 3600000) + ' hours'); urgency = 100; } else if (m.wallet && !m.payouts) { why = 'Wallet linked: one step from payouts'; urgency = 80; } else if (quiet > 2 * DAY) { why = m.lastSeen ? 'Quiet ' + Math.floor(quiet / DAY) + ' days: send a nudge' : 'Has not signed in yet'; urgency = 60; } else if (!m.wallet) { why = 'Active, no wallet yet'; urgency = 40; } else { why = 'Doing fine'; urgency = 10; } const nx = steps(m).find(s => s.next); say = !nx ? 'Great work. Want to build a team of your own next?' : nx.key === 'wallet' ? 'Want me to walk you through linking a wallet? SafePal or any other crypto wallet works.' : nx.key === 'payouts' ? 'Ready to switch on payouts? I will walk you through it.' : nx.key === 'purchase' ? 'You are set up. When you are ready, I can show you the first purchase step.' : 'Welcome! I am your coach. Reply here any time and I will help you get going.'; return { pickId: p.id, person: p.person, username: p.personName || null, why, say, urgency, daysLeft: Math.max(0, Math.ceil(left / DAY)), next: nx ? nx.label : null }; }).sort((a, b) => b.urgency - a.urgency || a.daysLeft - b.daysLeft || a.pickId - b.pickId); } module.exports = { TIERS, TIER_NAME, tierOf, tierRank, started, startedAt, score, blocked, pool, adoptionCount, standings, newDraft, nextAction, manual, record, finish, run, current, slotLabel, sweep, canRelease, bestCoach, rookie, potShares, steps, helpList, fnv };