diff --git a/override.js b/override.js new file mode 100644 index 0000000..9d848ee --- /dev/null +++ b/override.js @@ -0,0 +1,351 @@ +// 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 }); diff --git a/public/admin.html b/public/admin.html index f67b804..bda33ca 100644 --- a/public/admin.html +++ b/public/admin.html @@ -466,6 +466,13 @@

…

+
+

Level 4 override

3% of each purchase to the qualified 4th upline, paid weekly from the payer wallet
+

…

+
+

+
+
- + - + diff --git a/public/assets/admin.js b/public/assets/admin.js index 981e772..c532493 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -847,6 +847,7 @@ } async function loadPnl() { + loadOverride().catch(() => {}); // its own request: does not wait for the chain reads below const r = await api('/api/admin/pnl?days=' + pnlDays); const px = r.polUsd || 0; const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px; @@ -871,6 +872,29 @@ } document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); })); if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } }); + // Level 4 override (2026-10-23): week status from /api/admin/override; the pay button exists only while the live payer is ready + const OV_STATE = { 'not planned': 'not planned', planning: 'planning', planned: 'pending', paying: 'paying', held: 'held', paid: 'paid' }; + async function loadOverride(week) { + if (!$('ovPayer')) return; + let r; try { r = await (await fetch('/api/admin/override' + (week ? '?week=' + encodeURIComponent(week) : ''), { cache: 'no-store' })).json(); } catch (e) { $('ovPayer').textContent = 'Could not read the override: ' + e.message; return; } + const pz = r.payer || {}; + $('ovPayer').textContent = 'Mode: ' + (pz.mode || '?') + (pz.ready ? ' · PAYING automatically each Monday after 9 AM CT' : ' · not paying (' + (pz.why || []).join('; ') + ')') + + (pz.address ? ' · payer wallet ' + pz.address + ' holds ' + (pz.balancePol || '?') + ' POL' : '') + ' · weekly cap ' + (pz.capPol || '?') + ' POL · minimum ' + (pz.dustPol || '?') + ' POL' + + (pz.goLive ? ' · purchases from ' + new Date(pz.goLive).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : '') + (pz.lastError ? ' · last error: ' + pz.lastError.msg : ''); + $('ovPay').hidden = !pz.ready; + const sel = $('ovWeek'); if (!sel.options.length) { const now = new Date(); for (let i = 0; i < 10; i++) { const d = new Date(now.getTime() - i * 7 * 86400000); const v = d.toISOString().slice(0, 10); sel.innerHTML += ''; } sel.selectedIndex = 1; } + $('ovWeeks').innerHTML = (r.dueWeeks || []).length ? '' + r.dueWeeks.map(w => '').join('') + '
Week ofStatusTotal
' + esc(w.week) + '' + esc(OV_STATE[w.state] || w.state) + (w.heldWhy ? ' (' + esc(w.heldWhy) + ')' : '') + '' + esc(w.totalPol || '0') + ' POL
' : ''; + const st = r.status || {}; const t = r.totals || {}; + $('ovOut').innerHTML = '

Week of ' + esc(r.week || '') + ': ' + (r.purchases || 0) + ' purchases, $' + Number(t.salesUsd || 0).toFixed(2) + ' sales. Override due: $' + Number(t.wouldPayUsd || 0).toFixed(2) + ' (' + Number(t.wouldPayPol || 0).toFixed(4) + ' POL) to ' + (r.recipients || []).length + ' members; company keeps $' + Number(t.companyKeepsUsd || 0).toFixed(2) + '. Payout status: ' + esc(OV_STATE[st.state] || st.state || '?') + '' + (st.heldWhy ? ' (' + esc(st.heldWhy) + ')' : '') + '.

' + + ((st.rows || []).length ? '' + st.rows.map(x => '').join('') + '
MemberPOLUSDStatus
#' + x.memberId + '' + esc(x.pol) + '$' + Number(x.usd || 0).toFixed(2) + '' + esc(x.state) + (x.note ? ' ' + esc(x.note) + '' : '') + '' + (x.tx ? 'tx' : '') + '
' + : (r.recipients || []).length ? '' + r.recipients.map(x => '').join('') + '
MemberPOLUSDBuys
#' + x.recipientId + '' + Number(x.pol).toFixed(4) + '$' + Number(x.usd).toFixed(2) + '' + x.purchases + '
' : ''); + } + if ($('ovShow')) $('ovShow').addEventListener('click', () => loadOverride($('ovWeek').value)); + if ($('ovPay')) $('ovPay').addEventListener('click', async () => { + const wk = $('ovWeek').value; + if (!await IAP.confirmBox('This sends real POL from the payer wallet for every closed week up to the week containing ' + wk + ' that is not paid yet. Each member is paid once; anything already paid is skipped.', { title: 'Pay the override now?', ok: 'Pay now' })) return; + try { const r = await api('/api/admin/override/pay', { week: wk }); IAP.status('Override: ' + (r.results || []).map(x => x.week + ' ' + (x.state || x.held || (x.why || []).join(', '))).join(' · '), 'ok'); loadOverride(wk); } catch (e) { IAP.status(e.message, 'bad'); } + }); if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } }); async function loadAudit() { if (!$('audTable')) return; diff --git a/public/assets/common.js b/public/assets/common.js index 4bc8487..512fb05 100644 --- a/public/assets/common.js +++ b/public/assets/common.js @@ -93,7 +93,7 @@ window.IAP = (function () { case 'AdminPaid': return 'platform fee settled: ' + pol(ev.amountWei); case 'BuyerCounted': return '' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)'; case 'MemberActivated': return '' + nm(ev.id) + ' activated a payout wallet'; - case 'AwardPaid': return 'award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId); + case 'AwardPaid': return ev.override ? 'Level 4 override' + (ev.overrideWeek ? ' (week of ' + ev.overrideWeek + ')' : '') + ': ' + pol(ev.amountWei) + ' → ' + nm(ev.toId) : 'award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId); case 'CreditsConsumed': return '' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits'; case 'PriceCached': return 'oracle price refreshed'; case 'FallbackPriceUsed': return 'cached price bridged an oracle gap'; diff --git a/public/assets/contract.js b/public/assets/contract.js index 9091679..d5f2e94 100644 --- a/public/assets/contract.js +++ b/public/assets/contract.js @@ -3,6 +3,11 @@ const $ = id => document.getElementById(id); let c = {}; try { c = await (await fetch('/api/config')).json(); } catch (e) {} const addr = String(c.contract || ''); + // Level 4 override panel (2026-10-23): only when the site setting overrideMode is 'live' and overrideGoLive is set + if (String(c.overrideMode || '') === 'live' && Number(c.overrideGoLive) && $('ovPanel')) { + const d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' }); + document.querySelectorAll('[data-ov-start]').forEach(e => { e.textContent = d; }); $('ovPanel').hidden = false; + } $('cAddr').textContent = addr || 'not deployed yet'; $('cChain').textContent = c.chainName || ''; const src = 'https://repo.sourcify.dev/contracts/full_match/' + (c.chainId || 137) + '/' + addr + '/'; diff --git a/public/assets/wallet-screen.js b/public/assets/wallet-screen.js index ee3aaa6..5a301b0 100644 --- a/public/assets/wallet-screen.js +++ b/public/assets/wallet-screen.js @@ -17,7 +17,7 @@ .map(([k, v, n], i) => '
' + k + '' + v + '' + n + '
').join(''); $('walletBox').innerHTML = addr ? '
' + esc(addr) + '
' + (on ? 'PAYOUTS ON · member #' + ME.memberId + '' : 'WALLET LINKED · PAYOUTS OFF
Switch payouts on so the people you bring pay you from their first purchase.
') + '
' : 'No wallet linked yet.
Link one to be paid. Your email account keeps working either way.
'; const pays = E && Array.isArray(E.earnings) ? E.earnings : []; - $('payRows').innerHTML = pays.length ? pays.slice(0, 25).map(x => '
' + new Date((x.ts || 0) * (x.ts > 1e12 ? 1 : 1000)).toLocaleString() + '' + esc(x.buyerName || x.fromName || (x.names && x.buyerId && x.names[x.buyerId] ? '@' + x.names[x.buyerId] : x.buyerId ? 'member #' + x.buyerId : x.type === 'AwardPaid' ? 'award' : 'member')) + '' + (x.tier ? 'L' + x.tier + ' · ' + (x.tier === 1 ? '50%' : x.tier === 2 ? '20%' : '10%') : (x.type === 'AwardPaid' ? 'award' : '')) + '' + (x.priceCents ? '$' + (x.priceCents / 100) : '') + '+' + pol(x.amountWei || '0') + ' POL' + (U.usd > 0 ? '
' + usd(x.amountWei) + '' : '') + '
' + (x.tx ? '' + esc(String(x.tx).slice(0, 10)) + '…' : '') + '
').join('') + $('payRows').innerHTML = pays.length ? pays.slice(0, 25).map(x => '
' + new Date((x.ts || 0) * (x.ts > 1e12 ? 1 : 1000)).toLocaleString() + '' + esc(x.buyerName || x.fromName || (x.names && x.buyerId && x.names[x.buyerId] ? '@' + x.names[x.buyerId] : x.buyerId ? 'member #' + x.buyerId : x.type === 'AwardPaid' ? (x.override ? 'Level 4 override' : 'award') : 'member')) + '' + (x.tier ? 'L' + x.tier + ' · ' + (x.tier === 1 ? '50%' : x.tier === 2 ? '20%' : '10%') : (x.type === 'AwardPaid' ? (x.override ? 'L4 · 3%' : 'award') : '')) + '' + (x.priceCents ? '$' + (x.priceCents / 100) : '') + '+' + pol(x.amountWei || '0') + ' POL' + (U.usd > 0 ? '
' + usd(x.amountWei) + '' : '') + '
' + (x.tx ? '' + esc(String(x.tx).slice(0, 10)) + '…' : '') + '
').join('') : '
No payouts yet. They appear here the moment someone in your line buys.
'; $('payFoot').textContent = 'every line is a Polygon transaction · nothing is held by the site' + (U.usd > 0 ? ' · 1 POL ≈ $' + U.usd.toFixed(4) + ' at today’s price (updated ' + Math.max(0, Math.round((Date.now() - U.at) / 60000)) + ' min ago); dollar amounts are today’s value, not the value on the payout day' : ''); const rows = Array.isArray(POS) ? POS : (POS && (POS.positions || POS.list)) || []; diff --git a/public/contract.html b/public/contract.html index eaccb05..42a59a8 100644 --- a/public/contract.html +++ b/public/contract.html @@ -104,6 +104,17 @@ + +

What this is and is not

read before you buy
@@ -136,6 +147,6 @@ Advertising services with a performance referral program. Not an investment. Crypto transactions are irreversible.
- + diff --git a/public/credits.html b/public/credits.html index 9c4df5c..ed81059 100644 --- a/public/credits.html +++ b/public/credits.html @@ -80,7 +80,7 @@
- + diff --git a/public/earning.html b/public/earning.html index aeaa37e..d70c651 100644 --- a/public/earning.html +++ b/public/earning.html @@ -68,6 +68,6 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/join.html b/public/join.html index fc24a9c..e4ec288 100644 --- a/public/join.html +++ b/public/join.html @@ -105,7 +105,7 @@ body.squeeze .card{position:sticky;top:16px} a Crypto Team Build Network property - + diff --git a/public/launch.html b/public/launch.html index 5ecd63e..cbbb24f 100644 --- a/public/launch.html +++ b/public/launch.html @@ -104,7 +104,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/ledger.html b/public/ledger.html index 34f3fd9..e651474 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -64,7 +64,7 @@ a Crypto Team Build Network property - + diff --git a/public/my.html b/public/my.html index 5a283a4..3bef5fe 100644 --- a/public/my.html +++ b/public/my.html @@ -1007,7 +1007,7 @@ - + diff --git a/public/partners.html b/public/partners.html index 219f0d1..f5f9896 100644 --- a/public/partners.html +++ b/public/partners.html @@ -130,7 +130,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.
- + diff --git a/public/plays.html b/public/plays.html index e3dbd72..90217ef 100644 --- a/public/plays.html +++ b/public/plays.html @@ -192,7 +192,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
- + diff --git a/public/support.html b/public/support.html index b83a7ce..8e1560e 100644 --- a/public/support.html +++ b/public/support.html @@ -66,7 +66,7 @@ a Crypto Team Build Network property - + diff --git a/public/tx.html b/public/tx.html index bded2c4..d8219fb 100644 --- a/public/tx.html +++ b/public/tx.html @@ -34,7 +34,7 @@

← Back to the live ledger · Read the contract review

- + diff --git a/public/wall.html b/public/wall.html index 2270994..7bd128d 100644 --- a/public/wall.html +++ b/public/wall.html @@ -47,7 +47,7 @@ - + diff --git a/public/wallet.html b/public/wallet.html index 75da578..91eae07 100644 --- a/public/wallet.html +++ b/public/wallet.html @@ -32,6 +32,6 @@ - + diff --git a/public/wallets.html b/public/wallets.html index 6b0b1d7..b02fbd8 100644 --- a/public/wallets.html +++ b/public/wallets.html @@ -121,7 +121,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.
- + diff --git a/qa/override.test.cjs b/qa/override.test.cjs new file mode 100644 index 0000000..4033dee --- /dev/null +++ b/qa/override.test.cjs @@ -0,0 +1,236 @@ +// 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); +})(); diff --git a/qa/run.sh b/qa/run.sh index 9a1711e..b5abbb3 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -8,6 +8,7 @@ # bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard # bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits # bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy +# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data) # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. set -u @@ -31,6 +32,8 @@ stop_local() { # $1 = port if [ "$MODE" = "public" ]; then node qa/walk.mjs public || status=1 +elif [ "$MODE" = "override" ]; then + node qa/override.test.cjs || status=1 elif [ "$MODE" = "member" ]; then start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 elif [ "$MODE" = "sponsorfollow" ]; then diff --git a/server.js b/server.js index 79c7479..e5de542 100644 --- a/server.js +++ b/server.js @@ -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: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.recipientId); else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has ' + ev.newCount + ' 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: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.toId); + else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : 'Award payout') + ': ' + weiToPol(ev.amountWei) + ' POL \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 verify' + (sc.telegramCtaUrl ? '\nJoin free' : ''); @@ -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() });