// Holding tank on LinkSpin (2026-10-27): network ALIGNMENT first, the plain-activation hold, the 24-hour rotation, and // payouts switched on the moment someone is assigned. node qa/tank-hold.test.mjs (or: bash qa/run.sh tankhold) // Marty's rules under test: align with the network sponsor first; NEVER hold a purchase ("they'll just pay number one"); // hold only the free Switch on payouts for someone nobody knows; never fall back to #1 for an assigned member. // Part A, no server: the real tank.js + carry.js with in-memory accounts, a fake chain, a fake engine sender (no key, no // RPC) and a MOCKED CLOCK (tank.setClock); marks.js on a throwaway dir for the cross-copy claims. // Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, no ENGINE_KEY, a throwaway LS_SYNC_SECRET and // IAP_URL pointed at a mock InstantAdPay on 127.0.0.1 that answers sponsor-facts): /api/me + /api/sponsor per intent, // live alignment, a sponsored member never held, admin tank, the Credits screen in a browser. Never production. import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import http from 'node:http'; import crypto from 'node:crypto'; import { spawn } from 'node:child_process'; import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); const require = createRequire(path.join(SITE, 'package.json')); delete process.env.DATABASE_URL; delete process.env.ENGINE_KEY; delete process.env.ENGINE_KEY_FILE; let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra && !cond ? ' ' + extra : '')); if (!cond) fails++; }; const sleep = ms => new Promise(r => setTimeout(r, ms)); const H = 3600000; const addr = () => '0x' + crypto.randomBytes(20).toString('hex'); // ---------------- Part A ---------------- function fakeAccounts() { const by = new Map(); let n = 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' + (n++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H }, 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 setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; }, async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = Number(id) || 0; return { ok: true }; }, async listAll() { return [...by.values()].map(pub); }, 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)); } }; } function bench() { for (const f of ['tank.js', 'carry.js', 'marks.js']) delete require.cache[require.resolve(path.join(SITE, f))]; const tank = require(path.join(SITE, 'tank.js')); const carry = require(path.join(SITE, 'carry.js')); const marks = require(path.join(SITE, 'marks.js')); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-')); marks.init({ dataDir: dir }); const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {}; const iap = new Set(); const blocked = new Set(); const onchain = new Map(); const sends = []; const env = { now: Date.now(), failSends: 0 }; let nextId = 500; const chain = { recentEvents: () => events.slice().reverse(), getConfig: () => ({ explorer: 'https://polygonscan.com' }), memberCount: async () => 10000, memberIdByAccount: async a => onchain.get(String(a).toLowerCase()) || 0 }; carry.init({ dataDir: dir, accounts, chain, siteConfig: () => ({ defaultSponsorId: 1, carryNotices: '0' }), messages: { deliver: async () => {} }, tankGate: (a, o) => tank.gate(a, o), claim: k => marks.claim(k), now: () => env.now, payoutBlocked: async id => blocked.has(id), sendActivate: async (address, sponsorId) => { sends.push({ address: address.toLowerCase(), sponsorId }); await sleep(5); if (env.failSends > 0) { env.failSends--; return { id: 0, txHash: null, lastErr: new Error('gas price spike (test)') }; } const id = nextId++; onchain.set(address.toLowerCase(), id); return { id, txHash: '0x' + crypto.randomBytes(32).toString('hex'), lastErr: null }; } }); tank.init({ dataDir: dir, accounts, chain, messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 }, mailer: { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } }, site: 'https://linkspin.test', hooks: { network: async e => net[e] || null, iapOwns: async e => iap.has(e), payoutBlocked: async id => blocked.has(id), companyId: () => 1, lifted: e => carry.activateAssigned(e), claim: k => marks.claim(k), bound: async a => onchain.get(String(a.address).toLowerCase()) || 0, assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); } } }); tank.setClock(() => env.now); let block = 1000; const buyer = (email, memberId, o) => { const w = addr(); const a = accounts.add(email, Object.assign({ memberId, address: w, lastSeen: env.now - H }, o || {})); onchain.set(w, memberId); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2500, block: block++ }); return a; }; return { tank, carry, marks, accounts, events, chats, mails, alerts, assigned, net, iap, blocked, onchain, sends, env, buyer, dir }; } async function partA() { console.log('-- Part A: tank.js + carry.js, mocked clock, fake engine'); { // the hold is for the plain activation only; a purchase never waits const B = bench(); const { tank, carry, accounts, env, sends } = B; const t0 = env.now; accounts.add('free@x.co'); const h0 = await tank.holdFor(await accounts.byEmail('free@x.co')); ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: hold record, no clock yet'); accounts._by.get('free@x.co').address = addr(); const id0 = await carry.ensureOnChain(await accounts.byEmail('free@x.co'), 0, 'wallet'); ok(id0 === 0 && sends.length === 0, 'wallet linked, nobody known: the engine does NOT switch payouts on under #1'); const h1 = await tank.holdFor(await accounts.byEmail('free@x.co')); ok(h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'clock started at the wallet link, until = +24 h'); ok(carry.status().log.some(e => e.type === 'tankHold' && e.email === 'free@x.co'), 'the hold is logged in carry state'); accounts.add('kid@x.co', { sponsorRef: 'someone', address: addr() }); ok((await tank.holdFor(await accounts.byEmail('kid@x.co'))) === null, 'a member with a sponsor is never held'); // a sponsor placed on the contract because someone below is BUYING: never held (today's fallback stands) accounts.add('upl@x.co', { address: addr() }); accounts.add('buyer@x.co', { sponsorRef: 'upl', address: addr() }); const sid = await carry.ensureOnChain(await accounts.byEmail('upl@x.co'), 0); ok(sid > 0 && sends.length === 1 && sends[0].sponsorId === 1, 'tank member whose referral is buying: activated (under #1, the purchase is never held)', JSON.stringify(sends)); const w = await tank.waiting(); const fr = w.find(x => x.email === 'free@x.co'); ok(w[0] && w[0].email === 'free@x.co' && fr.ready && fr.holdUntil === t0 + 24 * H && fr.wallet, 'waiting(): ready member on top with holdUntil'); } { // ALIGN FIRST: the network knows a sponsor const B = bench(); const { tank, carry, accounts, net, sends } = B; B.buyer('boss@x.co', 31); accounts.add('t1@x.co', { address: addr() }); net['t1@x.co'] = { sponsorEmail: 'boss@x.co', via: 'same email' }; const id = await carry.ensureOnChain(await accounts.byEmail('t1@x.co'), 0, 'wallet'); ok(id > 0 && sends.length === 1 && sends[0].sponsorId === 31 && (await accounts.byEmail('t1@x.co')).sponsorRef === 'boss', 'InstantAdPay knows the sponsor: aligned and switched on under #31, not held, not #1', JSON.stringify(sends)); ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @boss from InstantAdPay'), 'alignment recorded with the reason'); accounts.add('t2@x.co', { address: addr() }); net['t2@x.co'] = { sponsorEmail: 'boss@x.co', via: 'same wallet' }; const h2 = await tank.holdFor(await accounts.byEmail('t2@x.co')); ok(h2 && h2.aligned && h2.aligned.via === 'same wallet', '/api/me path: aligned (by wallet), not held'); await sleep(40); ok(sends.some(s => s.sponsorId === 31 && s.address === (B.accounts._by.get('t2@x.co').address)), '...and payouts switched on under the aligned sponsor right away'); accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' }; ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'network sponsor with no LinkSpin account: held'); accounts.add('t4@x.co', { sponsorRef: 'boss' }); const rel = await tank.release('boss@x.co', 't4@x.co'); ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel)); net['t4@x.co'] = { sponsorEmail: 'boss@x.co' }; ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them'); accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' }; ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline'); } { // 24-hour rotation + activation right away under the adopter const B = bench(); const { tank, accounts, env, sends, chats, mails } = B; const t0 = env.now; accounts.add('free@x.co', { address: addr() }); B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13); B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16); const tk = await tank.readyTick(); ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh)); ok((await tank.readyTick()).fresh.length === 0, '...and not twice'); ok(tk.assigned.length === 0, 'not assigned before 24 h'); env.now = t0 + 24 * H - 10 * 60000; const r1 = await tank.readyTick(); ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', '24 h: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned)); const fa = await accounts.byEmail('free@x.co'); ok(fa.sponsorRef === 'a' && fa.memberId > 0, 'assigned AND on the contract right away', JSON.stringify({ s: fa.sponsorRef, id: fa.memberId })); ok(sends.length === 1 && sends[0].sponsorId === 11, 'engine activation under the adopter #11, never #1', JSON.stringify(sends)); const ch = chats.find(c => c.from === 'a@x.co' && c.to === 'free@x.co'); ok(ch && /Your payouts are now on under @a/.test(ch.text) && /https:\/\/polygonscan\.com\/tx\/0x[0-9a-f]{64}/.test(ch.text), 'assignment chat says payouts are on under @a with the Polygonscan link', ch && ch.text); ok(mails.some(m => m.to === 'free@x.co' && /Your payouts are now on under @a/.test(m.text)) && mails.some(m => m.to === 'a@x.co' && /their payouts are switched on under you/.test(m.text)), 'both sides emailed (member email carries the payouts line)'); ok((await tank.adminView()).adoptions[0].note === 'auto-assigned after 24 hours in the tank', 'adoption record note'); ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup "(auto-assigned)")'); // B next; then C (stale D, company E, no-payout F skipped); then back to A accounts.add('free2@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H; const r2 = await tank.readyTick(); ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: B next', JSON.stringify(r2.assigned)); accounts.add('free3@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H; const r3 = await tank.readyTick(); ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned)); // activation fails (gas): stays assigned, retried next tick, never #1 B.env.failSends = 1; for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H; accounts.add('free4@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H; for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H; const n0 = sends.length; const r4 = await tank.readyTick(); const f4 = await accounts.byEmail('free4@x.co'); ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co' && f4.sponsorRef === 'a' && !f4.memberId, 'rotation wraps to A; activation failed, sponsor kept, not on the contract yet', JSON.stringify({ a: r4.assigned, f4 })); env.now += 15 * 60000; const r5 = await tank.readyTick(); // the next tick, a new claim window const f4b = await accounts.byEmail('free4@x.co'); ok(f4b.memberId > 0 && sends.slice(n0).every(s => s.sponsorId === 11), 'retried on a later tick and switched on under A (#11), never #1', JSON.stringify(sends.slice(n0))); ok(chats.some(c => c.to === 'free4@x.co' && /Your LinkSpin payouts are now on under @a/.test(c.text)), 'follow-up chat once the retried activation lands'); // A full (2 open), B + C stale: nobody eligible -> keep holding, one admin alert accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000; accounts.add('free5@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H; const r6 = await tank.readyTick(); const f5 = await accounts.byEmail('free5@x.co'); ok(r6.assigned.length === 0 && r6.held === 1 && !f5.sponsorRef && !f5.memberId, 'nobody eligible: keeps holding, never the company'); ok(B.alerts.length === 1 && /free5@x\.co/.test(B.alerts[0]), 'admin alerted once'); await tank.readyTick(); await tank.sweep(); ok(B.alerts.length === 1, 'no second alert'); void r5; } { // manual adoption of a ready member: payouts on right away, follow-up chat with the link const B = bench(); const { tank, accounts, sends, chats } = B; accounts.add('m1@x.co', { address: addr() }); B.buyer('ad@x.co', 41); await tank.readyTick(); const r = await tank.adopt('ad@x.co', 'm1', 'Hi there'); ok(r.ok, 'manual adopt ok', JSON.stringify(r)); await sleep(60); const m1 = await accounts.byEmail('m1@x.co'); ok(m1.memberId > 0 && sends.length === 1 && sends[0].sponsorId === 41, 'manual adoption: engine activation under the adopter #41', JSON.stringify(sends)); ok(chats.some(c => c.from === 'ad@x.co' && c.to === 'm1@x.co' && /payouts are now on under @ad/.test(c.text) && /polygonscan\.com\/tx\//.test(c.text)), 'member told in chat: payouts on under @ad with the Polygonscan link'); } { // cross-site + cross-copy guards const B = bench(); const { tank, carry, accounts, env, sends, iap } = B; accounts.add('both@x.co', { address: addr() }); B.buyer('a@x.co', 11); iap.add('both@x.co'); const t1 = await tank.readyTick(); ok(t1.fresh.length === 0, 'someone in the InstantAdPay tank: not announced here (InstantAdPay posts it)'); env.now += 24 * H; const t2 = await tank.readyTick(); ok(t2.assigned.length === 0 && t2.deferred === 1 && !(await accounts.byEmail('both@x.co')).sponsorRef, 'InstantAdPay owns the auto-assign: LinkSpin defers'); iap.delete('both@x.co'); await B.marks.claim('tankauto:both@x.co:' + Math.floor(env.now / 600000)); // the other app copy already took this window const t3 = await tank.readyTick(); ok(t3.assigned.length === 0, 'deploy overlap: the window claimed by another copy, this copy does not assign'); env.now += 15 * 60000; for (const a of accounts._by.values()) if (a.email === 'a@x.co') a.lastSeen = env.now - H; const t4 = await tank.readyTick(); ok(t4.assigned.length === 1, 'next window: assigned once'); // two concurrent activations of the same member: one send accounts.add('dup@x.co', { address: addr(), sponsorRef: 'a' }); const [x, y] = await Promise.all([carry.activateAssigned('dup@x.co'), carry.activateAssigned('dup@x.co')]); ok(sends.filter(s => s.address === accounts._by.get('dup@x.co').address).length === 1 && ((x.id && !y.id) || (!x.id && y.id)), 'two concurrent activations: exactly one engine send', JSON.stringify([x, y])); accounts.add('dup2@x.co', { address: addr(), sponsorRef: 'a' }); await B.marks.claim('tankact:dup2@x.co:' + Math.floor(env.now / 600000)); const z = await carry.activateAssigned('dup2@x.co'); ok(!z.id && z.retry, 'another app copy holds the activation claim: nothing sent, retried later', JSON.stringify(z)); B.blocked.add(11); accounts.add('nop@x.co', { address: addr(), sponsorRef: 'a' }); const q = await carry.activateAssigned('nop@x.co'); ok(!q.id && /no-payout/.test(q.error), 'sponsor on a no-payout chain: not activated', JSON.stringify(q)); accounts.add('nowal@x.co', { address: addr(), sponsorRef: 'shellsp' }); accounts.add('shellsp@x.co', { username: 'shellsp' }); const n = await carry.activateAssigned('nowal@x.co'); ok(!n.id && n.retry && /no wallet/.test(n.error), 'sponsor without a wallet: not activated (never #1), retried', JSON.stringify(n)); } } // ---------------- Part B ---------------- async function partB() { console.log('-- Part B: local copy + mock InstantAdPay'); const PORT = Number(process.env.TANKHOLD_PORT || 8803), IAPPORT = PORT + 1; const BASE = 'http://127.0.0.1:' + PORT; const ADMIN_PW = 'localtest-th'; const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads')); const SECRET = crypto.randomBytes(24).toString('hex'); // throwaway const iapRows = {}; let factsCalls = 0; const mock = http.createServer((req, res) => { let d = ''; req.on('data', c => d += c); req.on('end', () => { const sig = crypto.createHmac('sha256', SECRET).update(String(req.headers['x-ls-ts'] || '') + '\n' + d).digest('hex'); if (sig !== req.headers['x-ls-sig']) { res.writeHead(401); return res.end('{"error":"bad signature"}'); } let b = {}; try { b = JSON.parse(d || '{}'); } catch (e) {} let out = { ok: true, proto: 2 }; if (req.url === '/api/partner/sponsor-facts') { factsCalls++; out = { ok: true, proto: 2, platform: 'instantadpay', rows: (b.emails || []).map(e => iapRows[e]).filter(Boolean), view: {} }; } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(out)); }); }); await new Promise(r => mock.listen(IAPPORT, '127.0.0.1', r)); const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@th.test', LS_SYNC_SECRET: SECRET, IAP_URL: 'http://127.0.0.1:' + IAPPORT }); for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'ENGINE_KEY_FILE', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_KEY', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY']) delete env[k]; const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d); let browser = null; const req = (method, p, o) => new Promise((resolve, reject) => { o = o || {}; const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 QA', 'X-Forwarded-For': o.ip || '10.8.0.1' }, o.headers || {}); if (o.cookie) headers.Cookie = o.cookie; let body = o.body; if (body) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; headers['Content-Length'] = body.length; } const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, json: j, text: buf.toString() }); }); }); r.on('error', reject); if (body) r.write(body); r.end(); }); let ipn = 1; async function signIn(email, extraCookie) { const ip = '10.8.' + (ipn++) + '.7'; const s = await req('POST', '/api/auth/email/start', { ip, cookie: extraCookie, body: { email, fts: Date.now() - 8000, hp_field_x9: '' } }); if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.text.slice(0, 200)); const v = await req('POST', '/api/auth/email/verify', { ip, cookie: extraCookie, body: { email, code: s.json.devCode } }); const c = [].concat(v.headers['set-cookie'] || []).map(x => x.split(';')[0]).join('; '); return extraCookie ? c + '; ' + extraCookie : c; } const { ethers } = require('ethers'); async function linkWallet(cookie) { const w = ethers.Wallet.createRandom(); const c = await req('POST', '/api/auth/challenge', { cookie, body: { address: w.address } }); const signature = await w.signMessage(c.json.message); return (await req('POST', '/api/auth/verify', { cookie, body: { address: w.address, signature } })).json; } const ADMIN = { Authorization: 'Bearer ' + ADMIN_PW }; try { let up = false; for (let i = 0; i < 60 && !up; i++) { try { up = (await req('GET', '/api/config')).status === 200; } catch (e) { await sleep(500); } } if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500)); // 1. nobody knows them: tankHold on /api/me, the free activation held, a purchase NOT held const tc = await signIn('qa-tank@example.com'); await req('POST', '/api/my/profile', { cookie: tc, body: { username: 'qatankone' } }); const lw = await linkWallet(tc); ok(lw && lw.linked, 'tank member links a wallet', JSON.stringify(lw)); const me = (await req('GET', '/api/me', { cookie: tc })).json; ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold)); ok(me && me.sponsorBlocked !== 'tankHold', '/api/me never blocks (the buy flow reads it)', JSON.stringify({ b: me && me.sponsorBlocked })); const act = (await req('GET', '/api/sponsor?intent=activate', { cookie: tc })).json; ok(act && act.sponsorBlocked === 'tankHold' && !act.sponsorId && act.tankHold && act.tankHold.until === me.tankHold.until, 'Switch on payouts (intent=activate): held, no fallback sponsor', JSON.stringify({ id: act && act.sponsorId, b: act && act.sponsorBlocked })); const buy = (await req('GET', '/api/sponsor?intent=buy', { cookie: tc })).json; ok(buy && !buy.sponsorBlocked && !buy.tankHold, 'a PURCHASE (intent=buy) is never held, no hold text', JSON.stringify({ id: buy && buy.sponsorId, b: buy && buy.sponsorBlocked, h: buy && buy.tankHold })); const adm = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json; const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com'); ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: Ready with holdUntil'); // 2. InstantAdPay knows their sponsor (live signed sponsor-facts): aligned, not held const bc = await signIn('qa-boss@example.com'); await req('POST', '/api/my/profile', { cookie: bc, body: { username: 'qaboss' } }); iapRows['qa-tank2@example.com'] = { email: 'qa-tank2@example.com', sponsorEmail: 'qa-boss@example.com', sponsorRef: 'qaboss', memberId: 0, wallet: true, joinedVia: null, lastSeen: Date.now() }; const tc2 = await signIn('qa-tank2@example.com'); const me2 = (await req('GET', '/api/me', { cookie: tc2 })).json; ok(me2 && !me2.tankHold && me2.sponsorName === '@qaboss', 'IAP knows the sponsor: aligned on /api/me, not held', JSON.stringify({ h: me2 && me2.tankHold, n: me2 && me2.sponsorName })); const act2 = (await req('GET', '/api/sponsor?intent=activate', { cookie: tc2 })).json; ok(act2 && act2.sponsorBlocked !== 'tankHold', '...and the free activation is not held', JSON.stringify(act2 && act2.sponsorBlocked)); const adm2 = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json; ok(adm2.aligned && adm2.aligned.some(x => x.email === 'qa-tank2@example.com' && x.to === 'qa-boss@example.com' && x.via === 'InstantAdPay sponsor'), 'admin tank lists the alignment (via InstantAdPay sponsor)'); ok(factsCalls >= 1, 'the live lookup went to the (mock) InstantAdPay, signed'); // 3. joined through a link: never held const jc = await signIn('qa-kid@example.com', 'iap.sponsor=qaboss'); await linkWallet(jc); const me3 = (await req('GET', '/api/me', { cookie: jc })).json; ok(me3 && !me3.tankHold, 'member who joined through a sponsor link: no hold', JSON.stringify(me3 && me3.tankHold)); // 4. the Credits screen: hold note, no Switch on payouts button, the buy button still there const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; let chromium = null; try { chromium = (await import(pathToFileURL(PW + '/index.js').href)).default.chromium; } catch (e) { console.log('SKIP browser check (no Playwright at ' + PW + ')'); } if (chromium) { browser = await chromium.launch(); const ctx = await browser.newContext({ viewport: { width: 390, height: 900 } }); await ctx.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} }); await ctx.addCookies(tc.split('; ').filter(Boolean).map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message)); await page.goto(BASE + '/credits', { waitUntil: 'load' }); await page.waitForFunction(() => { const w = document.getElementById('walletBox'); return w && w.textContent.trim().length > 0; }, null, { timeout: 30000 }).catch(() => {}); await page.waitForTimeout(500); const st = await page.evaluate(() => { const n = document.getElementById('tankHoldNote'); const hb = document.getElementById('holdBox'); return { note: n ? n.textContent : null, act: !!document.getElementById('activateBtn'), buy: !!document.getElementById('buyBtn'), hold: hb && !hb.hidden ? hb.textContent : null, wb: (document.getElementById('walletBox') || {}).textContent || null, url: location.href }; }); ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'Credits: hold text with time left', JSON.stringify(st)); ok(!st.act && st.buy && !st.hold, 'Credits: no Switch on payouts button, Buy still there, no hold box on the buy side', JSON.stringify(st)); try { fs.mkdirSync(path.join(SITE, 'qa/out'), { recursive: true }); await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-credits.png'), fullPage: true }); } catch (e) {} ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200)); } } finally { if (browser) await browser.close().catch(() => {}); try { srv.kill(); } catch (e) {} mock.close(); await sleep(500); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} } } await partA(); if (process.argv[2] !== 'unit') await partB(); console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed'); process.exit(fails ? 1 : 0);