Files
linkspin/qa/tank-hold.test.mjs
T

487 lines
44 KiB
JavaScript

// 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');
// since 2026-11-11 the cap is people held at one time who have not switched on payouts (default 10): fill A up by hand
for (let i = 0; i < tank.capOpen(); i++) { accounts.add('fill' + i + '@x.co'); await tank.adopt('a@x.co', 'fill' + i + '@x.co'); }
// 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 ----------------
// ---------------- Sign-up grace + "Who invited you?" (Marty approved 2026-11-07) ----------------
async function partGrace() {
console.log('-- Sign-up grace + Who invited you: tank.js with a mocked clock');
const M = 60000;
{ // hand adoption: blocked for 24 hours from created, open after, old members untouched
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('new@x.co', { created: t0 - H }); accounts.add('old@x.co');
const w = await tank.waiting(); const row = w.find(x => x.email === 'new@x.co');
ok(row && row.opensAt === t0 + 23 * H, 'waiting(): new sign-up carries opensAt = created + 24 h', JSON.stringify(row));
ok(w.find(x => x.email === 'old@x.co').opensAt === 0, 'waiting(): an old account is open now');
ok(w[w.length - 1].email === 'new@x.co', 'waiting(): grace members sort after the open ones');
ok((await tank.adoptable()).every(x => x.email !== 'new@x.co'), 'adoptable() leaves out grace members (Overview note, weekly email)');
const r = await tank.adopt('ad@x.co', 'new', 'hi');
ok(r.error && /less than 24 hours/.test(r.error) && /23 h 0 min/.test(r.error), 'grace blocks a hand adoption with a plain message', JSON.stringify(r));
ok(!(await accounts.byEmail('new@x.co')).sponsorRef, '...and writes no sponsor');
ok(!B.mails.length && !B.chats.length, '...and tells nobody');
env.now = t0 + 23 * H - M;
ok((await tank.adopt('ad@x.co', 'new', 'hi')).error, 'still blocked one minute before it opens');
env.now = t0 + 23 * H + M;
const r2 = await tank.adopt('ad@x.co', 'new', 'hi');
ok(r2.ok, 'opens after 24 hours', JSON.stringify(r2));
const r3 = await tank.adopt('ad@x.co', 'old', 'hi');
ok(r3.ok, 'an old account is adoptable at once (back in the tank later = no grace)', JSON.stringify(r3));
}
{ // wallet in the first hour: hand adoption opens at 24 h, the safety net keeps its own clock
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11); B.buyer('ad2@x.co', 12);
accounts.add('w@x.co', { created: t0 });
env.now = t0 + H; accounts._by.get('w@x.co').address = addr(); accounts._by.get('w@x.co').lastSeen = env.now;
const t1 = await tank.readyTick();
ok(t1.fresh.length === 0, 'wallet in the first hour: no "adopt them" notice during the grace', JSON.stringify(t1.fresh));
const h = await tank.holdFor(await accounts.byEmail('w@x.co'));
ok(h.hold.since === t0 + H && h.hold.until === t0 + 25 * H, 'the hold clock runs from the wallet link, not stretched by the grace', JSON.stringify(h.hold));
env.now = t0 + 23 * H; ok((await tank.readyTick()).fresh.length === 0, 'still no notice at 23 hours');
ok((await tank.adopt('ad@x.co', 'w', 'hi')).error, 'hand adoption refused at 23 hours');
env.now = t0 + 24 * H + M; for (const em of ['ad@x.co', 'ad2@x.co']) accounts._by.get(em).lastSeen = env.now;
const t2 = await tank.readyTick();
ok(t2.fresh.length === 1 && t2.fresh[0].until === t0 + 25 * H && !t2.assigned.length, 'grace over: notice once, with the real end of the hold', JSON.stringify(t2.fresh));
ok(tank.leftText(t2.fresh[0].until - env.now) === '59 min', 'the notice text can say the time really left', tank.leftText(t2.fresh[0].until - env.now));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
env.now = t0 + 25 * H - 10 * M;
const t3 = await tank.readyTick();
ok(t3.assigned.length === 1 && t3.assigned[0].adoptee === 'w@x.co', 'the rotation takes them inside 24 hours of the wallet link', JSON.stringify(t3.assigned));
}
{ // wallet in the first minutes: the rotation fires just before the grace ends, no notice ever goes out
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('fast@x.co', { created: t0, address: addr() });
env.now = t0 + 5 * M; ok((await tank.readyTick()).fresh.length === 0, 'wallet in minute 5: no notice');
env.now = t0 + 24 * H - 5 * M; accounts._by.get('ad@x.co').lastSeen = env.now;
const t = await tank.readyTick();
ok(t.assigned.length === 1 && t.fresh.length === 0, 'auto path unaffected: assigned inside the grace (24 h from the wallet link), no adopt notice', JSON.stringify({ a: t.assigned, f: t.fresh }));
ok((await accounts.byEmail('fast@x.co')).sponsorRef === 'ad', 'the safety net wrote the sponsor');
}
{ // grace ends in the last tick of the hold: the safety net takes them, nobody is told to adopt someone already gone
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('mid@x.co', { created: t0 });
env.now = t0 + 10 * M; accounts._by.get('mid@x.co').address = addr(); await tank.readyTick();
env.now = t0 + 24 * H + M; accounts._by.get('ad@x.co').lastSeen = env.now; // 9 minutes of hold left: inside the last tick
const t = await tank.readyTick();
ok(t.assigned.length === 1 && t.fresh.length === 0, 'no notice for someone the rotation takes in the same tick', JSON.stringify({ a: t.assigned, f: t.fresh }));
}
{ // the arrivals post: announced when the grace ends
const B = bench(); const { tank, env } = B; const t0 = env.now;
const list = [{ email: 'a', joined: t0 - 24 * H - 5 * M }, { email: 'b', joined: t0 - 24 * H - 20 * M }, { email: 'c', joined: t0 - H }];
ok(tank.openedSince(list, t0 - 15 * M).map(x => x.email).join() === 'a', 'openedSince: only people whose grace ended since the last check');
}
{ // Who invited you: every refusal, nothing written
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21);
accounts.add('m@x.co', { username: 'mm1', created: t0 });
accounts.add('kid@x.co', { username: 'kid', sponsorRef: 'mm1' }); // joined under m: a loop
accounts.add('free@x.co', { username: 'free' }); // no payouts, nobody above them
accounts.add('under@x.co', { username: 'under', sponsorRef: 'boss' }); // no payouts, but boss above them
accounts.add('has@x.co', { username: 'hassp', sponsorRef: 'boss' });
accounts.add('bound@x.co', { username: 'bound1', memberId: 55 });
const say = async (e, who) => { const r = await tank.nameSponsor(e, who); return r.error || ''; };
ok(/Type the username/.test(await say('m@x.co', ' ')), 'refused: empty');
ok(/That is you/.test(await say('m@x.co', '@MM1')), 'refused: self (any case, leading @)');
ok(/No member here/.test(await say('m@x.co', 'nosuchname')), 'refused: unknown username');
ok(/No member here/.test(await say('m@x.co', 'bad name!')), 'refused: not a username');
ok(/already have a sponsor/.test(await say('has@x.co', 'boss')), 'refused: already sponsored');
ok(/locked on the contract/.test(await say('bound@x.co', 'boss')), 'refused: member id');
ok(/in your own line/.test(await say('m@x.co', 'kid')), 'refused: chain loop (inDownlineOf)');
ok(/nobody above them/.test(await say('m@x.co', 'free')), 'refused: nobody on the contract in that line (would fall to the company)');
B.blocked.add(21);
ok(/cannot take new members/.test(await say('m@x.co', 'boss')), 'refused: no-payout chain');
B.blocked.delete(21);
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'no refusal wrote a sponsor or sent a notice');
const c = await tank.nameSponsor('m@x.co', 'boss', { check: true });
ok(c.ok && c.name === '@boss' && !(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'check mode validates and writes nothing', JSON.stringify(c));
ok((await tank.nameSponsor('m@x.co', 'under', { check: true })).ok, 'a sponsor with no payouts but someone above them on the contract is allowed');
B.net['m2@x.co'] = { sponsorEmail: 'boss@x.co', via: 'email' };
accounts.add('m2@x.co', { username: 'mm2' });
const al = await tank.nameSponsor('m2@x.co', 'under');
ok(al.error && al.aligned && (await accounts.byEmail('m2@x.co')).sponsorRef === 'boss', 'the sponsor the network already knows comes first', JSON.stringify(al));
}
{ // Who invited you: success
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
accounts.add('m@x.co', { username: 'mm1', created: t0 });
const m0 = await accounts.byEmail('m@x.co');
ok(tank.inviteAsk(m0) && tank.inviteAsk(m0).dismissed === false, 'inviteAsk: the card shows for a tank member');
ok(tank.inviteAsk(await accounts.byEmail('boss@x.co')) === null, 'inviteAsk: no card for a member with a sponsor line / member id');
tank.dismissInvite('m@x.co');
ok(tank.inviteAsk(m0).dismissed === true, 'Nobody invited me: card dismissed');
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && (await tank.waiting()).some(w => w.email === 'm@x.co'), '...nothing else changes: still in the tank');
const r = await tank.nameSponsor('m@x.co', '@Boss');
ok(r.ok && r.name === '@boss', 'prompt success', JSON.stringify(r));
const a = await accounts.byEmail('m@x.co');
ok(a.sponsorRef === 'boss', 'sponsor written');
ok((await tank.holdFor(a)) === null && tank.inviteAsk(a) === null, 'hold gone, card gone');
ok(!(await tank.waiting()).some(w => w.email === 'm@x.co'), 'out of the waiting list');
ok(B.mails.length === 1 && B.mails[0].to === 'boss@x.co' && /new referral/.test(B.mails[0].subject), 'the named sponsor gets the notice, nobody else', JSON.stringify(B.mails.map(x => x.to)));
ok(!B.chats.length, 'no chat written in the sponsor\'s name');
const v = await tank.adminView(); const rec = v.adoptions.find(x => x.adoptee === 'm@x.co');
ok(rec && rec.status === 'invited' && rec.adopter === 'boss@x.co', 'admin record: status invited');
ok((await tank.summaryFor('m@x.co')) === null, 'not an adoption: nothing counts toward the two, nothing open on the other site');
const again = await tank.nameSponsor('m@x.co', 'ad');
ok(/already have a sponsor/.test(again.error || '') && (await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'a second name is refused');
env.now = t0 + 8 * 86400000; await tank.sweep();
ok((await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'no 7-day window: still theirs after a week');
}
{ // a ready member names someone: the hold record clears the way an adoption does, no auto-assign
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
accounts.add('r@x.co', { username: 'rr1', created: t0, address: addr() });
await tank.readyTick();
ok(tank.readyRec('r@x.co'), 'setup: on the 24-hour clock');
const r = await tank.nameSponsor('r@x.co', 'boss');
ok(r.ok && !tank.readyRec('r@x.co'), 'the hold record clears', JSON.stringify(r));
env.now = t0 + 24 * H;
for (const em of ['boss@x.co', 'ad@x.co']) accounts._by.get(em).lastSeen = env.now;
ok(!(await tank.readyTick()).assigned.length && (await accounts.byEmail('r@x.co')).sponsorRef === 'boss', 'the rotation leaves them alone');
await sleep(40);
ok(B.sends.length === 1 && B.sends[0].sponsorId === 21, 'wallet linked: the engine switches payouts on under the named sponsor, same as an adoption', JSON.stringify(B.sends));
const B2 = bench(); B2.buyer('boss@x.co', 21); const w = addr(); B2.accounts.add('c@x.co', { username: 'cc1', address: w }); B2.onchain.set(w, 77);
ok(/locked on the contract/.test((await B2.tank.nameSponsor('c@x.co', 'boss')).error || ''), 'refused: wallet already on the contract, member number not saved yet');
}
}
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 a = { email: 'qa-sponsor@example.com', pass: null, sponsorRef: '', code: 'cqasp1', username: 'qasponsor', address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, memberId: 42 }; // a member with a contract position, for the Who invited you checks
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify({ v: 2, byEmail: { [a.email]: a }, byAddress: {}, byCode: { [a.code]: a.email }, joins: 0, positions: {} })); }
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));
{ // Who invited you + the sign-up grace, on the real pages (2026-11-07)
const nc = await signIn('qa-new@example.com'); await req('POST', '/api/my/profile', { cookie: nc, body: { username: 'qanewone' } });
const m0 = (await req('GET', '/api/me', { cookie: nc })).json;
ok(m0 && m0.inviteAsk && m0.inviteAsk.dismissed === false, '/api/me: inviteAsk for a tank member', JSON.stringify(m0 && m0.inviteAsk));
const sc = await signIn('qa-sponsor@example.com');
const tv = (await req('GET', '/api/my/tank', { cookie: sc })).json; const row6 = tv && tv.waiting.find(w => w.email === 'qa-new@example.com');
ok(row6 && row6.opensAt > Date.now(), '/api/my/tank: a new sign-up is listed with opensAt', JSON.stringify(row6));
const bad = await req('POST', '/api/my/tank/invited', { cookie: nc, body: { who: 'nosuchname' } });
ok(bad.status === 400 && /No member here/.test(bad.json.error), 'POST invited: unknown username refused', JSON.stringify(bad.json));
const self = await req('POST', '/api/my/tank/invited', { cookie: nc, body: { who: 'qanewone' } });
ok(self.status === 400 && /That is you/.test(self.json.error), 'POST invited: self refused', JSON.stringify(self.json));
ok((await req('POST', '/api/my/tank/invited', { body: { who: 'qasponsor' } })).status === 401, 'POST invited: signed out refused');
const c2 = await browser.newContext({ viewport: { width: 390, height: 900 } });
await c2.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} });
await c2.addCookies(nc.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 pg = await c2.newPage(); pg.on('pageerror', e => errs.push(e.message));
await pg.goto(BASE + '/links', { waitUntil: 'load' }); await pg.waitForSelector('#crInvite', { timeout: 15000 }).catch(() => {});
const has = sel => pg.evaluate(s => !!document.querySelector(s), sel);
ok(await has('#inviteWho'), 'Control Room (/links): Who invited you box shows');
const over = await pg.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
ok(over <= 0, 'no sideways scroll at phone width', String(over));
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-invite-card.png') }).catch(() => {});
await pg.fill('#inviteWho', 'nosuchname'); await pg.click('#inviteGo'); await pg.waitForTimeout(700);
ok(/No member here/.test(await pg.textContent('#inviteMsg')), 'box: the refusal shows in the box');
await pg.click('#inviteNo'); await pg.waitForTimeout(500);
ok(!(await has('#crInvite')), 'Nobody invited me: gone from the screen');
await pg.goto(BASE + '/links', { waitUntil: 'load' }); await pg.waitForTimeout(2500);
ok(!(await has('#crInvite')), 'stays gone on the next screen');
await pg.goto(BASE + '/tools', { waitUntil: 'load' }); await pg.waitForSelector('#inviteBack', { timeout: 15000 }).catch(() => {});
ok(await has('#inviteBack'), '/tools: the small link is there');
await pg.click('#inviteBack'); await pg.fill('#inviteWho', '@qasponsor'); await pg.click('#inviteGo'); await pg.waitForSelector('#dlgNo', { timeout: 5000 });
await pg.click('#dlgNo'); await pg.waitForTimeout(400);
ok(!(await req('GET', '/api/me', { cookie: nc })).json.sponsorName, 'box: Not them writes nothing');
await pg.click('#inviteGo'); await pg.waitForSelector('#dlgOk', { timeout: 5000 }); await pg.click('#dlgOk'); await pg.waitForTimeout(3000);
const m1 = (await req('GET', '/api/me', { cookie: nc })).json;
ok(m1 && m1.sponsorName === '@qasponsor' && !m1.inviteAsk, 'box: yes sets the sponsor, the box is gone', JSON.stringify({ n: m1 && m1.sponsorName, a: m1 && m1.inviteAsk }));
ok(!(await has('#crInvite')), 'box: gone after the reload');
const adm6 = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json;
ok(adm6.adoptions.some(a => a.adoptee === 'qa-new@example.com' && a.status === 'invited'), 'admin tank: the invited record shows');
await c2.close();
ok(!errs.length, 'no page errors (Who invited you)', 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();
await partGrace();
if (process.argv[2] !== 'unit') await partB();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
process.exit(fails ? 1 : 0);