Files
linkspin/qa/override.test.cjs
T
martbost 010c3afdd9 Level 4 override for LinkSpin: weekly dry-run report + the payer, shipped OFF (Marty approved 2026-10-23)
override.js is the InstantAdPay module (same code, same tests) with LinkSpin defaults: qualification is the
LinkSpin contract's own buyerCount >= 5 (referred first buys of $20+, which on the $10/$25/... ladder means
$25+, the level-3 bar), house id #1, hunt up to 25 hops, one recipient per purchase, purchases from
overrideGoLive on, weekly Mon-Sun Central, settled Monday after 9 AM CT.

- Default overrideMode 'dryrun': Monday who-would-be-paid summary to the admin Telegram chat
  (telegramAdminChatId; email to ADMIN_EMAIL if the bot is not set). No money moves.
- Payer pays only with overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY. LinkSpin has no MySQL,
  so every once-only step is an exclusive file create on the shared volume (fails closed); plan frozen
  per week, 'sending' persisted before the tx, lost answers -> review (never re-sent), dust carried,
  weekly cap held whole, balance + gas checked first.
- Members: AwardPaid from the payer emails + on-site notice "Your Level 4 override is paid"; Wallet
  screen and feeds label it "Level 4 override". /api/my/activity now reads the whole history (was the
  last 600 events, the IAP bug of 2026-09-16; LinkSpin is at 525).
- Admin: /api/admin/override (+ status, payer), POST /pay (live only), POST /resolve; P&L card.
- Contract page: Level 4 override panel hidden until overrideMode is live (contract.js reveals it).
- qa/override.test.cjs (bash qa/run.sh override): 30 checks, fake chain/signer, throwaway data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:20:02 -05:00

237 lines
19 KiB
JavaScript

