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>
This commit is contained in:
martbost
2026-10-23 15:20:02 -05:00
parent 1c2ef3780c
commit 010c3afdd9
23 changed files with 693 additions and 23 deletions
+38 -5
View File
@@ -80,6 +80,7 @@ const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays',
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
const PORT = Number(process.env.PORT || 3000);
const ROOT = __dirname;
@@ -706,6 +707,10 @@ async function boot() {
}
setTimeout(() => burner.tick().catch(e => console.error('burner', e.message)), 45 * 1000);
setInterval(() => burner.tick().catch(e => console.error('burner', e.message)), 5 * 60 * 1000);
// level-4 override: Monday report (dry run) or the weekly payer (live); summaries to Marty's admin Telegram, email fallback
override.init({ dataDir: DATA_DIR, chain, siteConfig, db, brand: 'LinkSpin', siteUrl: SITE_URL,
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) { await telegramSend(sc.telegramAdminChatId, text); return true; } if (ADMIN_EMAIL && mailer.hasKey()) { await mailer.send(ADMIN_EMAIL, 'LinkSpin: level-4 override', text.replace(/<[^>]+>/g, '')); return true; } return false; } });
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
if (OUTBOUND_MAIL) { // same for the lead follow-up sequence
setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000);
setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000);
@@ -986,7 +991,11 @@ async function emailOnEvent(ev) {
buyer + ' just bought an ad package on your level ' + ev.tier + (pur ? ' ($' + (pur.priceCents / 100).toFixed(2).replace(/\.00$/, '') + ')' : '') + '. Your ' + pct + ' percent share, ' + pol + ' POL' + usdShare(pur, pct) + ', landed in your wallet in the same transaction' + (ev.hops ? ', passed up to you because someone between you was not qualified for this level' : '') + '.\n\n' +
'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
}
else if (ev.type === 'AwardPaid') await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
else if (ev.type === 'AwardPaid') {
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
}
else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') {
// the member WAS qualified but their wallet rejected the POL (usually a smart-contract
// wallet that needs more than the capped gas): tell them and the admin, loudly
@@ -1019,7 +1028,7 @@ async function telegramOnEvent(ev) {
const sc = siteConfig();
if (!sc.telegramBotToken || !ev) return;
if (!sc.telegramChatId && !sc.telegramEchoChatId) return;
const names = await accounts.namesForMembers([ev.recipientId, ev.buyerId, ev.sponsorId, ev.newBuyerId, ev.id].filter(Boolean)).catch(() => ({}));
const names = await accounts.namesForMembers([ev.recipientId, ev.buyerId, ev.sponsorId, ev.newBuyerId, ev.id, ev.toId].filter(Boolean)).catch(() => ({}));
const who = id => '#' + id + (names[id] ? ' @' + names[id] : '');
const cc = chain.getConfig();
const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx;
@@ -1028,7 +1037,7 @@ async function telegramOnEvent(ev) {
if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.recipientId);
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package';
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} Award payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
if (!line) return null;
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
@@ -3350,10 +3359,11 @@ const server = http.createServer(async (req, res) => {
if (!s) return json(res, 401, { error: 'Sign in first.' });
const id = s.memberId || await auth.refreshMemberId(s);
if (!id) return json(res, 200, { memberId: 0, earnings: [], purchases: [], referrals: [] });
const evs = chain.recentEvents(600);
const evs = chain.recentEvents(1e9); // whole history (was the last 600: IAP lost older members' earnings that way on 2026-09-16)
return json(res, 200, {
memberId: id,
earnings: await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id))),
earnings: (await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id))))
.map(e => { const ov = e.type === 'AwardPaid' && override.txInfo(e.tx); return ov ? Object.assign({}, e, { override: true, overrideWeek: ov.week }) : e; }), // level-4 override label
// buys from the member's linked positions count too (Marty's #353 bought a package that Credits never showed, 2026-10-18);
// position = 2, 3 ... in the order the positions were added, null = the main wallet
purchases: await (async () => {
@@ -3656,6 +3666,29 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r);
}
// -- level-4 override (2026-10-23): ?week=YYYY-MM-DD (any day of the week) or ?from=&to= (ms); rows=1 adds every purchase.
// Carries the week's payout status and the payer state; pay-now and resolve work only while the live payer is ready.
if (p === '/api/admin/override' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const from = Number(u.searchParams.get('from')), to = Number(u.searchParams.get('to'));
const r = from && to ? await override.report(from, to) : await override.week(u.searchParams.get('week') || '');
if (u.searchParams.get('rows') !== '1') delete r.rows;
r.payer = await override.payerStatus().catch(e => ({ error: e.message }));
r.dueWeeks = override.dueWeeks(true).slice(-8).map(w => override.weekStatus(w));
return json(res, 200, r, { 'Cache-Control': 'no-store' });
}
if (p === '/api/admin/override/pay' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const live = override.liveState(); if (!live.ready) return json(res, 400, { error: 'The payer is off: ' + live.why.join('; ') });
const b = await readBody(req); const wk = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? String(b.week) : '';
return json(res, 200, await override.payDue({ force: true, week: wk || undefined }));
}
if (p === '/api/admin/override/resolve' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
return json(res, r && r.error ? 400 : 200, r);
}
if (p === '/api/admin/site' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { site: siteConfig() });