// Unit tests: the draft engine (draft.js) with a mocked clock, the pass-up split model (proof.model) against the DraftPosition fork // rehearsal numbers, Central-time weeks, and the league (league.js + the stub tank) end to end on a temp data dir. No network. // node qa/unit.test.cjs 'use strict'; const path = require('path'); const fs = require('fs'); const os = require('os'); const APP = path.resolve(__dirname, '..'); let pass = 0, fail = 0; const ok = (c, what, extra) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 400) : '')); } }; const D = 86400000, H = 3600000; const draft = require(path.join(APP, 'draft.js')); const RULES = { maxOpen: 10, maxAdoptions: 2, graceHours: 24, holdHours: 48, returnDays: 3 }; (async () => { console.log('1. tiers'); ok(draft.tierOf({}) === 'rookie' && draft.tierOf({ wallet: 1 }) === 'starter' && draft.tierOf({ wallet: 1, payouts: 2 }) === 'pro' && draft.tierOf({ purchase: 3 }) === 'allstar' && draft.tierOf({ purchase: 3, ownTeam: 4 }) === 'hof', 'tiers: Rookie, Starter (wallet), Pro (payouts), All-Star (purchase), Hall of Fame (own team)'); ok(!draft.started({ wallet: 5 }) && draft.started({ payouts: 5 }) && draft.started({ purchase: 5 }) && draft.startedAt({ payouts: 9, purchase: 7 }) === 7, '"started" = payouts on or a purchase (a wallet alone is not)'); console.log('2. the pool: tank rules'); const T = 1_800_000_000_000; const c = (id, o) => Object.assign({ id, username: id, joinedAt: T - 10 * D, lastSeen: T - H }, o || {}); const cands = [c('h_a'), c('h_locked', { locked: true }), c('h_spons', { sponsored: true }), c('h_spam', { spam: true }), c('h_throw', { throwaway: true }), c('h_new', { joinedAt: T - 5 * H }), c('h_twice', { adoptions: 2 }), c('h_once', { adoptions: 1 }), c('h_taken'), c('h_done'), c('h_ret')]; const picks0 = [{ id: 1, person: 'h_once', status: 'returned' }, { id: 2, person: 'h_taken', status: 'open' }, { id: 3, person: 'h_done', status: 'done' }, { id: 4, person: 'h_ret', status: 'returned' }]; const why = Object.fromEntries(cands.map(x => [x.id, draft.blocked(x, picks0, RULES, T)])); ok(why.h_locked === 'locked' && why.h_spons === 'sponsored' && why.h_spam === 'spam' && why.h_throw === 'spam', 'never anyone locked on a network contract, already sponsored, spam or throwaway', why); ok(why.h_new === 'grace', 'a sign-up inside the 24-hour grace is not draftable', why.h_new); ok(why.h_twice === 'adopted-twice' && why.h_once === 'adopted-twice', 'max 2 adoptions per person: 2 elsewhere, or 1 elsewhere + 1 pick here', [why.h_twice, why.h_once]); ok(why.h_taken === 'taken' && why.h_done === 'taken', 'someone on a team (open or started) is not draftable', [why.h_taken, why.h_done]); ok(why.h_ret === null && why.h_a === null, 'a person back in the pool after one return can be drafted once more', why.h_ret); const pl = draft.pool([c('h_x', { lastSeen: T - 30 * D }), c('h_y', { wallet: true }), c('h_z', { games: { plays: 12, title: 'Gem Kingdom', earnedWei: '1' } })], [], RULES, T); ok(pl.map(x => x.id).join() === 'h_y,h_z,h_x' && pl[0].score === 55 && pl[1].score === 47, 'best available by scouting score (wallet 30, plays up to 40, seen today 25, earned 10)', pl.map(x => [x.id, x.score])); ok(draft.score(c('h_q', { lastSeen: 0, games: null, surfWei: null }), T) === 0, 'missing scouting data adds nothing (never invented)'); console.log('3. draft order is earned'); const coaches = [{ address: '0xa', username: 'ann', since: 100 }, { address: '0xb', username: 'bob', since: 50 }, { address: '0xc', username: 'cy', since: 200 }, { address: '0xd', username: 'dee', since: 300 }]; const P = [{ coach: '0xc', week: 'W1', m: { payouts: 1 } }, { coach: '0xc', week: 'W1', m: { purchase: 1 } }, { coach: '0xa', week: 'W1', m: { payouts: 1 } }, { coach: '0xa', week: 'W1', m: { wallet: 1 } }, { coach: '0xb', week: 'W1', m: { payouts: 1 } }, { coach: '0xb', week: 'W0', m: { payouts: 1 } }]; const st = draft.standings(coaches, P, 'W2', 'W1'); ok(st.map(x => x.username).join() === 'cy,bob,ann,dee', 'most of last week\'s picks started first (cy 2); tie on 1 broken by lifetime (bob 2 > ann 1); a wallet alone does not count', st.map(x => [x.username, x.lastWeek, x.lifetime])); const st2 = draft.standings([{ address: '0xe', since: 10 }, { address: '0xf', since: 5 }], [], 'W2', 'W1'); ok(st2[0].address === '0xf', 'no picks yet: the earlier position picks first'); const st3a = draft.standings([{ address: '0x1', since: 0 }, { address: '0x2', since: 0 }, { address: '0x3', since: 0 }], [], 'W5', 'W4').map(x => x.address).join(); const st3b = draft.standings([{ address: '0x3', since: 0 }, { address: '0x2', since: 0 }, { address: '0x1', since: 0 }], [], 'W5', 'W4').map(x => x.address).join(); ok(st3a === st3b, 'a full tie is a fixed shuffle of (week, coach): same order whatever the input order', [st3a, st3b]); console.log('4. the draft with a mocked clock'); const d = draft.newDraft({ week: 'W2', at: T, rounds: 2, order: ['0xa', '0xb', '0xc'] }); ok(d.slots.length === 6 && d.slots.map(s => draft.slotLabel(s) + s.coach).join() === '1.10xa,1.20xb,1.30xc,2.10xa,2.20xb,2.30xc', 'straight rounds: the earned order every round', d.slots.map(draft.slotLabel)); const present = new Set(['0xa']); const queues = { '0xc': ['h_p4', 'h_p2'] }; const open = { '0xa': 0, '0xb': 0, '0xc': 0 }; const ctx = { pool: ['h_p1', 'h_p2', 'h_p3', 'h_p4', 'h_p5', 'h_p6'], present: a => present.has(a), queue: a => queues[a] || [], openCount: a => open[a], rules: RULES, pickSeconds: 90 }; let refuse = new Set(['h_p3']); const adopted = []; const adopt = act => { if (refuse.has(act.person)) { refuse.delete(act.person); return { error: 'locked a moment ago' }; } adopted.push([act.coach, act.person]); open[act.coach]++; return { ok: true, pickId: adopted.length }; }; await draft.run(d, ctx, adopt, T); ok(d.made.length === 0, 'the first coach is in the draft room: the clock runs, nothing is auto-picked yet'); let a = draft.manual(d, '0xb', 'h_p1', ctx, T + 1000); ok(a.error === 'You are not on the clock.', 'a coach who is not on the clock cannot pick', a); a = draft.manual(d, '0xa', 'h_p2', ctx, T + 1000); ok(a.type === 'pick', 'the coach on the clock picks by hand'); draft.record(d, a, adopt(a), T + 1000); await draft.run(d, ctx, adopt, T + 1000); ok(d.made.length === 3 && d.made[1].coach === '0xb' && d.made[1].person === 'h_p1' && d.made[1].auto, 'an absent coach is auto-picked at once: the best available', d.made); ok(d.made[2].coach === '0xc' && d.made[2].person === 'h_p4' && d.made[2].fromQueue, 'an absent coach with a queue gets their first available queued player', d.made[2]); ok(d.made.length === 3 && draft.current(d).coach === '0xa' && d.clockAt === T + 1000, 'round 2: the present coach gets a fresh clock', draft.current(d)); await draft.run(d, ctx, adopt, T + 1000 + 89000); ok(d.made.length === 3, 'still inside the 90-second clock: waiting'); await draft.run(d, ctx, adopt, T + 1000 + 90000); ok(d.made[3].person === 'h_p5' && d.unavailable.includes('h_p3'), 'clock ran out: auto-pick; the tank refused h_p3 (locked meanwhile), so it is skipped and the same coach gets the next one', d.made.slice(3)); ok(d.status === 'done' && d.made.length === 5 && d.why === 'pool empty', 'the pool ran out: the draft ends', [d.status, d.why, d.made.length]); ok(new Set(adopted.map(x => x[1])).size === adopted.length, 'nobody is drafted twice'); const d2 = draft.newDraft({ week: 'W2', at: T, rounds: 1, order: ['0xa', '0xb'] }); const full = { '0xa': 10, '0xb': 0 }; await draft.run(d2, Object.assign({}, ctx, { present: () => false, openCount: x => full[x] }), act => ({ ok: true }), T); ok(d2.made[0].skipped === 'team full' && d2.made[1].person === 'h_p1', 'a coach with a full team (10 open) is skipped for that slot', d2.made); const d3 = draft.newDraft({ week: 'W2', at: T, rounds: 3, order: [] }); ok(d3.status === 'done', 'no coaches: nothing to draft'); console.log('5. picks return to the pool'); const pk = (id, o) => Object.assign({ id, person: 'h_' + id, coach: '0xa', status: 'open', at: T - 4 * D, expires: T - D, m: {} }, o); const ps = [pk(1), pk(2), pk(3), pk(4, { expires: T + D }), pk(5, { status: 'done' })]; const sts = { h_1: { payouts: T - 2 * D }, h_2: { wallet: T - D }, h_3: { adoptions: 1 }, h_4: { wallet: T - H } }; const ch = draft.sweep(ps, id => sts[id] || null, RULES, T); const by = Object.fromEntries(ch.map(x => [x.pick.id, x])); ok(by[1].set.status === 'done' && by[1].set.tier === 'pro', 'a pick that switched on payouts stays for good (done, Pro)', by[1].set); ok(by[2].set.status === 'returned' && by[2].release === true, 'unconverted past the return window: back to the pool (released in the tank)', by[2]); ok(by[3].set.status === 'kept' && !by[3].release, 'past the window but adopted twice now (1 elsewhere + this one): stays with the coach, never back to nobody', by[3]); ok(by[4].set.tier === 'starter' && !by[4].set.status, 'inside the window: milestones refresh, no status change', by[4].set); ok(!by[5], 'started picks are not swept'); ok(draft.sweep([pk(9)], () => null, RULES, T).length === 0, 'the network cannot say: nothing changes'); ok(/less than 48 hours/.test(draft.canRelease(pk(7, { at: T - H }), RULES, T)) && draft.canRelease(pk(8, { at: T - 3 * D }), RULES, T) === null, 'a coach cannot release a pick inside the 48-hour hold'); console.log('6. boards'); const from = T, to = T + 7 * D; const bp = [{ id: 1, coach: '0xa', m: { payouts: T + D } }, { id: 2, coach: '0xa', m: { purchase: T + 2 * D } }, { id: 3, coach: '0xb', m: { payouts: T + H } }, { id: 4, coach: '0xb', m: { payouts: T + 3 * D } }, { id: 5, coach: '0xc', m: { payouts: T - D } }, { id: 6, coach: '0xc', m: { wallet: T + H } }]; const best = draft.bestCoach(bp, from, to, a2 => ({ '0xa': 'ann', '0xb': 'bob', '0xc': 'cy' })[a2]); ok(best.map(x => x.username + x.started).join() === 'ann2,bob2' && best[0].rank === 1, 'Best Coach: picks started inside the week; a tie goes to who got there first; last week\'s start and a wallet alone do not count', best); const shares = draft.potShares('1000000000000000001', [50, 30, 20], best); ok(shares.length === 2 && shares[0].wei === '500000000000000000' && shares[1].wei === '300000000000000000', 'pot shares by place (50/30/20 of the pot; places without a coach stay in the pot)', shares); const rk = draft.rookie([{ id: 1, week: 'W', m: { wallet: 5 } }, { id: 2, week: 'W', m: { payouts: 9 } }, { id: 3, week: 'W', m: { payouts: 7 } }, { id: 4, week: 'V', m: { purchase: 1 } }], 'W'); ok(rk && rk.pick.id === 3 && rk.tier === 'pro', 'Rookie of the Week: the pick that climbed highest that week, first to get there wins a tie', rk); const help = draft.helpList([pk(1, { expires: T + 5 * H, m: { lastSeen: T - H, username: 'u1' } }), pk(2, { expires: T + 2 * D, m: { wallet: 1, lastSeen: T - H, username: 'u2' } }), pk(3, { expires: T + 2 * D, m: { lastSeen: T - 4 * D, username: 'u3' } }), pk(4, { status: 'done' })], T); ok(help.map(x => x.pickId).join() === '1,2,3' && /Back to the pool in 5 hours/.test(help[0].why) && /payouts/.test(help[1].say) && /SafePal or any other crypto wallet/.test(help[2].say), 'who to help: back-to-pool soon first, then one step from payouts, then quiet; suggested messages', help); const allSay = help.map(x => x.say + x.why).join(' '); ok(!/[–—]/.test(allSay) && !/metamask|income|earn \$/i.test(allSay), 'coaching copy: no dashes, no wallet brand but SafePal, no income talk'); console.log('7. the pass-up split model = the contract (fork rehearsal 2026-11-15)'); const proof = require(path.join(APP, 'proof.js')); const q = 122663264805456062018n; const q1 = (l) => l.map((w, i) => ({ who: w[0], qualified: w[1] })); let mo = proof.model(q1([['A1', 1], ['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); ok(mo.pays.map(x => x.to + x.level + 'd' + x.depth).join() === 'A11d1,A32d3,A53d5,A64d6,A75d7' && mo.over.map(x => x.who).join() === 'A2,A4', 'B1 line: A1 L1, A3 A5 A6 A7 L2-L5, A2 A4 passed over', mo); ok(mo.pays[0].wei === '30665816201364015504' && mo.pays[1].wei === '6133163240272803100' && mo.pot === '12266326480545606201' && mo.company === '55198469162455227913', 'B1 exact wei: sponsor 30.665816 POL, level 6.133163 POL, pot 12.266326 POL, company 55.198469 POL (A1 + A3 deltas below)', mo); const mB3 = proof.model(q1([['B1', 1], ['A1', 1], ['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); const mB5 = proof.model(q1([['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); const got = n => [mo, mB3, mB5].reduce((t, m) => t + m.pays.filter(x => x.to === n).reduce((s, x) => s + BigInt(x.wei), 0n), 0n).toString(); ok(got('A1') === '36798979441636818604' && got('A3') === '42932142681909621704' && got('A5') === '18399489720818409300' && got('A6') === '18399489720818409300' && got('A7') === '12266326480545606200', 'the model\'s totals for A1 A3 A5 A6 A7 over B1 + B3 + B5 equal the fork rehearsal deltas to the wei', ['A1', 'A3', 'A5', 'A6', 'A7'].map(got)); ok(mB5.pays[0].to === 'A3' && mB5.pays[0].depth === 2 && mB5.pays.length === 4, 'an unqualified direct sponsor: the 25% passes up to the nearest qualified (A3 at place 2); one level unfilled goes to the company', mB5.pays); const none = proof.model(q1([['X', 0], ['Y', 0]]), 1000n); ok(none.pays.length === 0 && none.pot === '100' && none.company === '900', 'nobody qualified: pot 10%, company 90%', none); const deep = proof.model(Array.from({ length: 21 }, (_, i) => ({ who: 'D' + i, qualified: i === 20 })), 1000n); ok(deep.pays.length === 0, 'a qualified person at place 21 is beyond MAX_DEPTH and gets nothing'); const many = proof.model(Array.from({ length: 8 }, (_, i) => ({ who: 'M' + i, qualified: true })), 10000n); ok(many.pays.length === 5 && many.pays.map(x => x.wei).join() === '2500,500,500,500,500' && many.company === '4500' && many.pot === '1000', 'more than 5 qualified: only the nearest 5; 25/5/5/5/5 + pot 10 + company 45', many); console.log('8. Central-time weeks'); const store = require(path.join(APP, 'store.js')); ok(store.ctToMs('2026-11-16', 19) === Date.UTC(2026, 10, 17, 1) && store.ctToMs('2026-07-06', 19) === Date.UTC(2026, 6, 7, 0), 'Monday 7 PM Central = 01:00 UTC in November (CST), 00:00 UTC in July (CDT)'); ok(store.ctWeek(Date.UTC(2026, 10, 16, 5)) === '2026-11-09' && store.ctWeek(Date.UTC(2026, 10, 16, 7)) === '2026-11-16', 'the week turns at Monday midnight Central (05:00 UTC is still Sunday night)'); console.log('8b. tank refusals: a refused COACH passes the slot, a silent tank pauses the draft (2026-11-15, the real tank)'); { const d2 = draft.newDraft({ week: 'W9', at: T, rounds: 1, order: ['0xz', '0xa'] }); const ctx2 = { pool: ['h_1', 'h_2', 'h_3'], present: () => false, queue: () => [], openCount: () => 0, rules: RULES, pickSeconds: 90 }; let silent = true; const seen = []; const ad2 = act => { seen.push(act.coach + ':' + act.person); if (silent) return { error: 'no answer', wait: true }; if (act.coach === '0xz') return { error: 'no account', skip: 'tank: coach_unknown' }; return { ok: true, pickId: 1 }; }; await draft.run(d2, ctx2, ad2, T); ok(d2.made.length === 0 && d2.unavailable.length === 0 && d2.status === 'live', 'tank silent: nothing recorded, nobody marked unavailable, the draft waits for the next tick', d2.made); silent = false; await draft.run(d2, ctx2, ad2, T + 5000); ok(d2.made[0].skipped === 'tank: coach_unknown' && d2.made[1].person === 'h_1' && d2.unavailable.length === 0, 'a coach the tank refuses: their slot passes, the pool is not burned (the next coach gets h_1)', d2.made); } console.log('9. the league end to end (stub tank, temp data dir, mocked clock)'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fx-unit-')); Object.assign(process.env, { DATA_DIR: dir, DOCSTORE_URL: '', TANK_MODE: 'stub', DRAFT_ROUNDS: '2', PICK_RETURN_DAYS: '3' }); require(path.join(APP, 'config.js')).reset(); const C = require(path.join(APP, 'config.js')).get(); const league = require(path.join(APP, 'league.js')); const tank = require(path.join(APP, 'tankpool.js')); require(path.join(APP, 'docstore.js')).install(dir); store.load(); const monday7pm = store.ctToMs('2026-11-16', 19); league.clock.set(monday7pm - 2 * H); tank.init(C, { now: league.clock.now }); league.init(C, { proof: { draftDay: async () => true, potOf: () => '0' } }); const S = store.state(); const buy = (a, qty, at) => { S.purchases[a + ':0'] = { buyer: a, qty, at, blockAt: Math.floor(at / 1000), usdCents: 1000 * qty, weiPaid: '1', prizePaid: '0' }; store.upsertMember(a, { username: 'coach' + a.slice(-1) }); store.addCredits(a, 5 * qty); }; const A = '0x' + 'a'.repeat(40), B = '0x' + 'b'.repeat(40); buy(A, 1, monday7pm - 5 * D); buy(B, 1, monday7pm - 4 * D); let r = await league.tick(); ok(!r.draft || r.draft.week !== '2026-11-16', 'before the draft hour: no draft this week', r); const pool0 = await league.pool(league.clock.now()); ok(pool0.length === 29 && !pool0.some(x => /locked|sponsor|spam|temp_mail|brandnew|twice/.test(x.username)), 'stub pool: 29 draftable of 35 (locked, sponsored, spam, throwaway, inside the grace, adopted twice left out)', pool0.length); r = await league.instantPick(A, pool0[0].id); ok(r.ok && store.credits(A) === 4 && store.picksOf(A)[0].kind === 'instant', 'an instant pick from the current pool uses one of the 5 credits', r); r = await league.instantPick(A, pool0[0].id); ok(/no longer available/.test(r.error), 'the same player cannot be picked twice', r); league.clock.set(monday7pm + 1000); r = await league.tick(); const dW = store.draft('2026-11-16'); ok(dW && dW.status === 'done' && dW.made.filter(x => x.person).length === 4, 'at the draft hour: the draft runs (nobody in the room, all auto-picked): 2 coaches x 2 rounds', dW && dW.made); ok(dW.order[0] === A, 'draft order: no starts last week, so the earlier position (A) picks first', dW.order); ok(store.picks().every(p => p.status === 'open' && p.expires === p.at + 3 * D), 'every pick is an open adoption with a 3-day return window'); ok(tank.view().adopted === 5 && tank.view().adoptionMailsThatWouldSend === 5, 'every pick went through the tank adopt call (stub: nobody adopted for real, mails only counted)', tank.view()); r = await league.tick(); ok(store.draft('2026-11-16').made.length === dW.made.length, 'a second tick does not draft again'); const first = store.picksOf(B)[0]; tank.setStatus(first.person, { wallet: true, payouts: true }); league.clock.set(monday7pm + 2 * D); await league.tick(); ok(store.pick(first.id).status === 'done' && store.pick(first.id).tier === 'pro', 'a pick that switches on payouts is done (Pro) on the next sweep', store.pick(first.id)); league.clock.set(monday7pm + 3 * D + 2000); await league.tick(); const kept = store.picks().filter(p => p.status === 'kept').length; ok(store.picks().filter(p => p.status === 'returned').length + kept === 4 && store.picks().filter(p => p.status === 'done').length === 1 && store.picks().filter(p => p.status === 'kept').every(p => p.personName === 'onceadopted'), 'after 3 days the unconverted picks go back to the pool (a person on their 2nd adoption stays with the coach)', store.picks().map(p => p.personName + ':' + p.status)); const back = await league.pool(league.clock.now()); ok(back.length === 29 - 1 - kept + 1 && back.some(x => x.username === 'brandnew'), 'they are draftable again (29 - 1 started - any kept, + brandnew whose 24-hour grace has ended)', back.length); // next week: B started 1 last week -> B picks first const next7 = store.ctToMs('2026-11-23', 19); league.clock.set(next7 + 1000); await league.tick(); ok(store.draft('2026-11-23').order[0] === B, 'next Monday the order is earned: B (1 pick started last week) picks before A (0)', store.draft('2026-11-23').order); ok(store.picks().filter(p => p.week === '2026-11-23').every(p => !store.picks().some(q2 => q2.person === p.person && q2.status === 'done')), 'nobody already started on a team is drafted again'); fs.rmSync(dir, { recursive: true, force: true }); console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0); })().catch(e => { console.error('unit crashed:', e.stack || e.message); process.exit(1); });