// Level-4 override for LinkSpin (ported from InstantAdPay 2026-10-23, Marty approved the program the same day; design in
// memory iap-level4-override): 3% of every LinkSpin purchase goes to the buyer's 4th upline on the LinkSpin CONTRACT sponsor
// chain when that member has 5+ qualifying buyers (the contract's own buyerCount: referred buyers whose first package was
// $20 or more, which on LinkSpin's $10/$25/$50... ladder means $25 or more; the same bar that opens level 3). An unqualified
// 4th upline is skipped and the hunt climbs (cap 25 hops, the contract's HOP_CAP). Exactly one recipient per purchase;
// company ids (overrideHouseIds, default #1) keep it. Paid weekly with the contract's award(toMemberId) from a pre-funded
// payer wallet, purchases from overrideGoLive forward only (no back-pay).
//
// MODES (site setting overrideMode): 'off' | 'dryrun' (default: Monday who-would-be-paid report to Marty's admin Telegram,
// no money moves) | 'live' (pays only when overrideGoLive is set AND OVERRIDE_PAYER_KEY / OVERRIDE_PAYER_KEY_FILE is present).
// LinkSpin runs in JSON mode (no DATABASE_URL), so the one-time claims are exclusive file creates on the shared volume.
// The money-safety notes in the InstantAdPay copy of this file apply word for word; the code is the same module.
'use strict';
const fs = require('fs');
const path = require('path');
let ethersLib = null; try { ethersLib = require('ethers'); } catch (e) { /* optional: the payer stays off without it */ }
const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4;
const GAS_LIMIT = 150000n; // award(): reentrancy guard + member read + capped-gas send + event, ~60k; generous headroom
const WEI = 10n ** 18n;
// ---- Central-time week math (pure, shared by every instance) ----
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
const CT_HOUR = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' });
function weekOf(ts) { // the Monday (YYYY-MM-DD, Central) of the week holding ts
const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday];
return new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)).toISOString().slice(0, 10);
}
const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT = UTC-5, CST = UTC-6)
for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; }
return Date.parse(day + 'T05:00:00Z');
};
const addDays = (day, n) => new Date(Date.parse(day + 'T12:00:00Z') + n * 86400000).toISOString().slice(0, 10);
const weekBounds = monday => ({ from: ctMidnight(monday), to: ctMidnight(addDays(monday, 7)) });
// the week may be settled from 9 AM Central on the Monday after it
const payableAt = monday => ctMidnight(addDays(monday, 7)) + 9 * 3600000;
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
function create() {
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null, db = null, now = () => Date.now();
let BRAND = 'LinkSpin', SITE_URL = 'https://linkspin.app', HOUSE_DEFAULT = '1', payerOverride = null;
const lastError = { at: 0, msg: '' };
function init(o) {
DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; db = o.db || null;
if (o.brand) BRAND = o.brand; if (o.siteUrl) SITE_URL = o.siteUrl; if (o.houseDefault) HOUSE_DEFAULT = String(o.houseDefault);
if (o.payer) payerOverride = o.payer; // tests: a fake signer, never the real chain
if (o.now) now = o.now;
}
const cfg = () => {
const s = siteConfig();
const num = (v, d) => { const n = Number(v); return v === undefined || v === '' || !isFinite(n) ? d : n; };
return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || HOUSE_DEFAULT).split(',').map(x => Number(x.trim())).filter(Boolean),
goLive: Number(s.overrideGoLive || 0), dustWei: toWei(Math.max(0, num(s.overrideDustPol, 0.01)).toFixed(18)), capWei: toWei(Math.max(0, num(s.overridePayCapPol, 100)).toFixed(18)) };
};
// ---- the payer wallet (OVERRIDE_PAYER_KEY; never logged, never returned) ----
function keyHex() {
let k = String(process.env.OVERRIDE_PAYER_KEY || '').trim();
if (!k && process.env.OVERRIDE_PAYER_KEY_FILE) { try { k = fs.readFileSync(process.env.OVERRIDE_PAYER_KEY_FILE, 'utf8').trim(); } catch (e) {} }
if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
}
let realPayer = null;
function payer() {
if (payerOverride) return payerOverride;
const k = keyHex(); if (!k || !ethersLib) return null;
if (realPayer) return realPayer;
const c = chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc]; let idx = 0;
const wallet = () => new ethersLib.Wallet(k, new ethersLib.JsonRpcProvider(urls[idx % urls.length], Number(c.chainId), { staticNetwork: true }));
const ctr = w => new ethersLib.Contract(chain.getConfig().contract, ['function award(uint32 toMemberId) payable'], w);
const address = new ethersLib.Wallet(k).address;
realPayer = {
address,
balance: async () => { try { return await wallet().provider.getBalance(address); } catch (e) { idx++; throw e; } },
fees: async () => { const g = await chain.suggestedFees(); return { maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) }; },
// a revert here (unknown member, a wallet that refuses POL) costs nothing and sends nothing
preflight: async (id, wei) => { await ctr(wallet()).award.staticCall(Number(id), { value: BigInt(wei) }); },
send: async (id, wei, fees) => { const tx = await ctr(wallet()).award(Number(id), Object.assign({ value: BigInt(wei), gasLimit: GAS_LIMIT }, fees)); return { hash: tx.hash, wait: () => tx.wait(1) }; }
};
return realPayer;
}
function liveState() {
const c = cfg(), why = [];
if (c.mode !== 'live') why.push('overrideMode is ' + c.mode + ', not live');
if (!c.goLive) why.push('overrideGoLive is not set');
if (!payerOverride && !keyHex()) why.push('no payer key (OVERRIDE_PAYER_KEY)');
if (!payerOverride && !ethersLib) why.push('ethers is not installed');
return { ready: !why.length, why };
}
// ---- one-time claims, fail closed ----
const dir = (...p) => path.join(DATA_DIR, 'override', ...p);
const mkdirp = d => { try { fs.mkdirSync(d, { recursive: true }); } catch (e) {} };
const safe = k => String(k).replace(/[^a-zA-Z0-9_.:-]/g, '_').replace(/:/g, '__').slice(0, 150);
async function claim(key) {
if (db && db.enabled && db.enabled()) {
try { const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', ['ov:' + String(key).slice(0, 150), now()]); if (!(r && r.affectedRows === 1)) return false; }
catch (e) { lastError.at = now(); lastError.msg = 'claim ' + key + ': ' + e.message; return false; }
}
mkdirp(dir('claims'));
try { fs.closeSync(fs.openSync(dir('claims', safe(key)), 'wx')); return true; }
catch (e) { if (e.code !== 'EEXIST') { lastError.at = now(); lastError.msg = 'claim file ' + key + ': ' + e.message; } return false; }
}
const claimed = key => fs.existsSync(dir('claims', safe(key)));
// ---- payout store: one small JSON file per week header and per (week, member) row, each with a single writer ----
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
const writeJ = (f, o) => { mkdirp(path.dirname(f)); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
const getWeek = wk => readJ(dir('weeks', wk, 'week.json'));
const putWeek = (wk, patch) => { const cur = getWeek(wk) || { week: wk }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'week.json'), o); return o; };
const getRow = (wk, id) => readJ(dir('weeks', wk, 'm' + id + '.json'));
const putRow = (wk, id, patch) => { const cur = getRow(wk, id) || { week: wk, memberId: id }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'm' + id + '.json'), o); return o; };
const rowsOf = wk => { try { return fs.readdirSync(dir('weeks', wk)).filter(f => /^m\d+\.json$/.test(f)).map(f => readJ(dir('weeks', wk, f))).filter(Boolean).sort((a, b) => a.memberId - b.memberId); } catch (e) { return []; } };
const plannedWeeks = () => { try { return fs.readdirSync(dir('weeks')).filter(w => /^\d{4}-\d{2}-\d{2}$/.test(w)).sort(); } catch (e) { return []; } };
// ---- who gets the override on one purchase ----
const memo = new Map();
async function mem(id) {
const c = memo.get(id); if (c && now() - c.t < 600000) return c.v;
const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 };
memo.set(id, { t: now(), v }); return v;
}
// { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
async function recipientFor(buyerId) {
const ups = []; let cur = buyerId;
for (let i = 0; i < LEVEL - 1 + HOP_CAP; i++) { const s = (await mem(cur)).sponsorId; if (!s || s === cur) break; ups.push(s); cur = s; }
if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' };
const skipped = [], house = cfg().house;
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
const id = ups[i];
if (house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
const b = (await mem(id)).buyerCount;
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
skipped.push({ id, buyers: b });
}
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
}
// every Purchase in the full-history index (chain.recentEvents keeps the whole history in memory; the file is the fallback)
function purchases() {
try { if (chain && chain.recentEvents) return chain.recentEvents(1e9).filter(e => e.type === 'Purchase'); } catch (e) {}
try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; }
}
// purchases in [from, to) (and from overrideGoLive on): one row per purchase + totals per recipient
async function report(from, to) {
const c = cfg(); const rows = [], per = {};
for (const p of purchases()) {
if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue;
const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, usd = Math.round((p.priceCents || 0) * PCT) / 10000; // dollars: price cents x 3% / 100
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message, readFailed: true }));
rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: usd, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '', readFailed: !!r.readFailed });
if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usdCents: 0 }; o.purchases++; o.wei += wei; o.usdCents += (p.priceCents || 0) * PCT / 100; }
}
const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, wei: o.wei.toString(), pol: Number(o.wei) / 1e18, usd: Math.round(o.usdCents) / 100 })).sort((a, b) => b.usd - a.usd || a.recipientId - b.recipientId);
const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0);
return { mode: c.mode, from, to, purchases: rows.length, readFailures: rows.filter(x => x.readFailed).length, recipients,
totals: { wouldPayUsd: Math.round(paidUsd * 100) / 100, wouldPayPol: recipients.reduce((n, o) => n + o.pol, 0), companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows };
}
// last full week, or the week containing `day`
async function week(day) {
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(now() - 7 * 86400000);
const b = weekBounds(monday);
return Object.assign(await report(b.from, b.to), { week: monday, status: weekStatus(monday) });
}
// ---- planning: freeze who gets how much for one closed week (single writer via claim) ----
// carried rows from earlier weeks roll into this plan; under-dust totals are carried again
async function plan(wk) {
if (getWeek(wk)) return getWeek(wk);
const b = weekBounds(wk);
if (now() < b.to) return null; // not closed yet
const r = await report(b.from, b.to);
if (r.readFailures) { lastError.at = now(); lastError.msg = 'week ' + wk + ': ' + r.readFailures + ' sponsor reads failed, plan postponed'; return null; } // never plan on a partial read
if (!await claim('plan:' + wk)) return getWeek(wk); // another copy is planning (or did)
putWeek(wk, { state: 'planning', created: now(), from: b.from, to: b.to, purchases: r.purchases, salesUsd: r.totals.salesUsd, companyKeepsUsd: r.totals.companyKeepsUsd });
const per = {};
for (const o of r.recipients) per[o.recipientId] = { wei: BigInt(o.wei), usd: o.usd, purchases: o.purchases, carriedIn: 0n, carriedFrom: [] };
for (const w of plannedWeeks().filter(w => w < wk)) for (const row of rowsOf(w)) {
if (row.state !== 'carried') continue;
const o = per[row.memberId] = per[row.memberId] || { wei: 0n, usd: 0, purchases: 0, carriedIn: 0n, carriedFrom: [] };
o.wei += BigInt(row.amountWei); o.usd = Math.round((o.usd + (row.usd || 0)) * 100) / 100; o.carriedIn += BigInt(row.amountWei); o.carriedFrom.push(w);
putRow(w, row.memberId, { state: 'rolled', rolledInto: wk });
}
const dust = cfg().dustWei; let total = 0n, n = 0;
for (const [id, o] of Object.entries(per)) {
const st = o.wei < dust ? 'carried' : 'pending'; if (st === 'pending') { total += o.wei; n++; }
putRow(wk, Number(id), { amountWei: o.wei.toString(), usd: o.usd, purchases: o.purchases, carriedInWei: o.carriedIn.toString(), carriedFrom: o.carriedFrom, state: st, note: st === 'carried' ? 'under the ' + polStr(dust) + ' POL minimum, carried to next week' : '' });
}
return putWeek(wk, { state: n ? 'planned' : 'paid', totalWei: total.toString(), recipients: n, planned: now() });
}
// settle rows whose send answer was lost, from the chain index only (AwardPaid from the payer to that member, that amount)
function reconcile(wk, pay) {
if (!pay || !chain.recentEvents) return;
const b = weekBounds(wk), used = overrideTxs(true);
for (const row of rowsOf(wk)) {
if (row.state !== 'review' && row.state !== 'sent') continue;
const hit = chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && e.toId === row.memberId && String(e.amountWei) === String(row.amountWei)
&& String(e.from || '').toLowerCase() === String(pay.address).toLowerCase() && e.ts >= b.to
&& (row.txHash ? String(e.tx).toLowerCase() === String(row.txHash).toLowerCase() : !used.has(String(e.tx).toLowerCase())));
if (hit) putRow(wk, row.memberId, { state: 'paid', txHash: hit.tx, note: 'confirmed from the chain index' });
}
}
// admin decision for a stuck row: 'carry' (you checked the payer wallet and nothing went out) or 'paid' with the tx,
// which must be an AwardPaid in the chain index from the payer wallet to that member for that exact amount
async function resolve(wk, memberId, action, tx) {
const r = getRow(wk, Number(memberId)); if (!r) return { error: 'no such row' };
if (!['review', 'failed', 'sending', 'sent'].includes(r.state)) return { error: 'row is ' + r.state + ', nothing to resolve' };
if (action === 'carry') { putRow(wk, r.memberId, { state: 'carried', note: 'admin: nothing went out, carried to next week (was ' + r.state + ')' }); return finishWeek(wk); }
if (action === 'paid') {
const p = (payerOverride || keyHex()) ? payer() : null;
const hit = p && chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.amountWei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + polStr(r.amountWei) + ' POL in the chain index' };
putRow(wk, r.memberId, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return finishWeek(wk);
}
return { error: 'action must be carry or paid' };
}
// ---- paying one planned week (live only) ----
async function pay(wk) {
const live = liveState(); if (!live.ready) return { week: wk, paid: 0, why: live.why };
let w = getWeek(wk); if (!w) return { week: wk, why: ['not planned'] };
if (w.state === 'planning') return { week: wk, why: ['plan is being written (or a plan write stopped halfway: needs review if this lasts)'] };
const p = payer(); reconcile(wk, p);
let rows = rowsOf(wk).filter(r => r.state === 'pending');
if (!rows.length) return finishWeek(wk);
const c = cfg(); const total = rows.reduce((n, r) => n + BigInt(r.amountWei), 0n);
if (total > c.capWei) { putWeek(wk, { state: 'held', heldWhy: 'over the weekly cap: ' + polStr(total) + ' POL planned, cap ' + polStr(c.capWei) + ' POL' }); await alertOnce(wk, 'cap', '⛔ Level-4 override HELD · ' + BRAND + ' · week of ' + wk + '\nPlanned ' + polStr(total) + ' POL is over the weekly cap of ' + polStr(c.capWei) + ' POL. Nothing was sent. Raise overridePayCapPol or review the plan, then press Pay this week now in admin.'); return { week: wk, held: 'cap' }; }
let fees, bal;
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { lastError.at = now(); lastError.msg = 'payer read: ' + e.message; return { week: wk, why: ['payer read failed: ' + e.message] }; }
const gas = BigInt(rows.length) * GAS_LIMIT * fees.maxFeePerGas;
if (bal < total + gas) { putWeek(wk, { state: 'held', heldWhy: 'payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL, needs ' + polStr(total + gas) + ' (payouts ' + polStr(total) + ' + gas ' + polStr(gas) + ')' }); await alertOnce(wk, 'balance', '⚠️ Level-4 override HELD · ' + BRAND + ' · week of ' + wk + '\nPayer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; this week needs ' + polStr(total + gas) + ' POL (' + polStr(total) + ' payouts + up to ' + polStr(gas) + ' gas). Nothing was sent. Fund it and it pays on the next check (or press Pay this week now).'); return { week: wk, held: 'balance' }; }
putWeek(wk, { state: 'paying', heldWhy: '' });
let sent = 0;
for (const r0 of rows) {
if (!await claim('pay:' + wk + ':' + r0.memberId)) continue; // another copy owns this row
const r = getRow(wk, r0.memberId); if (!r || r.state !== 'pending') continue;
try { await p.preflight(r.memberId, r.amountWei); }
catch (e) { putRow(wk, r.memberId, { state: 'carried', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent, carried to next week' }); continue; }
putRow(wk, r.memberId, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
let tx;
try { tx = await p.send(r.memberId, r.amountWei, fees); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
putRow(wk, r.memberId, { state: 'sent', txHash: tx.hash });
console.log('override: week ' + wk + ' #' + r.memberId + ' ' + polStr(r.amountWei) + ' POL tx ' + tx.hash);
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putRow(wk, r.memberId, { state: 'paid', paidAt: now() }); sent++; } else putRow(wk, r.memberId, { state: 'failed', note: 'reverted on chain (no POL moved except gas); needs review' }); }
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
}
return Object.assign(await finishWeek(wk), { sentNow: sent });
}
async function finishWeek(wk) {
// a send that stopped halfway (no answer in 15 minutes) is never retried: it becomes review
for (const r of rowsOf(wk)) {
if (r.state === 'sending' && now() - (r.sendingAt || r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'the app stopped during the send; it may or may not have gone out' });
if (r.state === 'sent' && now() - (r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'sent, no receipt and not in the chain index after 15 minutes' });
}
reconcile(wk, (payerOverride || keyHex()) ? payer() : null);
const rows = rowsOf(wk); const open = rows.filter(r => ['pending', 'sending', 'sent', 'review', 'failed'].includes(r.state));
if (open.length) {
const stuck = open.filter(r => r.state === 'review' || r.state === 'failed'); // in-flight rows of another copy are not stuck
if (stuck.length) await alertOnce(wk, 'review', '\u{1F50E} Level-4 override needs review · ' + BRAND + ' · week of ' + wk + '\n' + stuck.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL: ' + r.state + (r.txHash ? ' ' + txLink(r.txHash) : '') + ' ' + (r.note || '')).join('\n') + '\nNothing is re-sent automatically. Check the payer wallet on the explorer, then resolve it in admin.');
return { week: wk, state: (getWeek(wk) || {}).state, open: open.length };
}
const w = putWeek(wk, { state: 'paid', done: now() });
await summaryPaid(wk);
return { week: wk, state: w.state };
}
const txLink = h => { const c = chain.getConfig(); return (c.explorer ? c.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + h; };
async function alertOnce(wk, kind, text) { if (!notify) return; if (!await claim('tg:' + wk + ':' + kind)) return; await notify(text, null).catch(() => {}); }
async function summaryPaid(wk) {
if (!notify || !await claim('tg:' + wk + ':paid')) return;
const w = getWeek(wk) || {}, rows = rowsOf(wk), paid = rows.filter(r => r.state === 'paid'), carried = rows.filter(r => r.state === 'carried');
const tot = paid.reduce((n, r) => n + BigInt(r.amountWei), 0n), usd = paid.reduce((n, r) => n + (r.usd || 0), 0);
await notify('\u{1F4B8} Level-4 override PAID · ' + BRAND + ' · week of ' + wk + '\n' + (w.purchases || 0) + ' purchases, $' + Number(w.salesUsd || 0).toFixed(2) + ' sales\n'
+ 'Paid ' + polStr(tot) + ' POL (about $' + usd.toFixed(2) + ' at purchase prices) to ' + paid.length + ' member' + (paid.length === 1 ? '' : 's') + '; company keeps $' + Number(w.companyKeepsUsd || 0).toFixed(2) + ' of the 3%.\n'
+ (paid.map(r => '#' + r.memberId + ': ' + polStr(r.amountWei) + ' POL ($' + (r.usd || 0).toFixed(2) + ') tx').join('\n') || 'Nobody qualified this week.')
+ (carried.length ? '\nCarried to next week (under the minimum or the wallet refused): ' + carried.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL').join(', ') : '')
+ '\nDetails: ' + SITE_URL + '/api/admin/override?week=' + wk, null).catch(() => {});
}
// weeks the live payer is responsible for: from the go-live week to the last closed one, in order
function dueWeeks(force) {
const c = cfg(); if (!c.goLive) return [];
const out = []; let wk = weekOf(c.goLive);
while (true) { const b = weekBounds(wk); if (now() < b.to) break; if (!force && now() < payableAt(wk)) break; out.push(wk); wk = addDays(wk, 7); if (out.length > 520) break; }
return out;
}
// settle every due week in order; stop at the first one that is not fully paid
async function payDue(opts) {
const o = opts || {}; const results = [];
if (!liveState().ready) return { ready: false, why: liveState().why, results };
for (const wk of dueWeeks(o.force)) {
if (o.week && wk > o.week) break;
let w = getWeek(wk);
if (!w) w = await plan(wk);
if (!w) { results.push({ week: wk, why: ['not planned yet: ' + (lastError.msg || 'waiting')] }); break; }
if (w.state === 'paid') { await summaryPaid(wk); results.push({ week: wk, state: 'paid' }); continue; }
const r = await pay(wk); results.push(r);
if ((getWeek(wk) || {}).state !== 'paid') break;
}
return { ready: true, results };
}
function weekStatus(wk) {
const w = getWeek(wk); if (!w) return { week: wk, state: claimed('plan:' + wk) ? 'planning' : 'not planned' };
const rows = rowsOf(wk);
return { week: wk, state: w.state, heldWhy: w.heldWhy || '', totalWei: w.totalWei, totalPol: w.totalWei ? polStr(w.totalWei) : '0',
rows: rows.map(r => ({ memberId: r.memberId, pol: polStr(r.amountWei), amountWei: r.amountWei, usd: r.usd, purchases: r.purchases, state: r.state, txHash: r.txHash || '', tx: r.txHash ? txLink(r.txHash) : '', note: r.note || '', carriedFrom: r.carriedFrom || [], rolledInto: r.rolledInto || '' })) };
}
async function payerStatus() {
const c = cfg(), live = liveState(); const out = { mode: c.mode, ready: live.ready, why: live.why, goLive: c.goLive || 0, capPol: polStr(c.capWei), dustPol: polStr(c.dustWei), house: c.house, keyPresent: !!(payerOverride || keyHex()), lastError: lastError.msg ? lastError : null };
const p = (payerOverride || keyHex()) ? payer() : null;
if (p) { out.address = p.address; try { out.balancePol = polStr(await p.balance()); } catch (e) { out.balanceError = e.message; } }
return out;
}
// AwardPaid txs this payer made (for the Earnings label and the payout email): tx -> { week, memberId }
let txCache = { at: 0, map: new Map() };
function overrideTxs(fresh) {
if (!fresh && now() - txCache.at < 30000) return txCache.map;
const m = new Map(); for (const wk of plannedWeeks()) for (const r of rowsOf(wk)) if (r.txHash) m.set(String(r.txHash).toLowerCase(), { week: wk, memberId: r.memberId });
txCache = { at: now(), map: m }; return m;
}
const txInfo = tx => { return overrideTxs(true).get(String(tx || '').toLowerCase()) || null; };
// ---- the scheduler: every 30 minutes ----
async function tick() {
const c = cfg(); if (c.mode === 'off') return;
const live = liveState();
if (live.ready) { try { await payDue(); } catch (e) { lastError.at = now(); lastError.msg = 'payDue: ' + e.message; console.error('override pay', e.message); } return; }
// dry run (or 'live' that is not ready): the Monday report, once per week across every copy of the app
const parts = Object.fromEntries(CT_HOUR.formatToParts(new Date(now())).map(p => [p.type, p.value]));
if (parts.weekday !== 'Mon' || Number(parts.hour) < 9 || !notify) return;
const r = await week(); if (r.readFailures) return; // try again in 30 minutes rather than report a partial week
if (!await claim('tg:' + r.week + ':dry')) return;
let st = {}; try { st = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 'utf8')); } catch (e) {}
st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } });
try { fs.writeFileSync(path.join(DATA_DIR, 'override-dryrun.json'), JSON.stringify(st)); } catch (e) {}
const top = r.recipients.slice(0, 8).map(o => '#' + o.recipientId + ': $' + o.usd.toFixed(2) + ' (' + o.pol.toFixed(2) + ' POL, ' + o.purchases + ' buys)').join('\n');
await notify('\u{1F4CA} Level-4 override, DRY RUN · ' + BRAND + ' · week of ' + r.week + '\n' + r.purchases + ' purchases, $' + r.totals.salesUsd.toFixed(2) + ' sales\n'
+ 'Would pay $' + r.totals.wouldPayUsd.toFixed(2) + ' (' + r.totals.wouldPayPol.toFixed(2) + ' POL) to ' + r.recipients.length + ' members; company keeps $' + r.totals.companyKeepsUsd.toFixed(2) + ' of the 3%.\n'
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
}
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
}
const main = create();
module.exports = Object.assign(main, { create, weekOf, ctMidnight, weekBounds, payableAt, polStr, toWei, PCT, MIN_BUYERS, HOP_CAP, LEVEL, GAS_LIMIT });