5xYourTeam The Draft v1 (phase 1, local only): weekly earned-order draft of holding-tank people, picks as adoptions (stub tank), coaching tools, cards, boards, trust pack

$10 one-time DraftPosition purchases (sponsor 25%, L2-5 5%, 10% Best Coach pot, 45% company) with keeper-signed hub-line
vouchers; pure draft engine with a mocked clock; no contact data anywhere; Telegram to an outbox unless TG_LIVE=1.
Unit 60/60, smoke 156/156 (Playwright 1280/390). Not deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 06:16:10 -06:00
commit f26ac15712
110 changed files with 6177 additions and 0 deletions
+344
View File
@@ -0,0 +1,344 @@
{
"note": "LOCAL TEST FIXTURE for the phase 1 stub tank. Not real people. Times are hours before the app booted.",
"people": [
{
"id": "h_3affc1ada35faebb",
"username": "rookie_one",
"door": "InstantAdPay",
"joinedHoursAgo": 939,
"seenHoursAgo": 3,
"walletHoursAgo": 104,
"games": {
"plays": 3,
"title": "Road Agent",
"earnedWei": "380000000000000000"
}
},
{
"id": "h_eb022863fe3bc491",
"username": "surfqueen",
"door": "LinkSpin",
"joinedHoursAgo": 910,
"seenHoursAgo": 20,
"surfWei": "269000000000000000"
},
{
"id": "h_6238d6f010f3f9c5",
"username": "newbie77",
"door": "BTC4Hits",
"joinedHoursAgo": 185,
"seenHoursAgo": null,
"games": {
"plays": 0,
"title": null,
"earnedWei": null
}
},
{
"id": "h_887d6e1bb8235fe8",
"username": "cryptomike",
"door": "Downline Banners",
"joinedHoursAgo": 100,
"seenHoursAgo": 50,
"walletHoursAgo": 163
},
{
"id": "h_a1436ef135f3db34",
"username": "gamerdad",
"door": "Viral Banner Blitz",
"joinedHoursAgo": 874,
"seenHoursAgo": 1,
"games": {
"plays": 54,
"title": "Shards of Valor",
"earnedWei": "90000000000000000"
}
},
{
"id": "h_fa121ef0eac78fde",
"username": "lunaclicks",
"door": "CryptoTeamBuild",
"joinedHoursAgo": 591,
"seenHoursAgo": 30,
"surfWei": "275000000000000000"
},
{
"id": "h_0aeabeb6af047906",
"username": "tradewinds",
"door": "LinkSpin",
"joinedHoursAgo": 367,
"seenHoursAgo": 3,
"walletHoursAgo": 103,
"games": {
"plays": 46,
"title": "ClutterHunt",
"earnedWei": "240000000000000000"
}
},
{
"id": "h_9f18ef0a0d91dc4d",
"username": "polypat",
"door": "InstantAdPay",
"joinedHoursAgo": 189,
"seenHoursAgo": 120
},
{
"id": "h_172d8f222f9eb21b",
"username": "clickfox",
"door": "InstantAdPay",
"joinedHoursAgo": 506,
"seenHoursAgo": 3,
"games": {
"plays": 30,
"title": "Circuit Brawl",
"earnedWei": "350000000000000000"
}
},
{
"id": "h_da20f879170c19a4",
"username": "maria_g",
"door": "LinkSpin",
"joinedHoursAgo": 664,
"seenHoursAgo": 3,
"walletHoursAgo": 112,
"surfWei": "120000000000000000"
},
{
"id": "h_3f3409eb1420f7eb",
"username": "bitbuilder",
"door": "BTC4Hits",
"joinedHoursAgo": 374,
"seenHoursAgo": 200,
"games": {
"plays": 29,
"title": "Circuit Brawl",
"earnedWei": "180000000000000000"
}
},
{
"id": "h_1b1edcfd7d4b6fe4",
"username": "sunnyside",
"door": "Downline Banners",
"joinedHoursAgo": 186,
"seenHoursAgo": 3
},
{
"id": "h_99673703afc3a234",
"username": "jetsetjoe",
"door": "Viral Banner Blitz",
"joinedHoursAgo": 639,
"seenHoursAgo": 50,
"walletHoursAgo": 19,
"games": {
"plays": 39,
"title": "PolyBreak",
"earnedWei": "300000000000000000"
}
},
{
"id": "h_47213d4ea578f9d1",
"username": "adsurfer",
"door": "CryptoTeamBuild",
"joinedHoursAgo": 922,
"seenHoursAgo": 70,
"surfWei": "99000000000000000"
},
{
"id": "h_9848af6d869e9db9",
"username": "kimchi_k",
"door": "LinkSpin",
"joinedHoursAgo": 423,
"seenHoursAgo": 30,
"games": {
"plays": 23,
"title": "Gem Kingdom",
"earnedWei": "80000000000000000"
}
},
{
"id": "h_3fe73adad20e7c82",
"username": "dealhunter",
"door": "InstantAdPay",
"joinedHoursAgo": 627,
"seenHoursAgo": 20,
"walletHoursAgo": 158
},
{
"id": "h_f06b5bded0aae139",
"username": "quietquill",
"door": "InstantAdPay",
"joinedHoursAgo": 763,
"seenHoursAgo": 50,
"games": {
"plays": 5,
"title": "PolyBreak",
"earnedWei": "80000000000000000"
}
},
{
"id": "h_f0fe77765837b89e",
"username": "lotusleaf",
"door": "LinkSpin",
"joinedHoursAgo": 407,
"seenHoursAgo": 200,
"surfWei": "98000000000000000"
},
{
"id": "h_39fea889d5a1d527",
"username": "hopscotch",
"door": "BTC4Hits",
"joinedHoursAgo": 404,
"seenHoursAgo": 200,
"walletHoursAgo": 194,
"games": {
"plays": 43,
"title": "Road Agent",
"earnedWei": "380000000000000000"
}
},
{
"id": "h_e25cdaa177422bbb",
"username": "pixelpaul",
"door": "Downline Banners",
"joinedHoursAgo": 882,
"seenHoursAgo": 8
},
{
"id": "h_0c4f10d69e5305f4",
"username": "nightowl22",
"door": "Viral Banner Blitz",
"joinedHoursAgo": 767,
"seenHoursAgo": 200,
"games": {
"plays": 13,
"title": "Shards of Valor",
"earnedWei": "260000000000000000"
}
},
{
"id": "h_86e910ef9cb5ff2f",
"username": "garden_gina",
"door": "CryptoTeamBuild",
"joinedHoursAgo": 133,
"seenHoursAgo": 50,
"walletHoursAgo": 46,
"surfWei": "297000000000000000"
},
{
"id": "h_e7b0293c9b3d76d1",
"username": "ridgeback",
"door": "LinkSpin",
"joinedHoursAgo": 31,
"seenHoursAgo": 8,
"games": {
"plays": 56,
"title": "PolyBreak",
"earnedWei": "260000000000000000"
}
},
{
"id": "h_bb41753eafce6811",
"username": "tinytrader",
"door": "InstantAdPay",
"joinedHoursAgo": 618,
"seenHoursAgo": 1
},
{
"id": "h_489c134cec719d65",
"username": "mapleleaf",
"door": "InstantAdPay",
"joinedHoursAgo": 559,
"seenHoursAgo": 1,
"walletHoursAgo": 52,
"games": {
"plays": 50,
"title": "Gem Kingdom",
"earnedWei": "240000000000000000"
}
},
{
"id": "h_e1abfd1b267ee264",
"username": "oceanview",
"door": "LinkSpin",
"joinedHoursAgo": 117,
"seenHoursAgo": 3,
"surfWei": "205000000000000000"
},
{
"id": "h_91c2569472b58816",
"username": "redrover",
"door": "BTC4Hits",
"joinedHoursAgo": 481,
"seenHoursAgo": 8,
"games": {
"plays": 9,
"title": "ClutterHunt",
"earnedWei": "350000000000000000"
}
},
{
"id": "h_a6b75313af665383",
"username": "buzzybee",
"door": "Downline Banners",
"joinedHoursAgo": 829,
"seenHoursAgo": 30,
"walletHoursAgo": 188
},
{
"id": "h_locked0000000001",
"username": "lockedlarry",
"door": "InstantAdPay",
"joinedHoursAgo": 300,
"seenHoursAgo": 2,
"locked": true
},
{
"id": "h_sponsored0000001",
"username": "hasasponsor",
"door": "LinkSpin",
"joinedHoursAgo": 300,
"seenHoursAgo": 2,
"sponsored": true
},
{
"id": "h_spam000000000001",
"username": "xx_spam_xx",
"door": "LinkSpin",
"joinedHoursAgo": 300,
"seenHoursAgo": 2,
"spam": true
},
{
"id": "h_throwaway000001",
"username": "temp_mail_9",
"door": "InstantAdPay",
"joinedHoursAgo": 300,
"seenHoursAgo": 2,
"throwaway": true
},
{
"id": "h_grace00000000001",
"username": "brandnew",
"door": "InstantAdPay",
"joinedHoursAgo": 5,
"seenHoursAgo": 1
},
{
"id": "h_twice00000000001",
"username": "twiceadopted",
"door": "InstantAdPay",
"joinedHoursAgo": 900,
"seenHoursAgo": 4,
"adoptionsElsewhere": 2
},
{
"id": "h_once000000000001",
"username": "onceadopted",
"door": "LinkSpin",
"joinedHoursAgo": 900,
"seenHoursAgo": 4,
"adoptionsElsewhere": 1,
"walletHoursAgo": 40
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 454 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 464 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 KiB

+1
View File
@@ -0,0 +1 @@
2026-11-15T12:15:13.035Z 156 passed, 0 failed
+418
View File
@@ -0,0 +1,418 @@
// 5xYourTeam local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out) with
// the STUB holding tank and a test clock, against local stand-ins, then checks: copy rules, pages, the promo kit, sign-in (wallet +
// network), position orders (line voucher signed by the keeper, already-bound line, hub down), purchases recorded from the chain
// (ledger split: sponsor 25%, levels 5%, pot 10%, company; passed over; Telegram card once; hub report), instant picks, a live
// draft (on the clock, manual pick, auto-picks, queue), coaching messages (no contact data anywhere), milestones -> cards, Best
// Coach + Rookie, picks returning to the pool, the release hold, the Draft Day card, old links, admin, a restart, and Playwright
// renders at 1280 and 390 with screenshots in qa/out.
// Nothing leaves this machine: hub, chain RPC and Telegram are local stand-ins. No real wallet, no money, nobody adopted.
// node qa/smoke.mjs SKIP_UI=1 node qa/smoke.mjs (HTTP only) UI_FONTS=1 (let Google Fonts load)
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const PORT = Number(process.env.SMOKE_APP_PORT || 3561), BASE = 'http://127.0.0.1:' + PORT;
const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'), HUB_SECRET = 'h'.repeat(40);
const KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
const KEEPER = new ethers.Wallet(KEEPER_PK).address;
const SHOP = '0x00000000000000000000000000000000005A5A5A';
const PRIZE = '0x000000000000000000000000000000000000bead';
const TANGEM = '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70';
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; let srv = null;
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 600) : '')); } };
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; try { await fn(q, r, b); } catch (e) { r.statusCode = 500; r.end(String(e.message)); } }).listen(port, '127.0.0.1').unref();
const H = 3600000, D = 86400000;
const POOL = JSON.parse(fs.readFileSync(path.join(APP, 'qa', 'fixtures', 'pool.json'), 'utf8')).people;
const pid = name => POOL.find(p => p.username === name).id;
// ---- stand-in network hub (signed as fivex) ----
const HUB = { people: new Map(), down: false, badSig: 0, resolves: 0, got: [] };
function person(username, wallet, sponsorId, id) { id = id || 'h_' + crypto.createHash('sha1').update(username).digest('hex').slice(0, 16); HUB.people.set(id, { id, username, wallet: wallet ? wallet.toLowerCase() : null, sponsorId: sponsorId || null }); return id; }
const hubView = p => { if (!p) return null; const sp = p.sponsorId && HUB.people.get(p.sponsorId); return { id: p.id, username: p.username, wallet: p.wallet, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null }; };
const HUB_PORT = PORT + 1;
listen(HUB_PORT, async (q, r, b) => {
r.setHeader('Content-Type', 'application/json');
if (q.method === 'GET' && q.url === '/v1/network-sites') return r.end('[]');
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"down"}'); }
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'fivex') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
const j = JSON.parse(b || '{}');
if (q.url === '/v1/resolve') {
HUB.resolves++; const all = [...HUB.people.values()]; let p = null;
if (j.id) p = HUB.people.get(j.id); else if (j.wallet) p = all.find(x => x.wallet === String(j.wallet).toLowerCase());
else if (j.ref) { const ref = String(j.ref).toLowerCase(); p = all.find(x => x.wallet === ref || x.username.toLowerCase() === ref); }
return r.end(JSON.stringify({ person: hubView(p) }));
}
HUB.got.push({ route: q.url, body: j }); r.end('{"ok":true}');
});
// ---- stand-in Polygon JSON-RPC (DraftPosition): quoteWei at POL $0.25 ($10 = 40 POL), sponsorOf, contract facts, logs ----
const IFACE = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 qty, uint256 ref, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 prizePaid, uint256 companyPaid)',
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
'event SponsorBound(address indexed member, address indexed sponsor)',
'function quoteWei(uint256 qty) view returns (uint256)', 'function sponsorOf(address) view returns (address)',
'function buy(uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256)',
'function owner() view returns (address)', 'function company() view returns (address)', 'function prizeWallet() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)',
'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function priceCents() view returns (uint256)']);
const CHAIN = { head: 1, logs: [], receipts: {}, bound: new Map(), replayAll: false, down: false, times: {} };
const CHAIN_PORT = PORT + 2;
listen(CHAIN_PORT, async (q, r, b) => {
const j = JSON.parse(b || '{}'); let result = null; r.setHeader('Content-Type', 'application/json');
if (CHAIN.down) return r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, error: { code: -1, message: 'down' } }));
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
if (j.method === 'eth_call') {
const tx = IFACE.parseTransaction({ data: j.params[0].data }); const enc = (fn, v) => IFACE.encodeFunctionResult(fn, v);
if (tx.name === 'quoteWei') result = enc('quoteWei', [1000n * tx.args[0] * 4n * 10n ** 16n]);
if (tx.name === 'sponsorOf') result = enc('sponsorOf', [CHAIN.bound.get(tx.args[0].toLowerCase()) || ethers.ZeroAddress]);
if (tx.name === 'owner' || tx.name === 'company') result = enc(tx.name, [TANGEM]);
if (tx.name === 'prizeWallet') result = enc('prizeWallet', [PRIZE]);
if (tx.name === 'keeper') result = enc('keeper', [KEEPER]);
if (tx.name === 'paused') result = enc('paused', [false]);
if (tx.name === 'totalOwed') result = enc('totalOwed', [0n]);
if (tx.name === 'orderCount') result = enc('orderCount', [BigInt(CHAIN.logs.length)]);
if (tx.name === 'priceCents') result = enc('priceCents', [1000n]);
}
if (j.method === 'eth_getBalance') result = '0x0';
if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null;
if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16);
if (j.method === 'eth_getBlockByNumber') { const n = j.params[0] === 'latest' ? CHAIN.head : parseInt(j.params[0], 16); result = { number: '0x' + n.toString(16), timestamp: '0x' + (CHAIN.times[n] || Math.floor(Date.now() / 1000)).toString(16), baseFeePerGas: '0x' + (30n * 10n ** 9n).toString(16) }; }
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result }));
});
// a position bought on the stand-in chain: Purchase log + a receipt with SponsorBound / PassedOver / Paid logs, like DraftPosition emits
let orderId = 0;
function chainBuy(o) {
const id = ++orderId; const block = ++CHAIN.head; const tx = '0x' + crypto.randomBytes(32).toString('hex');
CHAIN.times[block] = o.blockAt || Math.floor(Date.now() / 1000);
const qty = BigInt(o.qty || 1); const weiPaid = 1000n * qty * 4n * 10n ** 16n; const sp = weiPaid * 2500n / 10000n, lv = weiPaid * 500n / 10000n, pot = weiPaid / 10n;
const mk = (name, args, li) => { const e = IFACE.encodeEventLog(name, args); return { address: SHOP.toLowerCase(), topics: e.topics, data: e.data, blockNumber: '0x' + block.toString(16), transactionHash: tx, logIndex: '0x' + li.toString(16), removed: false }; };
const logs = []; let li = 0; let lvl = 0n;
for (const [m, s] of o.bound || []) { logs.push(mk('SponsorBound', [m, s], li++)); CHAIN.bound.set(m.toLowerCase(), s.toLowerCase()); }
for (const [w, d] of o.over || []) logs.push(mk('PassedOver', [id, w, d], li++));
(o.pays || []).forEach(([w, d], i) => { const a = i === 0 ? sp : lv; lvl += a; logs.push(mk('Paid', [id, w, a, i + 1, d], li++)); });
logs.push(mk('Paid', [id, PRIZE, pot, 6, 0], li++));
const company = weiPaid - lvl - pot; logs.push(mk('Paid', [id, TANGEM, company, 0, 0], li++));
const purchase = mk('Purchase', [id, o.buyer, qty, o.ref || 0, 1000n * qty, weiPaid, (o.pays || []).length, pot, company], li++);
logs.push(purchase); CHAIN.logs.push(purchase);
CHAIN.receipts[tx] = { status: '0x1', blockNumber: '0x' + block.toString(16), to: SHOP.toLowerCase(), from: o.buyer.toLowerCase(), logs };
return { tx, id, weiPaid, sp, lv, pot, company };
}
// ---- stand-in Telegram Bot API ----
const TG = []; const TG_PORT = PORT + 3;
listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', ALLOW_TEST_CLOCK: '1', TANK_MODE: 'stub',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0', DRAFT_TICK_MS: '200', DRAFT_PICK_SECONDS: '300',
CONTRACT_ADDRESS: SHOP, PRIZE_WALLET: PRIZE, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'fivex', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
TG_LIVE: '1', TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT, OWNER_USERNAME: 'coachann' });
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
let nextIp = 10;
function client(opts = {}) {
const jar = {}; const ip = opts.ip || ('203.0.113.' + (nextIp++)); const ua = opts.ua || ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeBrowser/' + ip);
return { jar, ip, ua,
async req(p, o = {}) {
const headers = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': ip, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, o.headers || {});
const r = await fetch(BASE + p, { method: o.method || 'GET', headers, body: o.body, redirect: 'manual' });
for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); }
return r;
},
async json(p, body, extra) { const r = await this.req(p, body === undefined ? { headers: extra } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extra), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); } };
}
const admin = (p, body) => client().json(p, body, { 'x-admin-token': ADMIN });
async function boot(extraEnv) {
const log = fs.openSync(path.join(OUT, 'server.log'), 'a');
srv = spawn(process.execPath, ['server.js'], { cwd: APP, env: Object.assign({}, ENV, extraEnv || {}), stdio: ['ignore', log, log] });
for (let i = 0; i < 80; i++) { try { const r = await fetch(BASE + '/health'); if (r.ok) return; } catch (e) {} await sleep(150); }
throw new Error('server did not start; see qa/out/server.log');
}
async function stop() { const p = srv; srv = null; if (!p) return; const done = new Promise(r => p.once('exit', r)); p.kill('SIGINT'); await Promise.race([done, sleep(3000)]); }
async function walletMember(o = {}) {
const w = o.wallet || ethers.Wallet.createRandom(); const c = client(); const a = w.address.toLowerCase();
if (o.hub) c.hubId = person(o.hub.username, a, o.hub.sponsorId, o.hub.id);
const ch = await c.json('/api/auth/challenge', { address: w.address });
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['fx.sid'];
return c;
}
const until = async (fn, ms) => { const end = Date.now() + (ms || 8000); let v; while (Date.now() < end) { v = await fn(); if (v) return v; await sleep(150); } return v; };
const ctToMs = (day, hour) => { const [y, m, d] = day.split('-').map(Number); for (const off of [6, 5]) { const t = Date.UTC(y, m - 1, d, hour + off); const h = Number(new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })); if (h % 24 === hour) return t; } return Date.UTC(y, m - 1, d, hour + 6); };
const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
async function main() {
if (await fetch(BASE).then(() => true, () => false)) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT');
console.log('data dir', DATA);
console.log('1. copy rules');
const pub = path.join(APP, 'public');
const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f)));
const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]).concat(['promokit.js', 'proof.js', 'server.js', 'draft.js', 'league.js', 'tools/pages.mjs', 'tools/art.mjs'].map(f => [f, fs.readFileSync(path.join(APP, f), 'utf8')]));
ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page, script or copy source', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0]));
const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n');
ok(!/metamask/i.test(html), 'pages never name MetaMask');
ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy: "SafePal or any other crypto wallet"');
ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money|get rich|up to \$?\d+ (a|per)|maximum (you|earn)/i.test(html), 'no income promises and no earnings caps in page copy');
ok(/never a subscription/i.test(html) && /A position buys a draft spot and coaching tools, not income\. Nothing is promised\./.test(html), 'position copy: one-time, never a subscription; "not income. Nothing is promised."');
ok(/TrustClickz/.test(html) && /615 Green Valley Drive, Moody, AL 35004/.test(html), 'legal pages name TrustClickz, 615 Green Valley Drive, Moody, AL 35004');
ok(/never their email or any contact details/.test(html) && /never an email, phone number or any other contact details/i.test(html), 'copy: coaches get the right to sponsor and help, never contact data');
console.log('2. boot (prototype mode, stub tank, test clock)');
// the test clock starts on Sunday 2026-11-15 noon Central: last Monday's draft (11-09) is long past and skipped, never run late
const SUN = ctToMs('2026-11-15', 12), MON = ctToMs('2026-11-16', 19);
await boot();
let r0 = await admin('/api/admin/clock', { now: SUN }); ok(r0.ok, 'admin moves the test clock (ALLOW_TEST_CLOCK=1, never in production)', r0);
await sleep(500);
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.position.usd === 10 && cfg.position.picksOnBuy === 5 && cfg.split.sponsorPct === 25 && cfg.split.levelPct === 5 && cfg.split.potPct === 10 && cfg.split.companyPct === 45 && cfg.tank === 'stub', 'config: $10 position, 5 picks, split 25/5x4/10/45, stub tank', cfg);
ok(cfg.shop.live === true && cfg.draft.dow === 1 && cfg.draft.hour === 19 && cfg.draft.rounds === 5 && cfg.picks.returnDays === 3, 'shop live (stand-in); draft Monday 7 PM Central, 5 rounds; picks return after 3 days', cfg.draft);
let st = await admin('/api/admin/status');
ok(st.draft === null || (st.draft && st.draft.made === 0), 'the app came up after last Monday\'s draft window: that draft is skipped, not run late', st.draft);
console.log('3. pages');
const anon = client();
for (const p of ['/', '/team', '/cards', '/join', '/ledger', '/contract', '/promote', '/builder', '/terms', '/disclaimer', '/privacy', '/admin', '/robots.txt', '/sitemap.xml', '/art/og-share.png', '/art/icon-192.png', '/assets/fx.css', '/assets/common.js']) { const r = await anon.req(p); ok(r.status === 200, 'GET ' + p + ' 200', r.status); }
let r = await anon.req('/team'); ok(r.headers.get('x-frame-options') === 'DENY', '/team is never framed');
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the draft board/.test(await r.text()), 'an unknown coach name: 404');
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
let b = await anon.json('/api/board');
ok(b.poolSize === 29 && b.pool.length === 24 && b.pool.every(p => p.gameWei === undefined && p.surfWei === undefined), 'the pool (stub tank: 29 draftable of 35); visitors see scouting facts but no earnings', { size: b.poolSize, keys: Object.keys(b.pool[0]) });
ok(!b.pool.some(p => /lockedlarry|hasasponsor|xx_spam_xx|temp_mail_9|brandnew|twiceadopted/.test(p.username)), 'never locked, sponsored, spam, throwaway, inside the grace or adopted twice', b.pool.map(p => p.username));
ok(!EMAIL_RE.test(JSON.stringify(b)), 'no email address anywhere in the board data');
console.log('4. promo kit');
{ const kr = await anon.req('/api/promo-kit?u=coachann'); const k = await kr.json();
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'GET /api/promo-kit 200 with CORS open');
ok(k.links[0].url === 'https://5xyourteam.com/coachann' && k.links.slice(1).every(l => l.url.endsWith('?ref=coachann')), 'kit links: the coach page + ?ref=', k.links.map(l => l.url));
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nw5x\?src=fivex&s1=coachann/.test(l.tracked)), 'every link has a LinkSpin-tracked twin (nw5x, source fivex)', k.links.map(l => l.tracked));
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
ok(!/[\u2014\u2013]/.test(words) && !/passive income|guaranteed (income|returns|profit)|make money|metamask/i.test(words) && /\$10 one-time position gives you 5 picks right away/.test(words) && /SafePal or any other crypto wallet/.test(words) && /never a subscription/.test(words), 'kit copy: no dashes, no income promises, facts from config, SafePal wording, never a subscription');
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'kit: 21 creatives in 3 angles', k.creatives.length);
const bad = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://5xyourteam.com', ''))); ok(!bad.length, 'kit: creative paths are ad-blocker neutral', bad.map(c => c.url));
let dimOk = true; const dimBad = [];
for (const c of k.creatives) { const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer()); const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20); if (rr.status !== 200 || w !== c.w || h !== c.h) { dimOk = false; dimBad.push(c.key + ' ' + w + 'x' + h); } }
ok(dimOk, 'kit: every creative is a PNG at its exact size', dimBad);
for (const p of ['/art/proof/fx-proof-navy.png', '/art/proof/fx-proof-gold.png', '/art/proof/fx-proof-field.png']) { const pr = await anon.req(p); ok(pr.status === 200 && pr.headers.get('content-type') === 'image/png', 'Telegram proof card ' + p); } }
console.log('5. sign-in');
// hub line above the coaches: top <- l2 (NO position) <- l1 <- coachann ; coachbob and coachcy are under coachann
const wTop = ethers.Wallet.createRandom(), wL2 = ethers.Wallet.createRandom(), wL1 = ethers.Wallet.createRandom();
const idTop = person('topcoach', wTop.address), idL2 = person('lineup2', wL2.address, idTop), idL1 = person('lineup1', wL1.address, idL2);
const A = await walletMember({ hub: { username: 'coachann', sponsorId: idL1 } });
let me = await A.json('/api/me'); ok(A.ok && me.username === 'coachann' && me.onNetwork && !me.coach, 'a wallet the hub knows: signed in, network username, not a coach yet', me);
const Bc = await walletMember({ hub: { username: 'coachbob', sponsorId: A.hubId } });
const Cc = await walletMember({ hub: { username: 'coachcy', sponsorId: A.hubId } });
const bad = client(); const x0 = ethers.Wallet.createRandom(), x1 = ethers.Wallet.createRandom();
const ch0 = await bad.json('/api/auth/challenge', { address: x0.address }); const v0 = await bad.json('/api/auth/verify', { address: x0.address, signature: await x1.signMessage(ch0.message) });
ok(v0._status === 400 && !bad.jar['fx.sid'], 'a signature from another wallet is refused');
const L = client(); r = await L.req('/sso/start?mode=go&via=iap&to=%2Fteam'); const loc = r.headers.get('location') || '';
ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=fivex'), 'network sign-in hops to InstantAdPay with r=fivex', loc);
const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET;
const wPick = ethers.Wallet.createRandom(); person('gamerdad', wPick.address, null, pid('gamerdad')); // a pool person who signs in later (their hub id = the fixture id)
const tok = nsso.mint({ iss: 'iap', aud: 'fivex', email: 'gamerdad@example.org', wallet: wPick.address.toLowerCase(), name: 'gamerdad', st: new URL(loc).searchParams.get('st'), to: '/team' });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok));
ok(r.status === 302 && r.headers.get('location') === '/team' && !!L.jar['fx.sid'], 'the network token signs a member in', { s: r.status, l: r.headers.get('location') });
const PICK = L;
ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as fivex with HUB_SECRET', HUB.badSig);
ok(!fs.readdirSync(DATA).some(f => /\.json$/.test(f) && fs.readFileSync(path.join(DATA, f), 'utf8').includes('gamerdad@example.org')), 'the sign-in email is never stored');
console.log('6. a position order (line voucher)');
let q = await A.json('/api/quote?qty=1'); ok(q.usd === 10 && q.picks === 5 && BigInt(q.wei) === 40n * 10n ** 18n, 'quote: $10 at $0.25 = 40 POL (from the contract)', q);
q = await A.json('/api/quote?qty=11'); ok(q._status === 400, '11 positions refused (1 to 10)');
let od = await A.json('/api/my/order', { qty: 1 });
const call = IFACE.parseTransaction({ data: od.data, value: od.value });
const line = call.args[2].map(a => a.toLowerCase());
ok(od._status === 200 && call.name === 'buy' && Number(call.args[0]) === 1 && BigInt(call.args[1]) > 0n, 'order = buy(qty 1, ref = a short hash of the hub id)', od);
ok(JSON.stringify(line) === JSON.stringify([wL1, wL2, wTop].map(w => w.address.toLowerCase())), 'the voucher line = the hub line\'s wallets nearest first', line);
const rec = ethers.verifyTypedData({ name: 'DraftPosition', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP.toLowerCase()) }, { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] },
{ buyer: ethers.getAddress(A.address), line: call.args[2], deadline: call.args[3] }, call.args[4]);
ok(rec === KEEPER, 'the voucher is signed by the keeper (EIP-712 DraftPosition v1)', rec);
ok(BigInt(od.value) === 40n * 10n ** 18n * 101n / 100n, 'value = quote + 1% (the contract refunds the excess in the same tx)', od.value);
CHAIN.bound.set(Bc.address, A.address);
od = await Bc.json('/api/my/order', { qty: 1 }); const c2 = IFACE.parseTransaction({ data: od.data, value: od.value });
ok(od.why === 'bound' && c2.args[2].length === 0 && c2.args[4] === '0x', 'a line already bound on chain: no voucher (the chain\'s binding wins)', od.why);
CHAIN.bound.delete(Bc.address); HUB.down = true; await sleep(350);
od = await Cc.json('/api/my/order', { qty: 1 }); ok(od._status === 503 && /sponsor line/.test(od.error), 'hub unreachable: the order waits (a line is never signed partial)', od);
HUB.down = false; await sleep(350);
console.log('7. positions recorded from the chain');
// coachann buys first (line bound, lineup1 paid 25% as sponsor; lineup2 passed over; topcoach 5%), then coachbob (2 positions) and coachcy
const tA = Math.floor(Date.now() / 1000) - 1800; // real block times (the Telegram card skips anything older than 2 hours)
const bA = chainBuy({ buyer: A.wallet.address, blockAt: tA, bound: [[A.wallet.address, wL1.address], [wL1.address, wL2.address], [wL2.address, wTop.address]], over: [[wL2.address, 2]], pays: [[wL1.address, 1], [wTop.address, 3]] });
let led = await until(async () => { const l = await anon.json('/api/ledger'); return l.items && l.items.length && l.items[0].pays.some(p => p.to) ? l : null; });
const it = led.items[0];
ok(led.items.length === 1 && it.buyerName === 'coachann' && it.usdCents === 1000, 'the ledger shows the position', it);
const pays = Object.fromEntries(it.pays.map(p => [p.label, p]));
ok(pays.sponsor.wei === bA.sp.toString() && pays.sponsor.wei === (10n ** 19n).toString() && pays['level 2'].wei === (2n * 10n ** 18n).toString() && pays['level 2'].depth === 3 && pays.pot.wei === (4n * 10n ** 18n).toString() && pays.company.wei === (24n * 10n ** 18n).toString(),
'split from the receipt: sponsor 25% = 10 POL, level 2 5% = 2 POL (place 3), pot 10% = 4 POL, company 24 POL (45% + the unfilled levels)', it.pays);
ok(it.passedOver.length === 1 && it.passedOver[0].depth === 2, 'passed over: place 2 (no position)', it.passedOver);
for (let i = 0; i < 30 && !TG.length; i++) await sleep(150);
const cap = (TG[0] && TG[0].body.caption) || '';
ok(TG.length === 1 && TG[0].method === 'sendPhoto' && TG[0].body.message_thread_id === 632242 && /\/art\/proof\/fx-proof-[a-z]+\.png$/.test(TG[0].body.photo), 'Telegram: one photo card in the payments topic', TG.map(t => t.method));
ok(/@coachann joined The Draft: a position · \$10\.00 \(40\.0000 POL\)/.test(cap) && /Sponsor 25%: 10\.0000 POL → /.test(cap) && /Level 2 5%: 2\.0000 POL → .*\(place 3 in the line\)/.test(cap) && /Best Coach pot 10%: 4\.0000 POL/.test(cap) && /5xYourTeam: 24\.0000 POL/.test(cap) && /passed over/.test(cap) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(cap) && !/[\u2014\u2013]/.test(cap), 'sale card: coach, every share with POL and place, pot, company, passed over, verify link, no dashes', cap);
chainBuy({ buyer: Bc.wallet.address, qty: 2, blockAt: tA + 600, pays: [[A.wallet.address, 1]] });
chainBuy({ buyer: Cc.wallet.address, blockAt: tA + 1200, pays: [[A.wallet.address, 1]] });
await until(async () => (await anon.json('/api/ledger')).items.length === 3);
me = await A.json('/api/me'); let my = await A.json('/api/my');
ok(me.coach && my.positions === 1 && my.credits === 5, 'coachann is a coach with 5 instant picks', { coach: me.coach, credits: my.credits });
my = await Bc.json('/api/my'); ok(my.positions === 2 && my.credits === 10, '2 positions = 10 instant picks', my.credits);
for (let i = 0; i < 30 && !HUB.got.length; i++) await sleep(150);
ok(HUB.got.some(g => g.route === '/v1/contract-bind' && g.body.contract === 'fivex' && g.body.wallet === A.address && g.body.sponsorRef === wL1.address.toLowerCase()), 'hub report: contract-bind for the coach with their direct sponsor', HUB.got.slice(0, 2));
CHAIN.replayAll = true; await sleep(800); CHAIN.replayAll = false;
led = await anon.json('/api/ledger'); ok(led.items.length === 3 && TG.length === 3, 'a flaky RPC re-sending old logs: no second record, no second Telegram post');
ok(led.totals.potWei === (16n * 10n ** 18n).toString(), 'ledger total to the Best Coach pot: 10% of 4 positions = 16 POL', led.totals);
b = await A.json('/api/board'); ok(b.pot.wei === (16n * 10n ** 18n).toString() && b.me.coach && b.pool[0].gameWei !== undefined, 'the board: this week\'s pot; coaches see earnings on scouting cards', b.pot);
console.log('8. instant picks');
const p1 = b.pool[0].id;
let ip = await A.json('/api/my/instant', { person: p1 }); ok(ip.ok && ip.credits === 4, 'an instant pick from the pool (5 -> 4 credits)', ip);
ip = await Bc.json('/api/my/instant', { person: p1 }); ok(/no longer available/.test(ip.error), 'the same player cannot be taken twice', ip);
ip = await PICK.json('/api/my/instant', { person: b.pool[1].id }); ok(ip._status === 403, 'no position: no instant pick', ip);
ip = await A.json('/api/my/instant', { person: pid('lockedlarry') }); ok(/no longer available/.test(ip.error), 'someone locked on a network contract can never be picked', ip);
const gd = pid('gamerdad');
ip = await A.json('/api/my/instant', { person: gd }); ok(ip.ok, 'coachann picks @gamerdad (who will sign in as a pick)', ip);
my = await A.json('/api/my');
ok(my.picks.length === 2 && my.picks.every(p => p.status === 'open' && p.kind === 'instant' && p.daysLeft === 3) && my.help.length === 2, 'My Team: 2 open instant picks with 3 days to start, both on the who-to-help list', my.picks.map(p => [p.username, p.daysLeft]));
ok(!EMAIL_RE.test(JSON.stringify(my)), 'no email address anywhere in My Team data');
console.log('9. coaching messages (through the site only)');
const gpk = my.picks.find(p => p.person === gd);
let m = await A.json('/api/my/message', { pick: gpk.id, text: 'Welcome! I am your coach <b>here</b>.' }); ok(m.ok, 'the coach writes to their pick');
m = await Bc.json('/api/my/message', { pick: gpk.id, text: 'hi' }); ok(m._status === 403, 'another coach cannot write to someone else\'s pick', m);
me = await PICK.json('/api/my'); ok(me.myCoach && me.myCoach.coach === 'coachann' && me.myCoach.messages.length === 1 && me.myCoach.messages[0].text === 'Welcome! I am your coach here.', 'the pick sees their coach and the message (markup stripped)', me.myCoach);
m = await PICK.json('/api/my/message', { pick: gpk.id, text: 'Thanks coach, how do I link a wallet?' }); ok(m.ok, 'the pick replies through the site');
let th = await A.json('/api/my/messages?pick=' + gpk.id); ok(th.items.length === 2 && th.items[1].mine === false && th.with === 'gamerdad', 'the coach sees the thread', th);
ok(!EMAIL_RE.test(JSON.stringify(me)) && !EMAIL_RE.test(JSON.stringify(th)), 'no contact data in the pick or coach views');
console.log('10. the live draft (test clock: Monday 7 PM Central)');
await A.json('/api/my/queue', { ids: [] });
const bq = (await Cc.json('/api/board')).pool; const cyWant = bq[bq.length - 1].id; // the lowest scouting score: nobody else's auto-pick
await Cc.json('/api/my/queue', { ids: [cyWant] });
await admin('/api/admin/clock', { now: MON - 2000 }); await A.json('/api/presence', {}); await sleep(2600);
b = await A.json('/api/board');
ok(b.draft && b.draft.status === 'live' && b.draft.onClock && b.draft.onClock.me && b.draft.onClock.slot === '1.1' && b.draft.coaches === 3, 'the draft starts at 7 PM Central: coachann (earliest position, no starts last week) is on the clock at 1.1', b.draft && b.draft.onClock);
ip = await Bc.json('/api/my/instant', { person: b.pool[0].id }); ok(/draft is live/.test(ip.error), 'no instant picks while the draft is live', ip);
let dp = await PICK.json('/api/draft/pick', { person: b.pool[0].id }); ok(/not on the clock/.test(dp.error), 'someone who is not on the clock cannot pick', dp);
const mine1 = b.pool[2].id; dp = await A.json('/api/draft/pick', { person: mine1 }); ok(dp.ok, 'coachann drafts by hand', dp);
b = await until(async () => { const x = await A.json('/api/board'); return x.draft.made >= 3 ? x : null; });
ok(b.draft.made === 3 && b.draft.onClock.slot === '2.1' && b.draft.onClock.me, 'coachbob and coachcy are away: auto-picked at once; round 2 puts coachann back on the clock', b.draft);
const cyRow = (await A.json('/api/board')).draft.rows.find(x => x.coach === 'coachcy');
ok(cyRow && cyRow.person === (bq.find(p => p.id === cyWant) || {}).username, 'coachcy (away) got the first player on their queue', cyRow);
await admin('/api/admin/clock', { now: MON + 400 * 1000 }); // past the 300-second clock and the 120-second room window: coachann is away now
const done = await until(async () => { const x = await A.json('/api/board'); return x.draft.status === 'done' ? x : null; }, 10000);
ok(done && done.draft.made === 15, 'the clock ran out and coachann was away: everyone auto-picked, 3 coaches x 5 rounds = 15 picks', done && done.draft);
const tdd = await until(async () => TG.find(t => /Draft Day results/.test(t.body.caption || '')), 5000);
ok(tdd && /\/art\/draftday\/week-2026-11-16\.png$/.test(tdd.body.photo) && /1\.1<\/b> @coachann takes @/.test(tdd.body.caption) && /15 players drafted · 3 coaches/.test(tdd.body.caption), 'the Draft Day card: results image + the picks, once', tdd && tdd.body);
const dd = await anon.json('/api/draftday?week=2026-11-16'); ok(dd.rows.length === 15 && dd.players === 15, 'the Draft Day data for the card', dd.players);
my = await A.json('/api/my'); ok(my.picks.filter(p => p.status === 'open').length === 7 && my.stats.onTeam === 7, 'coachann: 2 instant + 5 drafted = 7 open picks', my.stats);
console.log('11. milestones, cards, Best Coach, Rookie of the Week');
await admin('/api/admin/stub/status', { id: gd, wallet: true }); await admin('/api/admin/tick', {});
my = await A.json('/api/my'); let g = my.picks.find(p => p.person === gd);
ok(g.tier === 'starter' && g.steps.find(s => s.key === 'wallet').done && g.steps.find(s => s.next).key === 'payouts', 'a pick links a wallet: Starter, next step payouts', g.steps);
ok(my.help[0].pickId === g.id || my.help.some(h => h.pickId === g.id && /one step from payouts/.test(h.why)), 'who to help: @gamerdad is one step from payouts', my.help.slice(0, 3));
await admin('/api/admin/stub/status', { id: gd, payouts: true }); await admin('/api/admin/tick', {});
const bpk = (await Bc.json('/api/my')).picks.filter(p => p.status === 'open');
await admin('/api/admin/stub/status', { id: bpk[0].person, purchase: true }); await admin('/api/admin/stub/status', { id: bpk[1].person, wallet: true, payouts: true }); await admin('/api/admin/tick', {});
my = await A.json('/api/my'); g = my.picks.find(p => p.person === gd);
ok(g.status === 'done' && g.tier === 'pro', '@gamerdad switched on payouts: started, stays on the team (Pro card)', g);
b = await A.json('/api/board');
ok(b.best.length === 2 && b.best[0].coach === 'coachbob' && b.best[0].started === 2 && b.best[1].coach === 'coachann', 'Best Coach standings: coachbob 2 started, coachann 1', b.best);
ok(b.rookie && b.rookie.tier === 'allstar', 'Rookie of the Week: the pick that climbed highest (All-Star)', b.rookie);
const cards = await anon.json('/api/coach?u=coachann');
ok(cards.team.some(c => c.username === 'gamerdad' && c.tierName === 'Pro' && c.milestone === 'Payouts switched on') && !/"(gameWei|surfWei|earned\w*|weiPaid)"/.test(JSON.stringify(cards)), 'public cards: milestones only, never earnings', cards.team.slice(0, 3));
r = await anon.req('/coachann'); ok(r.status === 200 && /coach\.js/.test(await r.text()), 'GET /coachann serves the coach page');
const rc = await anon.json('/api/recent'); ok(rc.items.some(x => x.kind === 'level' && x.person === 'gamerdad') && rc.items.some(x => x.kind === 'pick'), 'toasts: picks and level-ups (real events only)', rc.items.slice(0, 4));
const pot = await admin('/api/admin/pot?week=2026-11-16');
ok(pot.shares.length === 2 && pot.shares[0].username === 'coachbob' && pot.shares[0].pct === 50, 'admin: the week\'s pot shares by place (rule open for Marty)', pot);
console.log('12. picks return to the pool; the release hold');
let rl = await A.json('/api/my/release', { pick: my.picks.find(p => p.status === 'open').id }); ok(/less than 48 hours/.test(rl.error), 'a pick cannot be released in its first 48 hours', rl);
await admin('/api/admin/clock', { now: MON + 3 * D + 3600000 }); await admin('/api/admin/tick', {});
my = await A.json('/api/my');
ok(my.picks.filter(p => p.status === 'open').length === 0 && my.picks.filter(p => p.status === 'returned').length >= 5 && my.picks.find(p => p.person === gd).status === 'done', 'after 3 days the unconverted picks go back to the pool; the started one stays', my.picks.map(p => p.status));
b = await anon.json('/api/board'); ok(b.poolSize > 15, 'they are draftable again', b.poolSize);
th = await A.json('/api/my/message', { pick: my.picks.find(p => p.status === 'returned').id, text: 'still there?' }); ok(/back in the pool/.test(th.error), 'a returned pick\'s thread is closed', th);
console.log('13. old site links');
r = await anon.req('/api/admin/oldrefs', { method: 'POST', headers: { 'x-admin-token': ADMIN }, body: JSON.stringify({ oldrefs: { janie23: 'coachann', 'bad key!': 'x' } }) });
const or = await r.json(); ok(or.ok && or.total === 1 && or.skipped === 1, 'admin loads the old-username map', or);
for (const [from, to] of [['/?janie23', '/coachann'], ['/splashpg.php?pid=4&r=janie23', '/coachann'], ['/lcp.php?r=JANIE23', '/coachann'], ['/index.php?r=janie23', '/coachann'], ['/members/login.php', '/team'], ['/?nobodyold', '/'], ['/whatever.php', '/']]) {
r = await anon.req(from); ok(r.status === 301 && r.headers.get('location') === to, 'old link ' + from + ' -> ' + to, r.headers.get('location')); }
r = await anon.req('/?ref=coachann'); ok(r.status === 200, '/?ref=<name> is not an old link');
console.log('14. admin');
r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin needs the token');
st = await admin('/api/admin/status'); const sj = JSON.stringify(st);
ok(st.shop.vouchers && st.shop.keeper === KEEPER && !sj.includes(KEEPER_PK.slice(2)) && !sj.includes(HUB_SECRET) && !sj.includes('standin-token') && !sj.includes(SSO_SECRET), 'admin status: keeper address only, no key or secrets', st.shop);
ok(st.tank.mode === 'stub' && st.tank.adoptionMailsThatWouldSend >= 17, 'stub tank: every pick went through adopt (mails counted, none sent)', st.tank);
const pp = await admin('/api/admin/pot/paid', { week: '2026-11-16', rank: 1, coach: Bc.address, wei: '8000000000000000000', tx: '0x' + 'ab'.repeat(32) });
ok(pp.ok && (await anon.json('/api/ledger')).payouts.length === 1, 'a Best Coach payout recorded with its tx shows on the ledger', pp);
const tpl = await until(async () => TG.find(t => /Best Coach, week of 2026-11-16: #1 @coachbob got 8\.0000 POL/.test(t.body.text || '')), 4000);
ok(!!tpl, 'one Telegram line per Best Coach payout');
console.log('15. restart (Telegram not live: the outbox)');
await sleep(700); { const sd = JSON.parse(fs.readFileSync(path.join(DATA, 'fivex.json'), 'utf8')).drafts['2026-11-16']; ok(sd && sd.status === 'done', 'the finished draft is saved as done before the restart', sd && sd.status); }
await stop(); await boot({ TG_LIVE: '' }); await admin('/api/admin/clock', { now: MON + 3 * D + 3700000 }); await sleep(500);
my = await A.json('/api/my'); ok(my.positions === 1 && my.picks.length === 7 && my.picks.find(p => p.person === gd).tier === 'pro', 'after a restart: positions, picks and milestones are kept');
const tgBefore = TG.length;
chainBuy({ buyer: Cc.wallet.address, blockAt: Math.floor(Date.now() / 1000), pays: [[A.wallet.address, 1]] });
await until(async () => (await anon.json('/api/ledger')).items.length === 4); await sleep(800);
st = await admin('/api/admin/status');
ok(TG.length === tgBefore && st.proof.queued === 1 && /outbox/.test(st.proof.telegram) && st.proof.outbox.some(x => /coachcy joined The Draft/.test(x.body.caption || '')), 'with TG_LIVE unset nothing is sent: the sale card waits in the outbox', st.proof);
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
console.log('16. Playwright renders (desktop 1280 + phone 390)');
// next Monday's draft: coachbob (2 started last week) picks first, then coachann, who is in the room: on the clock
await admin('/api/admin/clock', { now: ctToMs('2026-11-23', 19) - 2500 }); await A.json('/api/presence', {}); await sleep(3200);
b = await A.json('/api/board'); ok(b.draft && b.draft.status === 'live' && b.draft.onClock && b.draft.onClock.me && b.draft.made === 1, 'week 2: draft order earned (coachbob first); coachann is on the clock', b.draft && b.draft.onClock);
const { chromium } = require(PW); const browser = await chromium.launch();
for (const [label, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) {
const ctx = await browser.newContext({ viewport: vp, isMobile: label === 'phone', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + label });
await ctx.route(/^https:\/\//, rt => (process.env.UI_FONTS && /^https:\/\/fonts\.(googleapis|gstatic)\.com\//.test(rt.request().url())) ? rt.continue() : rt.abort());
await ctx.addCookies([{ name: 'fx.sid', value: A.jar['fx.sid'], url: BASE }]);
const errs = []; const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message));
for (const [p, sel] of [['/', '#pool .scout'], ['/team', '#focus:not([hidden]) .steps div'], ['/cards', '#mineCards .tc'], ['/join', '#jQty option'], ['/coachann', '#cTeam .tc'], ['/ledger', '#rows tbody tr'], ['/contract', '#facts th'], ['/promote', '#kit .card'], ['/builder', '#bList .kit-row'], ['/terms', '.legal .card'], ['/disclaimer', '.legal .card'], ['/privacy', '.legal .card']]) {
await pg.goto(BASE + p, { waitUntil: 'domcontentloaded' }); await pg.waitForSelector(sel, { timeout: 8000 }).catch(() => {});
await sleep(300);
const found = await pg.$$eval(sel, els => els.length);
const wide = await pg.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
ok(found > 0 && wide <= 1, label + ' ' + p + ': renders (' + sel + ') with no sideways scroll', { found, wide });
await pg.screenshot({ path: path.join(OUT, label + '-' + (p === '/' ? 'board' : p.slice(1)) + '.png'), fullPage: true });
}
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /ON THE CLOCK/.test(document.getElementById('heroKick').textContent), null, { timeout: 8000 }).catch(() => {});
ok(/YOU'RE ON THE CLOCK/.test(await pg.textContent('#heroKick')) && /Pick 2 of Round 1/.test(await pg.textContent('#heroTitle')) && (await pg.$$eval('[data-draft]', e => e.length)) > 0, label + ': board says YOU\'RE ON THE CLOCK with DRAFT buttons');
ok((await pg.textContent('footer')).includes('TrustClickz') && /Part of the network/.test(await pg.textContent('footer')) && /5xYourTeam/.test(await pg.textContent('footer .netline')), label + ': footer has the company line and the network line');
ok(errs.length === 0, label + ': no page errors', errs);
await ctx.close();
}
// a pick's view of /team (their coach and the thread)
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); await ctx.route(/^https:\/\//, rt => (process.env.UI_FONTS && /^https:\/\/fonts\.(googleapis|gstatic)\.com\//.test(rt.request().url())) ? rt.continue() : rt.abort());
await ctx.addCookies([{ name: 'fx.sid', value: PICK.jar['fx.sid'], url: BASE }]); const pg = await ctx.newPage();
await pg.goto(BASE + '/team', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#myCoach:not([hidden]) .msg', { timeout: 8000 }).catch(() => {});
ok(/@coachann/.test(await pg.textContent('#mcName')) && (await pg.$$eval('#mcThread .msg', e => e.length)) === 2, 'a pick sees their coach and the thread on /team');
await pg.screenshot({ path: path.join(OUT, 'desktop-team-as-pick.png'), fullPage: true });
const p2 = await (await browser.newContext({ viewport: { width: 1080, height: 1080 } })).newPage();
await p2.goto(BASE + '/draftday/2026-11-16', { waitUntil: 'domcontentloaded' }); await p2.waitForSelector('body[data-ready="1"]', { timeout: 8000 }).catch(() => {});
ok((await p2.$$eval('.dd-r', e => e.length)) === 6 && /15 players drafted/.test(await p2.textContent('#ddStats')), 'the Draft Day card renders from the week\'s results');
await p2.screenshot({ path: path.join(OUT, 'draftday-2026-11-16.png') });
await ctx.close(); }
await browser.close();
} else console.log('16. (Playwright renders skipped)');
await stop();
console.log('\n' + pass + ' passed, ' + fail + ' failed');
fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); });
+172
View File
@@ -0,0 +1,172 @@
// 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('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); });