diff --git a/README.md b/README.md index e98bbc5..64b3bbf 100644 --- a/README.md +++ b/README.md @@ -56,15 +56,29 @@ Deviation from the mockup on purpose: the mockup's coach card showed an email li ``` npm ci node server.js # prototype mode (files, stub tank); never launch this way -node qa/unit.test.cjs # 60 checks: tiers, tank rules, earned order, the clocked draft, returns, boards, the split model +node qa/unit.test.cjs # 62 checks: tiers, tank rules, earned order, the clocked draft, tank refusals, returns, boards, the split model # against the fork rehearsal (to the wei), Central weeks, the league end to end node qa/smoke.mjs # 156 checks against stand-in hub / chain / Telegram (ports 3561-3564) + Playwright 1280/390 UI_FONTS=1 node qa/smoke.mjs # same, Google Fonts allowed so qa/out screenshots show the real type +node qa/iap-tank.test.cjs # 23 checks: league + the real client against InstantAdPay's REAL draftpartner.js + tank.js (sibling + # checkout) behind a signed local server on 3565, then a dead port (3566); skips without the sibling node tools/pages.mjs # regenerate public/*.html (one source of copy + legal facts) node tools/art.mjs # icon, OG, proof cards, kit, tier cards; --draftday for a Draft Day PNG ``` +## The real holding tank (built 2026-11-15, local only) + +`TANK_MODE=iap` (or `hub`) switches tankpool.js from the stub to InstantAdPay's signed partner routes (`IAP_URL`, shared +`DRAFT_PARTNER_SECRET`, 32+ characters, the same value on both apps). InstantAdPay is the tank's home and the single source of the +pool: its tank.waiting() is already the one network tank (LinkSpin and hub arrivals included, anyone adopted on LinkSpin left out), +so LinkSpin needs no route of its own. Every pick is a real `tank.adopt()` there: the 2-adoption count, the 24-hour grace, rule 3, +the normal "X is now your sponsor" email (the only mail), the sponsor change through sponsorfollow and the hub. InstantAdPay +checks "holds a 5x position" from the coach claim this app signs (positions), a wallet linked there and someone on its contract in +the coach's line. Picks keep their 3-day window there too; whichever sweep runs first, both apps end with the same outcome +(returned / kept / done). A tank refusal about the coach passes the draft slot; a silent tank pauses the draft until the next tick. + + ## Phase 2 (needs Marty's go): see the open questions in the build report -Hub `HUB_SITES` entry `fivex` + secret; `tankpool.js` hub mode (pool read, adopt through the tank, status); the network-sites list +Hub `HUB_SITES` entry `fivex` + secret; `TANK_MODE=iap` + `DRAFT_PARTNER_SECRET` + `IAP_URL` (above); the network-sites list and LinkSpin `nw5x`; the contract on chain with the prize wallet; DOCSTORE_URL; old-member reconciliation; PolHunter mission. diff --git a/config.js b/config.js index 1f55d9e..c0628d8 100644 --- a/config.js +++ b/config.js @@ -59,8 +59,9 @@ function get() { iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''), joinUrl: String(e.JOIN_URL || 'https://instantadpay.com/join/{ref}'), - // the holding tank behind the draft: 'stub' (phase 1, local fixture, adopts nobody for real) | 'hub' (phase 2) - tankMode: /^hub$/i.test(String(e.TANK_MODE || '')) ? 'hub' : 'stub', + // the holding tank behind the draft: 'stub' (phase 1, local fixture, adopts nobody for real) | 'iap' (the real network tank on + // InstantAdPay through its signed partner routes, DRAFT_PARTNER_SECRET + IAP_URL; TANK_MODE=hub means the same) + tankMode: /^(iap|hub)$/i.test(String(e.TANK_MODE || '').trim()) ? 'iap' : 'stub', stubPool: String(e.STUB_POOL_FILE || '').trim(), owner: String(e.OWNER_USERNAME || 'martbost'), // builder fallback links (the DownlineHydra rule) testClock: e.ALLOW_TEST_CLOCK === '1' && e.NODE_ENV !== 'production' diff --git a/draft.js b/draft.js index 125e33d..f7cc2c7 100644 --- a/draft.js +++ b/draft.js @@ -41,7 +41,7 @@ function score(c, now) { if (c.games && Number(c.games.plays) > 0) s += Math.min(40, Number(c.games.plays)); const seen = Number(c.lastSeen) || 0; if (seen) { const age = now - seen; s += age < DAY ? 25 : age < 3 * DAY ? 12 : age < 7 * DAY ? 5 : 0; } - if (c.surfWei && BigInt(c.surfWei) > 0n) s += 10; + if ((c.surfWei && BigInt(c.surfWei) > 0n) || Number(c.surfCredits) > 0) s += 10; // InstantAdPay reports surfing as ad credits earned if (c.games && c.games.earnedWei && BigInt(c.games.earnedWei) > 0n) s += 10; return s; } @@ -118,6 +118,7 @@ function manual(d, coach, person, ctx, now) { function record(d, act, res, now) { if (act.type === 'skip') { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.slot.coach, skipped: act.why, at: now }); d.clockAt = now; } else if (res && res.ok) { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.coach, person: act.person, auto: act.type === 'auto', fromQueue: !!act.fromQueue, pickId: res.pickId || null, at: now }); d.taken.push(act.person); d.clockAt = now; } + else if (res && res.skip) { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.coach, skipped: res.skip, at: now }); d.clockAt = now; } // the tank refused the COACH (no account there, full, ...): the slot passes, nobody is burned else { d.unavailable.push(act.person); } // the tank refused this person (locked a moment ago, adopted elsewhere): the same coach chooses again return d; } @@ -130,6 +131,7 @@ async function run(d, ctx, adopt, now, maxSteps) { if (a.type === 'done') { if (d.status === 'live') finish(d, a.why, now); return d; } if (a.type === 'skip') { record(d, a, null, now); continue; } const res = await adopt(a); + if (res && res.wait) return d; // the tank did not answer: nothing recorded, the next tick tries the same slot again record(d, a, res, now); } return d; diff --git a/league.js b/league.js index 182b290..c9ce4bb 100644 --- a/league.js +++ b/league.js @@ -38,12 +38,16 @@ async function pool(now) { return draft.pool(await candidates(now), store.picks( const ownTeam = id => { const m = store.memberByHub(id); return m && store.positionsOf(m.address) > 0 ? (store.firstPositionAt(m.address) || 1) : 0; }; // ---- a pick = an adoption ---- +// refusals about the COACH (the draft passes their slot instead of marking the person unavailable) and the ones that mean "try later" +const COACH_CODES = new Set(['coach_unknown', 'not_vested', 'no_wallet', 'no_contract_line', 'excluded', 'payout_blocked', 'full', 'hub_off', 'not_eligible', 'bad_coach']); +const WAIT_CODES = new Set(['unreachable', 'no_secret']); async function makePick(coach, person, kind, extra, now) { const c = cands.find(x => x.id === person) || { id: person }; - const r = await tank.adopt({ coach: { address: coach, username: nameOf(coach), hubId: (store.member(coach) || {}).hubId || null }, person, kind }); - if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' }; + const r = await tank.adopt({ coach: { address: coach, username: nameOf(coach), hubId: (store.member(coach) || {}).hubId || null, positions: store.positionsOf(coach) }, person, kind, + week: weekInfo(now).week, slot: extra && extra.slot ? extra.slot : null }); + if (!r || !r.ok) { const code = r && r.code; return { error: (r && r.error) || 'The holding tank did not answer.', code: code || null, skip: COACH_CODES.has(code) ? 'tank: ' + code : null, wait: !r || WAIT_CODES.has(code) }; } const s = (await tank.status([person], now))[person] || {}; - const m = Object.assign({ lastSeen: s.lastSeen || 0, username: s.username || c.username || null, wallet: s.wallet || 0, payouts: s.payouts || 0, purchase: s.purchase || 0, ownTeam: ownTeam(person) }, { door: s.door || c.door || null, games: s.games || c.games || null, surfWei: s.surfWei || c.surfWei || null }); + const m = Object.assign({ lastSeen: s.lastSeen || 0, username: s.username || c.username || null, wallet: s.wallet || 0, payouts: s.payouts || 0, purchase: s.purchase || 0, ownTeam: ownTeam(person) }, { door: s.door || c.door || null, games: s.games || c.games || null, surfWei: s.surfWei || c.surfWei || null, surfCredits: s.surfCredits != null ? s.surfCredits : (c.surfCredits != null ? c.surfCredits : null) }); const p = store.addPick(Object.assign({ week: weekInfo(now).week, kind, coach, coachName: nameOf(coach), person, personName: c.username || s.username || null, door: c.door || null, status: 'open', at: now, expires: now + C.picks.returnDays * D, m, tier: draft.tierOf(m), ref: r.ref || null }, extra || {})); candsAt = 0; // the pool changed @@ -57,12 +61,22 @@ async function sweep(now) { if (!open.length) return { changed: 0 }; const ids = [...new Set(open.map(p => p.person))]; const sts = await tank.status(ids, now); - const statusOf = id => { const s = sts[id]; if (!s) return null; return Object.assign({}, s, { ownTeam: ownTeam(id) }); }; + const statusOf = id => { const s = sts[id]; if (!s) return null; const m = Object.assign({}, s, { ownTeam: ownTeam(id) }); delete m.pick; return m; }; + // the tank closed an open pick on its side (its own 3-day sweep, a release on InstantAdPay, a LinkSpin follow): follow its outcome + for (const p of open.filter(x => x.status === 'open')) { + const s = sts[p.person]; const pk = s && s.pick; if (!pk || !p.ref || pk.ref !== p.ref || pk.status === 'open') continue; + const m = statusOf(p.person); const set = pk.status === 'done' ? { status: 'done', doneAt: now } : pk.status === 'kept' ? { status: 'kept', keptAt: now } : { status: 'returned', returnedAt: now, closedBy: 'tank:' + pk.status }; + Object.assign(p, set, { m, tier: draft.tierOf(m) }); store.savePick(p); candsAt = 0; + } // done / kept picks only refresh their milestones (cards keep levelling up) for (const p of open.filter(x => x.status !== 'open')) { const m = statusOf(p.person); if (m) { const t = draft.tierOf(m); if (t !== p.tier || JSON.stringify(m) !== JSON.stringify(p.m)) { if (t !== p.tier) p.levelAt = now; p.m = m; p.tier = t; store.savePick(p); } } } const ch = draft.sweep(store.picks(), statusOf, rules(), now); for (const c of ch) { - if (c.release) { const r = await tank.release({ coach: c.pick.coach, person: c.pick.person, why: 'return window ended' }); if (!r || !r.ok) continue; } + if (c.release) { + const r = await tank.release({ coach: c.pick.coach, person: c.pick.person, ref: c.pick.ref || null, kind: 'return', why: 'return window ended' }); if (!r || !r.ok) continue; + if (r.outcome === 'kept') c.set = Object.assign({}, c.set, { status: 'kept', keptAt: now }); else if (r.outcome === 'done') c.set = Object.assign({}, c.set, { status: 'done', doneAt: now }); // the tank decides + delete c.set.returnedAt; if (c.set.status === 'returned') c.set.returnedAt = now; + } if (c.set.tier && c.set.tier !== c.pick.tier) c.pick.levelAt = now; // the toast time, on the league clock Object.assign(c.pick, c.set); store.savePick(c.pick); } @@ -118,6 +132,7 @@ async function manualPick(coach, person) { await candidates(now); const act = draft.manual(d, coach, person, ctx(d, now), now); if (act.error) return act; const res = await makePick(coach, person, 'draft', { slot: draft.slotLabel(act.slot), round: act.slot.round, auto: false }, now); + if (res.error && (res.wait || res.skip)) return { error: res.error }; // nothing recorded: the person stays available, the clock keeps running draft.record(d, act, res, now); store.putDraft(d); if (res.error) return res; await advance(d, now); @@ -142,7 +157,8 @@ async function release(coach, pickId) { const now = clock.now(); const p = store.pick(pickId); if (!p || p.coach !== coach) return { error: 'Not your pick.' }; const why = draft.canRelease(p, rules(), now); if (why) return { error: why }; - const r = await tank.release({ coach, person: p.person, why: 'released by the coach' }); if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' }; + const r = await tank.release({ coach, person: p.person, ref: p.ref || null, kind: 'coach', why: 'released by the coach' }); if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' }; + if (r.outcome === 'done') { p.status = 'done'; p.doneAt = now; store.savePick(p); candsAt = 0; return { error: 'They already started, so they stay on your team.' }; } p.status = 'returned'; p.releasedAt = now; p.released = true; store.savePick(p); candsAt = 0; return { ok: true }; }); diff --git a/package.json b/package.json index 258433f..aa2ad29 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "scripts": { "start": "node server.js", "test": "node qa/unit.test.cjs", - "qa": "node qa/smoke.mjs" + "qa": "node qa/smoke.mjs", + "test:iap": "node qa/iap-tank.test.cjs" }, "engines": { "node": ">=20" }, "dependencies": { diff --git a/public/assets/board.js b/public/assets/board.js index dad6963..617dd34 100644 --- a/public/assets/board.js +++ b/public/assets/board.js @@ -37,7 +37,7 @@ else if (coach) act = ''; else act = 'GET A POSITION'; const rows = [['Game plays', p.plays == null ? 'not tracked yet' : FX.n(p.plays)], ['Plays', p.game || (p.plays === 0 ? 'none yet' : p.plays == null ? 'not tracked yet' : 'none yet')]]; - if (coach) rows.push(['Earned in games', pol(p.gameWei)], ['Earned surfing', pol(p.surfWei)]); + if (coach) rows.push(['Earned in games', pol(p.gameWei)], ['Earned surfing', p.surfWei == null && p.surfCredits != null ? FX.n(p.surfCredits) + ' ad credits' : pol(p.surfWei)]); rows.push(['Last seen', FX.ago(p.lastSeen, b.now)], ['Came from', p.door || 'not tracked yet'], ['Wallet', p.wallet ? 'linked' : 'not yet']); return '
@' + esc(p.username || 'player') + '' + (p.hot ? 'HOT' : '') + '
' + rows.map(r => '
' + r[0] + '' + esc(r[1]) + '
').join('') + '
' + act + '
'; diff --git a/public/assets/team.js b/public/assets/team.js index f7589bd..026ff82 100644 --- a/public/assets/team.js +++ b/public/assets/team.js @@ -61,7 +61,7 @@ $('fKick').textContent = label + ' · ' + p.tierName.toUpperCase(); $('fName').textContent = '@' + (p.username || 'player'); $('fWhen').textContent = 'Picked ' + FX.when(p.at) + (p.status === 'open' ? ' · ' + (p.daysLeft ? p.daysLeft + ' day' + (p.daysLeft === 1 ? '' : 's') + ' left to start' : 'goes back to the pool today') : ' · started, stays on your team'); - $('fStats').innerHTML = [['Game plays', p.plays == null ? 'not tracked yet' : FX.n(p.plays) + (p.game ? ' (' + p.game + ')' : '')], ['Earned in games', pol(p.gameWei)], ['Earned surfing', pol(p.surfWei)], ['Came from', p.door || 'not tracked yet'], ['Last seen', FX.ago(p.lastSeen)]] + $('fStats').innerHTML = [['Game plays', p.plays == null ? 'not tracked yet' : FX.n(p.plays) + (p.game ? ' (' + p.game + ')' : '')], ['Earned in games', pol(p.gameWei)], ['Earned surfing', p.surfWei == null && p.surfCredits != null ? FX.n(p.surfCredits) + ' ad credits' : pol(p.surfWei)], ['Came from', p.door || 'not tracked yet'], ['Last seen', FX.ago(p.lastSeen)]] .map(r => '
' + r[0] + '' + esc(r[1]) + '
').join(''); $('fSteps').innerHTML = stepsHtml(p.steps); const h = D.help.find(x => x.pickId === p.id); diff --git a/qa/iap-tank.test.cjs b/qa/iap-tank.test.cjs new file mode 100644 index 0000000..2a5f7ee --- /dev/null +++ b/qa/iap-tank.test.cjs @@ -0,0 +1,143 @@ +// 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' }); + 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); + } 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); }); diff --git a/qa/unit.test.cjs b/qa/unit.test.cjs index 9e7529f..2640ac0 100644 --- a/qa/unit.test.cjs +++ b/qa/unit.test.cjs @@ -126,6 +126,18 @@ const RULES = { maxOpen: 10, maxAdoptions: 2, graceHours: 24, holdHours: 48, ret 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' }); diff --git a/server.js b/server.js index 8a63e3b..785767a 100644 --- a/server.js +++ b/server.js @@ -139,7 +139,7 @@ const isCoach = a => store.positionsOf(a) > 0; function scoutCard(c, full) { const out = { id: c.id, username: c.username || null, door: c.door || null, lastSeen: c.lastSeen || 0, joinedAt: c.joinedAt || 0, wallet: !!c.wallet, score: c.score || 0, hot: (c.score || 0) >= 60, plays: c.games ? Number(c.games.plays) || 0 : null, game: c.games ? c.games.title || null : null }; - if (full) { out.gameWei = c.games ? c.games.earnedWei || null : null; out.surfWei = c.surfWei || null; } + if (full) { out.gameWei = c.games ? c.games.earnedWei || null : null; out.surfWei = c.surfWei || null; out.surfCredits = c.surfCredits == null ? null : c.surfCredits; } return out; } function pickView(p, t) { @@ -147,7 +147,7 @@ function pickView(p, t) { return { id: p.id, person: p.person, username: p.personName || m.username || null, week: p.week, kind: p.kind, slot: p.slot || null, round: p.round || null, status: p.status, at: p.at, expires: p.expires, daysLeft: p.status === 'open' ? Math.max(0, Math.ceil((p.expires - t) / DAY)) : null, tier: p.tier || draft.tierOf(m), tierName: draft.TIER_NAME[p.tier || draft.tierOf(m)], door: p.door || m.door || null, lastSeen: m.lastSeen || 0, steps: draft.steps(m), plays: m.games ? Number(m.games.plays) || 0 : null, game: m.games ? m.games.title || null : null, - gameWei: m.games ? m.games.earnedWei || null : null, surfWei: m.surfWei || null, unread: store.msgsOfPick(p.id).filter(x => x.dir === 'in' && !x.read).length }; + gameWei: m.games ? m.games.earnedWei || null : null, surfWei: m.surfWei || null, surfCredits: m.surfCredits == null ? null : m.surfCredits, unread: store.msgsOfPick(p.id).filter(x => x.dir === 'in' && !x.read).length }; } // a trading card: milestones only, never earnings (public) function cardView(p) { diff --git a/tankpool.js b/tankpool.js index 869cc9e..c8f81d1 100644 --- a/tankpool.js +++ b/tankpool.js @@ -13,16 +13,21 @@ // 'stub' (phase 1, TANK_MODE unset): a local fixture (STUB_POOL_FILE, else qa/fixtures/pool.json) with relative times, adoption // state in the document stub-tank.json. It adopts nobody for real and sends no mail. Admin test routes can move a person's // milestones (POST /api/admin/stub/status) so the coaching tools, cards and boards can be exercised. -// 'hub' (phase 2): NOT WIRED. Every call answers { error } / [] so nothing is drafted. What it needs (open for Marty + the hub): -// - a pool read: the network tank's waiting list (InstantAdPay tank.waiting() is the source today, the hub has no tank route) -// with rule 3 applied (hub /v1/locked detail), username, door (hub joinedVia), last seen, wallet linked -// - scouting stats where they exist: game plays + POL earned (game wallet watchers), surf earnings (IAP ads.earnedTotals) -// - adopt: the tank's own adopt (so the 2-adoption count, the hold, the adoption email and the Telegram line stay in one place), -// e.g. IAP POST /api/admin/tank/adopt with the coach as adopter, then hub /v1/sponsor-change { by: 'adopt' } -// - status: payouts on / first purchase per person (IAP memberId + chain Purchase), hub /v1/activity/person for last seen +// 'iap' (phase 2, TANK_MODE=iap; 'hub' is read the same): the REAL network holding tank on InstantAdPay, through its signed partner +// routes (InstantAdPay site/draftpartner.js, 2026-11-15). One secret both sides, DRAFT_PARTNER_SECRET (32+ characters), sent as +// X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256('draft.v1.' + ts + newline + raw body); IAP_URL is the base. +// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card] } +// POST /api/partner/draft/adopt { rid, coach: { wallet, hubId, username, positions }, person, kind, week, slot } -> { ok, ref } | { error, code } +// POST /api/partner/draft/release { rid, coach: { wallet }, ref, person, why: 'coach' | 'return' } -> { ok, outcome } | { error, code } +// POST /api/partner/draft/status { ids } -> { ok, people: { id: milestones + pick | null } } +// InstantAdPay runs tank.adopt() for every pick (the 2-adoption count, the 24 h grace, rule 3, the normal adoption email, the hub's +// sponsor change) and checks "holds a 5x position" from the coach claim this app signs (positions = store.positionsOf). It owns the +// 3-day window too (its hourly sweep returns unstarted picks); this app's own sweep calls release(why 'return') and takes +// InstantAdPay's outcome (returned / kept / done). A call that fails answers { error } / [] / null: nothing is drafted or moved. 'use strict'; const fs = require('fs'); const path = require('path'); +const crypto = require('crypto'); const H = 3600000, D = 86400000; let C = null, mode = 'stub', fixture = null, nowFn = () => Date.now(); @@ -37,9 +42,34 @@ function init(cfg, opts) { try { fixture = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { fixture = { people: [] }; console.error('tankpool: no stub pool at', f); } fixture.base = nowFn(); // relative times are measured from boot console.log('tankpool: STUB mode (' + fixture.people.length + ' fixture people, nobody is adopted for real, no mail)'); - } else console.log('tankpool: hub mode is not wired yet (phase 2): the pool is empty and no pick can be made'); + } else console.log('tankpool: InstantAdPay mode (' + C.iapBase + '/api/partner/draft/*' + (secret() ? '' : ', DRAFT_PARTNER_SECRET MISSING: every call refuses') + ')'); } const isStub = () => mode === 'stub'; +// ---- the InstantAdPay client ---- +const secret = () => { const s = String(process.env.DRAFT_PARTNER_SECRET || '').trim(); return s.length >= 32 ? s : ''; }; +const remote = { calls: 0, failed: 0, lastError: null, lastPool: 0 }; +async function call(op, body, timeoutMs) { + const sec = secret(); if (!sec) return { error: 'The holding tank is not connected (no DRAFT_PARTNER_SECRET).', code: 'no_secret' }; + const raw = JSON.stringify(body || {}); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', sec).update('draft.v1.' + ts + '\n' + raw).digest('hex'); + remote.calls++; + try { + const r = await fetch(C.iapBase + '/api/partner/draft/' + op, { method: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs || 15000), headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig } }); + const j = await r.json().catch(() => null); + if (!j || typeof j !== 'object') throw new Error('InstantAdPay answered ' + r.status + ' with no JSON'); + if (r.status >= 500 || r.status === 401 || r.status === 404) throw new Error('InstantAdPay answered ' + r.status + (j.error ? ': ' + j.error : '')); + return j; // 200 { ok ... } or 400 { error, code } + } catch (e) { + remote.failed++; remote.lastError = { at: Date.now(), op, error: String(e.name === 'TimeoutError' ? 'timeout' : e.message).slice(0, 160) }; + console.error('tankpool:', op, 'failed:', remote.lastError.error); + return { error: 'The holding tank did not answer.', code: 'unreachable', transient: true }; + } +} +const rid = () => 'fx-' + Date.now().toString(36) + '-' + crypto.randomBytes(6).toString('hex'); +// a card from InstantAdPay -> the candidate shape draft.js reads (InstantAdPay already left out locked / sponsored / spam / twice) +const candOf = c => ({ id: String(c.id), username: c.username || null, joinedAt: Number(c.joinedAt) || 0, lastSeen: Number(c.lastSeen) || 0, door: c.door || null, wallet: !!c.wallet, + locked: false, sponsored: false, spam: false, throwaway: false, adoptions: Number(c.adoptions) || 0, games: c.games || null, surfWei: c.surfWei || null, + surfCredits: c.surfCredits == null ? null : Number(c.surfCredits) || 0, opensAt: Number(c.opensAt) || 0, ready: !!c.ready, holdUntil: Number(c.holdUntil) || 0 }); const ago = (h, base) => (h == null ? 0 : base - h * H); // a fixture person at time `now` (relative hours), with any admin override applied function person(p, s, now) { @@ -52,20 +82,35 @@ function person(p, s, now) { } async function candidates(now) { - if (!isStub()) return []; + if (!isStub()) { const r = await call('pool', {}); if (!r.ok || !Array.isArray(r.pool)) return []; remote.lastPool = r.pool.length; return r.pool.filter(c => c && c.id).map(candOf); } const s = st(); now = now || nowFn(); return fixture.people.filter(p => !s.adopted[p.id]).map(p => { const x = person(p, s, now); return Object.assign(x, { wallet: !!x.wallet }); }) .filter(x => !x.payouts && !x.purchase); // payouts on = out of the tank (the IAP rule) } async function status(ids, now) { - const out = {}; if (!isStub()) { for (const id of ids) out[id] = null; return out; } + const out = {}; + if (!isStub()) { + for (const id of ids) out[id] = null; + for (let i = 0; i < ids.length; i += 500) { + const r = await call('status', { ids: ids.slice(i, i + 500) }); if (!r.ok || !r.people) continue; // the network cannot say: nothing changes + for (const [id, s] of Object.entries(r.people)) if (s) out[id] = { lastSeen: Number(s.lastSeen) || 0, username: s.username || null, wallet: Number(s.wallet) || 0, payouts: Number(s.payouts) || 0, + purchase: Number(s.purchase) || 0, games: s.games || null, surfWei: s.surfWei || null, surfCredits: s.surfCredits == null ? null : Number(s.surfCredits) || 0, adoptions: Number(s.adoptions) || 0, door: s.door || null, pick: s.pick || null }; + } + return out; + } const s = st(); now = now || nowFn(); for (const id of ids) { const p = fixture.people.find(x => x.id === id); if (!p) { out[id] = null; continue; } const x = person(p, s, now); out[id] = { lastSeen: x.lastSeen, username: x.username, wallet: x.wallet, payouts: x.payouts, purchase: x.purchase, games: x.games, surfWei: x.surfWei, adoptions: x.adoptions, door: x.door }; } return out; } async function adopt(o) { - if (!isStub()) return { error: 'The holding tank is not connected yet.' }; + if (!isStub()) { + const c = o.coach || {}; const body = { rid: rid(), coach: { wallet: c.address, hubId: c.hubId || null, username: c.username || null, positions: Number(c.positions) || 0 }, + person: o.person, kind: o.kind || 'draft', week: o.week || null, slot: o.slot || null, note: o.note || '' }; + let r = await call('adopt', body); + if (r.transient) r = await call('adopt', body); // one retry with the SAME rid: InstantAdPay answers the first result, never two adoptions + return r.ok ? { ok: true, ref: r.ref || null, expires: r.expires || null } : { error: r.error || 'The holding tank refused.', code: r.code || null }; + } const s = st(); const p = fixture.people.find(x => x.id === o.person); if (!p) return { error: 'Not in the holding tank.' }; if (p.locked) return { error: 'Locked on a network contract.' }; @@ -76,7 +121,11 @@ async function adopt(o) { return { ok: true, ref: 'stub:' + p.id }; } async function release(o) { - if (!isStub()) return { error: 'The holding tank is not connected yet.' }; + if (!isStub()) { + const body = { rid: rid(), coach: { wallet: o.coach }, ref: o.ref || null, person: o.person, why: o.kind === 'return' || /window/.test(o.why || '') ? 'return' : 'coach' }; + let r = await call('release', body); if (r.transient) r = await call('release', body); + return r.ok ? { ok: true, outcome: r.outcome || 'returned', already: !!r.already } : { error: r.error || 'The holding tank refused.', code: r.code || null }; + } const s = st(); if (!s.adopted[o.person]) return { ok: true }; delete s.adopted[o.person]; s.log.push({ at: nowFn(), release: o.person, why: o.why || '' }); put(s); return { ok: true }; } @@ -87,5 +136,5 @@ function setStatus(id, patch) { for (const k of ['wallet', 'payouts', 'purchase', 'seen']) if (patch[k] !== undefined) o[k] = patch[k] ? (typeof patch[k] === 'number' ? patch[k] : t) : 0; put(s); return { ok: true, over: o }; } -function view() { if (!C) return {}; const s = isStub() ? st() : null; return { mode, fixture: fixture ? fixture.people.length : 0, adopted: s ? Object.keys(s.adopted).length : 0, adoptionMailsThatWouldSend: s ? s.mails : 0, log: s ? s.log.slice(-20) : [] }; } +function view() { if (!C) return {}; const s = isStub() ? st() : null; return { mode, remote: isStub() ? null : Object.assign({ url: C.iapBase, secret: !!secret() }, remote), fixture: fixture ? fixture.people.length : 0, adopted: s ? Object.keys(s.adopted).length : 0, adoptionMailsThatWouldSend: s ? s.mails : 0, log: s ? s.log.slice(-20) : [] }; } module.exports = { init, candidates, status, adopt, release, setStatus, view, isStub, H, D };