// Level-4 override payer tests (2026-10-23, LinkSpin copy of the InstantAdPay suite; same module). Throwaway DATA_DIR in the OS temp folder, a FAKE chain, a FAKE signer and a
// FAKE database: nothing here touches Polygon, the production volume or a real member. Run: node qa/override.test.cjs
'use strict';
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
const OV = require(path.join(__dirname, '..', 'override.js'));
const { create, weekOf, weekBounds, payableAt, polStr, toWei } = OV;
const E = 10n ** 18n;
let pass = 0, fail = 0;
async function test(name, fn) { try { await fn(); pass++; console.log(' ok ' + name); } catch (e) { fail++; console.log(' FAIL ' + name + '\n ' + (e && e.stack || e).toString().split('\n').slice(0, 3).join('\n ')); } }
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ovtest-'));
const tickAsync = () => new Promise(r => setImmediate(r));
// ---- fakes ----
// tree: spec { id: [sponsorId, buyerCount] }
function fakeChain(tree, purchases, extraEvents) {
const events = purchases.map((p, i) => Object.assign({ type: 'Purchase', tx: '0xbuy' + i, li: 0, block: 1000 + i }, p)).concat(extraEvents || []);
return {
events,
member: async id => { await tickAsync(); const t = tree[id]; if (!t) return { sponsorId: 0, buyerCount: 0 }; return { sponsorId: t[0], buyerCount: t[1] }; },
recentEvents: () => events,
getConfig: () => ({ explorer: 'https://polygonscan.example', contract: '0xcontract', chainId: 137 }),
suggestedFees: async () => ({ maxPriorityFeePerGas: '0x' + (30n * 10n ** 9n).toString(16), maxFeePerGas: '0x' + (100n * 10n ** 9n).toString(16) })
};
}
function fakePayer(balanceWei, opts) {
const o = opts || {}; let n = 0;
const p = { address: '0x00000000000000000000000000000000000000aa', bal: BigInt(balanceWei), sends: [], opts: o,
balance: async () => { await tickAsync(); return p.bal; },
fees: async () => ({ maxFeePerGas: 100n * 10n ** 9n, maxPriorityFeePerGas: 30n * 10n ** 9n }),
preflight: async id => { await tickAsync(); if ((o.reject || []).includes(id)) throw Object.assign(new Error('execution reverted'), { reason: 'Send failed' }); },
send: async (id, wei) => {
await tickAsync(); await tickAsync();
if ((o.throwOn || []).includes(id)) throw new Error('server response 502');
p.sends.push({ id, wei: BigInt(wei) }); p.bal -= BigInt(wei); const hash = '0x' + (++n).toString(16).padStart(64, '0');
return { hash, wait: async () => { await tickAsync(); return { status: 1 }; } };
} };
return p;
}
function fakeDb(opts) {
const set = new Set(); const o = opts || {};
return { set, enabled: () => true, q: async (sql, params) => {
await tickAsync();
if (o.broken) throw new Error('connection lost');
if (/^INSERT IGNORE INTO event_marks/.test(sql)) { if (set.has(params[0])) return { affectedRows: 0 }; set.add(params[0]); return { affectedRows: 1 }; }
throw new Error('unexpected sql ' + sql);
} };
}
function instance(o) {
const ov = create(); const sent = [];
ov.init({ dataDir: o.dir, chain: o.chain, db: o.db || null, payer: o.payer, now: () => o.clock.t, siteConfig: () => o.site, notify: async t => { (o.tg || sent).push(t); return true; } });
return ov;
}
// a world: buyers under a qualified #10 (6 buyers) four levels up; #20 unqualified (2 buyers) is skipped once
const WK1 = '2026-10-26', WK2 = '2026-11-02';
const goLive = weekBounds(WK1).from;
const TREE = { 1: [0, 99], 10: [1, 6], 20: [10, 2], 30: [20, 0], 40: [30, 0], 50: [40, 0], 60: [50, 0],
// a short line under the company: 70 -> 71 -> 1
71: [1, 1], 70: [71, 0],
// #11 (qualified, 5 buyers) is the 4th upline of #81
11: [1, 5], 12: [11, 0], 13: [12, 0], 14: [13, 0], 81: [14, 0] };
const at = (wk, h) => weekBounds(wk).from + h * 3600000;
const buy = (buyerId, cents, pol, ts) => ({ buyerId, priceCents: cents, paidWei: (toWei(String(pol))).toString(), ts });
(async () => {
console.log('override.test: week math');
await test('weekOf: Sunday 11:30 PM CT belongs to the week before, Monday 12:30 AM CT to the new week', () => {
assert.strictEqual(weekOf(Date.parse('2026-10-26T04:30:00Z')), '2026-10-19'); // Sun 23:30 CDT
assert.strictEqual(weekOf(Date.parse('2026-10-26T05:30:00Z')), '2026-10-26'); // Mon 00:30 CDT
});
await test('week across the November DST change: Mon 00:00 CDT to Mon 00:00 CST (169 hours)', () => {
const b = weekBounds('2026-10-26');
assert.strictEqual(new Date(b.from).toISOString(), '2026-10-26T05:00:00.000Z');
assert.strictEqual(new Date(b.to).toISOString(), '2026-11-02T06:00:00.000Z');
assert.strictEqual((b.to - b.from) / 3600000, 169);
assert.strictEqual(weekOf(Date.parse('2026-11-02T05:30:00Z')), '2026-10-26'); // Sun 23:30 CST
});
await test('week across the March DST change: 167 hours', () => { const b = weekBounds('2027-03-08'); assert.strictEqual((b.to - b.from) / 3600000, 167); });
await test('payable from 9 AM Central the Monday after', () => { assert.strictEqual(new Date(payableAt('2026-10-19')).toISOString(), '2026-10-26T14:00:00.000Z'); assert.strictEqual(new Date(payableAt('2026-10-26')).toISOString(), '2026-11-02T15:00:00.000Z'); });
await test('polStr / toWei round trip', () => { assert.strictEqual(polStr(toWei('12.3456')), '12.3456'); assert.strictEqual(toWei('0.01'), 10n ** 16n); });
console.log('override.test: who gets it');
const clock = { t: payableAt(WK1) + 3600000 };
await test('hunt: 4th upline #20 (2 buyers) is skipped, #10 (6 buyers) gets it with 1 hop', async () => {
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(60); // 60 -> 50, 40, 30, [20 skipped], 10
assert.strictEqual(r.recipientId, 10); assert.strictEqual(r.hops, 1); assert.deepStrictEqual(r.skipped, [{ id: 20, buyers: 2 }]);
});
await test('exactly 5 buyers qualifies (#11 for #81)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(81)).recipientId, 11); });
await test('house: a hunt that reaches #1 leaves it with the company', async () => {
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(40); // 40 -> 30, 20, 10, 1 : 4th up is #1
assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /company account #1/);
});
await test('overrideHouseIds can add company positions (#10 as house)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: { overrideHouseIds: '1,10' }, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(60)).recipientId, 0); });
await test('short line: company keeps it', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.match((await ov.recipientFor(70)).reason, /shorter than 4/); });
await test('hunt cap: 30 unqualified uplines above the 4th, nobody within 25 hops', async () => {
const t = { 1: [0, 99] }; for (let i = 200; i < 240; i++) t[i] = [i + 1, 0]; t[240] = [1, 0]; t[199] = [200, 0];
const ov = instance({ dir: tmp(), chain: fakeChain(t, []), clock, site: {}, payer: fakePayer(0) });
const r = await ov.recipientFor(199); assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /within 25 hops/); assert.strictEqual(r.skipped.length, 25);
});
console.log('override.test: the payer');
const PUR = [buy(60, 2000, 200, at(WK1, 30)), buy(60, 5000, 500, at(WK1, 50)), buy(81, 2000, 200, at(WK1, 60)), buy(40, 2000, 200, at(WK1, 70)),
buy(60, 2000, 200, goLive - 3600000) /* before go-live: never paid */, buy(81, 500, 0.2, at(WK2, 10)) /* next week */];
const LIVE = { overrideMode: 'live', overrideGoLive: goLive };
await test('default mode is dry run: nothing planned, nothing sent', async () => {
const dir = tmp(), payer = fakePayer(1000n * E); const ov = instance({ dir, chain: fakeChain(TREE, PUR), clock, site: { overrideGoLive: goLive }, payer });
const r = await ov.payDue(); assert.strictEqual(r.ready, false); assert.match(r.why.join(), /dryrun/); assert.strictEqual(payer.sends.length, 0);
assert.ok(!fs.existsSync(path.join(dir, 'override', 'weeks')));
});
await test('live without overrideGoLive is not ready', async () => { const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock, site: { overrideMode: 'live' }, payer }); assert.strictEqual(ov.liveState().ready, false); await ov.payDue(); assert.strictEqual(payer.sends.length, 0); });
await test('live without a payer key is not ready (real key path)', async () => { delete process.env.OVERRIDE_PAYER_KEY; const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => LIVE }); assert.match(ov.liveState().why.join(), /no payer key/); });
await test('a week is not planned before it closes, nor paid before Monday 9 AM CT', async () => {
const c2 = { t: weekBounds(WK1).to + 3600000 }; const payer = fakePayer(1000n * E); // Monday 1 AM
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock: c2, site: LIVE, payer });
assert.deepStrictEqual(ov.dueWeeks(), []); await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
assert.deepStrictEqual(ov.dueWeeks(true), [WK1]); // the admin's "pay this week now" may settle a closed week early
});
await test('two payers at once (deploy overlap, shared DB + volume): each recipient paid exactly once', async () => {
const dir = tmp(), db = fakeDb(), payer = fakePayer(1000n * E), tg = [], chain = fakeChain(TREE, PUR);
const A = instance({ dir, chain, db, payer, clock, site: LIVE, tg }), B = instance({ dir, chain, db, payer, clock, site: LIVE, tg });
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
const by = {}; for (const s of payer.sends) by[s.id] = (by[s.id] || 0n) + s.wei;
assert.strictEqual(payer.sends.length, 2, 'two recipients, two sends: ' + JSON.stringify(payer.sends.map(s => s.id)));
assert.strictEqual(by[10], toWei('21')); // 3% of 200 + 500 POL (two buys by #60)
assert.strictEqual(by[11], toWei('6')); // 3% of 200 POL
const st = A.weekStatus(WK1); assert.strictEqual(st.state, 'paid'); assert.ok(st.rows.every(r => r.state === 'paid' && r.txHash));
assert.strictEqual(tg.filter(t => /PAID/.test(t)).length, 1, 'one paid summary'); assert.match(tg.find(t => /PAID/.test(t)), /polygonscan\.example\/tx\//);
await Promise.all([A.payDue(), B.payDue()]); assert.strictEqual(payer.sends.length, 2, 'a second pass sends nothing');
});
await test('two payers at once with NO database (LinkSpin JSON mode): file claims alone hold', async () => {
const dir = tmp(), payer = fakePayer(1000n * E), chain = fakeChain(TREE, PUR);
const A = instance({ dir, chain, payer, clock, site: LIVE }), B = instance({ dir, chain, payer, clock, site: LIVE });
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
assert.strictEqual(payer.sends.length, 2);
});
await test('a database that errors fails closed: nothing is planned or sent', async () => {
const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), db: fakeDb({ broken: true }), payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'not planned');
});
await test('purchases before overrideGoLive are never paid (no back-pay)', async () => {
const payer = fakePayer(1000n * E); const late = { overrideMode: 'live', overrideGoLive: at(WK1, 55) }; // after #60's buys, before #81's
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: late });
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [11]);
});
await test('dust: under 0.01 POL is carried, then rolled into the next week and paid', async () => {
const dir = tmp(), payer = fakePayer(1000n * E);
const P = [buy(81, 500, 0.2, at(WK1, 30)), buy(81, 2000, 200, at(WK2, 30))]; // week 1: 3% of 0.2 = 0.006 POL
const ck = { t: clock.t }; const ov = instance({ dir, chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
const s1 = ov.weekStatus(WK1); assert.strictEqual(s1.state, 'paid'); assert.strictEqual(s1.rows[0].state, 'carried');
ck.t = payableAt(WK2) + 60000; await ov.payDue();
assert.strictEqual(payer.sends.length, 1); assert.strictEqual(payer.sends[0].wei, toWei('6.006'));
assert.strictEqual(ov.weekStatus(WK1).rows[0].state, 'rolled'); assert.deepStrictEqual(ov.weekStatus(WK2).rows[0].carriedFrom, [WK1]);
});
await test('a dust amount that stays under the minimum keeps carrying', async () => {
const payer = fakePayer(1000n * E), P = [buy(81, 500, 0.1, at(WK1, 30)), buy(81, 500, 0.1, at(WK2, 30))];
const ck = { t: payableAt(WK2) + 60000 }; const ov = instance({ dir: tmp(), chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK2).rows[0].state, 'carried'); assert.strictEqual(ov.weekStatus(WK2).rows[0].amountWei, toWei('0.006').toString());
});
await test('cap: a week over overridePayCapPol is held whole, nothing sent, one alert', async () => {
const tg = [], payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: Object.assign({ overridePayCapPol: 20 }, LIVE), tg });
await ov.payDue(); await ov.payDue();
assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); assert.match(ov.weekStatus(WK1).heldWhy, /cap/);
assert.strictEqual(tg.filter(t => /HELD/.test(t)).length, 1);
});
await test('a held week stops the weeks after it', async () => {
const payer = fakePayer(1000n * E), ck = { t: payableAt(WK2) + 60000 };
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: Object.assign({ overridePayCapPol: 20 }, LIVE) });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK2).state, 'not planned'); assert.strictEqual(payer.sends.length, 0);
});
await test('insufficient balance: held with a clear message, then pays once funded', async () => {
const tg = [], payer = fakePayer(26n * E); // needs 27 POL + gas
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE, tg });
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.match(ov.weekStatus(WK1).heldWhy, /holds 26\.0000 POL, needs 27\.0300/);
assert.match(tg.join(), /Fund it/);
payer.bal = 27n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 0, 'still short of the gas reserve');
payer.bal = 28n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
});
await test('a wallet that would refuse POL: pre-flight catches it, nothing sent, carried', async () => {
const payer = fakePayer(1000n * E, { reject: [11] }); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE });
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [10]);
const r11 = ov.weekStatus(WK1).rows.find(r => r.memberId === 11); assert.strictEqual(r11.state, 'carried'); assert.match(r11.note, /Send failed/);
assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
});
await test('a send whose answer is lost becomes review, is never re-sent, and blocks later weeks until resolved', async () => {
const tg = [], payer = fakePayer(1000n * E, { throwOn: [11] }), ck = { t: payableAt(WK2) + 60000 };
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: LIVE, tg });
await ov.payDue(); await ov.payDue(); await ov.payDue();
assert.deepStrictEqual(payer.sends.map(s => s.id), [10], 'only #10 went out, #11 never retried');
assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
assert.strictEqual(ov.weekStatus(WK2).state, 'not planned');
assert.strictEqual(tg.filter(t => /needs review/.test(t)).length, 1);
const bad = await ov.resolve(WK1, 11, 'paid', '0xnot-a-real-tx'); assert.ok(bad.error, 'an unverifiable tx is refused');
payer.opts.throwOn = []; // the node is healthy again
await ov.resolve(WK1, 11, 'carry'); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(payer.sends[1].id, 11); // week 2 pays #11: carried 6 + 0.006
assert.strictEqual(payer.sends[1].wei, toWei('6.006'));
});
await test('a review row is settled from the chain index when the AwardPaid shows up', async () => {
const payer = fakePayer(1000n * E, { throwOn: [11] }), chain = fakeChain(TREE, PUR);
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
chain.events.push({ type: 'AwardPaid', tx: '0xlanded', from: payer.address, toId: 11, amountWei: toWei('6').toString(), ts: clock.t });
await ov.payDue(); const r = ov.weekStatus(WK1).rows.find(x => x.memberId === 11); assert.strictEqual(r.state, 'paid'); assert.strictEqual(r.txHash, '0xlanded');
assert.strictEqual(payer.sends.length, 1); assert.ok(ov.txInfo('0xLANDED'));
});
await test('a plan is frozen: a buyer count that changes after planning does not change the amounts', async () => {
const tree = JSON.parse(JSON.stringify(TREE)); const payer = fakePayer(26n * E), chain = fakeChain(tree, PUR);
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); // planned, short of funds
tree[20][1] = 9; // #20 qualifies later
payer.bal = 100n * E; await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id).sort(), [10, 11]);
});
await test('dry run Monday report: once per week across two copies, says no money moved', async () => {
const dir = tmp(), tg = [], chain = fakeChain(TREE, PUR), mon = { t: payableAt(WK1) + 600000 };
const A = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) }), B = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) });
await Promise.all([A.tick(), B.tick(), A.tick()]);
assert.strictEqual(tg.length, 1); assert.match(tg[0], /DRY RUN/); assert.match(tg[0], /No money moved/); assert.match(tg[0], /\$0\.21|\$2\.10/);
});
await test('payer status never exposes a key', async () => {
process.env.OVERRIDE_PAYER_KEY = '0x' + '11'.repeat(32);
const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => ({}) });
const s = JSON.stringify(ov.liveState()) + JSON.stringify(Object.assign({}, await ov.payerStatus().catch(e => ({ e: e.message }))));
assert.ok(!s.includes('1111111111'), 'no key material'); delete process.env.OVERRIDE_PAYER_KEY;
});
console.log('override.test: ' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
})();