Files
5xyourteam/qa/iap-tank.test.cjs

167 lines
15 KiB
JavaScript

// The REAL holding tank behind The Draft, end to end, LOCAL ONLY (2026-11-15):
// 5xYourTeam league.js + tankpool.js in 'iap' mode -> signed HTTP on 127.0.0.1:3565 -> InstantAdPay's REAL draftpartner.js + tank.js
// (loaded from the sibling checkout ../../onchain-ad-membership/site) with in-memory accounts, a fake chain, a fake hub and the
// league's mocked clock. Nothing leaves this machine; the IAP mailer is a list. Skips (exit 0) when the sibling repo is missing.
// Then the same client against a dead port (3566): no pool, no pick, nothing recorded.
// node qa/iap-tank.test.cjs (IAP_SITE_DIR = the InstantAdPay site dir if it is not side by side)
'use strict';
const path = require('path');
const fs = require('fs');
const os = require('os');
const http = require('http');
const crypto = require('crypto');
const APP = path.resolve(__dirname, '..');
const IAP = process.env.IAP_SITE_DIR || path.resolve(APP, '..', '..', 'onchain-ad-membership', 'site');
const PORT = Number(process.env.FX_IAP_PORT || 3565), DEAD = Number(process.env.FX_DEAD_PORT || 3566);
const D = 86400000, H = 3600000;
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) : '')); } };
if (!fs.existsSync(path.join(IAP, 'draftpartner.js'))) { console.log('skip: InstantAdPay site with draftpartner.js not found at ' + IAP); process.exit(0); }
const SECRET = 'fx-iap-test-secret-' + 'z'.repeat(40);
function fakeAccounts() {
const by = new Map(); let nextId = 100;
const pub = a => a ? Object.assign({}, a) : null;
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
return { _by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * D, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async byAddress(w) { const x = String(w || '').toLowerCase(); return find(a => a.address && a.address.toLowerCase() === x); },
async positionOwner() { return null; },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
async listAll() { return [...by.values()].map(pub); }, isUnclaimedShell: () => false,
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); } };
}
(async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fx-iaptank-'));
const iapDir = path.join(dir, 'iap'); fs.mkdirSync(iapDir);
delete process.env.DATABASE_URL;
Object.assign(process.env, { DATA_DIR: path.join(dir, 'fx'), DOCSTORE_URL: '', TANK_MODE: 'iap', IAP_URL: 'http://127.0.0.1:' + PORT, DRAFT_PARTNER_SECRET: SECRET, DRAFT_ROUNDS: '2', PICK_RETURN_DAYS: '3', DRAFT_LIVE: '1' }); // sections 1-5 live; section 6 = staging test mode
fs.mkdirSync(process.env.DATA_DIR);
require(path.join(APP, 'config.js')).reset(); const C = require(path.join(APP, 'config.js')).get();
const store = require(path.join(APP, 'store.js')); const league = require(path.join(APP, 'league.js')); const tank = require(path.join(APP, 'tankpool.js'));
require(path.join(APP, 'docstore.js')).install(C.dataDir); store.load();
const monday7pm = store.ctToMs('2026-11-16', 19);
league.clock.set(monday7pm - 2 * H);
// ---- InstantAdPay side: the real modules ----
const itank = require(path.join(IAP, 'tank.js')); const dp = require(path.join(IAP, 'draftpartner.js'));
const accounts = fakeAccounts(); const events = []; const mails = []; const chats = []; const locked = new Set(); const ids = new Map();
const now = () => league.clock.now();
itank.init({ dataDir: iapDir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) },
follow: { setDeliberate: async (email, token) => accounts.setSponsorRef(email, token) },
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject) => { mails.push({ to, subject }); } }, site: 'https://iap.test',
hooks: { network: () => null, isSuspended: () => false, excluded: () => false, payoutBlocked: async () => false, companyId: () => 1,
networkHeld: async accts => new Map(accts.filter(a => locked.has(a.email)).map(a => [a.email, 'locked'])), networkLocked: async e => (locked.has(e) ? 'locked' : null),
isDraftPick: id => dp.isDraftPick(id), assigned: () => {}, adminAlert: () => {}, claim: () => true, activated: () => false, notify: async () => {} } });
itank.setClock(now);
await dp.init({ dataDir: iapDir, accounts, chain: { recentEvents: () => events.slice().reverse() }, tank: itank, ads: null, requireHub: true, clock: now, secret: SECRET,
hooks: { hubInfo: e => (ids.has(e) ? { id: ids.get(e), door: 'vbb' } : null), networkOn: () => true, excluded: () => false, spamEmails: () => [], suggestDomain: () => null } });
const srv = http.createServer((req, res) => { let raw = ''; req.on('data', c => { raw += c; }); req.on('end', async () => {
const send = (st, j) => { res.writeHead(st, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(j)); };
const sg = dp.verify(req.headers, raw); if (!sg.body) return send(sg.status, { error: sg.error });
const op = req.url.replace('/api/partner/draft/', ''); const r = await dp.handle(op, sg.body); send(r.error ? 400 : 200, r); }); });
await new Promise(r => srv.listen(PORT, '127.0.0.1', r));
// the network tank: 8 waiting, 1 locked on a contract, 1 inside the grace
const hid = () => 'h_' + crypto.randomBytes(8).toString('hex');
for (let i = 1; i <= 8; i++) { const e = 'p' + i + '@x.co'; accounts.add(e, { username: 'player' + i, address: i <= 2 ? '0x' + String(i).repeat(40) : null }); ids.set(e, hid()); }
accounts.add('locked@x.co', { username: 'lockedone' }); locked.add('locked@x.co'); ids.set('locked@x.co', hid());
accounts.add('brand@x.co', { username: 'brandnew', created: now() - 2 * H }); ids.set('brand@x.co', hid());
// coaches: A and B hold 5x positions; on InstantAdPay they have a wallet + payouts on, NO $20 package. Z holds a position but has no IAP account.
const A = '0x' + 'a'.repeat(40), B = '0x' + 'b'.repeat(40), Z = '0x' + 'c'.repeat(40);
accounts.add('ann@x.co', { username: 'ann', memberId: 51, address: A }); accounts.add('bob@x.co', { username: 'bob', memberId: 52, address: B });
league.init(C, { proof: { draftDay: async () => true, potOf: () => '0' } }); tank.init(C, { now });
const S = store.state();
const buy = (a, qty, at, name) => { S.purchases[a + ':0'] = { buyer: a, qty, at, blockAt: Math.floor(at / 1000), usdCents: 1000 * qty, weiPaid: '1', prizePaid: '0' }; store.upsertMember(a, { username: name }); store.addCredits(a, 5 * qty); };
buy(A, 1, monday7pm - 5 * D, 'ann'); buy(B, 1, monday7pm - 4 * D, 'bob'); buy(Z, 1, monday7pm - 3 * D, 'zed');
const sponsorOf = async e => (await accounts.byEmail(e)).sponsorRef;
const emailOfId = id => [...ids.entries()].find(x => x[1] === id)[0];
try {
console.log('1. the pool comes from InstantAdPay');
const pool0 = await league.pool(now());
ok(pool0.length === 8 && !pool0.some(x => /locked|brand/.test(x.username)) && pool0.every(x => /^h_[0-9a-f]{16}$/.test(x.id) && x.door === 'Viral Banner Blitz'), 'pool: 8 draftable (locked + inside the grace left out), hub ids, the door', pool0.map(x => x.username));
ok(!JSON.stringify(pool0).includes('@'), 'pool: no contact data reaches 5xYourTeam');
console.log('2. instant picks are real adoptions');
const p1 = pool0[0];
let r = await league.instantPick(A, p1.id);
ok(r.ok && /^iap:\d+$/.test(store.pick(r.pickId).ref), 'instant pick: InstantAdPay adopted (ref iap:N)', r);
ok(await sponsorOf(emailOfId(p1.id)) === 'ann', 'InstantAdPay: the pick now has the coach as sponsor');
ok(mails.length === 1 && /ann is now your sponsor on InstantAdPay/.test(mails[0].subject), 'the normal adoption email is the one mail', mails);
r = await league.instantPick(Z, pool0[1].id);
ok(r.error && store.picksOf(Z).length === 0 && store.credits(Z) === 5, 'a coach with no InstantAdPay account: refused, nothing recorded, the credit is kept', r);
r = await league.instantPick(B, p1.id); ok(r.error, 'the same player cannot be picked twice', r);
console.log('3. the Monday draft runs every pick through InstantAdPay');
league.clock.set(monday7pm + 1000); await league.tick();
const dW = store.draft('2026-11-16');
ok(dW && dW.status === 'done' && dW.made.filter(x => x.person).length === 4, 'draft: 2 coaches x 2 rounds (Z skipped: refused by the tank, the slot is not lost to a person)', dW && dW.made.map(x => x.person ? 'pick' : x.skipped || 'x'));
const open = store.picks().filter(p => p.status === 'open');
ok(open.length === 5 && open.every(p => p.ref && p.expires === p.at + 3 * D), 'five open picks, each with its InstantAdPay ref and a 3-day window', open.length);
ok(mails.length === 5, 'five adoption emails, nothing else', mails.length);
const iapOpen = (await Promise.all(open.map(p => itank.openOf(emailOfId(p.person))))).map(x => x.length);
ok(iapOpen.every(n => n === 1), 'InstantAdPay holds one open adoption per pick');
console.log('4. statuses, release, returns');
const started = open.find(p => p.coach === B); accounts._by.get(emailOfId(started.person)).memberId = 99; accounts._by.get(emailOfId(started.person)).address = '0x' + '9'.repeat(40);
league.clock.set(monday7pm + 1 * D); await league.tick();
ok(store.pick(started.id).status === 'done' && store.pick(started.id).tier === 'pro', 'a pick who switched on payouts on InstantAdPay is done (Pro)', store.pick(started.id));
const relp = open.find(p => p.coach === A && p.id !== started.id);
r = await league.release(A, relp.id); ok(r.error && /48 hours/.test(r.error), 'release: refused inside the 48-hour hold', r);
league.clock.set(monday7pm + 2 * D + H); r = await league.release(A, relp.id);
ok(r.ok && store.pick(relp.id).status === 'returned' && await sponsorOf(emailOfId(relp.person)) === '', 'release after 48 h: back in the tank on InstantAdPay too', r);
// InstantAdPay's own hourly sweep returns one at 3 days before this app's tick: the league follows its outcome
league.clock.set(monday7pm + 3 * D + 2 * H);
const isw = await dp.sweep();
ok(isw.returned >= 1, 'InstantAdPay sweep: unstarted picks back at 3 days', isw);
await league.tick();
const after = store.picks();
ok(after.filter(p => p.status === 'open').length === 0 && after.filter(p => p.status === 'done').length === 1, 'the league follows: no open picks left, the started one stays done', after.map(p => p.personName + ':' + p.status + (p.closedBy ? '(' + p.closedBy + ')' : '')));
const back = await league.pool(now());
ok(back.length === 8 - 1 + 1 && back.some(x => x.username === 'brandnew'), 'back in the pool (8 - 1 started + brandnew after its grace), original join times', back.length);
const dr = require(path.join(APP, 'draft.js')); ok(back.filter(x => x.adoptions === 0 && dr.adoptionCount(x, store.picks()) === 1).length >= 4, 'returned people: 0 adoptions outside 5x + their 1 pick here = 1 of 2 (no double count)');
ok(!JSON.stringify(store.state()).includes('@x.co'), '5xYourTeam stored no email anywhere');
console.log('5. InstantAdPay unreachable');
C.iapBase = 'http://127.0.0.1:' + DEAD;
const n0 = store.picks().length;
ok((await tank.candidates(now())).length === 0, 'no answer: an empty pool (nothing drafted)');
r = await league.instantPick(A, back[0].id);
ok(r.error && store.picks().length === n0, 'no answer: a pick is refused and nothing is recorded', r);
const st = await tank.status([back[0].id], now()); ok(st[back[0].id] === null, 'no answer: status is null (nothing changes on the sweep)');
ok(tank.view().remote.failed >= 3 && tank.view().remote.secret === true, 'the admin view counts the failures', tank.view().remote);
console.log('6. staging test mode (DRAFT_LIVE not 1): the pool is read, picks are previews, nobody is adopted, no mail');
C.iapBase = 'http://127.0.0.1:' + PORT; delete process.env.DRAFT_LIVE;
const m0 = mails.length, c0 = chats.length;
ok(tank.preview() === true && tank.live() === false && tank.view().testMode === true, 'test mode is on without DRAFT_LIVE=1', tank.view());
const tp = await league.pool(now()); ok(tp.length > 0, 'the pool is still read from InstantAdPay', tp.length);
const who = tp[0]; const whoEmail = emailOfId(who.id); const sp0 = await sponsorOf(whoEmail);
r = await league.instantPick(A, who.id);
ok(r.ok && /^preview:/.test(store.pick(r.pickId).ref), 'instant pick in test mode: recorded here as a preview (ref preview:...)', r);
ok(await sponsorOf(whoEmail) === sp0 && (await itank.openOf(whoEmail)).length === 0, 'InstantAdPay: no sponsor change, no open adoption');
ok(mails.length === m0 && chats.length === c0, 'no adoption email, no chat', mails.slice(m0));
ok(!(await league.pool(now())).some(x => x.id === who.id), 'a previewed person leaves the pool on this site only');
const nextMon = store.ctToMs('2026-11-23', 19); league.clock.set(nextMon + 1000); await league.tick();
const d2 = store.draft('2026-11-23'); const made2 = d2 ? d2.made.filter(x => x.person) : [];
ok(d2 && d2.status === 'done' && made2.length > 0, 'the Monday draft runs in test mode', d2 && d2.made.map(x => x.person ? 'pick' : x.skipped || 'x'));
const prev = store.picks().filter(p => p.status === 'open');
ok(prev.length > 0 && prev.every(p => /^preview:/.test(p.ref || '')), 'every open pick is a preview', prev.map(p => p.ref));
let clean = true; for (const p of prev) { const e = emailOfId(p.person); if ((await itank.openOf(e)).length || (await sponsorOf(e)) !== '') clean = false; }
ok(clean, 'InstantAdPay: no drafted person got a sponsor or an open adoption');
ok(mails.length === m0 && chats.length === c0, 'still no email or chat after the draft', mails.length - m0);
league.clock.set(nextMon + 3 * D); const rp = prev.find(p => p.coach === A) || prev[0]; r = await league.release(rp.coach, rp.id);
ok(r.ok && store.pick(rp.id).status === 'returned' && mails.length === m0, 'releasing a preview pick touches nothing on InstantAdPay', r);
ok(tank.view().adoptionMailsSkipped >= 1 + made2.length, 'the admin view counts the adoptions (and emails) that test mode skipped', tank.view());
} finally { srv.close(); fs.rmSync(dir, { recursive: true, force: true }); }
console.log('\n' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
})().catch(e => { console.error('iap-tank test crashed:', e.stack || e.message); process.exit(1); });