// Level-4 override (Marty, decided 2026-10-17; design in memory iap-level4-override): 3% of every purchase goes to the // buyer's 4th upline when that member has 5+ qualifying buyers (the contract's own buyerCount, same bar as level 3); an // unqualified 4th upline is skipped and the hunt climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one // recipient per purchase, so it never costs more than 3%; funded off-chain from the company's 20% and paid weekly with // the contract's award() from a pre-funded engine wallet, purchases from go-live forward only. // THIS MODULE IS THE DRY RUN: it computes who would be paid from real purchases and reports it. No money moves. 'use strict'; const fs = require('fs'); const path = require('path'); let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null; const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4; function init(o) { DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; } const cfg = () => { const s = siteConfig(); return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean), goLive: Number(s.overrideGoLive || 0) }; }; // sponsor + qualifying-buyer count per member, read from the contract (cached 10 minutes per report run) const memo = new Map(); async function mem(id) { const c = memo.get(id); if (c && Date.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: Date.now(), v }); return v; } // who the override for one purchase goes to: { 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 = []; for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) { const id = ups[i], b = (await mem(id)).buyerCount; if (cfg().house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped }; 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 }; } // Central-time week: Monday 00:00 to the next Monday const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' }); function weekOf(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]; const d = new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)); return d.toISOString().slice(0, 10); // the Monday, as a date key } const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT or CST) for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (weekOf(t) && new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; } return Date.parse(day + 'T05:00:00Z'); }; function purchases() { try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; } } // the report for purchases in [from, to): one row per purchase + totals per recipient (amounts in wei strings and cents) 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, cents = 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 })); rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: cents, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '' }); if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usd: 0 }; o.purchases++; o.wei += wei; o.usd += cents; } } const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, pol: Number(o.wei) / 1e18, usd: Math.round(o.usd * 100) / 100 })).sort((a, b) => b.usd - a.usd); 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, 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(Date.now() - 7 * 86400000); const from = ctMidnight(monday), to = ctMidnight(new Date(Date.parse(monday) + 7 * 86400000).toISOString().slice(0, 10)); return Object.assign(await report(from, to), { week: monday }); } // Monday morning: the dry-run summary to Marty's private Telegram, once per week, and a copy on the volume const STATE = () => path.join(DATA_DIR, 'override-dryrun.json'); async function tick() { if (cfg().mode === 'off' || !notify) return; const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' }).formatToParts(new Date()).map(p => [p.type, p.value])); if (parts.weekday !== 'Mon' || Number(parts.hour) < 9) return; let st = {}; try { st = JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) {} const r = await week(); if (st.lastWeek === r.week) return; st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } }); try { fs.writeFileSync(STATE(), 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 ยท 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. Details: https://instantadpay.com/api/admin/override?week=' + r.week, null).catch(() => {}); } module.exports = { init, report, week, recipientFor, tick, PCT, MIN_BUYERS, HOP_CAP };