diff --git a/blog.js b/blog.js index 2213595..3b266e8 100644 --- a/blog.js +++ b/blog.js @@ -108,7 +108,7 @@ function head(o) { + '
'; } function tail() { - return '
'; + return ''; } const authorBox = () => '
InstantAdPay
' + AUTHOR + 'Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.
'; const cardHtml = p => '' + (p.cover ? '' : '') + '

' + esc(p.title) + '

' + esc(p.excerpt) + '

' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '

'; diff --git a/chatbot.js b/chatbot.js index 150018b..14736c9 100644 --- a/chatbot.js +++ b/chatbot.js @@ -30,6 +30,7 @@ function key() { function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- +// TODO(level-4 override, 2026-10-23): at go-live add the CANNED entry + FACTS line drafted in D:/tmp/override-copy/instantadpay-override-copy.md (section 3), and bump KNOWLEDGE_DATE only in that deploy. const KNOWLEDGE_DATE = '2026-10-23'; // bump whenever the canned answers / prompt are brought up to date const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const CANNED = [ diff --git a/leaderboard.js b/leaderboard.js index 6bae66b..6476cdf 100644 --- a/leaderboard.js +++ b/leaderboard.js @@ -141,7 +141,7 @@ async function renderPage() { const w = winners(); if (w.length) h += '

Past winners

' + w.slice(0, 12).map(x => '
' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + ': ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '
').join(''); h += '

Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.

'; - h += ''; + h += ''; return h; } module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds }; diff --git a/override.js b/override.js index 43035ab..e6849a0 100644 --- a/override.js +++ b/override.js @@ -1,92 +1,366 @@ -// 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 }; +// Level-4 override (Marty, decided 2026-10-17, approved to build for real 2026-10-23; design in memory iap-level4-override): +// 3% of every purchase goes to the buyer's 4th upline on the CONTRACT sponsor chain when that member has 5+ qualifying +// buyers (the contract's own buyerCount, the 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%; company ids (overrideHouseIds) keep it. Funded off-chain from the company's 20% and 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' nothing at all. +// 'dryrun' (default) the Monday who-would-be-paid report to Marty's private Telegram. No money moves. +// 'live' pays, but ONLY when overrideGoLive is set AND a payer key is present (env OVERRIDE_PAYER_KEY or +// OVERRIDE_PAYER_KEY_FILE). Missing either one: it reports as a dry run and says why it did not pay. +// +// MONEY SAFETY (why each piece exists): +// - Every "do this once" is a claim that only one running copy of the app can win: an exclusive file create on the +// shared volume (fs 'wx'), plus a row in event_marks when MySQL is on. A deploy runs two copies for ~30 s (the +// 2026-09-25 double Friday bonus); a claim that cannot be checked counts as LOST (fail closed), never as won. +// - A week's plan (who gets how much) is computed once, written to the volume and never recomputed, so a later read +// of buyer counts cannot change an amount that is already being paid. +// - A payout row is marked 'sending' on disk BEFORE the transaction is sent and gets its tx hash the moment the node +// accepts it. A row whose answer was lost is 'review': it is never sent again automatically. The chain index can +// settle it (an AwardPaid from the payer wallet to that member for that exact amount), or the admin does. +// - Amounts under the dust minimum (overrideDustPol, default 0.01 POL) and pre-flight failures (award() would revert, +// no gas spent) are carried to the next week's plan. +// - Hard cap per week (overridePayCapPol, default 100 POL): a plan over the cap is held whole, nothing is sent. +// - The wallet must hold the week's total plus gas for every send, or nothing is sent and Marty is told. +// - Weeks are paid in order; a week that is held or needs review stops the later weeks until it is resolved. +'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 = 'InstantAdPay', SITE_URL = 'https://instantadpay.com', 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 a57981e..e112375 100644 --- a/public/admin.html +++ b/public/admin.html @@ -1,616 +1,623 @@ - - - - - -Admin | InstantAdPay - - - - - - - - -
-
-
-

InstantAdPay

-

Admin sign in

-

Only the admin address can sign in here. A one-time code goes to that inbox.

-
-
-

- - -

- - -

-

Back to the member area

-
-
-
- - - - - - - - - + + + + + +Admin | InstantAdPay + + + + + + + + +
+
+
+

InstantAdPay

+

Admin sign in

+

Only the admin address can sign in here. A one-time code goes to that inbox.

+
+
+

+ + +

+ + +

+

Back to the member area

+
+
+
+ + + + + + + + + diff --git a/public/assets/admin.js b/public/assets/admin.js index 4e5991d..87b71bb 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -1,1259 +1,1283 @@ -// Admin portal: email-code sign-in (allowlisted to ADMIN_EMAIL on the server), -// house ads that cost nothing, every campaign, members, reports, settings. -(function () { - const $ = IAP.$; - const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); - async function api(path, body, method) { - const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} }; - if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); } - const r = await (await fetch(path, opts)).json(); - if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error); - return r; - } - function busy(btn, fn) { - return async (...a) => { - if (btn.disabled) return; - btn.disabled = true; - try { await fn(...a); } catch (e) { IAP.status(e.message || 'Something went wrong.', 'bad'); } - finally { btn.disabled = false; } - }; - } - const when = ts => ts ? new Date(Number(ts)).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : ''; - let rates = {}, sizes = [], houseOwner = 'house@instantadpay.com'; - - // ── sign-in ── - $('adSend').addEventListener('click', busy($('adSend'), async () => { - $('adErr').hidden = true; - const r = await api('/api/admin/auth/start', { email: $('adEmail').value }); - $('adCodeRow').hidden = false; $('adVerify').hidden = false; - if (r.devCode) $('adCode').value = r.devCode; - IAP.status(r.sent ? 'Code sent. Check your inbox.' : 'Dev mode: code filled in.', 'ok'); - $('adCode').focus(); - })); - $('adVerify').addEventListener('click', busy($('adVerify'), async () => { - $('adErr').hidden = true; - await api('/api/admin/auth/verify', { email: $('adEmail').value, code: $('adCode').value }); - await render(); - })); - $('adCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('adVerify').click(); }); - $('adEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('adVerify').hidden ? $('adSend') : $('adVerify')).click(); }); - $('adLogout').addEventListener('click', async e => { - e.preventDefault(); - try { await api('/api/admin/auth/logout', {}); } catch (err) {} - location.reload(); - }); - - // ── panes ── - const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' }; - const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings }; - function setPane(name) { - const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email) - if (!TITLES[name]) name = 'overview'; - document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; }); - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name)); - $('boTitle').textContent = TITLES[name]; - const keepQ = name === 'support' && paneQ ? '?' + paneQ : ''; - if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ); - $('adminArea').classList.remove('side-open'); - return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad')); - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane))); - document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); }); - window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); - $('boBurger').addEventListener('click', () => $('adminArea').classList.toggle('side-open')); - - async function render() { - let me = { admin: false }; - try { me = await api('/api/admin/me'); } catch (e) {} - $('authArea').hidden = !!me.admin; - $('adminArea').hidden = !me.admin; - if (!me.admin) return; - $('adWho').textContent = me.email || 'admin'; - try { - const c = await IAP.getConfig(); - $('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : ''); - } catch (e) {} - setPane(location.hash.slice(1) || 'overview'); - supportBadge(); - } - - // ── overview ── - async function loadOverview() { - const o = await api('/api/admin/overview'); - rates = o.rates || rates; - $('ovAccounts').textContent = (o.accounts || 0).toLocaleString(); - $('ovMembers').textContent = o.memberCount == null ? '?' : Number(o.memberCount).toLocaleString(); - $('ovActive').textContent = (o.byStatus && o.byStatus.active) || 0; - $('ovCampSub').textContent = o.campaigns + ' total · ' + o.house + ' house'; - $('ovReports').textContent = o.openReports || 0; - $('ovBurnSub').textContent = (o.pendingBurns || 0) + ' pending burns'; - $('repBadge').hidden = !o.openReports; $('repBadge').textContent = o.openReports || ''; - const f = o.followups || {}; - $('ovDrips').textContent = f.active || 0; - $('ovDripSub').textContent = (f.done || 0) + ' finished · ' + (f.unsubscribed || 0) + ' unsubscribed'; - const bt = Object.entries(o.byType || {}).sort((a, b) => b[1] - a[1]); - $('ovByType').innerHTML = bt.length ? bt.map(([t, n]) => '
' + esc(t) + '' + n + '
').join('') : 'No campaigns yet.'; - const ch = o.chain || {}; - $('ovChain').innerHTML = '
' + esc(ch.chainName) + ' (chain ' + esc(ch.chainId) + ')
' - + '
' + esc(ch.contract) + '
' - + (ch.explorer ? 'Open in explorer →' : ''); - } - - // ── house ads ── - const HROWS = { banner: ['hBannerRow'], text: ['hTextRow'], login: [], solo: ['hSoloRow'], video: ['hVideoRow'], featured: ['hFeatRow'], visits: ['hVisitsRow'] }; - function showHouseRows() { - const t = $('hType').value; - ['hBannerRow', 'hTextRow', 'hSoloRow', 'hVideoRow', 'hFeatRow', 'hVisitsRow'].forEach(id => { $(id).hidden = !(HROWS[t] || []).includes(id); }); - $('hBudget').hidden = t === 'featured' || t === 'visits'; - houseHints(); - } - function houseHints() { - const r = rates || {}; - const soloCost = r.soloCostPerRecipient || 5, soloMin = r.soloMinRecipients || 10; - const cap = Number($('hBudget').value) || 100000; - $('hSoloHint').textContent = 'Delivers to one inbox per ' + soloCost + ' credits of cap (minimum ' + soloMin + ' recipients). A cap of ' + cap.toLocaleString() + ' reaches up to ' + Math.floor(cap / soloCost).toLocaleString() + ' members.'; - const days = Number($('hFeatDays').value) || 0; - $('hFeatHint').textContent = days ? days + '-day run in the featured strip (' + (r.featuredPerDay || 40) + ' credits/day, free here). Book up to ' + (r.featuredWindowDays || 7) + ' days ahead.' : ''; - const n = Number($('hVisitCount').value) || 0; - $('hVisitHint').textContent = 'Packs start at ' + (r.visitMinPack || 20) + ' visits.' + (n ? ' ' + n + ' verified visits, delivered one per member.' : ''); - } - $('hType').addEventListener('change', showHouseRows); - ['hBudget', 'hFeatDays', 'hVisitCount'].forEach(id => $(id).addEventListener('input', houseHints)); - $('hFeatDays').addEventListener('change', houseHints); - $('hImageUploadBtn').addEventListener('click', () => $('hImageFile').click()); - $('hVideoUploadBtn').addEventListener('click', () => $('hVideoFile').click()); - async function upload(fileInput, info, target, kind) { - const f = fileInput.files[0]; if (!f) return; - info.textContent = 'Uploading ' + f.name + '…'; - try { - const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { info.textContent = r.error; } - else { target.value = r.url; info.textContent = f.name + ' uploaded'; } - } catch (e) { info.textContent = 'Upload failed. Try again.'; } - fileInput.value = ''; - } - $('hImageFile').addEventListener('change', () => upload($('hImageFile'), $('hImageInfo'), $('hImage'))); - $('hVideoFile').addEventListener('change', () => upload($('hVideoFile'), $('hVideoInfo'), $('hVideoUrl'))); - let hVidDims = null; - function probeVideoDims(url) { - return new Promise(resolve => { - const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; - const done = d => { v.src = ''; resolve(d); }; - v.onloadedmetadata = () => done(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); - v.onerror = () => done(null); - setTimeout(() => done(null), 12000); - v.src = url; - }); - } - $('hCreate').addEventListener('click', busy($('hCreate'), async () => { - $('hErr').hidden = true; - const t = $('hType').value; - if (t === 'video' && $('hVideoUrl').value) hVidDims = await probeVideoDims($('hVideoUrl').value); - const days = Number($('hFeatDays').value), count = Number($('hVisitCount').value); - const body = { type: t, name: $('hName').value, targetUrl: $('hTarget').value, - imageUrl: $('hImage').value, size: $('hSize').value, - title: t === 'video' ? $('hVideoTitle').value : t === 'featured' ? $('hFeatTitle').value : t === 'visits' ? $('hVisitTitle').value : t === 'solo' ? $('hSoloTitle').value : $('hTitle').value, - body: t === 'solo' ? $('hSoloBody').value : $('hBody').value, - ctaLabel: t === 'video' ? $('hVideoCta').value : $('hSoloCta').value, - videoUrl: $('hVideoUrl').value, watchSecs: Number($('hWatchSecs').value), - videoW: hVidDims ? hVidDims.w : null, videoH: hVidDims ? hVidDims.h : null, - days, startDay: Number($('hFeatStart').value) || 0, count, placement: t === 'visits' && $('hVisitPlace') ? $('hVisitPlace').value : undefined, - budget: t === 'featured' ? days * (rates.featuredPerDay || 40) - : t === 'visits' ? count * (($('hVisitPlace') && $('hVisitPlace').value === 'golden') ? (rates.goldenDoorCost || 6) : ($('hVisitPlace') && $('hVisitPlace').value === 'doors') ? (rates.doorPackCost || 4) : (rates.visitCostPerVisit || 3)) - : (Number($('hBudget').value) || 0) }; - try { - await api('/api/admin/campaigns', body); - } catch (e) { $('hErr').textContent = e.message; $('hErr').hidden = false; throw e; } - IAP.status('House ad is live. It serves right away at no cost.', 'ok'); - ['hName', 'hBudget', 'hTarget', 'hImage', 'hTitle', 'hBody', 'hSoloTitle', 'hSoloBody', 'hSoloCta', - 'hVideoUrl', 'hVideoTitle', 'hVideoCta', 'hFeatTitle', 'hVisitTitle', 'hVisitCount'].forEach(id => { $(id).value = ''; }); - $('hImageInfo').textContent = ''; $('hVideoInfo').textContent = ''; hVidDims = null; - await loadHouse(); - })); - function campRow(c, showOwner) { - const left = Math.max(0, (c.budget || 0) - (c.spent || 0)); - const creative = c.type === 'banner' && c.imageUrl ? '' : esc(c.title || c.name); - const act = c.status === 'active' ? '' - : c.status === 'paused' ? '' : ''; - return '#' + c.id + (c.house ? 'HOUSE' : '') + '' - + (showOwner ? '' + esc(c.house ? 'house' : c.owner) + '' : '') - + '' + esc(c.type) + '' - + '' + esc(c.name) + '
' + creative + '
' + esc(c.targetUrl) + '' - + '' + esc(c.status) + '' - + '' + (c.spent || 0).toLocaleString() + ' / ' + (c.budget || 0).toLocaleString() + '
' + left.toLocaleString() + ' left
' - + '' + (c.imps || 0).toLocaleString() + (c.impsNas ? ' +' + c.impsNas + ' nas' : '') + '
' + (c.clicks || 0) + ' clicks
' - + '' + when(c.created) + '' - + '' + act + ''; - } - function campHead(showOwner) { - return 'ID' + (showOwner ? 'Owner' : '') + 'TypeCampaignStatusSpent / capDeliveryCreated'; - } - async function loadHouse() { - const r = await api('/api/admin/campaigns'); - rates = r.rates || rates; sizes = r.bannerSizes || sizes; houseOwner = r.houseOwner || houseOwner; - if (!$('hSize').options.length) $('hSize').innerHTML = sizes.map(s => '').join(''); - if (!$('hWatchSecs').options.length) $('hWatchSecs').innerHTML = (rates.videoTiers || []).map(t => '').join(''); - if (!$('hFeatDays').options.length) $('hFeatDays').innerHTML = (rates.featuredDurations || [1, 2, 7]).map(d => '').join(''); - showHouseRows(); - loadWallAds(); - const house = (r.campaigns || []).filter(c => c.house); - $('houseSub').textContent = house.filter(c => c.status === 'active').length + ' active · ' + house.length + ' total'; - $('houseTable').innerHTML = house.length ? campHead(false) + house.map(c => campRow(c, false)).join('') : 'No house ads yet. Place one above.'; - } - // wall fallback ads editor - let wallAds = []; - function drawWallAds() { - const w = $('wallAdsList'); - w.innerHTML = wallAds.map((a, i) => '
WALL AD ' + (i + 1) + '' - + '
' - + '

' - + '

' - + '

' - + (a.bannerUrl ? '' : '') - + '
').join('') || '

No wall ads set. Walls fall back to a plain InstantAdPay card.

'; - } - function readWallAds() { - return [...document.querySelectorAll('#wallAdsList .drip-step')].map(c => ({ name: c.querySelector('.wa-name').value.trim(), targetUrl: c.querySelector('.wa-target').value.trim(), bannerUrl: c.querySelector('.wa-banner').value.trim() })); - } - async function loadWallAds() { - try { const r = await api('/api/admin/wall-ads'); wallAds = r.ads || []; $('wallAdsSub').textContent = r.usingDefaults ? 'none set: walls show the default InstantAdPay card' : wallAds.length + ' in rotation'; drawWallAds(); } catch (e) {} - } - $('wallAdsList').addEventListener('click', async e => { - const up = e.target.closest('.wa-upload'); - if (up) { up.parentElement.querySelector('.wa-file').click(); return; } - const b = e.target.closest('[data-wact]'); if (!b) return; - const i = Number(b.closest('.drip-step').dataset.i); wallAds = readWallAds(); - if (b.dataset.wact === 'remove') wallAds.splice(i, 1); - if (b.dataset.wact === 'up' && i > 0) [wallAds[i - 1], wallAds[i]] = [wallAds[i], wallAds[i - 1]]; - if (b.dataset.wact === 'down' && i < wallAds.length - 1) [wallAds[i + 1], wallAds[i]] = [wallAds[i], wallAds[i + 1]]; - drawWallAds(); - }); - $('wallAdsList').addEventListener('change', async e => { - const f = e.target.closest('.wa-file'); if (!f || !f.files[0]) return; - const file = f.files[0]; const card = f.closest('.drip-step'); - try { - const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': file.type }, body: file })).json(); - if (r.error) IAP.status(r.error, 'bad'); else { card.querySelector('.wa-banner').value = r.url; IAP.status('Uploaded.', 'ok'); } - } catch (err) { IAP.status('Upload failed.', 'bad'); } - f.value = ''; - }); - $('wallAdsAdd').addEventListener('click', () => { wallAds = readWallAds(); wallAds.push({ name: '', targetUrl: '', bannerUrl: '' }); drawWallAds(); }); - $('wallAdsSave').addEventListener('click', busy($('wallAdsSave'), async () => { - $('wallAdsErr').hidden = true; - try { const r = await api('/api/admin/wall-ads', { ads: readWallAds() }, 'PATCH'); wallAds = r.ads || []; drawWallAds(); IAP.status('Wall ads saved.', 'ok'); await loadWallAds(); } - catch (e) { $('wallAdsErr').textContent = e.message; $('wallAdsErr').hidden = false; } - })); - document.addEventListener('click', async e => { - const b = e.target.closest('[data-act][data-id]'); if (!b) return; - b.disabled = true; - try { - await api('/api/admin/campaigns/' + b.dataset.id + '/' + b.dataset.act, {}); - IAP.status('Campaign #' + b.dataset.id + ' ' + (b.dataset.act === 'pause' ? 'paused' : 'resumed') + '.', 'ok'); - await Promise.all([loadHouse(), loadCampaigns()]); - } catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } - }); - - // ── all campaigns ── - let allCamps = []; - async function loadCampaigns() { - loadLoginLine().catch(e => IAP.status(e.message, 'bad')); - const r = await api('/api/admin/campaigns'); - allCamps = r.campaigns || []; - drawCamps(); - } - // prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time. - const lqWhen = ts => ts ? esc(ctWhen(ts)) : 'unknown'; // ctWhen (below) prints Central time - async function loadLoginLine() { - const d = await api('/api/admin/login-queue'); - $('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open'; - $('lqTable').innerHTML = 'PlaceIDOwnerCampaignPaidQueued atEstimated start' - + (d.queue.length ? d.queue.map(c => '#' + c.place + '#' + c.id + '' + esc(c.owner) + '' - + '' + esc(c.name) + '
' + esc(c.targetUrl) + '
' - + '' + Number(c.paid || 0).toLocaleString() + '' + lqWhen(c.queuedAt) + '' + lqWhen(c.estStart) + '' - + '').join('') - : 'Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.'); - } - document.addEventListener('click', async e => { - const b = e.target.closest('[data-lqcancel]'); if (!b) return; - const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' }); - if (!ok) return; - b.disabled = true; - try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); } - catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } - }); - function drawCamps() { - const q = ($('campFilter').value || '').trim().toLowerCase(); - const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q)); - $('campSub').textContent = list.length + ' of ' + allCamps.length; - $('campTable').innerHTML = list.length ? campHead(true) + list.map(c => campRow(c, true)).join('') : 'Nothing matches.'; - } - $('campFilter').addEventListener('input', drawCamps); - - // ── members ── - let allMembers = []; - async function loadTank() { - try { - const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return; - $('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window'; - $('tankWait').innerHTML = 'WaitingEmailJoinedLast sign-in' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '').join('') : 'empty'); - $('tankAdopt').innerHTML = 'MemberAdopted byWhenWindow endsStatus' + (r.adoptions.length ? r.adoptions.map(a => '' + esc(a.adopteeName) + '' + esc(a.adopterName) + '' + when(a.ts) + '' + (a.status === 'released' ? '' : when(a.expires)) + '' + esc(a.status) + '').join('') : 'none yet'); - } catch (e) {} - } - async function loadMembers() { - loadTank(); loadFraud(); - const r = await api('/api/admin/members'); - allMembers = r.members || []; - drawMembers(); - } - function drawMembers() { - const q = ($('memFilter').value || '').trim().toLowerCase(); - const list = allMembers.filter(a => !q || [a.email, a.username, a.memberId, a.sponsorRef, a.address, a.code].join(' ').toLowerCase().includes(q)); - $('memSub').textContent = list.length + ' of ' + allMembers.length; - $('memTable').innerHTML = 'EmailUsernameMember #WalletSponsorPositionsViaCodeJoined' - + list.map(a => '' + esc(a.email) + '' + (a.username ? '@' + esc(a.username) : 'none') + '' - + '' + (a.memberId ? '#' + a.memberId : 'free') + '' - + '' + (a.address ? esc(a.address.slice(0, 8) + '…' + a.address.slice(-6)) : 'none') + '' - + '' + (a.sponsorName ? esc(a.sponsorName) + (a.sponsorVia === 'code' ? ' via code ' + esc(a.sponsorRef) + '' : a.sponsorVia === 'member #' ? ' via #' + esc(a.sponsorRef) + '' : '') : a.sponsorRef ? 'dead link: ' + esc(a.sponsorRef) + '' : 'none') + '' + (a.positions ? a.positions : '0') + '' + esc(a.joinedVia || '') + '' + esc(a.code || '') + '' - + '' + when(a.created) + (a.suspended ? ' suspended' : '') + ((a.flags || []).length ? ' ' + esc((a.flags || []).join(' ')) + '' : '') + '' - + ' ').join(''); - } - $('memFilter').addEventListener('input', drawMembers); - document.addEventListener('click', async e => { - const b = e.target.closest('[data-susp]'); if (!b) return; - const on = b.dataset.on === '1'; - if (on) { if (!await IAP.confirmBox('Unsuspend ' + b.dataset.susp + '? They can sign in again.', { title: 'Unsuspend', ok: 'Unsuspend', cancel: 'Cancel' })) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: false }, 'PATCH'); } - else { const why = await IAP.ask({ title: 'Suspend ' + b.dataset.susp, text: 'They will be signed out everywhere and cannot sign in. Reason (shown to admins only):', value: 'duplicate account', ok: 'Suspend' }); if (why === null || why === undefined) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: true, reason: why, flags: ['multi-account'] }, 'PATCH'); } - loadMembers(); - }); - async function loadFraud() { - const box = $('fraudBox'); if (!box) return; - try { - const r = await api('/api/admin/fraud'); - const grp = (title, list) => list.length ? '

' + title + '

' + list.map(g => '
' + esc(g.key) + ': ' + g.emails.map(x => esc(x)).join(', ') + '
').join('') : ''; - box.innerHTML = '

Duplicate signals

' + r.total + ' accounts with sign-in signals recorded (since 2026-09-16). Shared browser = same device cookie; shared IP within 30 days. Households are legal; two buying accounts on one browser are not.

' - + grp('Shared browser', r.sharedDevice) + grp('Shared IP', r.sharedIp) - + (r.flagged.length ? '

Flagged

' + r.flagged.map(f => '
' + esc(f.email) + ' [' + esc(f.flags.join(', ')) + ']' + (f.suspended ? ' suspended' : '') + '
').join('') : '') - + (r.suspended.length ? '

Suspended

' + r.suspended.map(x => '
' + esc(x.email) + ' (' + esc(x.reason || '') + ', ' + when(x.at) + ')
').join('') : '') - + (!r.sharedDevice.length && !r.sharedIp.length && !r.flagged.length && !r.suspended.length ? '

Nothing shared or flagged yet.

' : '') - // Approved exceptions (Marty, 2026-09-17): people okayed to hold more than one - // account. Lives right under the signals so the two are read together. - + '
' - + '

Approved exceptions

' - + '

People you have okayed to hold more than one account. They are never blocked at sign-up, never hard-flagged, and keep their leaderboard and adoption rights. Add the address of the account they ALREADY have, or the new one, either works. Suspension still overrides this.

' - + '
' - + '' - + '' - + '
' - + '
' - + ((r.allow || []).length - ? (r.allow || []).map(a => '
' - + '' + esc(a.email) + '' - + (a.note ? '' + esc(a.note) + '' : '') - + '' + when(a.at) + '' - + 'remove
').join('') - : '

No exceptions yet. Everyone is held to one account per person.

') - + '
'; - const say = (t, bad) => { const m = $('allowMsg'); if (m) { m.textContent = t; m.style.color = bad ? 'var(--bad)' : 'var(--mint)'; } }; - const addBtn = $('allowAdd'); - if (addBtn) addBtn.addEventListener('click', async () => { - const em = ($('allowEmail').value || '').trim(); const note = ($('allowNote').value || '').trim(); - if (!em) return say('Enter an email address.', true); - addBtn.disabled = true; say('Saving…'); - try { await api('/api/admin/fraud/allow', { email: em, note }); say('Added.'); loadFraud(); } - catch (err) { say(err.message, true); addBtn.disabled = false; } - }); - box.querySelectorAll('[data-allow-rm]').forEach(a => a.addEventListener('click', async ev => { - ev.preventDefault(); - const em = a.getAttribute('data-allow-rm'); - if (!(await IAP.confirmBox(em + ' goes back to the normal one-account-per-person checks. Existing accounts are not touched.', { title: 'Remove exception', ok: 'Remove', cancel: 'Cancel' }))) return; - try { await api('/api/admin/fraud/allow', { email: em, remove: true }); loadFraud(); } - catch (err) { say(err.message, true); } - })); - } catch (e) { box.innerHTML = '

' + esc(e.message) + '

'; } - } - document.addEventListener('click', async e => { - const b = e.target.closest('[data-spon]'); if (!b) return; - const v = await IAP.ask({ title: 'Sponsor for ' + b.dataset.spon, text: 'Username, share code, or member #. Leave blank to clear.', value: b.dataset.cur, ok: 'Save' }); - if (v === null || v === undefined) return; - try { - await api('/api/admin/members', { email: b.dataset.spon, sponsorRef: v.trim() }, 'PATCH'); - IAP.status('Sponsor updated.', 'ok'); - await loadMembers(); - } catch (err) { IAP.status(err.message, 'bad'); } - }); - - // ── member card: search, drill down, act (Marty, 2026-09-13) ── - let mcCur = null; - const polOf = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } }; - const ago = ts => { if (!ts) return 'never'; const d = Date.now() - Number(ts); const h = Math.floor(d / 3600000); return h < 1 ? Math.max(1, Math.floor(d / 60000)) + ' min ago' : h < 48 ? h + ' h ago' : Math.floor(h / 24) + ' days ago'; }; - const memLink = (email, label) => '' + esc(label) + ''; - async function openMember(q) { - const msg = $('memSearchMsg'); msg.hidden = true; - let d; - try { d = await api('/api/admin/member?q=' + encodeURIComponent(q)); } catch (e) { msg.textContent = e.message; msg.hidden = false; msg.className = 'small bad'; return; } - renderMember(d); - } - function kv(rows) { return '' + rows.map(r => '').join('') + '
' + r[0] + '' + r[1] + '
'; } - function renderMember(d) { - mcCur = d; const a = d.account; $('memHits').hidden = true; - $('memCard').hidden = false; document.querySelectorAll('#pane-members > .card').forEach(c => { if (c.id !== 'memCard' && c.id !== 'memSearchCard') c.hidden = true; }); - $('mcName').textContent = (a.username ? '@' + a.username : a.email) + (a.memberId ? ' · member #' + a.memberId : ' · free member'); - $('mcSub').textContent = 'joined ' + when(a.created) + ' · last seen ' + ago(a.lastSeen); - $('mcWall').hidden = !a.username; if (a.username) $('mcWall').href = '/wall/' + a.username; - const ch = d.chain, cr = d.credits, t = d.totals; - const level = ch && !ch.readError ? (ch.buyerCount >= 5 ? 'level 3 (5+ buyers)' : ch.buyerCount >= 2 ? 'level 2 (2 buyers)' : 'level 1') : ''; - let h = '
'; - h += '

Identity

' + kv([ - ['Email', esc(a.email)], ['Username', a.username ? '@' + esc(a.username) : 'not set'], ['Share code', esc(a.code || '')], - // A linked wallet is NOT an active position: linking is a free signature, switching on - // payouts is a separate transaction that creates the position. The address used to sit here - // on its own, which reads as "he is set up" when he is not (Marty, 2026-09-17, @mcbit1). - ['Main wallet', a.address - ? '' + esc(a.address) + '' - + (ch && !ch.readError - ? ' payouts ON' - : ' payouts OFF') - : 'none linked'], - ['PolyWarriors mint passes', d.pwPasses ? '' + (d.pwPasses.n || 0) + ' unused (earned ' + (d.pwPasses.earned || 0) + ', used ' + (d.pwPasses.used || 0) + ')' : 'none'], - ['Extra positions', d.positions.length ? d.positions.map(p => '' + esc(p.address.slice(0, 8) + '…' + p.address.slice(-6)) + '' + (p.memberId ? ' = #' + p.memberId : ' (unregistered)')).join('
') : 'none'], - ['Sponsor (site)', d.upline.length ? memLink(d.upline[0].email, d.upline[0].name) + ' token ' + esc(a.sponsorRef || '') + '' : (a.sponsorRef ? 'unresolved: ' + esc(a.sponsorRef) + '' : 'none (company)')], - ['Upline chain', d.upline.length > 1 ? d.upline.map(u => memLink(u.email, u.name)).join(' → ') : '-'], - ['Joined via', esc(a.joinedVia || 'join page') + (a.joinedRef ? ' from ' + esc(a.joinedRef) : '')], - ['Line banner', a.lineTargetUrl ? '' + esc(a.lineTargetUrl.slice(0, 50)) + '' : 'not set'], - ['Chat', a.chatAvailable ? 'available' : 'switched off']]) + '
'; - h += '

On-chain and money

' + kv([ - // Say WHICH of the two "not registered" states this is, and what it costs them, so the row - // above never gets read as "he is fine". - ['Registered', ch - ? (ch.readError ? 'read error' : 'yes, #' + ch.memberId + ' under ' + (ch.sponsorId ? '#' + ch.sponsorId + (d.names[ch.sponsorId] ? ' @' + esc(d.names[ch.sponsorId]) : '') : 'nobody')) - : (a.address - ? 'no wallet linked, but payouts were never switched on, so no position exists. Sales in their line walk up to their sponsor and lock there.' - : 'no no wallet linked yet.')], - ['Qualifying buyers', ch && !ch.readError ? ch.buyerCount + ' · ' + level : '-'], - ['Packages bought', t.purchases + (t.purchases ? ' · $' + (t.spentCents / 100).toFixed(0) + ' · ' + polOf(t.spentWei) + ' POL' : '')], - ['Payouts received', t.payoutsIn + (t.payoutsIn ? ' · ' + polOf(t.receivedWei) + ' POL' : '')], - ['Credits', cr ? cr.available.toLocaleString() + ' available · ' + cr.inCampaigns.toLocaleString() + ' in campaigns · ' + cr.total.toLocaleString() + ' total' : '-'], - ['Earned pool', d.earnedSplit ? d.earnedSplit.total.toLocaleString() + ' (' + (d.earnedSplit.grade || 0).toLocaleString() + ' purchased-grade)' : '-'], - ['Old-site account', d.legacy ? 'had a ' + (d.legacy.brand === 'both' ? 'Faucet Wave and Tier One Ads' : d.legacy.brand === 'tier1ads' ? 'Tier One Ads' : 'Faucet Wave') + ' account (' + d.legacy.seg + ') · welcome-back credits ' + (d.legacy.grant ? d.legacy.grant.credits + ' issued ' + when(d.legacy.grant.at) : 'not issued (joined outside the legacy bridge)') : 'none on record'], - ['Promo codes', d.promos.length ? d.promos.map(p => esc(p.code) + ' (' + p.credits + ', ' + when(p.ts) + ')').join('
') : 'none'], - ['Drip', d.drip ? (d.drip.stopped ? 'stopped' : 'step ' + d.drip.step + ', next ' + when(d.drip.next_at)) + (d.drip.angle ? ' · ' + esc(d.drip.angle) : '') : '-'], - ['Holding tank', d.tank ? (d.tank.waiting ? 'waiting for a sponsor' : 'not in tank') + (d.tank.adoptedBy.length ? ' · adopted by ' + d.tank.adoptedBy.map(x => memLink(x.email, x.name)).join(', ') : '') + (d.tank.adopted.length ? ' · adopted ' + d.tank.adopted.map(x => memLink(x.email, x.name)).join(', ') : '') : '-'], - ['Earning', d.earning ? 'today ' + d.earning.today + '/5' + (d.earning.claimed ? ' claimed' : '') + ' · streak day ' + d.earning.streakDay + (d.activeDays14 !== undefined ? ' · active ' + d.activeDays14 + ' of last 14 days, ' + d.claims14 + ' claims' : '') : '-'], - ['Visits / videos / chat', (d.visits || 0) + ' verified visits · ' + (d.videos || 0) + ' video watches · ' + (d.messageCount || 0) + ' messages']]) + '
'; - // line - h += '

Line (' + d.lineCounts.join(' / ') + ')

'; - if (!d.line.length) h += '

Nobody in their line yet.

'; - for (const L of d.line) { - h += '

Level ' + L.level + ' · ' + L.members.length + '

' - + L.members.map(m => '').join('') + '
MemberMember #WalletBoughtQualifiedJoinedLast seen
' + memLink(m.email, m.name) + (L.level === 1 ? '
' + esc(m.email) + '' : '') + '
' + (m.memberId ? '#' + m.memberId : 'free') + '' + (m.wallet ? 'yes' : 'no') + '' + (m.bought ? 'yes' : 'no') + '' + (m.qualified ? 'yes' : '') + '' + when(m.joined) + '' + ago(m.lastSeen) + '
'; - } - // purchases + payouts + campaigns - h += '

Purchases

' - + (d.purchases.length ? d.purchases.map(p => '').join('') : '') + '
WhenPositionPackagePaidTx
' + when(p.ts) + '#' + p.buyerId + '$' + (p.priceCents / 100).toFixed(0) + ' · ' + Number(p.credits || 0).toLocaleString() + ' cr' + polOf(p.paidWei) + ' POL' + esc(p.tx.slice(0, 10)) + '…
No purchases.
'; - h += '

Payouts received

' - + (d.received.length ? d.received.map(r => '').join('') : '') + '
WhenFromTierAmount
' + when(r.ts) + '#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '' + r.tier + '' + polOf(r.amountWei) + ' POL
Nothing received yet.
'; - h += '

Campaigns (' + d.campaigns.length + ')

' - + (d.campaigns.length ? d.campaigns.map(c => '').join('') : '') + '
#TypeStatusBudgetSpentViewsClicksCreated
' + c.id + '' + esc(c.type) + '' + esc(c.status) + '' + Number(c.budget || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + (c.pack ? Number(c.views || 0).toLocaleString() + ' of ' + Number(c.pack).toLocaleString() + ' visits' : Number(c.views || 0).toLocaleString()) + '' + Number(c.clicks || 0).toLocaleString() + '' + when(c.created) + '
No campaigns.
'; - $('mcBody').innerHTML = h; - if (location.hash !== '#members') history.replaceState(null, '', '#members'); - loadTrace(d); - } - // payment trace under the member card (2026-09-16): per purchase, who was paid / skipped and why - async function loadTrace(d) { - const ch = d.chain || {}; const mid = ch.memberId || (d.account && d.account.memberId) || 0; - const box = document.createElement('div'); box.id = 'mcTrace'; box.innerHTML = '

Payment trace

Reading the chain…

'; - $('mcBody').appendChild(box); - if (!mid) { box.innerHTML = '

Payment trace

Not activated on the chain, nothing to trace.

'; return; } - try { - const r = await api('/api/admin/trace?who=' + mid); - const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; - let h = '

Payment trace

' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' · every purchase this member was part of, newest first.

'; - if (!r.purchases.length) h += '

No purchases involving them yet.

'; - for (const p of r.purchases) { - h += '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought $' + (p.priceCents / 100).toFixed(0) + ' (' + polOf(p.paidWei) + ' POL)' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + ' · ' + esc(p.tx.slice(0, 12)) + '…
'; - for (const t of p.tiers) { - let line = 'L' + t.tier + ' ' + t.pct + '%: '; - for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' buyers then' : esc(x.reason)) + ') → '; - line += t.paidTo ? '' + nm(t.paidTo) + ' ' + polOf(t.amountWei) + ' POL' : 'no catcher → company'; - h += '
' + line + '
'; - } - h += '
platform ' + polOf(p.adminWei) + ' POL
'; - } - box.innerHTML = h; - } catch (e) { box.innerHTML = '

Payment trace

' + esc(e.message) + '

'; } - } - function closeMember() { $('memCard').hidden = true; document.querySelectorAll('#pane-members > .card').forEach(c => { c.hidden = false; }); } - // live matches while typing: any part of the username, email, member #, share code or wallet - let memHitList = []; - function memMatches(q) { - q = q.toLowerCase(); - return allMembers.filter(a => [a.username, a.email, a.memberId ? '#' + a.memberId : '', a.memberId, a.code, a.address, a.sponsorName].filter(Boolean).join(' ').toLowerCase().includes(q)).slice(0, 12); - } - async function memTypeahead() { - const q = $('memSearch').value.trim(); - if (!allMembers.length) { try { const r = await api('/api/admin/members'); allMembers = r.members || []; } catch (e) {} } - if (q.length < 2) { $('memHits').hidden = true; memHitList = []; return; } - memHitList = memMatches(q); - $('memHits').innerHTML = memHitList.length ? memHitList.map(a => '').join('') - : '

No member matches that.

'; - $('memHits').hidden = false; - } - $('memSearch').addEventListener('input', memTypeahead); - $('memSearch').addEventListener('focus', memTypeahead); - $('memOpen').addEventListener('click', () => { const q = $('memSearch').value.trim(); if (!q) return; if (memHitList.length) openMember(memHitList[0].email); else openMember(q); }); - $('memSearch').addEventListener('keydown', e => { if (e.key === 'Enter') $('memOpen').click(); if (e.key === 'Escape') $('memHits').hidden = true; }); - document.addEventListener('click', e => { if (!e.target.closest('#memSearchCard')) $('memHits').hidden = true; }); - $('mcBack').addEventListener('click', closeMember); - document.addEventListener('click', e => { const l = e.target.closest('[data-mcopen]'); if (l) { e.preventDefault(); openMember(l.dataset.mcopen); } }); - document.querySelectorAll('[data-mcact]').forEach(b => b.addEventListener('click', busy(b, async () => { - if (!mcCur) return; const a = mcCur.account, act = b.dataset.mcact; let body = null; - if (act === 'username') { const v = await IAP.ask({ title: 'Username for ' + a.email, text: '3-20 letters, numbers or underscore. Changing it breaks any invite links they already handed out.', value: a.username || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { username: v }; } - if (act === 'sponsor') { const v = await IAP.ask({ title: 'Sponsor for ' + (a.username ? '@' + a.username : a.email), text: 'Username, share code or member #. Blank = no sponsor (company). Re-points free referrals and future purchases; on-chain sponsorship never changes.', value: a.sponsorRef || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { sponsorRef: v }; } - if (act === 'wallet') { const v = await IAP.ask({ title: 'Main wallet for ' + a.email, text: 'Paste the 0x address that should be their main wallet (the one that paid, if a purchase came from an unlinked account). The member number is re-read from the chain. Blank = unlink.', value: a.address || '', ok: 'Swap' }); if (v === null || v === undefined) return; if (!await IAP.confirmBox('Swap the main wallet for ' + a.email + ' to ' + (v.trim() || 'nothing') + '?', { title: 'Sure?', ok: 'Swap it', cancel: 'Cancel' })) return; body = { address: v }; } - if (act === 'credits') { const v = await IAP.ask({ title: 'Grant credits to ' + (a.username ? '@' + a.username : a.email), text: 'Whole number of earned-pool credits (1 credit = 1 cent of delivery). They can spend them on campaigns right away.', type: 'number', value: '', placeholder: '250', ok: 'Grant' }); if (!v) return; const note = await IAP.ask({ title: 'Reason (kept in the server log)', value: '', placeholder: 'e.g. refund for broken banner', ok: 'Grant' }); body = { grantCredits: v, note: note || '' }; } - if (act === 'delete') { - if (a.memberId) { IAP.status('Registered members cannot be deleted; their position is on-chain.', 'bad'); return; } - if (!await IAP.confirmBox('Delete the free account ' + a.email + '? Their sign-in, referrals link and credits go away. There is no undo.', { title: 'Delete account', ok: 'Delete', cancel: 'Keep it' })) return; - await api('/api/admin/member?email=' + encodeURIComponent(a.email), undefined, 'DELETE'); IAP.status('Account deleted.', 'ok'); closeMember(); loadMembers().catch(() => {}); return; - } - if (!body) return; - const d = await api('/api/admin/member', Object.assign({ email: a.email }, body), 'PATCH'); - renderMember(d); IAP.status('Saved.', 'ok'); loadMembers().catch(() => {}); - }))); - - // ── every admin table: click a header to sort (numbers sort as numbers), inputs with - // class "tfilter" filter the table named in data-for ── - document.addEventListener('click', e => { - const th = e.target.closest('.adm-table th'); if (!th || th.closest('table').classList.contains('kv')) return; - const table = th.closest('table'), hdr = th.parentElement, idx = [...hdr.children].indexOf(th); - const rows = [...table.querySelectorAll('tr')].filter(r => r !== hdr && r.children.length > 1); - const num = s => { const t = String(s).replace(/[$,%\s]/g, '').replace(/…$/, ''); return t !== '' && !isNaN(t) ? Number(t) : null; }; - const dir = th.dataset.dir === 'asc' ? 'desc' : 'asc'; - hdr.querySelectorAll('th').forEach(x => { delete x.dataset.dir; x.classList.remove('sort-asc', 'sort-desc'); }); - th.dataset.dir = dir; th.classList.add('sort-' + dir); - rows.sort((r1, r2) => { const a = (r1.children[idx] || {}).textContent || '', b = (r2.children[idx] || {}).textContent || ''; const na = num(a), nb = num(b); const c = na !== null && nb !== null ? na - nb : a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); return dir === 'asc' ? c : -c; }); - rows.forEach(r => (hdr.parentElement).appendChild(r)); - }); - document.addEventListener('input', e => { - const inp = e.target.closest('.tfilter'); if (!inp) return; - const table = $(inp.dataset.for); if (!table) return; - const q = inp.value.trim().toLowerCase(); let shown = 0; - [...table.querySelectorAll('tr')].forEach((r, i) => { if (i === 0 || r.querySelector('th')) return; const hit = !q || r.textContent.toLowerCase().includes(q); r.hidden = !hit; if (hit) shown++; }); - const c = inp.parentElement.querySelector('.tfilter-count'); if (c) c.textContent = q ? shown + ' shown' : ''; - }); - - // ── release notes + roadmap (Marty, 2026-09-14) ── - async function loadReleases() { - loadUpdates(); - const d = await api('/api/admin/releases'); - $('rnSub').textContent = d.notes.length + ' notes'; $('rmSub').textContent = d.roadmap.length + ' items'; - $('rnTable').innerHTML = 'DateTitleTags' + (d.notes.length ? d.notes.map(n => '' + esc(n.date) + '' + esc(n.title) + '' + esc(n.tags.join(', ')) + ' ').join('') : 'No notes yet.'); - $('rmTable').innerHTML = 'StatusTitleETA#' + (d.roadmap.length ? d.roadmap.map(r => '' + esc(r.status) + '' + esc(r.title) + '' + (r.note ? '
' + esc(r.note) + '' : '') + '' + esc(r.eta || '') + '' + (r.order || '') + ' ').join('') : 'Nothing on the roadmap yet.'); - $('rnTable').querySelectorAll('[data-rnedit]').forEach(b => b.addEventListener('click', () => { const n = d.notes.find(x => x.id === b.dataset.rnedit); if (!n) return; $('rnId').value = n.id; $('rnTitle').value = n.title; $('rnDate').value = n.date; $('rnTags').value = n.tags.join(', '); $('rnBody').value = n.body; $('rnTitle').focus(); })); - $('rmTable').querySelectorAll('[data-rmedit]').forEach(b => b.addEventListener('click', () => { const r = d.roadmap.find(x => x.id === b.dataset.rmedit); if (!r) return; $('rmId').value = r.id; $('rmTitle').value = r.title; $('rmStatus').value = r.status; $('rmEta').value = r.eta || ''; $('rmOrder').value = r.order || ''; $('rmNote').value = r.note || ''; $('rmTitle').focus(); })); - $('rnTable').querySelectorAll('[data-rndel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this release note?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=notes&id=' + encodeURIComponent(b.dataset.rndel), undefined, 'DELETE'); loadReleases(); })); - $('rmTable').querySelectorAll('[data-rmdel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this roadmap item?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=roadmap&id=' + encodeURIComponent(b.dataset.rmdel), undefined, 'DELETE'); loadReleases(); })); - } - // ── member update emails (Marty, 2026-09-14) ── - async function loadUpdates() { - if (!$('updCard')) return; - try { - const d = await api('/api/admin/updates'); - $('updSub').textContent = (d.mailer ? '' : 'mailer not configured · ') + (d.lastSentAt ? 'last send ' + new Date(d.lastSentAt).toLocaleString() : 'nothing sent yet') + (d.running ? ' · sending now' : ''); - const keep = $('updAudience').value; - $('updAudience').innerHTML = Object.entries(d.audiences).map(([k, v]) => '').join(''); - if (keep) $('updAudience').value = keep; - if (!d.counts) setTimeout(() => loadUpdates().catch(() => {}), 15000); // the counts are being worked out in the background - // a re-render (the background count refresh) must keep whatever is ticked; only the first render pre-ticks fresh notes, - // and a saved draft decides for itself (Marty, 2026-09-28: a test send carried every note because a refresh re-ticked them) - const wasTicked = new Set([...$('updNotes').querySelectorAll('input:checked')].map(i => i.value)), rendered = $('updNotes').querySelector('input') !== null; - $('updNotes').innerHTML = d.notes.length ? d.notes.map(n => '').join('') : 'No release notes yet.'; - $('updLog').innerHTML = 'WhenSubjectAudienceSent' + (d.sends.length ? d.sends.map(x => '' + new Date(x.ts).toLocaleString() + '' + esc(x.subject) + '' + esc(d.audiences[x.audience] || x.audience) + '' + x.sent + ' of ' + x.total + (x.skipped ? ' · ' + x.skipped + ' opted out' : '') + (x.failed ? ' · ' + x.failed + ' failed' : '') + (x.unknown ? ' · ' + x.unknown + ' unchecked (Sendy gave no answer)' : '') + (x.status === 'running' ? ' · running' : '') + '').join('') : 'None yet.'); - if (d.draft && !updDraftLoaded) { updDraftLoaded = true; $('updSubject').value = d.draft.subject || ''; $('updIntro').value = d.draft.intro || ''; $('updClosing').value = d.draft.closing || ''; if (d.draft.audience) $('updAudience').value = d.draft.audience; $('updNotes').querySelectorAll('input').forEach(i => { i.checked = (d.draft.noteIds || []).includes(i.value); }); $('updSub').textContent += ' · draft loaded (saved ' + new Date(d.draft.savedAt).toLocaleString() + ')'; } - if (d.running) setTimeout(loadUpdates, 4000); - } catch (e) { $('updSub').textContent = e.message; } - } - let updDraftLoaded = false; - const updInput = () => ({ subject: $('updSubject').value, intro: $('updIntro').value, closing: $('updClosing').value, noteIds: [...$('updNotes').querySelectorAll('input:checked')].map(i => i.value), audience: $('updAudience').value }); - if ($('updCard')) { - $('updSaveDraft').addEventListener('click', busy($('updSaveDraft'), async () => { await api('/api/admin/updates/draft', updInput()); IAP.status('Draft saved.', 'ok'); })); - $('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; })); - $('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); })); - $('updSend').addEventListener('click', busy($('updSend'), async () => { - const inp = updInput(); if (!inp.noteIds.length && !String(inp.intro || '').trim()) { IAP.status('Write an intro or pick at least one note.', 'bad'); return; } - const opt = $('updAudience').selectedOptions[0].textContent; - if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return; - const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates(); - })); - } - $('rnClear').addEventListener('click', () => { ['rnId', 'rnTitle', 'rnDate', 'rnTags', 'rnBody'].forEach(id => { $(id).value = ''; }); }); - $('rmClear').addEventListener('click', () => { ['rmId', 'rmTitle', 'rmEta', 'rmOrder', 'rmNote'].forEach(id => { $(id).value = ''; }); $('rmStatus').value = 'planned'; }); - $('rnSave').addEventListener('click', busy($('rnSave'), async () => { await api('/api/admin/releases', { kind: 'note', id: $('rnId').value || null, title: $('rnTitle').value, date: $('rnDate').value, tags: $('rnTags').value, body: $('rnBody').value }); IAP.status('Note saved.', 'ok'); $('rnClear').click(); loadReleases(); })); - $('rmSave').addEventListener('click', busy($('rmSave'), async () => { await api('/api/admin/releases', { kind: 'roadmap', id: $('rmId').value || null, title: $('rmTitle').value, status: $('rmStatus').value, eta: $('rmEta').value, order: $('rmOrder').value, note: $('rmNote').value }); IAP.status('Roadmap item saved.', 'ok'); $('rmClear').click(); loadReleases(); })); - - // ── reports + burns ── - // ── profit and loss ── - let pnlDays = 30; - const pol = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } }; - const usdOf = (w, px) => { try { return '$' + ((Number(BigInt(w || '0') / 10n ** 14n) / 10000) * px).toLocaleString(undefined, { maximumFractionDigits: 0 }); } catch (e) { return '$0'; } }; - // ── traffic: referring domains / sources, landing pages, angles, by day ── - let trfDays = 30; - document.querySelectorAll('#trfRange [data-days]').forEach(b => b.addEventListener('click', () => { trfDays = Number(b.dataset.days); document.querySelectorAll('#trfRange [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadTraffic().catch(e => IAP.status(e.message, 'bad')); })); - async function loadPromos() { - const d = await (await fetch('/api/admin/promos')).json(); - if (d.error) throw new Error(d.error); - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const when = t => t ? new Date(t).toLocaleDateString() : ''; - $('pcTable').innerHTML = 'CodeCreditsPartnerUsesMaxExpiresStatus' - + (d.codes.length ? d.codes.map(c => '' + esc(c.code) + '' + c.credits.toLocaleString() + '' + esc(c.partner) + '' + c.uses + '' + (c.maxUses || '∞') + '' + (c.expires ? when(c.expires) : '') + '' + (c.active ? 'active' : 'off') + '').join('') : 'No codes yet.'); - $('pcRecent').innerHTML = 'WhenCodeEmailCreditsVia' - + (d.recent.length ? d.recent.map(r => '' + new Date(r.ts).toLocaleString() + '' + esc(r.code) + '' + esc(r.email) + '' + r.credits + '' + esc(r.via) + '').join('') : 'No redemptions yet.'); - document.querySelectorAll('[data-pctoggle]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/admin/promos', { code: b.dataset.pctoggle, active: b.dataset.on === '1' }, 'PATCH'); loadPromos(); } catch (e) { IAP.status(e.message, 'bad'); } - })); - } - if ($('pcSave')) $('pcSave').addEventListener('click', async () => { - const msg = $('pcMsg'); msg.hidden = false; - try { - const r = await api('/api/admin/promos', { code: $('pcCode').value, credits: $('pcCredits').value, partner: $('pcPartner').value, maxUses: $('pcMax').value, expires: $('pcExpires').value || null, active: true }); - msg.textContent = 'Saved ' + r.code.code + ': ' + r.code.credits + ' credits.'; msg.style.color = 'var(--mint)'; - $('pcCode').value = ''; $('pcCredits').value = ''; $('pcPartner').value = ''; loadPromos(); - } catch (e) { msg.textContent = e.message; msg.style.color = '#ff8a8a'; } - }); - async function loadTraffic() { - loadPromos().catch(e => IAP.status(e.message, 'bad')); - loadLoginShows().catch(e => IAP.status(e.message, 'bad')); - const d = await (await fetch('/api/admin/traffic?days=' + trfDays)).json(); - if (d.error) throw new Error(d.error); - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const n = v => Number(v || 0).toLocaleString(); - $('trfSub').textContent = 'last ' + d.days + ' days · ' + n(d.totals.hits) + ' page views · ' + n(d.totals.joinViews) + ' join-page views · ' + n(d.totals.signups) + ' signups · ' + n(d.totals.buyers) + ' buyers'; - // conversion columns (Marty, 2026-09-13): visits = page views + join-page views; signup rate is per visit, - // registered and buyer rates are per signup (what happened to the people who did sign up) - const pct = (num, den) => den ? (100 * num / den).toFixed(num && 100 * num / den < 10 ? 1 : 0) + '%' : '-'; - $('trfSources').innerHTML = 'SourcePage
viewsJoin-page
viewsSignupsVisit →
signupRegisteredSignup →
registered$20+
buyersSignup →
buyer' - + (d.sources.length ? d.sources.map(s => '' + esc(s.source) + '' + n(s.hits) + '' + n(s.joinViews) + '' + n(s.signups) + '' + pct(s.signups, s.hits + s.joinViews) + '' + n(s.registered) + '' + pct(s.registered, s.signups) + '' + n(s.buyers) + '' + pct(s.buyers, s.signups) + '').join('') : 'Nothing recorded in this range yet.'); - // games to members (2026-10-05): card taps that reached InstantAdPay, first packages bought, dollars, per game (all time) - if (d.starter) { const st = d.starter, rows = Object.values(st.games); - $('stSub').textContent = (st.settings.on ? 'on' : 'off') + ' · welcome bonus ' + st.settings.bonus + ' credits · ' + st.granted + ' granted'; - $('trfStarter').innerHTML = 'GameOffer tapsFirst packagesPackage $Tap → buy' + rows.map(g => '' + esc(g.name) + '' + n(g.visits) + '' + n(g.buyers) + '$' + g.usd.toFixed(2) + '' + pct(g.buyers, g.visits) + '').join(''); } - $('trfPaths').innerHTML = 'PageViews' + (d.paths.length ? d.paths.map(p => '' + esc(p.path) + '' + n(p.hits) + '').join('') : 'No page views yet.'); - $('trfAngles').innerHTML = 'AngleJoin-page
viewsSignupsView →
signup' + (d.angles.length ? d.angles.map(a => '' + esc(a.angle) + '' + n(a.views) + '' + n(a.signups) + '' + pct(a.signups, a.views) + '').join('') : 'No angle data yet.'); - $('trfDaily').innerHTML = 'DayPage viewsSignups' + (d.daily.length ? d.daily.slice().reverse().map(x => '' + esc(x.day) + '' + n(x.hits) + '' + n(x.signups) + '').join('') : 'Nothing yet.'); - } - // login-ad showings per Central day (2026-10-18): the dashboard gate vs the games' sign-in kit, member slot vs house ad, - // and sign-ins that had no login ad to show. A week of these decides whether the 3-slot cap goes up. - async function loadLoginShows() { - const d = await (await fetch('/api/admin/login-shows?days=14')).json(); - if (d.error) throw new Error(d.error); - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const n = v => Number(v || 0).toLocaleString(), shown = x => x.member + x.house; - const week = d.days.slice(0, 7).reduce((a, x) => { a.dash += shown(x.dashboard); a.games += shown(x.games); return a; }, { dash: 0, games: 0 }); - $('lsSub').textContent = 'last 7 days: ' + n(week.dash + week.games) + ' shown (' + n(week.dash) + ' dashboard, ' + n(week.games) + ' games) · slots ' + d.slots.used + ' of ' + d.slots.max + ' taken'; - $('trfLogin').innerHTML = 'Day (CT)Dashboard
shownGames
shownTotal
shownOf which
house adSign-ins with
no login adBy game' - + d.days.map(x => '' + esc(x.day) + '' + n(shown(x.dashboard)) + '' + n(shown(x.games)) + '' + n(shown(x.dashboard) + shown(x.games)) + '' + n(x.dashboard.house + x.games.house) + '' + n(x.dashboard.none + x.games.none) + '' - + (Object.keys(x.byGame).length ? Object.entries(x.byGame).map(([g, v]) => esc(g) + ' ' + n(v)).join(', ') : '-') + '').join(''); - } - // ── blog: coaching articles, public at /blog (Marty, 2026-09-12) ── - let blCur = null; // slug being edited, or null for a new one - function blCount() { - const t = $('blTitle').value.length, e = $('blExcerpt').value.length; - $('blTitleCount').textContent = t + '/60' + (t > 60 ? ' (long)' : ''); - $('blExcCount').textContent = e + ' chars' + (e && (e < 120 || e > 160) ? ' (aim 120-160)' : ''); - const w = $('blBody').textContent.trim().split(/\s+/).filter(Boolean).length; - $('blWords').textContent = w + ' words'; - } - ['blTitle', 'blExcerpt'].forEach(id => $(id).addEventListener('input', blCount)); - $('blBody').addEventListener('input', blCount); - $('blTitle').addEventListener('input', () => { if (!blCur && !$('blSlug').dataset.touched) $('blSlug').value = $('blTitle').value.toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80); }); - $('blSlug').addEventListener('input', () => { $('blSlug').dataset.touched = '1'; }); - document.querySelectorAll('.ed-bar [data-bl]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand(b.dataset.bl, false, null); })); - document.querySelectorAll('.ed-bar [data-blblock]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand('formatBlock', false, b.dataset.blblock); })); - $('blLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; - const u = await IAP.ask({ title: 'Link address', label: 'https://', placeholder: 'https://instantadpay.com/join/martbost', ok: 'Insert' }); - if (u) { $('blBody').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } - }); - $('blImgBtn').addEventListener('click', () => $('blImgFile').click()); - $('blImgFile').addEventListener('change', async () => { - const f = $('blImgFile').files[0]; if (!f) return; - try { - const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) throw new Error(r.error); - $('blBody').focus(); - const html = ''; - if (!document.execCommand('insertHTML', false, html)) $('blBody').insertAdjacentHTML('beforeend', html); - blCount(); - } catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); } - $('blImgFile').value = ''; - }); - $('blCoverBtn').addEventListener('click', () => $('blCoverFile').click()); - $('blCoverFile').addEventListener('change', () => upload($('blCoverFile'), $('blCoverInfo'), $('blCover'))); - $('blHtmlBtn').addEventListener('click', () => { - const raw = !$('blHtml').hidden; - if (raw) { $('blBody').innerHTML = $('blHtml').value; $('blHtml').hidden = true; $('blBody').hidden = false; } - else { $('blHtml').value = $('blBody').innerHTML; $('blBody').hidden = true; $('blHtml').hidden = false; } - blCount(); - }); - function blBodyHtml() { return $('blHtml').hidden ? $('blBody').innerHTML : $('blHtml').value; } - function blMsg(t, bad) { $('blMsg').textContent = t; $('blMsg').hidden = !t; $('blMsg').className = 'small ' + (bad ? 'bad' : 'ok'); } - function blOpen(post) { - blCur = post ? post.slug : null; - $('blogList').hidden = true; $('blogEditor').hidden = false; - $('blEdTitle').textContent = post ? 'Edit article' : 'New article'; - $('blEdSub').textContent = post ? (post.status === 'published' ? 'published ' + when(post.publishedAt) + ' · ' + (post.views || 0) + ' views' : 'draft') : ''; - $('blTitle').value = post ? post.title : ''; $('blSlug').value = post ? post.slug : ''; delete $('blSlug').dataset.touched; - $('blTags').value = post ? post.tags.join(', ') : ''; $('blExcerpt').value = post ? post.excerpt : ''; $('blCover').value = post ? post.cover : ''; $('blCoverInfo').textContent = ''; - $('blHtml').hidden = true; $('blBody').hidden = false; $('blBody').innerHTML = post ? post.body : ''; - $('blUnpublish').hidden = !(post && post.status === 'published'); $('blDelete').hidden = !post; - $('blPreview').hidden = !post; if (post) $('blPreview').href = '/blog/' + post.slug; - $('blPublish').textContent = post && post.status === 'published' ? 'Save and publish' : 'Publish'; - blMsg(''); blCount(); $('blTitle').focus(); - } - async function blSave(status) { - const body = { existingSlug: blCur, title: $('blTitle').value, slug: $('blSlug').value, tags: $('blTags').value, excerpt: $('blExcerpt').value, cover: $('blCover').value, body: blBodyHtml(), status }; - const r = await api('/api/admin/blog', body); - blCur = r.post.slug; - $('blSlug').value = r.post.slug; $('blPreview').hidden = false; $('blPreview').href = '/blog/' + r.post.slug; $('blDelete').hidden = false; - $('blUnpublish').hidden = r.post.status !== 'published'; $('blPublish').textContent = r.post.status === 'published' ? 'Save and publish' : 'Publish'; - $('blEdTitle').textContent = 'Edit article'; - blMsg(r.post.status === 'published' ? 'Published. Live at instantadpay.com/blog/' + r.post.slug + (r.syndicating ? ' · posting to X and Instagram now (see the Social column in the list).' : '') : 'Draft saved.'); - IAP.status(r.post.status === 'published' ? 'Published.' : 'Draft saved.', 'ok'); - } - $('blSaveDraft').addEventListener('click', busy($('blSaveDraft'), () => blSave('draft'))); - $('blPublish').addEventListener('click', busy($('blPublish'), () => blSave('published'))); - $('blUnpublish').addEventListener('click', busy($('blUnpublish'), () => blSave('draft'))); - $('blClose').addEventListener('click', () => { $('blogEditor').hidden = true; $('blogList').hidden = false; loadBlog().catch(e => IAP.status(e.message, 'bad')); }); - $('blDelete').addEventListener('click', busy($('blDelete'), async () => { - if (!blCur) return; - if (!await IAP.confirmBox('The page at /blog/' + blCur + ' stops existing. There is no undo.', { title: 'Delete this article?', ok: 'Delete', cancel: 'Keep it' })) return; - await api('/api/admin/blog?slug=' + encodeURIComponent(blCur), undefined, 'DELETE'); - $('blClose').click(); - })); - $('blNew').addEventListener('click', () => blOpen(null)); - async function loadBlog() { - const d = await api('/api/admin/blog'); - const pub = d.posts.filter(p => p.status === 'published').length; - $('blSub').textContent = pub + ' published · ' + (d.posts.length - pub) + ' drafts'; - const synd = p => { const s = p.syndicated; if (!s) return p.status === 'published' ? 'not posted' : ''; const r = s.results || {}; const part = ['x', 'instagram'].map(k => r[k] ? (r[k].ok ? k + ' ✓' : k + ' ✗') : k + ' –').join(' · '); return '' + part + ''; }; - $('blSyndNote').hidden = false; $('blSyndNote').textContent = d.syndication ? 'Publishing an article posts it to X (@cryptoteambuild) and Instagram (marketingwithmarty) through Blotato, once per article, with the cover image.' : 'Social syndication is off: no Blotato key on the server.'; - $('blTable').innerHTML = 'TitleStatusSocialTagsViewsUpdated' - + (d.posts.length ? d.posts.map(p => '' + esc(p.title) + '
/blog/' + esc(p.slug) + '' + (p.status === 'published' ? 'published' : 'draft') + '' + synd(p) + '' + esc(p.tags.join(', ')) + '' + (p.views || 0) + '' + when(p.updated) + ' View' + (p.status === 'published' && d.syndication && !(p.syndicated && p.syndicated.done) ? ' ' : '') + '').join('') - : 'No articles yet. Start with "New article".'); - $('blTable').querySelectorAll('[data-blsynd]').forEach(b => b.addEventListener('click', busy(b, async () => { - const r = await api('/api/admin/blog/syndicate', { slug: b.dataset.blsynd }); - const res = r.syndicated && r.syndicated.results || {}; const bad = Object.entries(res).filter(([, v]) => !v.ok).map(([k, v]) => k + ': ' + v.error); - IAP.status(bad.length ? 'Posted with problems: ' + bad.join(' | ') : 'Posted to X and Instagram.', bad.length ? 'bad' : 'ok'); loadBlog().catch(() => {}); - }))); - $('blTable').querySelectorAll('[data-bledit]').forEach(b => b.addEventListener('click', async () => { - try { const r = await api('/api/admin/blog?slug=' + encodeURIComponent(b.dataset.bledit)); blOpen(r.post); } catch (e) { IAP.status(e.message, 'bad'); } - })); - } - - async function loadPnl() { - 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; - const months = pnlDays ? pnlDays / 30 : Math.max(1, (r.latest - r.fromBlock) / 43200 / 30); - const fixed = (r.fixedMonthlyUsd || 0) * months; - $('pnlTiles').innerHTML = [ - ['Packages sold', r.purchases.count, Object.entries(r.purchases.byPackage || {}).map(([k, v]) => v + '×' + k).join(' · ') || '—'], - ['Gross volume', pol(r.purchases.volumeWei) + ' POL', usdOf(r.purchases.volumeWei, px) + ' at today\'s rate · $' + (r.purchases.usdCents / 100).toLocaleString() + ' at sale'], - ['Platform (fees + dust + unclaimed)', pol(r.platformWei) + ' POL', usdOf(r.platformWei, px)], - ['Paid to members', pol(r.memberPayoutsWei) + ' POL', usdOf(r.memberPayoutsWei, px)], - ['Net after fixed costs', '$' + Math.round(platUsd - fixed).toLocaleString(), 'fixed ' + Math.round(fixed).toLocaleString() + ' over ' + months.toFixed(1) + ' month(s)'], - ['Pass-ups', r.passedUp.count, r.passedUp.unqualified + ' unqualified · ' + r.passedUp.sendFailed + ' send-failed'] - ].map(t => '
' + esc(String(t[1])) + '
' + esc(t[0]) + '
' + esc(t[2]) + '
').join(''); - // PolHunter: a marketing cost paid from its own faucet, so it is read across rather than - // derived from our chain events (Marty, 2026-09-23) - const ph = r.polhunter, phEl = $('pnlHunt'); - if (phEl) { - if (!ph || ph.error || !ph.totals) phEl.innerHTML = 'PolHunter figures unavailable' + (ph && ph.error ? ' (' + esc(ph.error) + ')' : '') + '.'; - else { - const t = ph.totals, rf = ph.referrals || {}, usd = n => '$' + (Number(n) * px).toFixed(2); - const findPol = Math.max(0, Number(t.pol || 0) - Number(rf.paidPol || 0)); - phEl.innerHTML = 'LinePOLUSD now' - + [['Mission finds (' + Number(t.paid || 0).toLocaleString() + ' paid)', findPol], - ['Referral bounties (' + Number(rf.bounties || 0) + ')', null], - ['Referral matches (' + Number(rf.matches || 0) + ')', null], - ['Referral payouts total', Number(rf.pol || 0)], - ['All PolHunter payouts', Number(t.pol || 0)]] - .filter(x => x[1] !== null) - .map(x => '' + x[0] + '' + Number(x[1]).toFixed(4) + '' + usd(x[1]) + '').join('') - + 'Hunters paid' + Number(t.hunters || 0) + 'today ' + Number(t.today || 0).toFixed(3) + ' POL'; - } - } - // every game's payouts, all time, running total (Marty, 2026-10-18). PassiveDrip is a drip - // program rather than a game, so it sits under the total instead of inside it. - const ga = r.gamesAll, gaEl = $('pnlGames'); - if (gaEl) { - if (!ga || ga.error || !Array.isArray(ga.games) || !ga.games.length) gaEl.innerHTML = '' + (ga && ga.scanning ? 'Reading the game wallets from Polygon for the first time. Refresh in a minute.' : 'Game payout figures unavailable' + (ga && ga.error ? ' (' + esc(ga.error) + ')' : '') + '.') + ''; - else { - const wp = w => Number(BigInt(w) / 10n ** 12n) / 1e6, games = ga.games.filter(g => g.slug !== 'passivedrip'), pd = ga.games.find(g => g.slug === 'passivedrip'); - const row = (name, w, n, pl, cls) => '' + name + '' + wp(w).toFixed(4) + '$' + (wp(w) * px).toFixed(2) + '' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + ''; - const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0); - gaEl.innerHTML = 'GamePOLUSD nowPayouts to players' - + games.map(g => row(esc(g.name) + (g.error ? ' stale' : ''), g.wei, g.count, g.players)).join('') - + 'All game payouts' + wp(tw).toFixed(4) + '$' + (wp(tw) * px).toFixed(2) + '' + tn.toLocaleString() + ' payouts' - + (pd ? row('PassiveDrip (not a game)', pd.wei, pd.count, pd.players) : '') - + 'Read ' + (ga.at ? new Date(ga.at).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' }) + ' CT' : 'just now') + (ga.scanning ? ', refreshing' : '') + '. Updates every 10 minutes.'; - } - } - $('pnlSplit').innerHTML ='LinePOLUSD now' - + [['Level 1 (50%)', r.byTier[1]], ['Level 2 (20%)', r.byTier[2]], ['Level 3 (10%)', r.byTier[3]], ['Platform (20% + pass-ups)', r.platformWei]].map(x => '' + x[0] + '' + pol(x[1]) + '' + usdOf(x[1], px) + '').join(''); - const W = r.wallets || {}, B = r.balances || {}; - $('pnlWallets').innerHTML = 'WalletAddressBalance' - + [['Owner / fee A (Tangem)', W.feeA, B.feeA], ['Fee B', W.feeB, B.feeB], ['Engine (gas)', W.engine, B.engine]].filter(x => x[1]).map(x => '' + x[0] + '' + esc(x[1]) + '' + (x[2] == null ? '?' : pol(x[2]) + ' POL') + '').join(''); - renderLedger(r); - $('pnlFixed').value = r.fixedMonthlyUsd || 0; - const b = r.burner || {}; - $('burnerLine').textContent = !b.hasEthers ? 'ethers is not installed in this build.' : !b.keyPresent ? 'No engine key configured (ENGINE_KEY). Burns stay pending until it is set.' : b.mismatch ? 'ENGINE_KEY does not match the contract engine signer. Disabled.' : 'Engine wallet ' + b.address + ' holds ' + pol(b.balanceWei) + ' POL. That is its gas fund, not a cost: one burn uses about 0.003 POL (roughly 48,000 gas), paid by this wallet, never by the member. ' + b.burned + ' burn' + (b.burned === 1 ? '' : 's') + ' since boot' + (b.lastRun ? ' · last check ' + when(b.lastRun) : '') + (b.lastError ? ' · last error: ' + b.lastError : '') + (b.skipped && Object.keys(b.skipped).length ? ' · skipped (needs review): ' + Object.entries(b.skipped).map(([k, v]) => k + ' (' + v + ')').join(', ') : ''); - } - // The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that - // makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody - // wrote down (Marty, 2026-09-23). - const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' }; - const LD_CAT = { advertising: 'Advertising', games: 'Game marketing', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' }; - const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' }; - const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 }); - function renderLedger(r) { - const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {}; - if ($('pnlLedger')) { - $('pnlLedger').innerHTML = 'DateWalletKindPOLWhat for' - + (rows.length ? rows.map(e => '' + e.date + '' + (LD_WALLET[e.wallet] || e.wallet) + '' - + '' + (LD_KIND[e.kind] || e.kind) + (e.kind === 'cost' ? ' (' + (LD_CAT[e.category] || e.category || 'other') + ')' : '') + '' - + '' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount) - + (e.usd ? ' ($' + Number(e.usd).toFixed(2) + ')' : '') + '' - + '' + esc(e.note || '') + '' - + '').join('') - : 'Nothing recorded yet.'); - $('pnlLedger').querySelectorAll('[data-ldkill]').forEach(b => b.addEventListener('click', async () => { - if (!await IAP.confirmBox('Remove this ledger line?')) return; - try { await api('/api/admin/ledger/delete', { id: b.dataset.ldkill }); loadPnl(); } - catch (e) { IAP.status('Could not remove it: ' + e.message, 'bad'); } - })); - } - if ($('pnlRecon')) { - const drift = Number(rec.drift || 0); - const ok = Math.abs(drift) < 0.01; - $('pnlRecon').innerHTML = 'Receiver A earned ' + pol4(rec.earnedPol) + ' POL on chain' - + (t.revenuePol ? ' plus ' + pol4(t.revenuePol) + ' outside revenue' : '') - + (t.drawPol ? ', less ' + pol4(t.drawPol) + ' drawn' : '') - + (t.transferPol ? ', ' + (t.transferPol > 0 ? 'plus ' : 'less ') + '' + pol4(Math.abs(t.transferPol)) + ' transferred in for storage' : '') - + '. Expected ' + pol4(rec.expected) + ', actually holding ' + pol4(rec.actual) + '. ' - + (ok ? 'Reconciled.' - : 'Unexplained: ' + pol4(drift) + ' POL ' - + '(' + (drift > 0 ? 'more on hand than accounted for, so income or a transfer in is missing a line' - : 'less on hand than accounted for, so a draw is missing a line') + ')'); - } - } - if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => { - const body = { dir: $('ldDir').value, kind: $('ldKind').value, category: $('ldCat') ? $('ldCat').value : '', wallet: $('ldWallet').value, - amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0, - date: $('ldDate').value, note: $('ldNote').value }; - try { - await api('/api/admin/ledger', body); - $('ldAmount').value = ''; $('ldUsd').value = ''; $('ldNote').value = ''; - IAP.status('Line added.', 'good'); loadPnl(); - } catch (e) { IAP.status(e.message, 'bad'); } - }); - // a draw is almost never revenue and an outside deposit almost never a draw: move the kind with - // the direction, but leave it editable - if ($('ldDir')) $('ldDir').addEventListener('change', () => { - $('ldKind').value = $('ldDir').value === 'in' ? 'revenue' : 'draw'; - }); - 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'); } }); - 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; - try { - $('audSub').textContent = 'checking…'; - const a = await api('/api/admin/audit'); - const bad = a.checks.filter(c => !c.ok).length; - $('audSub').textContent = (bad ? bad + ' issue' + (bad === 1 ? '' : 's') : 'all counters reconcile') + ' · checked ' + new Date(a.checkedAt).toLocaleTimeString(); - $('audTable').innerHTML = 'CheckStatusDetail' + a.checks.map(c => '' + esc(c.name) + '' + (c.ok ? 'ok' : '' + c.issues.length + ' issue' + (c.issues.length === 1 ? '' : 's') + '') + '' + esc(c.detail) + (c.issues.length ? '
' + c.issues.map(esc).join('
') : '') + '').join(''); - } catch (e) { $('audSub').textContent = e.message; } - } - if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit)); - // ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ── - const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' }; - const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' }; - const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : ''; - const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '$1'); - let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = []; - async function supportBadge() { - try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; } - } - async function loadSupport(q) { - const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1]; - if (ref) return openTicket(ref); - $('spView').hidden = true; $('spList').hidden = false; - const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString(); - const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]); - spTemplates = tp.templates || []; spCats = r.categories || spCats; - const c = r.counts || {}; - $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || ''); - $('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread'; - const chip = (v, label, n) => ''; - $('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All'); - if (!$('spCategory').options.length) $('spCategory').innerHTML = '' + spCats.map(x => '').join(''); - $('spTable').innerHTML = 'TicketSubjectFromCategoryStatusLast activity' - + (r.tickets.length ? r.tickets.map(t => '' + (t.adminUnread ? '● ' : '') + esc(t.ref) - + (t.platform !== 'iap' ? ' ' + esc(t.platform) + '' : '') + (t.priority === 'high' ? ' high' : '') + '' - + '' + (t.adminUnread ? '' + esc(t.subject) + '' : esc(t.subject)) + '
' + esc(t.source) + '
' - + '' + esc(t.name || '') + '
' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '
' - + '' + esc(t.category) + '' + esc(SP_STATUS[t.status] || t.status) + '' + esc(ctWhen(t.updated)) + '').join('') - : 'No tickets here.'); - drawTemplates(); - } - $('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); - $('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); - $('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); - let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); }); - $('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } }); - async function openTicket(ref) { - const v = await api('/api/admin/support/' + encodeURIComponent(ref)); - if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} } - if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other']; - drawTicket(v); supportBadge(); - } - function drawTicket(v) { - const t = v.ticket, rq = v.requester || {}; - $('spList').hidden = true; $('spView').hidden = false; - const sel = (id, opts, cur) => ''; - const stOpts = Object.entries(SP_STATUS); - $('spView').innerHTML = '

‹ All tickets

' - + '

' + esc(t.subject) + '

' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + '
' - + '
' - + '' - + '
' - + '

Requester

' + (rq.member ? 'member account' : 'no account with this email') + '
' - + kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [ - ['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' · open member card'], - ['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '' + esc(v.link) + '']])) - + '
' - + '

Thread

' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + '
' - + v.messages.map(m => '
' - + '
' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '' + esc(ctWhen(m.created)) + '
' - + '
' + spLink(m.body) + '
' - + (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '

' : '') - + (m.bodyEn ? '
🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)\n' + spLink(m.bodyEn) + '
' : '') - + ((m.attachments || []).length ? '
' + m.attachments.map(a => 'attachment').join('') + '
' : '') + '
').join('') - + '
' - + '

Reply

emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '
' - + '

' - + '' - + '

' - + '' - + '

'; - $('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20) - const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return; - const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal); - const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body); - await setPane('kb'); window.IAPKB.compose(draft); - })); - $('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); - const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } }; - $('spSt').addEventListener('change', () => patch({ status: $('spSt').value })); - $('spPr').addEventListener('change', () => patch({ priority: $('spPr').value })); - $('spCat').addEventListener('change', () => patch({ category: $('spCat').value })); - if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); }); - $('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; }); - $('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; }); - $('spSend').addEventListener('click', busy($('spSend'), async () => { - const internal = $('spInternal').checked; - if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return; - drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value })); - supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok'); - })); - } - function drawTemplates() { - $('spTpls').innerHTML = spTemplates.map((x, i) => '
' - + '
').join('') || '

No saved replies. Add one below.

'; - } - const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value })); - $('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); }); - $('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); }); - $('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); })); - - async function loadReports() { - loadAudit(); - const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]); - const reps = r.reports || []; - $('repTable').innerHTML = reps.length ? 'WhenCampaignReasonNoteBy' - + reps.map(x => '' + when(x.ts) + '#' + x.campaignId + '' + esc(x.reason) + '' + esc(x.note || '') + '' + esc(x.reporter || 'anon') + '' - + '' + (x.resolved ? 'resolved' : '') + '').join('') - : 'No reports.'; - const burns = b.pending || []; - $('burnTable').innerHTML = burns.length ? 'WhenMemberCreditsRefBurn id' - + burns.map(x => '' + when(x.ts) + '#' + x.memberId + '' + x.amount + '' + esc(x.ref) + '' + esc(x.id) + '').join('') - : 'Nothing pending.'; - } - document.addEventListener('click', async e => { - const b = e.target.closest('[data-resolve]'); if (!b) return; - b.disabled = true; - try { await api('/api/admin/reports/' + b.dataset.resolve + '/resolve', {}); IAP.status('Report resolved.', 'ok'); await Promise.all([loadReports(), loadOverview()]); } - catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } - }); - - // ── settings: graphical editors (follow-up emails, rates, site settings) ── - let dripSeq = [], ratesObj = {}, siteObj = {}; - let lastFocusedField = null; - document.addEventListener('focusin', e => { if (e.target && (e.target.matches('textarea.ds-body') || e.target.matches('input.ds-subject'))) lastFocusedField = e.target; }); - document.addEventListener('click', e => { - const c = e.target.closest('[data-ph]'); if (!c) return; - const el = lastFocusedField; if (!el) { IAP.status('Click into a subject or body first, then the chip.', 'bad'); return; } - const ph = c.dataset.ph, st = el.selectionStart || 0, en = el.selectionEnd || st; - el.value = el.value.slice(0, st) + ph + el.value.slice(en); - el.focus(); el.selectionStart = el.selectionEnd = st + ph.length; - el.dispatchEvent(new Event('input')); - }); - const whenLabel = h => { h = Number(h) || 0; if (h < 24) return h + ' hour' + (h === 1 ? '' : 's') + ' after sign-up'; const d = h / 24; return (Number.isInteger(d) ? d : d.toFixed(1)) + ' day' + (d === 1 ? '' : 's') + ' after sign-up'; }; - function drawDrip() { - const wrap = $('dripSteps'); - wrap.innerHTML = dripSeq.map((st, i) => '
' - + '
EMAIL ' + (i + 1) + '' - + 'send hours after sign-up (' + esc(whenLabel(st.hours)) + ')' - + '' - + '
' - + '' - + '' - + '
').join('') || '

No emails yet. Add one below.

'; - } - function readDrip() { - return [...document.querySelectorAll('#dripSteps .drip-step')].map(card => ({ - hours: Number(card.querySelector('.ds-hours').value) || 0, - subject: card.querySelector('.ds-subject').value.trim(), - body: card.querySelector('.ds-body').value.trim() - })); - } - $('dripSteps').addEventListener('input', e => { - if (e.target.classList.contains('ds-hours')) { const l = e.target.closest('.ds-when').querySelector('.ds-whenlbl'); if (l) l.textContent = '(' + whenLabel(e.target.value) + ')'; } - }); - $('dripSteps').addEventListener('click', async e => { - const b = e.target.closest('[data-act]'); if (!b) return; - const card = b.closest('.drip-step'), i = Number(card.dataset.i); - dripSeq = readDrip(); - if (b.dataset.act === 'remove') { if (!await IAP.confirmBox('Remove email ' + (i + 1) + ' from the sequence?', { title: 'Remove step', ok: 'Remove', cancel: 'Keep' })) return; dripSeq.splice(i, 1); drawDrip(); return; } - if (b.dataset.act === 'up' && i > 0) { [dripSeq[i - 1], dripSeq[i]] = [dripSeq[i], dripSeq[i - 1]]; drawDrip(); return; } - if (b.dataset.act === 'down' && i < dripSeq.length - 1) { [dripSeq[i + 1], dripSeq[i]] = [dripSeq[i], dripSeq[i + 1]]; drawDrip(); return; } - if (b.dataset.act === 'test') { - b.disabled = true; - try { await saveDrip(); await api('/api/admin/drip/test', { step: i }); IAP.status('Email ' + (i + 1) + ' sent to your inbox.', 'ok'); } - catch (err) { IAP.status(err.message, 'bad'); } - b.disabled = false; - } - }); - async function saveDrip() { - $('dripErr').hidden = true; - const seq = readDrip(); - const r = await api('/api/admin/drip', { sequence: seq }, 'PATCH').catch(err => { $('dripErr').textContent = err.message; $('dripErr').hidden = false; throw err; }); - dripSeq = r.sequence; drawDrip(); - return r; - } - $('dripSave').addEventListener('click', busy($('dripSave'), async () => { await saveDrip(); IAP.status('Sequence saved.', 'ok'); await loadSettings(); })); - $('dripAdd').addEventListener('click', () => { - dripSeq = readDrip(); - const last = dripSeq[dripSeq.length - 1]; - dripSeq.push({ hours: last ? Number(last.hours) + 48 : 24, subject: '', body: '\n\nMarty\n\n{{footer}}' }); - drawDrip(); - const cards = document.querySelectorAll('#dripSteps .drip-step'); const c = cards[cards.length - 1]; if (c) { c.scrollIntoView({ behavior: 'smooth', block: 'center' }); c.querySelector('.ds-subject').focus(); } - }); - $('dripReset').addEventListener('click', busy($('dripReset'), async () => { - if (!await IAP.confirmBox('Replace the saved sequence with the built-in defaults?', { title: 'Reset sequence', ok: 'Replace', cancel: 'Cancel' })) return; - const r = await api('/api/admin/drip', { reset: true }, 'PATCH'); - dripSeq = r.sequence; drawDrip(); IAP.status('Defaults restored.', 'ok'); await loadSettings(); - })); - - // rates: labels + hints for the known keys; anything unknown still gets a plain field - const RATE_META = { - bannerBatch: ['Banner: views per batch', 'impressions counted before a banner campaign is charged'], - bannerCreditsPerBatch: ['Banner: credits per batch', 'charged to the advertiser per batch'], - textBatch: ['Text ad: views per batch', ''], textCreditsPerBatch: ['Text ad: credits per batch', ''], - loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'], - loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'], - burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'], - welcomeCredits: ['Welcome credits', 'granted after the welcome tour'], - dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'], - dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'], - viewDwellSeconds: ['Ad view: seconds per ad', 'the countdown; server-enforced'], - soloCostPerRecipient: ['Solo ad: credits per recipient', ''], soloMinRecipients: ['Solo ad: minimum recipients', ''], - soloReadCredits: ['Solo ad: reader reward (credits)', ''], soloReadCapPerDay: ['Solo ad: rewarded reads per day', ''], soloReadDwellSeconds: ['Solo ad: seconds to read', ''], - videoWatchCapPerDay: ['Video: rewarded watches per day', ''], - featuredPerDay: ['Featured link: credits per day', ''], featuredSlotsPerDay: ['Featured link: slots per day', ''], featuredWindowDays: ['Featured link: booking window (days)', ''], - featuredDurations: ['Featured link: durations offered (days)', 'comma-separated'], - doorPackCost: ['Spooky Doors: door pack, credits per door', 'placement "Behind Spooky Doors"'], goldenDoorCost: ['Spooky Doors: Golden Door, credits per door', 'placement "Golden Spooky Door"'], - goldenBonusCandy: ['Spooky Doors: Golden Door bonus candy', 'sent to the game as bonus'], sdSeasonEnd: ['Spooky Doors: season end (Central day, exclusive)', 'from this day door packs run as normal visits (YYYY-MM-DD)'], - visitCostPerVisit: ['Verified visit: credits per visit', ''], visitMinPack: ['Verified visit: smallest pack', ''], visitReward: ['Verified visit: viewer reward (credits)', ''], visitDwellSeconds: ['Verified visit: seconds on site', ''], visitCapPerDay: ['Verified visit: rewarded visits per day', ''], - videoTiers: ['Video ad tiers', 'watch length → advertiser cost → viewer reward'], - milestoneBonus: ['Milestone bonuses (credits)', 'one-time, when a member reaches each step'] - }; - const humanize = k => k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase()); - function drawRates() { - const wrap = $('ratesForm'); const html = []; - for (const [k, v] of Object.entries(ratesObj)) { - const [label, hint] = RATE_META[k] || [humanize(k), '']; - if (typeof v === 'number') html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
'); - else if (typeof v === 'boolean') html.push('
'); - else if (Array.isArray(v) && v.every(x => typeof x === 'number')) html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
'); - else if (Array.isArray(v) && v.every(x => x && typeof x === 'object')) { - const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; const txt = new Set(cols.filter(c => v.some(x => typeof x[c] === 'string'))); // text columns (doorHouseAds) stay text - html.push('
' + (hint ? '' + esc(hint) + '' : '') - + '' + cols.map(c => '').join('') + '' - + v.map((row, i) => '' + cols.map(c => '').join('') + '').join('') + '
' + esc(c) + '
'); - } else if (v && typeof v === 'object') { - html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
' - + Object.entries(v).map(([sk, sv]) => '').join('') + '
'); - } else html.push('
'); - } - wrap.innerHTML = html.join(''); - } - function readRates() { - const out = {}; - document.querySelectorAll('#ratesForm [data-rk]').forEach(el => { - const k = el.dataset.rk, kind = el.dataset.kind; - if (kind === 'numlist') out[k] = el.value.split(/[\s,]+/).filter(Boolean).map(Number).filter(n => !isNaN(n)); - else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = i.dataset.str ? i.value.trim() : Number(i.value); }); return o; }); - else if (kind === 'object') { const o = {}; el.querySelectorAll('input[data-sub]').forEach(i => { o[i.dataset.sub] = Number(i.value); }); out[k] = o; } - else if (el.type === 'checkbox') out[k] = !!el.checked; - else if (el.type === 'number') out[k] = Number(el.value); - else out[k] = el.value; - }); - return out; - } - $('ratesSave').addEventListener('click', busy($('ratesSave'), async () => { - $('ratesErr').hidden = true; - try { const r = await api('/api/admin/rates', readRates(), 'PATCH'); ratesObj = r.rates || readRates(); drawRates(); IAP.status('Rates saved.', 'ok'); } - catch (e) { $('ratesErr').textContent = e.message; $('ratesErr').hidden = false; } - })); - - // site settings: key / value rows; booleans as checkboxes, numbers stay numbers - const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' }; - function drawSite() { - const wrap = $('siteForm'); - wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '
' + esc(SITE_META[k] || humanize(k)) + '' - + (typeof v === 'boolean' ? '' - : typeof v === 'number' ? '' - : '') - + '
').join('') || '

No settings saved yet.

'; - } - function readSite() { - const out = {}; - document.querySelectorAll('#siteForm [data-sk]').forEach(el => { - const k = el.dataset.sk; - if (el.type === 'checkbox') out[k] = !!el.checked; - else if (el.type === 'number') out[k] = Number(el.value); - else { const v = el.value; if (/^[\[{]/.test(v)) { try { out[k] = JSON.parse(v); return; } catch (e) {} } out[k] = v; } - }); - return out; - } - $('siteForm').addEventListener('click', e => { - const b = e.target.closest('[data-sdel]'); if (!b) return; - siteObj = readSite(); siteObj[b.dataset.sdel] = ''; drawSite(); - }); - $('siteAddKey').addEventListener('click', () => { - const k = $('siteNewKey').value.trim(); if (!/^[A-Za-z][A-Za-z0-9_]{0,40}$/.test(k)) { IAP.status('Setting names are letters and numbers, no spaces.', 'bad'); return; } - siteObj = readSite(); if (!(k in siteObj)) siteObj[k] = ''; $('siteNewKey').value = ''; drawSite(); - const el = document.querySelector('#siteForm [data-sk="' + k + '"]'); if (el) el.focus(); - }); - $('siteSave').addEventListener('click', busy($('siteSave'), async () => { - $('siteErr').hidden = true; - try { const r = await api('/api/admin/site', readSite(), 'PATCH'); siteObj = r.site || readSite(); drawSite(); IAP.status('Site settings saved.', 'ok'); } - catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; } - })); - - // ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ---- - async function loadGamePass() { - const r = await api('/api/admin/gamepass/stats'); - const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2); - const tile = (v, lb, cls, sub) => '
' + v + '
' + lb + '
' + (sub ? '' + sub + '' : '') + '
'; - const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {}; - $('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only') - + tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time') - + tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package') - + tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet')) - + tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants') - + tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total') - + tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total') - + tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members'); - $('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : ''; - const would = (r.capHits && r.capHits.would) || {}; - $('gpWeek').innerHTML = '' - + '' - + '' - + '' - + (S.enforced ? '' : '') - + '' - + '
Carried forward (deferred progress paid on a later day)' + pol(W.carried) + ' POL
Dropped (daily play over the daily cap)' + pol(W.dropped) + ' POL
Deferred out (progress over the total cap, pays later)' + pol(W.deferredOut) + ' POL
Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits.
Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)' + S.price + ' credits · ' + S.days + ' days
' - + (Q.byGame && Object.keys(Q.byGame).length ? '

By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '

' : ''); - // per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month - const TS = r.tiers || {}, TC = S.tiers || {}; - $('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales'; - $('gpTiers').innerHTML = '' - + (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return ''; }).join('') - + '
TierPriceActiveSold weekSold monthAll timeRenewals 30dEnding in 7 daysCompedWaiting
' + esc(x.name || k) + (c.sale ? '' : '
not on sale') + '
' + (c.price || 0) + ' cr
' + (c.days || 0) + ' d
' + (x.active || 0) + '' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '' + (x.renewals30d || 0) + '' + (x.expiring7d || 0) + '' + (x.comped || 0) + '' + (x.waitingOrders || 0) + '

Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).

'; - // pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled) - const PM = P.pay || {}, SL = r.sales || []; - $('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')' - + ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')'; - const txLink = h => h ? '' + esc(String(h).slice(0, 10)) + '…' : ''; - $('gpSales').innerHTML = !SL.length ? '

No pass sold yet.

' : '' - + SL.map(x => '').join('') - + '
WhenMemberPassPaid byPassPackagePackage tx
' + when(x.ts) + '' + esc(x.email) + '' + esc(x.name || x.tier) + '' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + '' + usd(x.usd) + '' + (x.packageUsd ? usd(x.packageUsd) : '') + '' + txLink(x.tx) + '
'; - $('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid'; - const L = T.last; - $('gpTour').innerHTML = !L ? '

No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).

' - : '

' + esc(L.label) + ': ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '

' - + (L.winners && L.winners.length ? '' + L.winners.map(w => '').join('') + '
#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '' + w.score + ' plays' + pol(w.pol) + ' POL' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '
' : '

No pass holder reported any plays that week.

') - + ((T.history || []).length > 1 ? '

Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '

' : ''); - } - $('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); })); - $('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); })); - $('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => { - const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; } - if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return; - const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass(); - })); - - async function loadSettings() { - const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]); - ratesObj = r.rates || {}; drawRates(); - siteObj = s.site || {}; drawSite(); - dripSeq = d.sequence || []; drawDrip(); - const st = d.stats || {}; - $('dripSub').textContent = (st.active || 0) + ' in flight · ' + (st.done || 0) + ' finished · ' + (st.unsubscribed || 0) + ' unsubscribed' + (d.mailReady ? '' : ' · NO MAIL KEY: nothing sends'); - } - - render(); -})(); -// ---- tax summary (2026-10-04) + the cost category picker -(function () { - const $ = id => document.getElementById(id); - if ($('ldKind') && $('ldCat')) { const sync = () => { $('ldCat').hidden = $('ldKind').value !== 'cost'; }; $('ldKind').addEventListener('change', sync); sync(); } - if (!$('taxYear')) return; - const y = new Date().getFullYear(); for (let v = y; v >= 2025; v--) { const o = document.createElement('option'); o.value = v; o.textContent = v; $('taxYear').appendChild(o); } - const money = n => '$' + Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); - $('taxRun').addEventListener('click', async () => { - $('taxOut').textContent = 'Working it out...'; - try { - const r = await (await fetch('/api/admin/tax?year=' + $('taxYear').value, { credentials: 'same-origin' })).json(); - if (r.error) throw new Error(r.error); - const cats = Object.entries(r.expenses.byCategory || {}).map(([k, v]) => '' + (r.expenses.labels[k] || k) + '' + money(v) + '').join(''); - $('taxOut').innerHTML = '' - + '' - + (r.income.outsideUsd ? '' : '') - + '' - + (cats || '') - + '' - + '' - + '
' + r.year + '
Income: platform share of ' + r.income.sales + ' package sales' + money(r.income.platformUsd) + '
Outside revenue' + money(r.income.outsideUsd) + '
Total income' + money(r.income.totalUsd) + '
No costs recorded yet
Advertising and promotion (advertising + game marketing + player rewards)' + money(r.expenses.advertisingAndPromotionUsd) + '
Total costs' + money(r.expenses.totalUsd) + '
Net' + money(r.netUsd) + '
' - + '

Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).

'; - $('taxCsvText').value = r.csv; $('taxCsv').hidden = false; - } catch (e) { $('taxOut').textContent = 'Could not build the summary: ' + e.message; } - }); - $('taxCsv').addEventListener('click', async () => { - try { await navigator.clipboard.writeText($('taxCsvText').value); IAP.status('CSV copied. Paste it into a spreadsheet.', 'good'); } - catch (e) { $('taxCsvText').hidden = false; $('taxCsvText').select(); IAP.status('Selected. Copy it with your keyboard.', 'good'); } - }); -})(); +// Admin portal: email-code sign-in (allowlisted to ADMIN_EMAIL on the server), +// house ads that cost nothing, every campaign, members, reports, settings. +(function () { + const $ = IAP.$; + const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + async function api(path, body, method) { + const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} }; + if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); } + const r = await (await fetch(path, opts)).json(); + if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error); + return r; + } + function busy(btn, fn) { + return async (...a) => { + if (btn.disabled) return; + btn.disabled = true; + try { await fn(...a); } catch (e) { IAP.status(e.message || 'Something went wrong.', 'bad'); } + finally { btn.disabled = false; } + }; + } + const when = ts => ts ? new Date(Number(ts)).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : ''; + let rates = {}, sizes = [], houseOwner = 'house@instantadpay.com'; + + // ── sign-in ── + $('adSend').addEventListener('click', busy($('adSend'), async () => { + $('adErr').hidden = true; + const r = await api('/api/admin/auth/start', { email: $('adEmail').value }); + $('adCodeRow').hidden = false; $('adVerify').hidden = false; + if (r.devCode) $('adCode').value = r.devCode; + IAP.status(r.sent ? 'Code sent. Check your inbox.' : 'Dev mode: code filled in.', 'ok'); + $('adCode').focus(); + })); + $('adVerify').addEventListener('click', busy($('adVerify'), async () => { + $('adErr').hidden = true; + await api('/api/admin/auth/verify', { email: $('adEmail').value, code: $('adCode').value }); + await render(); + })); + $('adCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('adVerify').click(); }); + $('adEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('adVerify').hidden ? $('adSend') : $('adVerify')).click(); }); + $('adLogout').addEventListener('click', async e => { + e.preventDefault(); + try { await api('/api/admin/auth/logout', {}); } catch (err) {} + location.reload(); + }); + + // ── panes ── + const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' }; + const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings }; + function setPane(name) { + const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email) + if (!TITLES[name]) name = 'overview'; + document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; }); + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name)); + $('boTitle').textContent = TITLES[name]; + const keepQ = name === 'support' && paneQ ? '?' + paneQ : ''; + if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ); + $('adminArea').classList.remove('side-open'); + return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad')); + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane))); + document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); }); + window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); + $('boBurger').addEventListener('click', () => $('adminArea').classList.toggle('side-open')); + + async function render() { + let me = { admin: false }; + try { me = await api('/api/admin/me'); } catch (e) {} + $('authArea').hidden = !!me.admin; + $('adminArea').hidden = !me.admin; + if (!me.admin) return; + $('adWho').textContent = me.email || 'admin'; + try { + const c = await IAP.getConfig(); + $('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : ''); + } catch (e) {} + setPane(location.hash.slice(1) || 'overview'); + supportBadge(); + } + + // ── overview ── + async function loadOverview() { + const o = await api('/api/admin/overview'); + rates = o.rates || rates; + $('ovAccounts').textContent = (o.accounts || 0).toLocaleString(); + $('ovMembers').textContent = o.memberCount == null ? '?' : Number(o.memberCount).toLocaleString(); + $('ovActive').textContent = (o.byStatus && o.byStatus.active) || 0; + $('ovCampSub').textContent = o.campaigns + ' total · ' + o.house + ' house'; + $('ovReports').textContent = o.openReports || 0; + $('ovBurnSub').textContent = (o.pendingBurns || 0) + ' pending burns'; + $('repBadge').hidden = !o.openReports; $('repBadge').textContent = o.openReports || ''; + const f = o.followups || {}; + $('ovDrips').textContent = f.active || 0; + $('ovDripSub').textContent = (f.done || 0) + ' finished · ' + (f.unsubscribed || 0) + ' unsubscribed'; + const bt = Object.entries(o.byType || {}).sort((a, b) => b[1] - a[1]); + $('ovByType').innerHTML = bt.length ? bt.map(([t, n]) => '
' + esc(t) + '' + n + '
').join('') : 'No campaigns yet.'; + const ch = o.chain || {}; + $('ovChain').innerHTML = '
' + esc(ch.chainName) + ' (chain ' + esc(ch.chainId) + ')
' + + '
' + esc(ch.contract) + '
' + + (ch.explorer ? 'Open in explorer →' : ''); + } + + // ── house ads ── + const HROWS = { banner: ['hBannerRow'], text: ['hTextRow'], login: [], solo: ['hSoloRow'], video: ['hVideoRow'], featured: ['hFeatRow'], visits: ['hVisitsRow'] }; + function showHouseRows() { + const t = $('hType').value; + ['hBannerRow', 'hTextRow', 'hSoloRow', 'hVideoRow', 'hFeatRow', 'hVisitsRow'].forEach(id => { $(id).hidden = !(HROWS[t] || []).includes(id); }); + $('hBudget').hidden = t === 'featured' || t === 'visits'; + houseHints(); + } + function houseHints() { + const r = rates || {}; + const soloCost = r.soloCostPerRecipient || 5, soloMin = r.soloMinRecipients || 10; + const cap = Number($('hBudget').value) || 100000; + $('hSoloHint').textContent = 'Delivers to one inbox per ' + soloCost + ' credits of cap (minimum ' + soloMin + ' recipients). A cap of ' + cap.toLocaleString() + ' reaches up to ' + Math.floor(cap / soloCost).toLocaleString() + ' members.'; + const days = Number($('hFeatDays').value) || 0; + $('hFeatHint').textContent = days ? days + '-day run in the featured strip (' + (r.featuredPerDay || 40) + ' credits/day, free here). Book up to ' + (r.featuredWindowDays || 7) + ' days ahead.' : ''; + const n = Number($('hVisitCount').value) || 0; + $('hVisitHint').textContent = 'Packs start at ' + (r.visitMinPack || 20) + ' visits.' + (n ? ' ' + n + ' verified visits, delivered one per member.' : ''); + } + $('hType').addEventListener('change', showHouseRows); + ['hBudget', 'hFeatDays', 'hVisitCount'].forEach(id => $(id).addEventListener('input', houseHints)); + $('hFeatDays').addEventListener('change', houseHints); + $('hImageUploadBtn').addEventListener('click', () => $('hImageFile').click()); + $('hVideoUploadBtn').addEventListener('click', () => $('hVideoFile').click()); + async function upload(fileInput, info, target, kind) { + const f = fileInput.files[0]; if (!f) return; + info.textContent = 'Uploading ' + f.name + '…'; + try { + const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { info.textContent = r.error; } + else { target.value = r.url; info.textContent = f.name + ' uploaded'; } + } catch (e) { info.textContent = 'Upload failed. Try again.'; } + fileInput.value = ''; + } + $('hImageFile').addEventListener('change', () => upload($('hImageFile'), $('hImageInfo'), $('hImage'))); + $('hVideoFile').addEventListener('change', () => upload($('hVideoFile'), $('hVideoInfo'), $('hVideoUrl'))); + let hVidDims = null; + function probeVideoDims(url) { + return new Promise(resolve => { + const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; + const done = d => { v.src = ''; resolve(d); }; + v.onloadedmetadata = () => done(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); + v.onerror = () => done(null); + setTimeout(() => done(null), 12000); + v.src = url; + }); + } + $('hCreate').addEventListener('click', busy($('hCreate'), async () => { + $('hErr').hidden = true; + const t = $('hType').value; + if (t === 'video' && $('hVideoUrl').value) hVidDims = await probeVideoDims($('hVideoUrl').value); + const days = Number($('hFeatDays').value), count = Number($('hVisitCount').value); + const body = { type: t, name: $('hName').value, targetUrl: $('hTarget').value, + imageUrl: $('hImage').value, size: $('hSize').value, + title: t === 'video' ? $('hVideoTitle').value : t === 'featured' ? $('hFeatTitle').value : t === 'visits' ? $('hVisitTitle').value : t === 'solo' ? $('hSoloTitle').value : $('hTitle').value, + body: t === 'solo' ? $('hSoloBody').value : $('hBody').value, + ctaLabel: t === 'video' ? $('hVideoCta').value : $('hSoloCta').value, + videoUrl: $('hVideoUrl').value, watchSecs: Number($('hWatchSecs').value), + videoW: hVidDims ? hVidDims.w : null, videoH: hVidDims ? hVidDims.h : null, + days, startDay: Number($('hFeatStart').value) || 0, count, placement: t === 'visits' && $('hVisitPlace') ? $('hVisitPlace').value : undefined, + budget: t === 'featured' ? days * (rates.featuredPerDay || 40) + : t === 'visits' ? count * (($('hVisitPlace') && $('hVisitPlace').value === 'golden') ? (rates.goldenDoorCost || 6) : ($('hVisitPlace') && $('hVisitPlace').value === 'doors') ? (rates.doorPackCost || 4) : (rates.visitCostPerVisit || 3)) + : (Number($('hBudget').value) || 0) }; + try { + await api('/api/admin/campaigns', body); + } catch (e) { $('hErr').textContent = e.message; $('hErr').hidden = false; throw e; } + IAP.status('House ad is live. It serves right away at no cost.', 'ok'); + ['hName', 'hBudget', 'hTarget', 'hImage', 'hTitle', 'hBody', 'hSoloTitle', 'hSoloBody', 'hSoloCta', + 'hVideoUrl', 'hVideoTitle', 'hVideoCta', 'hFeatTitle', 'hVisitTitle', 'hVisitCount'].forEach(id => { $(id).value = ''; }); + $('hImageInfo').textContent = ''; $('hVideoInfo').textContent = ''; hVidDims = null; + await loadHouse(); + })); + function campRow(c, showOwner) { + const left = Math.max(0, (c.budget || 0) - (c.spent || 0)); + const creative = c.type === 'banner' && c.imageUrl ? '' : esc(c.title || c.name); + const act = c.status === 'active' ? '' + : c.status === 'paused' ? '' : ''; + return '#' + c.id + (c.house ? 'HOUSE' : '') + '' + + (showOwner ? '' + esc(c.house ? 'house' : c.owner) + '' : '') + + '' + esc(c.type) + '' + + '' + esc(c.name) + '
' + creative + '
' + esc(c.targetUrl) + '' + + '' + esc(c.status) + '' + + '' + (c.spent || 0).toLocaleString() + ' / ' + (c.budget || 0).toLocaleString() + '
' + left.toLocaleString() + ' left
' + + '' + (c.imps || 0).toLocaleString() + (c.impsNas ? ' +' + c.impsNas + ' nas' : '') + '
' + (c.clicks || 0) + ' clicks
' + + '' + when(c.created) + '' + + '' + act + ''; + } + function campHead(showOwner) { + return 'ID' + (showOwner ? 'Owner' : '') + 'TypeCampaignStatusSpent / capDeliveryCreated'; + } + async function loadHouse() { + const r = await api('/api/admin/campaigns'); + rates = r.rates || rates; sizes = r.bannerSizes || sizes; houseOwner = r.houseOwner || houseOwner; + if (!$('hSize').options.length) $('hSize').innerHTML = sizes.map(s => '').join(''); + if (!$('hWatchSecs').options.length) $('hWatchSecs').innerHTML = (rates.videoTiers || []).map(t => '').join(''); + if (!$('hFeatDays').options.length) $('hFeatDays').innerHTML = (rates.featuredDurations || [1, 2, 7]).map(d => '').join(''); + showHouseRows(); + loadWallAds(); + const house = (r.campaigns || []).filter(c => c.house); + $('houseSub').textContent = house.filter(c => c.status === 'active').length + ' active · ' + house.length + ' total'; + $('houseTable').innerHTML = house.length ? campHead(false) + house.map(c => campRow(c, false)).join('') : 'No house ads yet. Place one above.'; + } + // wall fallback ads editor + let wallAds = []; + function drawWallAds() { + const w = $('wallAdsList'); + w.innerHTML = wallAds.map((a, i) => '
WALL AD ' + (i + 1) + '' + + '
' + + '

' + + '

' + + '

' + + (a.bannerUrl ? '' : '') + + '
').join('') || '

No wall ads set. Walls fall back to a plain InstantAdPay card.

'; + } + function readWallAds() { + return [...document.querySelectorAll('#wallAdsList .drip-step')].map(c => ({ name: c.querySelector('.wa-name').value.trim(), targetUrl: c.querySelector('.wa-target').value.trim(), bannerUrl: c.querySelector('.wa-banner').value.trim() })); + } + async function loadWallAds() { + try { const r = await api('/api/admin/wall-ads'); wallAds = r.ads || []; $('wallAdsSub').textContent = r.usingDefaults ? 'none set: walls show the default InstantAdPay card' : wallAds.length + ' in rotation'; drawWallAds(); } catch (e) {} + } + $('wallAdsList').addEventListener('click', async e => { + const up = e.target.closest('.wa-upload'); + if (up) { up.parentElement.querySelector('.wa-file').click(); return; } + const b = e.target.closest('[data-wact]'); if (!b) return; + const i = Number(b.closest('.drip-step').dataset.i); wallAds = readWallAds(); + if (b.dataset.wact === 'remove') wallAds.splice(i, 1); + if (b.dataset.wact === 'up' && i > 0) [wallAds[i - 1], wallAds[i]] = [wallAds[i], wallAds[i - 1]]; + if (b.dataset.wact === 'down' && i < wallAds.length - 1) [wallAds[i + 1], wallAds[i]] = [wallAds[i], wallAds[i + 1]]; + drawWallAds(); + }); + $('wallAdsList').addEventListener('change', async e => { + const f = e.target.closest('.wa-file'); if (!f || !f.files[0]) return; + const file = f.files[0]; const card = f.closest('.drip-step'); + try { + const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': file.type }, body: file })).json(); + if (r.error) IAP.status(r.error, 'bad'); else { card.querySelector('.wa-banner').value = r.url; IAP.status('Uploaded.', 'ok'); } + } catch (err) { IAP.status('Upload failed.', 'bad'); } + f.value = ''; + }); + $('wallAdsAdd').addEventListener('click', () => { wallAds = readWallAds(); wallAds.push({ name: '', targetUrl: '', bannerUrl: '' }); drawWallAds(); }); + $('wallAdsSave').addEventListener('click', busy($('wallAdsSave'), async () => { + $('wallAdsErr').hidden = true; + try { const r = await api('/api/admin/wall-ads', { ads: readWallAds() }, 'PATCH'); wallAds = r.ads || []; drawWallAds(); IAP.status('Wall ads saved.', 'ok'); await loadWallAds(); } + catch (e) { $('wallAdsErr').textContent = e.message; $('wallAdsErr').hidden = false; } + })); + document.addEventListener('click', async e => { + const b = e.target.closest('[data-act][data-id]'); if (!b) return; + b.disabled = true; + try { + await api('/api/admin/campaigns/' + b.dataset.id + '/' + b.dataset.act, {}); + IAP.status('Campaign #' + b.dataset.id + ' ' + (b.dataset.act === 'pause' ? 'paused' : 'resumed') + '.', 'ok'); + await Promise.all([loadHouse(), loadCampaigns()]); + } catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } + }); + + // ── all campaigns ── + let allCamps = []; + async function loadCampaigns() { + loadLoginLine().catch(e => IAP.status(e.message, 'bad')); + const r = await api('/api/admin/campaigns'); + allCamps = r.campaigns || []; + drawCamps(); + } + // prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time. + const lqWhen = ts => ts ? esc(ctWhen(ts)) : 'unknown'; // ctWhen (below) prints Central time + async function loadLoginLine() { + const d = await api('/api/admin/login-queue'); + $('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open'; + $('lqTable').innerHTML = 'PlaceIDOwnerCampaignPaidQueued atEstimated start' + + (d.queue.length ? d.queue.map(c => '#' + c.place + '#' + c.id + '' + esc(c.owner) + '' + + '' + esc(c.name) + '
' + esc(c.targetUrl) + '
' + + '' + Number(c.paid || 0).toLocaleString() + '' + lqWhen(c.queuedAt) + '' + lqWhen(c.estStart) + '' + + '').join('') + : 'Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.'); + } + document.addEventListener('click', async e => { + const b = e.target.closest('[data-lqcancel]'); if (!b) return; + const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' }); + if (!ok) return; + b.disabled = true; + try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); } + catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } + }); + function drawCamps() { + const q = ($('campFilter').value || '').trim().toLowerCase(); + const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q)); + $('campSub').textContent = list.length + ' of ' + allCamps.length; + $('campTable').innerHTML = list.length ? campHead(true) + list.map(c => campRow(c, true)).join('') : 'Nothing matches.'; + } + $('campFilter').addEventListener('input', drawCamps); + + // ── members ── + let allMembers = []; + async function loadTank() { + try { + const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return; + $('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window'; + $('tankWait').innerHTML = 'WaitingEmailJoinedLast sign-in' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '').join('') : 'empty'); + $('tankAdopt').innerHTML = 'MemberAdopted byWhenWindow endsStatus' + (r.adoptions.length ? r.adoptions.map(a => '' + esc(a.adopteeName) + '' + esc(a.adopterName) + '' + when(a.ts) + '' + (a.status === 'released' ? '' : when(a.expires)) + '' + esc(a.status) + '').join('') : 'none yet'); + } catch (e) {} + } + async function loadMembers() { + loadTank(); loadFraud(); + const r = await api('/api/admin/members'); + allMembers = r.members || []; + drawMembers(); + } + function drawMembers() { + const q = ($('memFilter').value || '').trim().toLowerCase(); + const list = allMembers.filter(a => !q || [a.email, a.username, a.memberId, a.sponsorRef, a.address, a.code].join(' ').toLowerCase().includes(q)); + $('memSub').textContent = list.length + ' of ' + allMembers.length; + $('memTable').innerHTML = 'EmailUsernameMember #WalletSponsorPositionsViaCodeJoined' + + list.map(a => '' + esc(a.email) + '' + (a.username ? '@' + esc(a.username) : 'none') + '' + + '' + (a.memberId ? '#' + a.memberId : 'free') + '' + + '' + (a.address ? esc(a.address.slice(0, 8) + '…' + a.address.slice(-6)) : 'none') + '' + + '' + (a.sponsorName ? esc(a.sponsorName) + (a.sponsorVia === 'code' ? ' via code ' + esc(a.sponsorRef) + '' : a.sponsorVia === 'member #' ? ' via #' + esc(a.sponsorRef) + '' : '') : a.sponsorRef ? 'dead link: ' + esc(a.sponsorRef) + '' : 'none') + '' + (a.positions ? a.positions : '0') + '' + esc(a.joinedVia || '') + '' + esc(a.code || '') + '' + + '' + when(a.created) + (a.suspended ? ' suspended' : '') + ((a.flags || []).length ? ' ' + esc((a.flags || []).join(' ')) + '' : '') + '' + + ' ').join(''); + } + $('memFilter').addEventListener('input', drawMembers); + document.addEventListener('click', async e => { + const b = e.target.closest('[data-susp]'); if (!b) return; + const on = b.dataset.on === '1'; + if (on) { if (!await IAP.confirmBox('Unsuspend ' + b.dataset.susp + '? They can sign in again.', { title: 'Unsuspend', ok: 'Unsuspend', cancel: 'Cancel' })) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: false }, 'PATCH'); } + else { const why = await IAP.ask({ title: 'Suspend ' + b.dataset.susp, text: 'They will be signed out everywhere and cannot sign in. Reason (shown to admins only):', value: 'duplicate account', ok: 'Suspend' }); if (why === null || why === undefined) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: true, reason: why, flags: ['multi-account'] }, 'PATCH'); } + loadMembers(); + }); + async function loadFraud() { + const box = $('fraudBox'); if (!box) return; + try { + const r = await api('/api/admin/fraud'); + const grp = (title, list) => list.length ? '

' + title + '

' + list.map(g => '
' + esc(g.key) + ': ' + g.emails.map(x => esc(x)).join(', ') + '
').join('') : ''; + box.innerHTML = '

Duplicate signals

' + r.total + ' accounts with sign-in signals recorded (since 2026-09-16). Shared browser = same device cookie; shared IP within 30 days. Households are legal; two buying accounts on one browser are not.

' + + grp('Shared browser', r.sharedDevice) + grp('Shared IP', r.sharedIp) + + (r.flagged.length ? '

Flagged

' + r.flagged.map(f => '
' + esc(f.email) + ' [' + esc(f.flags.join(', ')) + ']' + (f.suspended ? ' suspended' : '') + '
').join('') : '') + + (r.suspended.length ? '

Suspended

' + r.suspended.map(x => '
' + esc(x.email) + ' (' + esc(x.reason || '') + ', ' + when(x.at) + ')
').join('') : '') + + (!r.sharedDevice.length && !r.sharedIp.length && !r.flagged.length && !r.suspended.length ? '

Nothing shared or flagged yet.

' : '') + // Approved exceptions (Marty, 2026-09-17): people okayed to hold more than one + // account. Lives right under the signals so the two are read together. + + '
' + + '

Approved exceptions

' + + '

People you have okayed to hold more than one account. They are never blocked at sign-up, never hard-flagged, and keep their leaderboard and adoption rights. Add the address of the account they ALREADY have, or the new one, either works. Suspension still overrides this.

' + + '
' + + '' + + '' + + '
' + + '
' + + ((r.allow || []).length + ? (r.allow || []).map(a => '
' + + '' + esc(a.email) + '' + + (a.note ? '' + esc(a.note) + '' : '') + + '' + when(a.at) + '' + + 'remove
').join('') + : '

No exceptions yet. Everyone is held to one account per person.

') + + '
'; + const say = (t, bad) => { const m = $('allowMsg'); if (m) { m.textContent = t; m.style.color = bad ? 'var(--bad)' : 'var(--mint)'; } }; + const addBtn = $('allowAdd'); + if (addBtn) addBtn.addEventListener('click', async () => { + const em = ($('allowEmail').value || '').trim(); const note = ($('allowNote').value || '').trim(); + if (!em) return say('Enter an email address.', true); + addBtn.disabled = true; say('Saving…'); + try { await api('/api/admin/fraud/allow', { email: em, note }); say('Added.'); loadFraud(); } + catch (err) { say(err.message, true); addBtn.disabled = false; } + }); + box.querySelectorAll('[data-allow-rm]').forEach(a => a.addEventListener('click', async ev => { + ev.preventDefault(); + const em = a.getAttribute('data-allow-rm'); + if (!(await IAP.confirmBox(em + ' goes back to the normal one-account-per-person checks. Existing accounts are not touched.', { title: 'Remove exception', ok: 'Remove', cancel: 'Cancel' }))) return; + try { await api('/api/admin/fraud/allow', { email: em, remove: true }); loadFraud(); } + catch (err) { say(err.message, true); } + })); + } catch (e) { box.innerHTML = '

' + esc(e.message) + '

'; } + } + document.addEventListener('click', async e => { + const b = e.target.closest('[data-spon]'); if (!b) return; + const v = await IAP.ask({ title: 'Sponsor for ' + b.dataset.spon, text: 'Username, share code, or member #. Leave blank to clear.', value: b.dataset.cur, ok: 'Save' }); + if (v === null || v === undefined) return; + try { + await api('/api/admin/members', { email: b.dataset.spon, sponsorRef: v.trim() }, 'PATCH'); + IAP.status('Sponsor updated.', 'ok'); + await loadMembers(); + } catch (err) { IAP.status(err.message, 'bad'); } + }); + + // ── member card: search, drill down, act (Marty, 2026-09-13) ── + let mcCur = null; + const polOf = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } }; + const ago = ts => { if (!ts) return 'never'; const d = Date.now() - Number(ts); const h = Math.floor(d / 3600000); return h < 1 ? Math.max(1, Math.floor(d / 60000)) + ' min ago' : h < 48 ? h + ' h ago' : Math.floor(h / 24) + ' days ago'; }; + const memLink = (email, label) => '' + esc(label) + ''; + async function openMember(q) { + const msg = $('memSearchMsg'); msg.hidden = true; + let d; + try { d = await api('/api/admin/member?q=' + encodeURIComponent(q)); } catch (e) { msg.textContent = e.message; msg.hidden = false; msg.className = 'small bad'; return; } + renderMember(d); + } + function kv(rows) { return '' + rows.map(r => '').join('') + '
' + r[0] + '' + r[1] + '
'; } + function renderMember(d) { + mcCur = d; const a = d.account; $('memHits').hidden = true; + $('memCard').hidden = false; document.querySelectorAll('#pane-members > .card').forEach(c => { if (c.id !== 'memCard' && c.id !== 'memSearchCard') c.hidden = true; }); + $('mcName').textContent = (a.username ? '@' + a.username : a.email) + (a.memberId ? ' · member #' + a.memberId : ' · free member'); + $('mcSub').textContent = 'joined ' + when(a.created) + ' · last seen ' + ago(a.lastSeen); + $('mcWall').hidden = !a.username; if (a.username) $('mcWall').href = '/wall/' + a.username; + const ch = d.chain, cr = d.credits, t = d.totals; + const level = ch && !ch.readError ? (ch.buyerCount >= 5 ? 'level 3 (5+ buyers)' : ch.buyerCount >= 2 ? 'level 2 (2 buyers)' : 'level 1') : ''; + let h = '
'; + h += '

Identity

' + kv([ + ['Email', esc(a.email)], ['Username', a.username ? '@' + esc(a.username) : 'not set'], ['Share code', esc(a.code || '')], + // A linked wallet is NOT an active position: linking is a free signature, switching on + // payouts is a separate transaction that creates the position. The address used to sit here + // on its own, which reads as "he is set up" when he is not (Marty, 2026-09-17, @mcbit1). + ['Main wallet', a.address + ? '' + esc(a.address) + '' + + (ch && !ch.readError + ? ' payouts ON' + : ' payouts OFF') + : 'none linked'], + ['PolyWarriors mint passes', d.pwPasses ? '' + (d.pwPasses.n || 0) + ' unused (earned ' + (d.pwPasses.earned || 0) + ', used ' + (d.pwPasses.used || 0) + ')' : 'none'], + ['Extra positions', d.positions.length ? d.positions.map(p => '' + esc(p.address.slice(0, 8) + '…' + p.address.slice(-6)) + '' + (p.memberId ? ' = #' + p.memberId : ' (unregistered)')).join('
') : 'none'], + ['Sponsor (site)', d.upline.length ? memLink(d.upline[0].email, d.upline[0].name) + ' token ' + esc(a.sponsorRef || '') + '' : (a.sponsorRef ? 'unresolved: ' + esc(a.sponsorRef) + '' : 'none (company)')], + ['Upline chain', d.upline.length > 1 ? d.upline.map(u => memLink(u.email, u.name)).join(' → ') : '-'], + ['Joined via', esc(a.joinedVia || 'join page') + (a.joinedRef ? ' from ' + esc(a.joinedRef) : '')], + ['Line banner', a.lineTargetUrl ? '' + esc(a.lineTargetUrl.slice(0, 50)) + '' : 'not set'], + ['Chat', a.chatAvailable ? 'available' : 'switched off']]) + '
'; + h += '

On-chain and money

' + kv([ + // Say WHICH of the two "not registered" states this is, and what it costs them, so the row + // above never gets read as "he is fine". + ['Registered', ch + ? (ch.readError ? 'read error' : 'yes, #' + ch.memberId + ' under ' + (ch.sponsorId ? '#' + ch.sponsorId + (d.names[ch.sponsorId] ? ' @' + esc(d.names[ch.sponsorId]) : '') : 'nobody')) + : (a.address + ? 'no wallet linked, but payouts were never switched on, so no position exists. Sales in their line walk up to their sponsor and lock there.' + : 'no no wallet linked yet.')], + ['Qualifying buyers', ch && !ch.readError ? ch.buyerCount + ' · ' + level : '-'], + ['Packages bought', t.purchases + (t.purchases ? ' · $' + (t.spentCents / 100).toFixed(0) + ' · ' + polOf(t.spentWei) + ' POL' : '')], + ['Payouts received', t.payoutsIn + (t.payoutsIn ? ' · ' + polOf(t.receivedWei) + ' POL' : '')], + ['Credits', cr ? cr.available.toLocaleString() + ' available · ' + cr.inCampaigns.toLocaleString() + ' in campaigns · ' + cr.total.toLocaleString() + ' total' : '-'], + ['Earned pool', d.earnedSplit ? d.earnedSplit.total.toLocaleString() + ' (' + (d.earnedSplit.grade || 0).toLocaleString() + ' purchased-grade)' : '-'], + ['Old-site account', d.legacy ? 'had a ' + (d.legacy.brand === 'both' ? 'Faucet Wave and Tier One Ads' : d.legacy.brand === 'tier1ads' ? 'Tier One Ads' : 'Faucet Wave') + ' account (' + d.legacy.seg + ') · welcome-back credits ' + (d.legacy.grant ? d.legacy.grant.credits + ' issued ' + when(d.legacy.grant.at) : 'not issued (joined outside the legacy bridge)') : 'none on record'], + ['Promo codes', d.promos.length ? d.promos.map(p => esc(p.code) + ' (' + p.credits + ', ' + when(p.ts) + ')').join('
') : 'none'], + ['Drip', d.drip ? (d.drip.stopped ? 'stopped' : 'step ' + d.drip.step + ', next ' + when(d.drip.next_at)) + (d.drip.angle ? ' · ' + esc(d.drip.angle) : '') : '-'], + ['Holding tank', d.tank ? (d.tank.waiting ? 'waiting for a sponsor' : 'not in tank') + (d.tank.adoptedBy.length ? ' · adopted by ' + d.tank.adoptedBy.map(x => memLink(x.email, x.name)).join(', ') : '') + (d.tank.adopted.length ? ' · adopted ' + d.tank.adopted.map(x => memLink(x.email, x.name)).join(', ') : '') : '-'], + ['Earning', d.earning ? 'today ' + d.earning.today + '/5' + (d.earning.claimed ? ' claimed' : '') + ' · streak day ' + d.earning.streakDay + (d.activeDays14 !== undefined ? ' · active ' + d.activeDays14 + ' of last 14 days, ' + d.claims14 + ' claims' : '') : '-'], + ['Visits / videos / chat', (d.visits || 0) + ' verified visits · ' + (d.videos || 0) + ' video watches · ' + (d.messageCount || 0) + ' messages']]) + '
'; + // line + h += '

Line (' + d.lineCounts.join(' / ') + ')

'; + if (!d.line.length) h += '

Nobody in their line yet.

'; + for (const L of d.line) { + h += '

Level ' + L.level + ' · ' + L.members.length + '

' + + L.members.map(m => '').join('') + '
MemberMember #WalletBoughtQualifiedJoinedLast seen
' + memLink(m.email, m.name) + (L.level === 1 ? '
' + esc(m.email) + '' : '') + '
' + (m.memberId ? '#' + m.memberId : 'free') + '' + (m.wallet ? 'yes' : 'no') + '' + (m.bought ? 'yes' : 'no') + '' + (m.qualified ? 'yes' : '') + '' + when(m.joined) + '' + ago(m.lastSeen) + '
'; + } + // purchases + payouts + campaigns + h += '

Purchases

' + + (d.purchases.length ? d.purchases.map(p => '').join('') : '') + '
WhenPositionPackagePaidTx
' + when(p.ts) + '#' + p.buyerId + '$' + (p.priceCents / 100).toFixed(0) + ' · ' + Number(p.credits || 0).toLocaleString() + ' cr' + polOf(p.paidWei) + ' POL' + esc(p.tx.slice(0, 10)) + '…
No purchases.
'; + h += '

Payouts received

' + + (d.received.length ? d.received.map(r => '').join('') : '') + '
WhenFromTierAmount
' + when(r.ts) + '#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '' + r.tier + '' + polOf(r.amountWei) + ' POL
Nothing received yet.
'; + h += '

Campaigns (' + d.campaigns.length + ')

' + + (d.campaigns.length ? d.campaigns.map(c => '').join('') : '') + '
#TypeStatusBudgetSpentViewsClicksCreated
' + c.id + '' + esc(c.type) + '' + esc(c.status) + '' + Number(c.budget || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + (c.pack ? Number(c.views || 0).toLocaleString() + ' of ' + Number(c.pack).toLocaleString() + ' visits' : Number(c.views || 0).toLocaleString()) + '' + Number(c.clicks || 0).toLocaleString() + '' + when(c.created) + '
No campaigns.
'; + $('mcBody').innerHTML = h; + if (location.hash !== '#members') history.replaceState(null, '', '#members'); + loadTrace(d); + } + // payment trace under the member card (2026-09-16): per purchase, who was paid / skipped and why + async function loadTrace(d) { + const ch = d.chain || {}; const mid = ch.memberId || (d.account && d.account.memberId) || 0; + const box = document.createElement('div'); box.id = 'mcTrace'; box.innerHTML = '

Payment trace

Reading the chain…

'; + $('mcBody').appendChild(box); + if (!mid) { box.innerHTML = '

Payment trace

Not activated on the chain, nothing to trace.

'; return; } + try { + const r = await api('/api/admin/trace?who=' + mid); + const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; + let h = '

Payment trace

' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' · every purchase this member was part of, newest first.

'; + if (!r.purchases.length) h += '

No purchases involving them yet.

'; + for (const p of r.purchases) { + h += '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought $' + (p.priceCents / 100).toFixed(0) + ' (' + polOf(p.paidWei) + ' POL)' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + ' · ' + esc(p.tx.slice(0, 12)) + '…
'; + for (const t of p.tiers) { + let line = 'L' + t.tier + ' ' + t.pct + '%: '; + for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' buyers then' : esc(x.reason)) + ') → '; + line += t.paidTo ? '' + nm(t.paidTo) + ' ' + polOf(t.amountWei) + ' POL' : 'no catcher → company'; + h += '
' + line + '
'; + } + h += '
platform ' + polOf(p.adminWei) + ' POL
'; + } + box.innerHTML = h; + } catch (e) { box.innerHTML = '

Payment trace

' + esc(e.message) + '

'; } + } + function closeMember() { $('memCard').hidden = true; document.querySelectorAll('#pane-members > .card').forEach(c => { c.hidden = false; }); } + // live matches while typing: any part of the username, email, member #, share code or wallet + let memHitList = []; + function memMatches(q) { + q = q.toLowerCase(); + return allMembers.filter(a => [a.username, a.email, a.memberId ? '#' + a.memberId : '', a.memberId, a.code, a.address, a.sponsorName].filter(Boolean).join(' ').toLowerCase().includes(q)).slice(0, 12); + } + async function memTypeahead() { + const q = $('memSearch').value.trim(); + if (!allMembers.length) { try { const r = await api('/api/admin/members'); allMembers = r.members || []; } catch (e) {} } + if (q.length < 2) { $('memHits').hidden = true; memHitList = []; return; } + memHitList = memMatches(q); + $('memHits').innerHTML = memHitList.length ? memHitList.map(a => '').join('') + : '

No member matches that.

'; + $('memHits').hidden = false; + } + $('memSearch').addEventListener('input', memTypeahead); + $('memSearch').addEventListener('focus', memTypeahead); + $('memOpen').addEventListener('click', () => { const q = $('memSearch').value.trim(); if (!q) return; if (memHitList.length) openMember(memHitList[0].email); else openMember(q); }); + $('memSearch').addEventListener('keydown', e => { if (e.key === 'Enter') $('memOpen').click(); if (e.key === 'Escape') $('memHits').hidden = true; }); + document.addEventListener('click', e => { if (!e.target.closest('#memSearchCard')) $('memHits').hidden = true; }); + $('mcBack').addEventListener('click', closeMember); + document.addEventListener('click', e => { const l = e.target.closest('[data-mcopen]'); if (l) { e.preventDefault(); openMember(l.dataset.mcopen); } }); + document.querySelectorAll('[data-mcact]').forEach(b => b.addEventListener('click', busy(b, async () => { + if (!mcCur) return; const a = mcCur.account, act = b.dataset.mcact; let body = null; + if (act === 'username') { const v = await IAP.ask({ title: 'Username for ' + a.email, text: '3-20 letters, numbers or underscore. Changing it breaks any invite links they already handed out.', value: a.username || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { username: v }; } + if (act === 'sponsor') { const v = await IAP.ask({ title: 'Sponsor for ' + (a.username ? '@' + a.username : a.email), text: 'Username, share code or member #. Blank = no sponsor (company). Re-points free referrals and future purchases; on-chain sponsorship never changes.', value: a.sponsorRef || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { sponsorRef: v }; } + if (act === 'wallet') { const v = await IAP.ask({ title: 'Main wallet for ' + a.email, text: 'Paste the 0x address that should be their main wallet (the one that paid, if a purchase came from an unlinked account). The member number is re-read from the chain. Blank = unlink.', value: a.address || '', ok: 'Swap' }); if (v === null || v === undefined) return; if (!await IAP.confirmBox('Swap the main wallet for ' + a.email + ' to ' + (v.trim() || 'nothing') + '?', { title: 'Sure?', ok: 'Swap it', cancel: 'Cancel' })) return; body = { address: v }; } + if (act === 'credits') { const v = await IAP.ask({ title: 'Grant credits to ' + (a.username ? '@' + a.username : a.email), text: 'Whole number of earned-pool credits (1 credit = 1 cent of delivery). They can spend them on campaigns right away.', type: 'number', value: '', placeholder: '250', ok: 'Grant' }); if (!v) return; const note = await IAP.ask({ title: 'Reason (kept in the server log)', value: '', placeholder: 'e.g. refund for broken banner', ok: 'Grant' }); body = { grantCredits: v, note: note || '' }; } + if (act === 'delete') { + if (a.memberId) { IAP.status('Registered members cannot be deleted; their position is on-chain.', 'bad'); return; } + if (!await IAP.confirmBox('Delete the free account ' + a.email + '? Their sign-in, referrals link and credits go away. There is no undo.', { title: 'Delete account', ok: 'Delete', cancel: 'Keep it' })) return; + await api('/api/admin/member?email=' + encodeURIComponent(a.email), undefined, 'DELETE'); IAP.status('Account deleted.', 'ok'); closeMember(); loadMembers().catch(() => {}); return; + } + if (!body) return; + const d = await api('/api/admin/member', Object.assign({ email: a.email }, body), 'PATCH'); + renderMember(d); IAP.status('Saved.', 'ok'); loadMembers().catch(() => {}); + }))); + + // ── every admin table: click a header to sort (numbers sort as numbers), inputs with + // class "tfilter" filter the table named in data-for ── + document.addEventListener('click', e => { + const th = e.target.closest('.adm-table th'); if (!th || th.closest('table').classList.contains('kv')) return; + const table = th.closest('table'), hdr = th.parentElement, idx = [...hdr.children].indexOf(th); + const rows = [...table.querySelectorAll('tr')].filter(r => r !== hdr && r.children.length > 1); + const num = s => { const t = String(s).replace(/[$,%\s]/g, '').replace(/…$/, ''); return t !== '' && !isNaN(t) ? Number(t) : null; }; + const dir = th.dataset.dir === 'asc' ? 'desc' : 'asc'; + hdr.querySelectorAll('th').forEach(x => { delete x.dataset.dir; x.classList.remove('sort-asc', 'sort-desc'); }); + th.dataset.dir = dir; th.classList.add('sort-' + dir); + rows.sort((r1, r2) => { const a = (r1.children[idx] || {}).textContent || '', b = (r2.children[idx] || {}).textContent || ''; const na = num(a), nb = num(b); const c = na !== null && nb !== null ? na - nb : a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); return dir === 'asc' ? c : -c; }); + rows.forEach(r => (hdr.parentElement).appendChild(r)); + }); + document.addEventListener('input', e => { + const inp = e.target.closest('.tfilter'); if (!inp) return; + const table = $(inp.dataset.for); if (!table) return; + const q = inp.value.trim().toLowerCase(); let shown = 0; + [...table.querySelectorAll('tr')].forEach((r, i) => { if (i === 0 || r.querySelector('th')) return; const hit = !q || r.textContent.toLowerCase().includes(q); r.hidden = !hit; if (hit) shown++; }); + const c = inp.parentElement.querySelector('.tfilter-count'); if (c) c.textContent = q ? shown + ' shown' : ''; + }); + + // ── release notes + roadmap (Marty, 2026-09-14) ── + async function loadReleases() { + loadUpdates(); + const d = await api('/api/admin/releases'); + $('rnSub').textContent = d.notes.length + ' notes'; $('rmSub').textContent = d.roadmap.length + ' items'; + $('rnTable').innerHTML = 'DateTitleTags' + (d.notes.length ? d.notes.map(n => '' + esc(n.date) + '' + esc(n.title) + '' + esc(n.tags.join(', ')) + ' ').join('') : 'No notes yet.'); + $('rmTable').innerHTML = 'StatusTitleETA#' + (d.roadmap.length ? d.roadmap.map(r => '' + esc(r.status) + '' + esc(r.title) + '' + (r.note ? '
' + esc(r.note) + '' : '') + '' + esc(r.eta || '') + '' + (r.order || '') + ' ').join('') : 'Nothing on the roadmap yet.'); + $('rnTable').querySelectorAll('[data-rnedit]').forEach(b => b.addEventListener('click', () => { const n = d.notes.find(x => x.id === b.dataset.rnedit); if (!n) return; $('rnId').value = n.id; $('rnTitle').value = n.title; $('rnDate').value = n.date; $('rnTags').value = n.tags.join(', '); $('rnBody').value = n.body; $('rnTitle').focus(); })); + $('rmTable').querySelectorAll('[data-rmedit]').forEach(b => b.addEventListener('click', () => { const r = d.roadmap.find(x => x.id === b.dataset.rmedit); if (!r) return; $('rmId').value = r.id; $('rmTitle').value = r.title; $('rmStatus').value = r.status; $('rmEta').value = r.eta || ''; $('rmOrder').value = r.order || ''; $('rmNote').value = r.note || ''; $('rmTitle').focus(); })); + $('rnTable').querySelectorAll('[data-rndel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this release note?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=notes&id=' + encodeURIComponent(b.dataset.rndel), undefined, 'DELETE'); loadReleases(); })); + $('rmTable').querySelectorAll('[data-rmdel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this roadmap item?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=roadmap&id=' + encodeURIComponent(b.dataset.rmdel), undefined, 'DELETE'); loadReleases(); })); + } + // ── member update emails (Marty, 2026-09-14) ── + async function loadUpdates() { + if (!$('updCard')) return; + try { + const d = await api('/api/admin/updates'); + $('updSub').textContent = (d.mailer ? '' : 'mailer not configured · ') + (d.lastSentAt ? 'last send ' + new Date(d.lastSentAt).toLocaleString() : 'nothing sent yet') + (d.running ? ' · sending now' : ''); + const keep = $('updAudience').value; + $('updAudience').innerHTML = Object.entries(d.audiences).map(([k, v]) => '').join(''); + if (keep) $('updAudience').value = keep; + if (!d.counts) setTimeout(() => loadUpdates().catch(() => {}), 15000); // the counts are being worked out in the background + // a re-render (the background count refresh) must keep whatever is ticked; only the first render pre-ticks fresh notes, + // and a saved draft decides for itself (Marty, 2026-09-28: a test send carried every note because a refresh re-ticked them) + const wasTicked = new Set([...$('updNotes').querySelectorAll('input:checked')].map(i => i.value)), rendered = $('updNotes').querySelector('input') !== null; + $('updNotes').innerHTML = d.notes.length ? d.notes.map(n => '').join('') : 'No release notes yet.'; + $('updLog').innerHTML = 'WhenSubjectAudienceSent' + (d.sends.length ? d.sends.map(x => '' + new Date(x.ts).toLocaleString() + '' + esc(x.subject) + '' + esc(d.audiences[x.audience] || x.audience) + '' + x.sent + ' of ' + x.total + (x.skipped ? ' · ' + x.skipped + ' opted out' : '') + (x.failed ? ' · ' + x.failed + ' failed' : '') + (x.unknown ? ' · ' + x.unknown + ' unchecked (Sendy gave no answer)' : '') + (x.status === 'running' ? ' · running' : '') + '').join('') : 'None yet.'); + if (d.draft && !updDraftLoaded) { updDraftLoaded = true; $('updSubject').value = d.draft.subject || ''; $('updIntro').value = d.draft.intro || ''; $('updClosing').value = d.draft.closing || ''; if (d.draft.audience) $('updAudience').value = d.draft.audience; $('updNotes').querySelectorAll('input').forEach(i => { i.checked = (d.draft.noteIds || []).includes(i.value); }); $('updSub').textContent += ' · draft loaded (saved ' + new Date(d.draft.savedAt).toLocaleString() + ')'; } + if (d.running) setTimeout(loadUpdates, 4000); + } catch (e) { $('updSub').textContent = e.message; } + } + let updDraftLoaded = false; + const updInput = () => ({ subject: $('updSubject').value, intro: $('updIntro').value, closing: $('updClosing').value, noteIds: [...$('updNotes').querySelectorAll('input:checked')].map(i => i.value), audience: $('updAudience').value }); + if ($('updCard')) { + $('updSaveDraft').addEventListener('click', busy($('updSaveDraft'), async () => { await api('/api/admin/updates/draft', updInput()); IAP.status('Draft saved.', 'ok'); })); + $('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; })); + $('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); })); + $('updSend').addEventListener('click', busy($('updSend'), async () => { + const inp = updInput(); if (!inp.noteIds.length && !String(inp.intro || '').trim()) { IAP.status('Write an intro or pick at least one note.', 'bad'); return; } + const opt = $('updAudience').selectedOptions[0].textContent; + if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return; + const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates(); + })); + } + $('rnClear').addEventListener('click', () => { ['rnId', 'rnTitle', 'rnDate', 'rnTags', 'rnBody'].forEach(id => { $(id).value = ''; }); }); + $('rmClear').addEventListener('click', () => { ['rmId', 'rmTitle', 'rmEta', 'rmOrder', 'rmNote'].forEach(id => { $(id).value = ''; }); $('rmStatus').value = 'planned'; }); + $('rnSave').addEventListener('click', busy($('rnSave'), async () => { await api('/api/admin/releases', { kind: 'note', id: $('rnId').value || null, title: $('rnTitle').value, date: $('rnDate').value, tags: $('rnTags').value, body: $('rnBody').value }); IAP.status('Note saved.', 'ok'); $('rnClear').click(); loadReleases(); })); + $('rmSave').addEventListener('click', busy($('rmSave'), async () => { await api('/api/admin/releases', { kind: 'roadmap', id: $('rmId').value || null, title: $('rmTitle').value, status: $('rmStatus').value, eta: $('rmEta').value, order: $('rmOrder').value, note: $('rmNote').value }); IAP.status('Roadmap item saved.', 'ok'); $('rmClear').click(); loadReleases(); })); + + // ── reports + burns ── + // ── profit and loss ── + let pnlDays = 30; + const pol = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } }; + const usdOf = (w, px) => { try { return '$' + ((Number(BigInt(w || '0') / 10n ** 14n) / 10000) * px).toLocaleString(undefined, { maximumFractionDigits: 0 }); } catch (e) { return '$0'; } }; + // ── traffic: referring domains / sources, landing pages, angles, by day ── + let trfDays = 30; + document.querySelectorAll('#trfRange [data-days]').forEach(b => b.addEventListener('click', () => { trfDays = Number(b.dataset.days); document.querySelectorAll('#trfRange [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadTraffic().catch(e => IAP.status(e.message, 'bad')); })); + async function loadPromos() { + const d = await (await fetch('/api/admin/promos')).json(); + if (d.error) throw new Error(d.error); + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const when = t => t ? new Date(t).toLocaleDateString() : ''; + $('pcTable').innerHTML = 'CodeCreditsPartnerUsesMaxExpiresStatus' + + (d.codes.length ? d.codes.map(c => '' + esc(c.code) + '' + c.credits.toLocaleString() + '' + esc(c.partner) + '' + c.uses + '' + (c.maxUses || '∞') + '' + (c.expires ? when(c.expires) : '') + '' + (c.active ? 'active' : 'off') + '').join('') : 'No codes yet.'); + $('pcRecent').innerHTML = 'WhenCodeEmailCreditsVia' + + (d.recent.length ? d.recent.map(r => '' + new Date(r.ts).toLocaleString() + '' + esc(r.code) + '' + esc(r.email) + '' + r.credits + '' + esc(r.via) + '').join('') : 'No redemptions yet.'); + document.querySelectorAll('[data-pctoggle]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/admin/promos', { code: b.dataset.pctoggle, active: b.dataset.on === '1' }, 'PATCH'); loadPromos(); } catch (e) { IAP.status(e.message, 'bad'); } + })); + } + if ($('pcSave')) $('pcSave').addEventListener('click', async () => { + const msg = $('pcMsg'); msg.hidden = false; + try { + const r = await api('/api/admin/promos', { code: $('pcCode').value, credits: $('pcCredits').value, partner: $('pcPartner').value, maxUses: $('pcMax').value, expires: $('pcExpires').value || null, active: true }); + msg.textContent = 'Saved ' + r.code.code + ': ' + r.code.credits + ' credits.'; msg.style.color = 'var(--mint)'; + $('pcCode').value = ''; $('pcCredits').value = ''; $('pcPartner').value = ''; loadPromos(); + } catch (e) { msg.textContent = e.message; msg.style.color = '#ff8a8a'; } + }); + async function loadTraffic() { + loadPromos().catch(e => IAP.status(e.message, 'bad')); + loadLoginShows().catch(e => IAP.status(e.message, 'bad')); + const d = await (await fetch('/api/admin/traffic?days=' + trfDays)).json(); + if (d.error) throw new Error(d.error); + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const n = v => Number(v || 0).toLocaleString(); + $('trfSub').textContent = 'last ' + d.days + ' days · ' + n(d.totals.hits) + ' page views · ' + n(d.totals.joinViews) + ' join-page views · ' + n(d.totals.signups) + ' signups · ' + n(d.totals.buyers) + ' buyers'; + // conversion columns (Marty, 2026-09-13): visits = page views + join-page views; signup rate is per visit, + // registered and buyer rates are per signup (what happened to the people who did sign up) + const pct = (num, den) => den ? (100 * num / den).toFixed(num && 100 * num / den < 10 ? 1 : 0) + '%' : '-'; + $('trfSources').innerHTML = 'SourcePage
viewsJoin-page
viewsSignupsVisit →
signupRegisteredSignup →
registered$20+
buyersSignup →
buyer' + + (d.sources.length ? d.sources.map(s => '' + esc(s.source) + '' + n(s.hits) + '' + n(s.joinViews) + '' + n(s.signups) + '' + pct(s.signups, s.hits + s.joinViews) + '' + n(s.registered) + '' + pct(s.registered, s.signups) + '' + n(s.buyers) + '' + pct(s.buyers, s.signups) + '').join('') : 'Nothing recorded in this range yet.'); + // games to members (2026-10-05): card taps that reached InstantAdPay, first packages bought, dollars, per game (all time) + if (d.starter) { const st = d.starter, rows = Object.values(st.games); + $('stSub').textContent = (st.settings.on ? 'on' : 'off') + ' · welcome bonus ' + st.settings.bonus + ' credits · ' + st.granted + ' granted'; + $('trfStarter').innerHTML = 'GameOffer tapsFirst packagesPackage $Tap → buy' + rows.map(g => '' + esc(g.name) + '' + n(g.visits) + '' + n(g.buyers) + '$' + g.usd.toFixed(2) + '' + pct(g.buyers, g.visits) + '').join(''); } + $('trfPaths').innerHTML = 'PageViews' + (d.paths.length ? d.paths.map(p => '' + esc(p.path) + '' + n(p.hits) + '').join('') : 'No page views yet.'); + $('trfAngles').innerHTML = 'AngleJoin-page
viewsSignupsView →
signup' + (d.angles.length ? d.angles.map(a => '' + esc(a.angle) + '' + n(a.views) + '' + n(a.signups) + '' + pct(a.signups, a.views) + '').join('') : 'No angle data yet.'); + $('trfDaily').innerHTML = 'DayPage viewsSignups' + (d.daily.length ? d.daily.slice().reverse().map(x => '' + esc(x.day) + '' + n(x.hits) + '' + n(x.signups) + '').join('') : 'Nothing yet.'); + } + // login-ad showings per Central day (2026-10-18): the dashboard gate vs the games' sign-in kit, member slot vs house ad, + // and sign-ins that had no login ad to show. A week of these decides whether the 3-slot cap goes up. + async function loadLoginShows() { + const d = await (await fetch('/api/admin/login-shows?days=14')).json(); + if (d.error) throw new Error(d.error); + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const n = v => Number(v || 0).toLocaleString(), shown = x => x.member + x.house; + const week = d.days.slice(0, 7).reduce((a, x) => { a.dash += shown(x.dashboard); a.games += shown(x.games); return a; }, { dash: 0, games: 0 }); + $('lsSub').textContent = 'last 7 days: ' + n(week.dash + week.games) + ' shown (' + n(week.dash) + ' dashboard, ' + n(week.games) + ' games) · slots ' + d.slots.used + ' of ' + d.slots.max + ' taken'; + $('trfLogin').innerHTML = 'Day (CT)Dashboard
shownGames
shownTotal
shownOf which
house adSign-ins with
no login adBy game' + + d.days.map(x => '' + esc(x.day) + '' + n(shown(x.dashboard)) + '' + n(shown(x.games)) + '' + n(shown(x.dashboard) + shown(x.games)) + '' + n(x.dashboard.house + x.games.house) + '' + n(x.dashboard.none + x.games.none) + '' + + (Object.keys(x.byGame).length ? Object.entries(x.byGame).map(([g, v]) => esc(g) + ' ' + n(v)).join(', ') : '-') + '').join(''); + } + // ── blog: coaching articles, public at /blog (Marty, 2026-09-12) ── + let blCur = null; // slug being edited, or null for a new one + function blCount() { + const t = $('blTitle').value.length, e = $('blExcerpt').value.length; + $('blTitleCount').textContent = t + '/60' + (t > 60 ? ' (long)' : ''); + $('blExcCount').textContent = e + ' chars' + (e && (e < 120 || e > 160) ? ' (aim 120-160)' : ''); + const w = $('blBody').textContent.trim().split(/\s+/).filter(Boolean).length; + $('blWords').textContent = w + ' words'; + } + ['blTitle', 'blExcerpt'].forEach(id => $(id).addEventListener('input', blCount)); + $('blBody').addEventListener('input', blCount); + $('blTitle').addEventListener('input', () => { if (!blCur && !$('blSlug').dataset.touched) $('blSlug').value = $('blTitle').value.toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80); }); + $('blSlug').addEventListener('input', () => { $('blSlug').dataset.touched = '1'; }); + document.querySelectorAll('.ed-bar [data-bl]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand(b.dataset.bl, false, null); })); + document.querySelectorAll('.ed-bar [data-blblock]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand('formatBlock', false, b.dataset.blblock); })); + $('blLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; + const u = await IAP.ask({ title: 'Link address', label: 'https://', placeholder: 'https://instantadpay.com/join/martbost', ok: 'Insert' }); + if (u) { $('blBody').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } + }); + $('blImgBtn').addEventListener('click', () => $('blImgFile').click()); + $('blImgFile').addEventListener('change', async () => { + const f = $('blImgFile').files[0]; if (!f) return; + try { + const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) throw new Error(r.error); + $('blBody').focus(); + const html = ''; + if (!document.execCommand('insertHTML', false, html)) $('blBody').insertAdjacentHTML('beforeend', html); + blCount(); + } catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); } + $('blImgFile').value = ''; + }); + $('blCoverBtn').addEventListener('click', () => $('blCoverFile').click()); + $('blCoverFile').addEventListener('change', () => upload($('blCoverFile'), $('blCoverInfo'), $('blCover'))); + $('blHtmlBtn').addEventListener('click', () => { + const raw = !$('blHtml').hidden; + if (raw) { $('blBody').innerHTML = $('blHtml').value; $('blHtml').hidden = true; $('blBody').hidden = false; } + else { $('blHtml').value = $('blBody').innerHTML; $('blBody').hidden = true; $('blHtml').hidden = false; } + blCount(); + }); + function blBodyHtml() { return $('blHtml').hidden ? $('blBody').innerHTML : $('blHtml').value; } + function blMsg(t, bad) { $('blMsg').textContent = t; $('blMsg').hidden = !t; $('blMsg').className = 'small ' + (bad ? 'bad' : 'ok'); } + function blOpen(post) { + blCur = post ? post.slug : null; + $('blogList').hidden = true; $('blogEditor').hidden = false; + $('blEdTitle').textContent = post ? 'Edit article' : 'New article'; + $('blEdSub').textContent = post ? (post.status === 'published' ? 'published ' + when(post.publishedAt) + ' · ' + (post.views || 0) + ' views' : 'draft') : ''; + $('blTitle').value = post ? post.title : ''; $('blSlug').value = post ? post.slug : ''; delete $('blSlug').dataset.touched; + $('blTags').value = post ? post.tags.join(', ') : ''; $('blExcerpt').value = post ? post.excerpt : ''; $('blCover').value = post ? post.cover : ''; $('blCoverInfo').textContent = ''; + $('blHtml').hidden = true; $('blBody').hidden = false; $('blBody').innerHTML = post ? post.body : ''; + $('blUnpublish').hidden = !(post && post.status === 'published'); $('blDelete').hidden = !post; + $('blPreview').hidden = !post; if (post) $('blPreview').href = '/blog/' + post.slug; + $('blPublish').textContent = post && post.status === 'published' ? 'Save and publish' : 'Publish'; + blMsg(''); blCount(); $('blTitle').focus(); + } + async function blSave(status) { + const body = { existingSlug: blCur, title: $('blTitle').value, slug: $('blSlug').value, tags: $('blTags').value, excerpt: $('blExcerpt').value, cover: $('blCover').value, body: blBodyHtml(), status }; + const r = await api('/api/admin/blog', body); + blCur = r.post.slug; + $('blSlug').value = r.post.slug; $('blPreview').hidden = false; $('blPreview').href = '/blog/' + r.post.slug; $('blDelete').hidden = false; + $('blUnpublish').hidden = r.post.status !== 'published'; $('blPublish').textContent = r.post.status === 'published' ? 'Save and publish' : 'Publish'; + $('blEdTitle').textContent = 'Edit article'; + blMsg(r.post.status === 'published' ? 'Published. Live at instantadpay.com/blog/' + r.post.slug + (r.syndicating ? ' · posting to X and Instagram now (see the Social column in the list).' : '') : 'Draft saved.'); + IAP.status(r.post.status === 'published' ? 'Published.' : 'Draft saved.', 'ok'); + } + $('blSaveDraft').addEventListener('click', busy($('blSaveDraft'), () => blSave('draft'))); + $('blPublish').addEventListener('click', busy($('blPublish'), () => blSave('published'))); + $('blUnpublish').addEventListener('click', busy($('blUnpublish'), () => blSave('draft'))); + $('blClose').addEventListener('click', () => { $('blogEditor').hidden = true; $('blogList').hidden = false; loadBlog().catch(e => IAP.status(e.message, 'bad')); }); + $('blDelete').addEventListener('click', busy($('blDelete'), async () => { + if (!blCur) return; + if (!await IAP.confirmBox('The page at /blog/' + blCur + ' stops existing. There is no undo.', { title: 'Delete this article?', ok: 'Delete', cancel: 'Keep it' })) return; + await api('/api/admin/blog?slug=' + encodeURIComponent(blCur), undefined, 'DELETE'); + $('blClose').click(); + })); + $('blNew').addEventListener('click', () => blOpen(null)); + async function loadBlog() { + const d = await api('/api/admin/blog'); + const pub = d.posts.filter(p => p.status === 'published').length; + $('blSub').textContent = pub + ' published · ' + (d.posts.length - pub) + ' drafts'; + const synd = p => { const s = p.syndicated; if (!s) return p.status === 'published' ? 'not posted' : ''; const r = s.results || {}; const part = ['x', 'instagram'].map(k => r[k] ? (r[k].ok ? k + ' ✓' : k + ' ✗') : k + ' –').join(' · '); return '' + part + ''; }; + $('blSyndNote').hidden = false; $('blSyndNote').textContent = d.syndication ? 'Publishing an article posts it to X (@cryptoteambuild) and Instagram (marketingwithmarty) through Blotato, once per article, with the cover image.' : 'Social syndication is off: no Blotato key on the server.'; + $('blTable').innerHTML = 'TitleStatusSocialTagsViewsUpdated' + + (d.posts.length ? d.posts.map(p => '' + esc(p.title) + '
/blog/' + esc(p.slug) + '' + (p.status === 'published' ? 'published' : 'draft') + '' + synd(p) + '' + esc(p.tags.join(', ')) + '' + (p.views || 0) + '' + when(p.updated) + ' View' + (p.status === 'published' && d.syndication && !(p.syndicated && p.syndicated.done) ? ' ' : '') + '').join('') + : 'No articles yet. Start with "New article".'); + $('blTable').querySelectorAll('[data-blsynd]').forEach(b => b.addEventListener('click', busy(b, async () => { + const r = await api('/api/admin/blog/syndicate', { slug: b.dataset.blsynd }); + const res = r.syndicated && r.syndicated.results || {}; const bad = Object.entries(res).filter(([, v]) => !v.ok).map(([k, v]) => k + ': ' + v.error); + IAP.status(bad.length ? 'Posted with problems: ' + bad.join(' | ') : 'Posted to X and Instagram.', bad.length ? 'bad' : 'ok'); loadBlog().catch(() => {}); + }))); + $('blTable').querySelectorAll('[data-bledit]').forEach(b => b.addEventListener('click', async () => { + try { const r = await api('/api/admin/blog?slug=' + encodeURIComponent(b.dataset.bledit)); blOpen(r.post); } catch (e) { IAP.status(e.message, 'bad'); } + })); + } + + 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; + const months = pnlDays ? pnlDays / 30 : Math.max(1, (r.latest - r.fromBlock) / 43200 / 30); + const fixed = (r.fixedMonthlyUsd || 0) * months; + $('pnlTiles').innerHTML = [ + ['Packages sold', r.purchases.count, Object.entries(r.purchases.byPackage || {}).map(([k, v]) => v + '×' + k).join(' · ') || '—'], + ['Gross volume', pol(r.purchases.volumeWei) + ' POL', usdOf(r.purchases.volumeWei, px) + ' at today\'s rate · $' + (r.purchases.usdCents / 100).toLocaleString() + ' at sale'], + ['Platform (fees + dust + unclaimed)', pol(r.platformWei) + ' POL', usdOf(r.platformWei, px)], + ['Paid to members', pol(r.memberPayoutsWei) + ' POL', usdOf(r.memberPayoutsWei, px)], + ['Net after fixed costs', '$' + Math.round(platUsd - fixed).toLocaleString(), 'fixed ' + Math.round(fixed).toLocaleString() + ' over ' + months.toFixed(1) + ' month(s)'], + ['Pass-ups', r.passedUp.count, r.passedUp.unqualified + ' unqualified · ' + r.passedUp.sendFailed + ' send-failed'] + ].map(t => '
' + esc(String(t[1])) + '
' + esc(t[0]) + '
' + esc(t[2]) + '
').join(''); + // PolHunter: a marketing cost paid from its own faucet, so it is read across rather than + // derived from our chain events (Marty, 2026-09-23) + const ph = r.polhunter, phEl = $('pnlHunt'); + if (phEl) { + if (!ph || ph.error || !ph.totals) phEl.innerHTML = 'PolHunter figures unavailable' + (ph && ph.error ? ' (' + esc(ph.error) + ')' : '') + '.'; + else { + const t = ph.totals, rf = ph.referrals || {}, usd = n => '$' + (Number(n) * px).toFixed(2); + const findPol = Math.max(0, Number(t.pol || 0) - Number(rf.paidPol || 0)); + phEl.innerHTML = 'LinePOLUSD now' + + [['Mission finds (' + Number(t.paid || 0).toLocaleString() + ' paid)', findPol], + ['Referral bounties (' + Number(rf.bounties || 0) + ')', null], + ['Referral matches (' + Number(rf.matches || 0) + ')', null], + ['Referral payouts total', Number(rf.pol || 0)], + ['All PolHunter payouts', Number(t.pol || 0)]] + .filter(x => x[1] !== null) + .map(x => '' + x[0] + '' + Number(x[1]).toFixed(4) + '' + usd(x[1]) + '').join('') + + 'Hunters paid' + Number(t.hunters || 0) + 'today ' + Number(t.today || 0).toFixed(3) + ' POL'; + } + } + // every game's payouts, all time, running total (Marty, 2026-10-18). PassiveDrip is a drip + // program rather than a game, so it sits under the total instead of inside it. + const ga = r.gamesAll, gaEl = $('pnlGames'); + if (gaEl) { + if (!ga || ga.error || !Array.isArray(ga.games) || !ga.games.length) gaEl.innerHTML = '' + (ga && ga.scanning ? 'Reading the game wallets from Polygon for the first time. Refresh in a minute.' : 'Game payout figures unavailable' + (ga && ga.error ? ' (' + esc(ga.error) + ')' : '') + '.') + ''; + else { + const wp = w => Number(BigInt(w) / 10n ** 12n) / 1e6, games = ga.games.filter(g => g.slug !== 'passivedrip'), pd = ga.games.find(g => g.slug === 'passivedrip'); + const row = (name, w, n, pl, cls) => '' + name + '' + wp(w).toFixed(4) + '$' + (wp(w) * px).toFixed(2) + '' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + ''; + const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0); + gaEl.innerHTML = 'GamePOLUSD nowPayouts to players' + + games.map(g => row(esc(g.name) + (g.error ? ' stale' : ''), g.wei, g.count, g.players)).join('') + + 'All game payouts' + wp(tw).toFixed(4) + '$' + (wp(tw) * px).toFixed(2) + '' + tn.toLocaleString() + ' payouts' + + (pd ? row('PassiveDrip (not a game)', pd.wei, pd.count, pd.players) : '') + + 'Read ' + (ga.at ? new Date(ga.at).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' }) + ' CT' : 'just now') + (ga.scanning ? ', refreshing' : '') + '. Updates every 10 minutes.'; + } + } + $('pnlSplit').innerHTML ='LinePOLUSD now' + + [['Level 1 (50%)', r.byTier[1]], ['Level 2 (20%)', r.byTier[2]], ['Level 3 (10%)', r.byTier[3]], ['Platform (20% + pass-ups)', r.platformWei]].map(x => '' + x[0] + '' + pol(x[1]) + '' + usdOf(x[1], px) + '').join(''); + const W = r.wallets || {}, B = r.balances || {}; + $('pnlWallets').innerHTML = 'WalletAddressBalance' + + [['Owner / fee A (Tangem)', W.feeA, B.feeA], ['Fee B', W.feeB, B.feeB], ['Engine (gas)', W.engine, B.engine]].filter(x => x[1]).map(x => '' + x[0] + '' + esc(x[1]) + '' + (x[2] == null ? '?' : pol(x[2]) + ' POL') + '').join(''); + renderLedger(r); + $('pnlFixed').value = r.fixedMonthlyUsd || 0; + const b = r.burner || {}; + $('burnerLine').textContent = !b.hasEthers ? 'ethers is not installed in this build.' : !b.keyPresent ? 'No engine key configured (ENGINE_KEY). Burns stay pending until it is set.' : b.mismatch ? 'ENGINE_KEY does not match the contract engine signer. Disabled.' : 'Engine wallet ' + b.address + ' holds ' + pol(b.balanceWei) + ' POL. That is its gas fund, not a cost: one burn uses about 0.003 POL (roughly 48,000 gas), paid by this wallet, never by the member. ' + b.burned + ' burn' + (b.burned === 1 ? '' : 's') + ' since boot' + (b.lastRun ? ' · last check ' + when(b.lastRun) : '') + (b.lastError ? ' · last error: ' + b.lastError : '') + (b.skipped && Object.keys(b.skipped).length ? ' · skipped (needs review): ' + Object.entries(b.skipped).map(([k, v]) => k + ' (' + v + ')').join(', ') : ''); + } + // The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that + // makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody + // wrote down (Marty, 2026-09-23). + const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' }; + const LD_CAT = { advertising: 'Advertising', games: 'Game marketing', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' }; + const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' }; + const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 }); + function renderLedger(r) { + const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {}; + if ($('pnlLedger')) { + $('pnlLedger').innerHTML = 'DateWalletKindPOLWhat for' + + (rows.length ? rows.map(e => '' + e.date + '' + (LD_WALLET[e.wallet] || e.wallet) + '' + + '' + (LD_KIND[e.kind] || e.kind) + (e.kind === 'cost' ? ' (' + (LD_CAT[e.category] || e.category || 'other') + ')' : '') + '' + + '' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount) + + (e.usd ? ' ($' + Number(e.usd).toFixed(2) + ')' : '') + '' + + '' + esc(e.note || '') + '' + + '').join('') + : 'Nothing recorded yet.'); + $('pnlLedger').querySelectorAll('[data-ldkill]').forEach(b => b.addEventListener('click', async () => { + if (!await IAP.confirmBox('Remove this ledger line?')) return; + try { await api('/api/admin/ledger/delete', { id: b.dataset.ldkill }); loadPnl(); } + catch (e) { IAP.status('Could not remove it: ' + e.message, 'bad'); } + })); + } + if ($('pnlRecon')) { + const drift = Number(rec.drift || 0); + const ok = Math.abs(drift) < 0.01; + $('pnlRecon').innerHTML = 'Receiver A earned ' + pol4(rec.earnedPol) + ' POL on chain' + + (t.revenuePol ? ' plus ' + pol4(t.revenuePol) + ' outside revenue' : '') + + (t.drawPol ? ', less ' + pol4(t.drawPol) + ' drawn' : '') + + (t.transferPol ? ', ' + (t.transferPol > 0 ? 'plus ' : 'less ') + '' + pol4(Math.abs(t.transferPol)) + ' transferred in for storage' : '') + + '. Expected ' + pol4(rec.expected) + ', actually holding ' + pol4(rec.actual) + '. ' + + (ok ? 'Reconciled.' + : 'Unexplained: ' + pol4(drift) + ' POL ' + + '(' + (drift > 0 ? 'more on hand than accounted for, so income or a transfer in is missing a line' + : 'less on hand than accounted for, so a draw is missing a line') + ')'); + } + } + if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => { + const body = { dir: $('ldDir').value, kind: $('ldKind').value, category: $('ldCat') ? $('ldCat').value : '', wallet: $('ldWallet').value, + amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0, + date: $('ldDate').value, note: $('ldNote').value }; + try { + await api('/api/admin/ledger', body); + $('ldAmount').value = ''; $('ldUsd').value = ''; $('ldNote').value = ''; + IAP.status('Line added.', 'good'); loadPnl(); + } catch (e) { IAP.status(e.message, 'bad'); } + }); + // a draw is almost never revenue and an outside deposit almost never a draw: move the kind with + // the direction, but leave it editable + if ($('ldDir')) $('ldDir').addEventListener('change', () => { + $('ldKind').value = $('ldDir').value === 'in' ? 'revenue' : 'draw'; + }); + 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; + try { + $('audSub').textContent = 'checking…'; + const a = await api('/api/admin/audit'); + const bad = a.checks.filter(c => !c.ok).length; + $('audSub').textContent = (bad ? bad + ' issue' + (bad === 1 ? '' : 's') : 'all counters reconcile') + ' · checked ' + new Date(a.checkedAt).toLocaleTimeString(); + $('audTable').innerHTML = 'CheckStatusDetail' + a.checks.map(c => '' + esc(c.name) + '' + (c.ok ? 'ok' : '' + c.issues.length + ' issue' + (c.issues.length === 1 ? '' : 's') + '') + '' + esc(c.detail) + (c.issues.length ? '
' + c.issues.map(esc).join('
') : '') + '').join(''); + } catch (e) { $('audSub').textContent = e.message; } + } + if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit)); + // ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ── + const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' }; + const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' }; + const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : ''; + const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '$1'); + let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = []; + async function supportBadge() { + try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; } + } + async function loadSupport(q) { + const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1]; + if (ref) return openTicket(ref); + $('spView').hidden = true; $('spList').hidden = false; + const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString(); + const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]); + spTemplates = tp.templates || []; spCats = r.categories || spCats; + const c = r.counts || {}; + $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || ''); + $('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread'; + const chip = (v, label, n) => ''; + $('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All'); + if (!$('spCategory').options.length) $('spCategory').innerHTML = '' + spCats.map(x => '').join(''); + $('spTable').innerHTML = 'TicketSubjectFromCategoryStatusLast activity' + + (r.tickets.length ? r.tickets.map(t => '' + (t.adminUnread ? '● ' : '') + esc(t.ref) + + (t.platform !== 'iap' ? ' ' + esc(t.platform) + '' : '') + (t.priority === 'high' ? ' high' : '') + '' + + '' + (t.adminUnread ? '' + esc(t.subject) + '' : esc(t.subject)) + '
' + esc(t.source) + '
' + + '' + esc(t.name || '') + '
' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '
' + + '' + esc(t.category) + '' + esc(SP_STATUS[t.status] || t.status) + '' + esc(ctWhen(t.updated)) + '').join('') + : 'No tickets here.'); + drawTemplates(); + } + $('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + $('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + $('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); }); + $('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } }); + async function openTicket(ref) { + const v = await api('/api/admin/support/' + encodeURIComponent(ref)); + if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} } + if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other']; + drawTicket(v); supportBadge(); + } + function drawTicket(v) { + const t = v.ticket, rq = v.requester || {}; + $('spList').hidden = true; $('spView').hidden = false; + const sel = (id, opts, cur) => ''; + const stOpts = Object.entries(SP_STATUS); + $('spView').innerHTML = '

‹ All tickets

' + + '

' + esc(t.subject) + '

' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + '
' + + '
' + + '' + + '
' + + '

Requester

' + (rq.member ? 'member account' : 'no account with this email') + '
' + + kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [ + ['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' · open member card'], + ['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '' + esc(v.link) + '']])) + + '
' + + '

Thread

' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + '
' + + v.messages.map(m => '
' + + '
' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '' + esc(ctWhen(m.created)) + '
' + + '
' + spLink(m.body) + '
' + + (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '

' : '') + + (m.bodyEn ? '
🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)\n' + spLink(m.bodyEn) + '
' : '') + + ((m.attachments || []).length ? '
' + m.attachments.map(a => 'attachment').join('') + '
' : '') + '
').join('') + + '
' + + '

Reply

emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '
' + + '

' + + '' + + '

' + + '' + + '

'; + $('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20) + const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return; + const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal); + const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body); + await setPane('kb'); window.IAPKB.compose(draft); + })); + $('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } }; + $('spSt').addEventListener('change', () => patch({ status: $('spSt').value })); + $('spPr').addEventListener('change', () => patch({ priority: $('spPr').value })); + $('spCat').addEventListener('change', () => patch({ category: $('spCat').value })); + if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); }); + $('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; }); + $('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; }); + $('spSend').addEventListener('click', busy($('spSend'), async () => { + const internal = $('spInternal').checked; + if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return; + drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value })); + supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok'); + })); + } + function drawTemplates() { + $('spTpls').innerHTML = spTemplates.map((x, i) => '
' + + '
').join('') || '

No saved replies. Add one below.

'; + } + const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value })); + $('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); }); + $('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); }); + $('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); })); + + async function loadReports() { + loadAudit(); + const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]); + const reps = r.reports || []; + $('repTable').innerHTML = reps.length ? 'WhenCampaignReasonNoteBy' + + reps.map(x => '' + when(x.ts) + '#' + x.campaignId + '' + esc(x.reason) + '' + esc(x.note || '') + '' + esc(x.reporter || 'anon') + '' + + '' + (x.resolved ? 'resolved' : '') + '').join('') + : 'No reports.'; + const burns = b.pending || []; + $('burnTable').innerHTML = burns.length ? 'WhenMemberCreditsRefBurn id' + + burns.map(x => '' + when(x.ts) + '#' + x.memberId + '' + x.amount + '' + esc(x.ref) + '' + esc(x.id) + '').join('') + : 'Nothing pending.'; + } + document.addEventListener('click', async e => { + const b = e.target.closest('[data-resolve]'); if (!b) return; + b.disabled = true; + try { await api('/api/admin/reports/' + b.dataset.resolve + '/resolve', {}); IAP.status('Report resolved.', 'ok'); await Promise.all([loadReports(), loadOverview()]); } + catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } + }); + + // ── settings: graphical editors (follow-up emails, rates, site settings) ── + let dripSeq = [], ratesObj = {}, siteObj = {}; + let lastFocusedField = null; + document.addEventListener('focusin', e => { if (e.target && (e.target.matches('textarea.ds-body') || e.target.matches('input.ds-subject'))) lastFocusedField = e.target; }); + document.addEventListener('click', e => { + const c = e.target.closest('[data-ph]'); if (!c) return; + const el = lastFocusedField; if (!el) { IAP.status('Click into a subject or body first, then the chip.', 'bad'); return; } + const ph = c.dataset.ph, st = el.selectionStart || 0, en = el.selectionEnd || st; + el.value = el.value.slice(0, st) + ph + el.value.slice(en); + el.focus(); el.selectionStart = el.selectionEnd = st + ph.length; + el.dispatchEvent(new Event('input')); + }); + const whenLabel = h => { h = Number(h) || 0; if (h < 24) return h + ' hour' + (h === 1 ? '' : 's') + ' after sign-up'; const d = h / 24; return (Number.isInteger(d) ? d : d.toFixed(1)) + ' day' + (d === 1 ? '' : 's') + ' after sign-up'; }; + function drawDrip() { + const wrap = $('dripSteps'); + wrap.innerHTML = dripSeq.map((st, i) => '
' + + '
EMAIL ' + (i + 1) + '' + + 'send hours after sign-up (' + esc(whenLabel(st.hours)) + ')' + + '' + + '
' + + '' + + '' + + '
').join('') || '

No emails yet. Add one below.

'; + } + function readDrip() { + return [...document.querySelectorAll('#dripSteps .drip-step')].map(card => ({ + hours: Number(card.querySelector('.ds-hours').value) || 0, + subject: card.querySelector('.ds-subject').value.trim(), + body: card.querySelector('.ds-body').value.trim() + })); + } + $('dripSteps').addEventListener('input', e => { + if (e.target.classList.contains('ds-hours')) { const l = e.target.closest('.ds-when').querySelector('.ds-whenlbl'); if (l) l.textContent = '(' + whenLabel(e.target.value) + ')'; } + }); + $('dripSteps').addEventListener('click', async e => { + const b = e.target.closest('[data-act]'); if (!b) return; + const card = b.closest('.drip-step'), i = Number(card.dataset.i); + dripSeq = readDrip(); + if (b.dataset.act === 'remove') { if (!await IAP.confirmBox('Remove email ' + (i + 1) + ' from the sequence?', { title: 'Remove step', ok: 'Remove', cancel: 'Keep' })) return; dripSeq.splice(i, 1); drawDrip(); return; } + if (b.dataset.act === 'up' && i > 0) { [dripSeq[i - 1], dripSeq[i]] = [dripSeq[i], dripSeq[i - 1]]; drawDrip(); return; } + if (b.dataset.act === 'down' && i < dripSeq.length - 1) { [dripSeq[i + 1], dripSeq[i]] = [dripSeq[i], dripSeq[i + 1]]; drawDrip(); return; } + if (b.dataset.act === 'test') { + b.disabled = true; + try { await saveDrip(); await api('/api/admin/drip/test', { step: i }); IAP.status('Email ' + (i + 1) + ' sent to your inbox.', 'ok'); } + catch (err) { IAP.status(err.message, 'bad'); } + b.disabled = false; + } + }); + async function saveDrip() { + $('dripErr').hidden = true; + const seq = readDrip(); + const r = await api('/api/admin/drip', { sequence: seq }, 'PATCH').catch(err => { $('dripErr').textContent = err.message; $('dripErr').hidden = false; throw err; }); + dripSeq = r.sequence; drawDrip(); + return r; + } + $('dripSave').addEventListener('click', busy($('dripSave'), async () => { await saveDrip(); IAP.status('Sequence saved.', 'ok'); await loadSettings(); })); + $('dripAdd').addEventListener('click', () => { + dripSeq = readDrip(); + const last = dripSeq[dripSeq.length - 1]; + dripSeq.push({ hours: last ? Number(last.hours) + 48 : 24, subject: '', body: '\n\nMarty\n\n{{footer}}' }); + drawDrip(); + const cards = document.querySelectorAll('#dripSteps .drip-step'); const c = cards[cards.length - 1]; if (c) { c.scrollIntoView({ behavior: 'smooth', block: 'center' }); c.querySelector('.ds-subject').focus(); } + }); + $('dripReset').addEventListener('click', busy($('dripReset'), async () => { + if (!await IAP.confirmBox('Replace the saved sequence with the built-in defaults?', { title: 'Reset sequence', ok: 'Replace', cancel: 'Cancel' })) return; + const r = await api('/api/admin/drip', { reset: true }, 'PATCH'); + dripSeq = r.sequence; drawDrip(); IAP.status('Defaults restored.', 'ok'); await loadSettings(); + })); + + // rates: labels + hints for the known keys; anything unknown still gets a plain field + const RATE_META = { + bannerBatch: ['Banner: views per batch', 'impressions counted before a banner campaign is charged'], + bannerCreditsPerBatch: ['Banner: credits per batch', 'charged to the advertiser per batch'], + textBatch: ['Text ad: views per batch', ''], textCreditsPerBatch: ['Text ad: credits per batch', ''], + loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'], + loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'], + burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'], + welcomeCredits: ['Welcome credits', 'granted after the welcome tour'], + dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'], + dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'], + viewDwellSeconds: ['Ad view: seconds per ad', 'the countdown; server-enforced'], + soloCostPerRecipient: ['Solo ad: credits per recipient', ''], soloMinRecipients: ['Solo ad: minimum recipients', ''], + soloReadCredits: ['Solo ad: reader reward (credits)', ''], soloReadCapPerDay: ['Solo ad: rewarded reads per day', ''], soloReadDwellSeconds: ['Solo ad: seconds to read', ''], + videoWatchCapPerDay: ['Video: rewarded watches per day', ''], + featuredPerDay: ['Featured link: credits per day', ''], featuredSlotsPerDay: ['Featured link: slots per day', ''], featuredWindowDays: ['Featured link: booking window (days)', ''], + featuredDurations: ['Featured link: durations offered (days)', 'comma-separated'], + doorPackCost: ['Spooky Doors: door pack, credits per door', 'placement "Behind Spooky Doors"'], goldenDoorCost: ['Spooky Doors: Golden Door, credits per door', 'placement "Golden Spooky Door"'], + goldenBonusCandy: ['Spooky Doors: Golden Door bonus candy', 'sent to the game as bonus'], sdSeasonEnd: ['Spooky Doors: season end (Central day, exclusive)', 'from this day door packs run as normal visits (YYYY-MM-DD)'], + visitCostPerVisit: ['Verified visit: credits per visit', ''], visitMinPack: ['Verified visit: smallest pack', ''], visitReward: ['Verified visit: viewer reward (credits)', ''], visitDwellSeconds: ['Verified visit: seconds on site', ''], visitCapPerDay: ['Verified visit: rewarded visits per day', ''], + videoTiers: ['Video ad tiers', 'watch length → advertiser cost → viewer reward'], + milestoneBonus: ['Milestone bonuses (credits)', 'one-time, when a member reaches each step'] + }; + const humanize = k => k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase()); + function drawRates() { + const wrap = $('ratesForm'); const html = []; + for (const [k, v] of Object.entries(ratesObj)) { + const [label, hint] = RATE_META[k] || [humanize(k), '']; + if (typeof v === 'number') html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
'); + else if (typeof v === 'boolean') html.push('
'); + else if (Array.isArray(v) && v.every(x => typeof x === 'number')) html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
'); + else if (Array.isArray(v) && v.every(x => x && typeof x === 'object')) { + const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; const txt = new Set(cols.filter(c => v.some(x => typeof x[c] === 'string'))); // text columns (doorHouseAds) stay text + html.push('
' + (hint ? '' + esc(hint) + '' : '') + + '' + cols.map(c => '').join('') + '' + + v.map((row, i) => '' + cols.map(c => '').join('') + '').join('') + '
' + esc(c) + '
'); + } else if (v && typeof v === 'object') { + html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
' + + Object.entries(v).map(([sk, sv]) => '').join('') + '
'); + } else html.push('
'); + } + wrap.innerHTML = html.join(''); + } + function readRates() { + const out = {}; + document.querySelectorAll('#ratesForm [data-rk]').forEach(el => { + const k = el.dataset.rk, kind = el.dataset.kind; + if (kind === 'numlist') out[k] = el.value.split(/[\s,]+/).filter(Boolean).map(Number).filter(n => !isNaN(n)); + else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = i.dataset.str ? i.value.trim() : Number(i.value); }); return o; }); + else if (kind === 'object') { const o = {}; el.querySelectorAll('input[data-sub]').forEach(i => { o[i.dataset.sub] = Number(i.value); }); out[k] = o; } + else if (el.type === 'checkbox') out[k] = !!el.checked; + else if (el.type === 'number') out[k] = Number(el.value); + else out[k] = el.value; + }); + return out; + } + $('ratesSave').addEventListener('click', busy($('ratesSave'), async () => { + $('ratesErr').hidden = true; + try { const r = await api('/api/admin/rates', readRates(), 'PATCH'); ratesObj = r.rates || readRates(); drawRates(); IAP.status('Rates saved.', 'ok'); } + catch (e) { $('ratesErr').textContent = e.message; $('ratesErr').hidden = false; } + })); + + // site settings: key / value rows; booleans as checkboxes, numbers stay numbers + const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' }; + function drawSite() { + const wrap = $('siteForm'); + wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '
' + esc(SITE_META[k] || humanize(k)) + '' + + (typeof v === 'boolean' ? '' + : typeof v === 'number' ? '' + : '') + + '
').join('') || '

No settings saved yet.

'; + } + function readSite() { + const out = {}; + document.querySelectorAll('#siteForm [data-sk]').forEach(el => { + const k = el.dataset.sk; + if (el.type === 'checkbox') out[k] = !!el.checked; + else if (el.type === 'number') out[k] = Number(el.value); + else { const v = el.value; if (/^[\[{]/.test(v)) { try { out[k] = JSON.parse(v); return; } catch (e) {} } out[k] = v; } + }); + return out; + } + $('siteForm').addEventListener('click', e => { + const b = e.target.closest('[data-sdel]'); if (!b) return; + siteObj = readSite(); siteObj[b.dataset.sdel] = ''; drawSite(); + }); + $('siteAddKey').addEventListener('click', () => { + const k = $('siteNewKey').value.trim(); if (!/^[A-Za-z][A-Za-z0-9_]{0,40}$/.test(k)) { IAP.status('Setting names are letters and numbers, no spaces.', 'bad'); return; } + siteObj = readSite(); if (!(k in siteObj)) siteObj[k] = ''; $('siteNewKey').value = ''; drawSite(); + const el = document.querySelector('#siteForm [data-sk="' + k + '"]'); if (el) el.focus(); + }); + $('siteSave').addEventListener('click', busy($('siteSave'), async () => { + $('siteErr').hidden = true; + try { const r = await api('/api/admin/site', readSite(), 'PATCH'); siteObj = r.site || readSite(); drawSite(); IAP.status('Site settings saved.', 'ok'); } + catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; } + })); + + // ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ---- + async function loadGamePass() { + const r = await api('/api/admin/gamepass/stats'); + const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2); + const tile = (v, lb, cls, sub) => '
' + v + '
' + lb + '
' + (sub ? '' + sub + '' : '') + '
'; + const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {}; + $('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only') + + tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time') + + tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package') + + tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet')) + + tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants') + + tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total') + + tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total') + + tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members'); + $('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : ''; + const would = (r.capHits && r.capHits.would) || {}; + $('gpWeek').innerHTML = '' + + '' + + '' + + '' + + (S.enforced ? '' : '') + + '' + + '
Carried forward (deferred progress paid on a later day)' + pol(W.carried) + ' POL
Dropped (daily play over the daily cap)' + pol(W.dropped) + ' POL
Deferred out (progress over the total cap, pays later)' + pol(W.deferredOut) + ' POL
Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits.
Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)' + S.price + ' credits · ' + S.days + ' days
' + + (Q.byGame && Object.keys(Q.byGame).length ? '

By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '

' : ''); + // per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month + const TS = r.tiers || {}, TC = S.tiers || {}; + $('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales'; + $('gpTiers').innerHTML = '' + + (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return ''; }).join('') + + '
TierPriceActiveSold weekSold monthAll timeRenewals 30dEnding in 7 daysCompedWaiting
' + esc(x.name || k) + (c.sale ? '' : '
not on sale') + '
' + (c.price || 0) + ' cr
' + (c.days || 0) + ' d
' + (x.active || 0) + '' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '' + (x.renewals30d || 0) + '' + (x.expiring7d || 0) + '' + (x.comped || 0) + '' + (x.waitingOrders || 0) + '

Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).

'; + // pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled) + const PM = P.pay || {}, SL = r.sales || []; + $('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')' + + ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')'; + const txLink = h => h ? '' + esc(String(h).slice(0, 10)) + '…' : ''; + $('gpSales').innerHTML = !SL.length ? '

No pass sold yet.

' : '' + + SL.map(x => '').join('') + + '
WhenMemberPassPaid byPassPackagePackage tx
' + when(x.ts) + '' + esc(x.email) + '' + esc(x.name || x.tier) + '' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + '' + usd(x.usd) + '' + (x.packageUsd ? usd(x.packageUsd) : '') + '' + txLink(x.tx) + '
'; + $('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid'; + const L = T.last; + $('gpTour').innerHTML = !L ? '

No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).

' + : '

' + esc(L.label) + ': ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '

' + + (L.winners && L.winners.length ? '' + L.winners.map(w => '').join('') + '
#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '' + w.score + ' plays' + pol(w.pol) + ' POL' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '
' : '

No pass holder reported any plays that week.

') + + ((T.history || []).length > 1 ? '

Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '

' : ''); + } + $('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); })); + $('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); })); + $('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => { + const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; } + if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return; + const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass(); + })); + + async function loadSettings() { + const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]); + ratesObj = r.rates || {}; drawRates(); + siteObj = s.site || {}; drawSite(); + dripSeq = d.sequence || []; drawDrip(); + const st = d.stats || {}; + $('dripSub').textContent = (st.active || 0) + ' in flight · ' + (st.done || 0) + ' finished · ' + (st.unsubscribed || 0) + ' unsubscribed' + (d.mailReady ? '' : ' · NO MAIL KEY: nothing sends'); + } + + render(); +})(); +// ---- tax summary (2026-10-04) + the cost category picker +(function () { + const $ = id => document.getElementById(id); + if ($('ldKind') && $('ldCat')) { const sync = () => { $('ldCat').hidden = $('ldKind').value !== 'cost'; }; $('ldKind').addEventListener('change', sync); sync(); } + if (!$('taxYear')) return; + const y = new Date().getFullYear(); for (let v = y; v >= 2025; v--) { const o = document.createElement('option'); o.value = v; o.textContent = v; $('taxYear').appendChild(o); } + const money = n => '$' + Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + $('taxRun').addEventListener('click', async () => { + $('taxOut').textContent = 'Working it out...'; + try { + const r = await (await fetch('/api/admin/tax?year=' + $('taxYear').value, { credentials: 'same-origin' })).json(); + if (r.error) throw new Error(r.error); + const cats = Object.entries(r.expenses.byCategory || {}).map(([k, v]) => '' + (r.expenses.labels[k] || k) + '' + money(v) + '').join(''); + $('taxOut').innerHTML = '' + + '' + + (r.income.outsideUsd ? '' : '') + + '' + + (cats || '') + + '' + + '' + + '
' + r.year + '
Income: platform share of ' + r.income.sales + ' package sales' + money(r.income.platformUsd) + '
Outside revenue' + money(r.income.outsideUsd) + '
Total income' + money(r.income.totalUsd) + '
No costs recorded yet
Advertising and promotion (advertising + game marketing + player rewards)' + money(r.expenses.advertisingAndPromotionUsd) + '
Total costs' + money(r.expenses.totalUsd) + '
Net' + money(r.netUsd) + '
' + + '

Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).

'; + $('taxCsvText').value = r.csv; $('taxCsv').hidden = false; + } catch (e) { $('taxOut').textContent = 'Could not build the summary: ' + e.message; } + }); + $('taxCsv').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('taxCsvText').value); IAP.status('CSV copied. Paste it into a spreadsheet.', 'good'); } + catch (e) { $('taxCsvText').hidden = false; $('taxCsvText').select(); IAP.status('Selected. Copy it with your keyboard.', 'good'); } + }); +})(); diff --git a/public/assets/common.js b/public/assets/common.js index 49389d3..13eaa91 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'; @@ -284,3 +284,14 @@ window.IAP = (function () { if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; } }, true); })(); +// Level 4 override copy (2026-10-23): blocks marked data-when="override-live" stay hidden until the site setting +// overrideMode is 'live' and overrideGoLive is set; [data-ov-start] gets the start date in Central time +(function () { + var els = document.querySelectorAll('[data-when="override-live"]'); if (!els.length || !window.IAP) return; + IAP.getConfig().then(function (c) { + if (String(c.overrideMode || '') !== 'live' || !Number(c.overrideGoLive)) return; + var d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' }); + document.querySelectorAll('[data-ov-start]').forEach(function (e) { e.textContent = d; }); + els.forEach(function (e) { e.hidden = false; }); + }).catch(function () {}); +})(); diff --git a/public/assets/my.js b/public/assets/my.js index 4421d2e..99f9fac 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -1,3523 +1,3523 @@ -// member share links go out on the share domain (2026-10-20): https://ctbgo.com/ -> /join/ on InstantAdPay. -// The domain comes from site config (shareDomain); empty falls back to this site's own /join link. -let SHARE_DOMAIN = ''; -const SHARE_READY = fetch('/api/config').then(r => r.json()).then(c => { SHARE_DOMAIN = String((c && c.shareDomain) || '').trim(); }).catch(() => {}); -function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(String(ref)) ? 'https://' + SHARE_DOMAIN + '/' + ref : location.origin + '/join/' + ref; } -// My account: email-first join/login, wallet link at purchase time, -// free payout activation, invite link, on-chain activity. -(async function () { - // back-office shell: no marketing nav here; rehearsal notice lives in the top bar - const $ = IAP.$; - // dwell timers pause when the tab is away; a focused ad frame or a touch device counts as active (phones never report hasFocus reliably) - const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches)); - try { - const c = await IAP.getConfig(); - if (c.rehearsal && $('boRehearsal')) { - $('boRehearsal').hidden = false; - $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; - } - if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; - } catch (e) {} - // if they arrived through a sponsor's link, show who they're joining under - (async () => { - try { - const sp = await (await fetch('/api/sponsor?intent=view')).json(); // display only: never an alert - if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } - } catch (e) {} - })(); - - async function api(path, body) { - const r = await (await fetch(path, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); - if (r.error) { const e = new Error(r.error); e.data = r; throw e; } // e.data: the full answer (e.g. top-up switch options) - return r; - } - - function nextMove(d) { - if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; - if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; - if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.'; - if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $20+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; - if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; - return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; - } - // featured rotation strip on the overview - let featItems = [], featIdx = 0, featTimer = null; - function renderOneFeatured() { - if (!featItems.length) return; - const i = featItems[featIdx % featItems.length]; - $('featStrip').innerHTML = '' + esc(i.title) + '' - + (i.by ? '' + esc(i.by) + '' : '') + ''; - } - async function loadFeatured() { - try { - const r = await (await fetch('/api/featured')).json(); - const card = $('featuredCard'); if (!card) return; - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); - $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; - renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one - clearInterval(featTimer); - if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); - // self-sell: today's open slots + a CTA to feature your own link - try { - const st = await (await fetch('/api/featured/stats')).json(); - const today = (st.occupancy || []).find(d => d.offset === 0); - const cta = $('featCta'); - if (cta) { - cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') - + 'Feature your link →'; - const fb = $('featBuy'); - if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); - } - } catch (e) {} - } catch (e) {} - } - - // achievement badges: the milestone ladder as unlockable medals + share-to-image - const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) - { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, - { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, - { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, - { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 }, - { key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }, - { key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 } - ]; - let lastMilestones = []; - function renderBadges(d) { - const reached = d.milestonesReached || []; - lastMilestones = reached; - const strip = $('badgeStrip'); - if (!strip) return; - $('badgeCard').hidden = false; - strip.innerHTML = BADGES.map(b => { - const got = reached.includes(b.key); - return '
' - + '' + b.label + ' badge' - + '
' + b.label + '
' + b.sub + '
' - + (got ? ' ' : '
🔒 locked
') + '
'; - }).join(''); - strip.querySelectorAll('[data-badge]').forEach(btn => - btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); - strip.querySelectorAll('[data-badgepost]').forEach(btn => - btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); - fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) - if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); - (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); - }).catch(() => {}); - // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) - if (d.milestonesGranted && d.milestonesGranted.length) { - const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); - const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); - IAP.status('🏆 Achievement unlocked: ' + names + (total > 0 ? ': +' + total + ' bonus credits!' : '! See it in your badges.'), 'ok'); - d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); - } - } - // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) - function composeBadge(key, d, cb) { - const b = BADGES.find(x => x.key === key); if (!b) return cb(null); - const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; - const img = new Image(); - img.onload = () => { - const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; - const x = c.getContext('2d'); - x.drawImage(img, 0, 0); - if (who) { - x.textAlign = 'center'; x.textBaseline = 'middle'; - x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; - const y = c.height * (b.ribbonY || 0.75); - x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); - x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); - x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); - } - cb(c); - }; - img.onerror = () => cb(null); - img.src = b.img; - } - async function postBadge(key, d, btn, manual) { - if (btn && btn.disabled) return; - if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } - composeBadge(key, d, c => { - if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } - c.toBlob(async bl => { - try { - const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); - if (r.error) throw new Error(r.error); - if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } - if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); - } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } - }, 'image/jpeg', 0.86); - }); - } - // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at - // /b// carries it as the preview image; every network gets that link. - function shareBadge(key, d) { - const b = BADGES.find(x => x.key === key); if (!b) return; - if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } - IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); - composeBadge(key, d, c => { - if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } - c.toBlob(async bl => { - let page = null; - try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } - catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } - openShareSheet(b, d, bl, page); - }, 'image/jpeg', 0.9); - }); - } - function openShareSheet(b, d, blob, page) { - const text = 'I just unlocked the ' + b.label + ' badge on InstantAdPay (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; - const enc = encodeURIComponent; - const links = [ - ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], - ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], - ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], - ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], - ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] - ]; - const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; - back.innerHTML = ''; - document.body.appendChild(back); - const close = () => back.remove(); - back.addEventListener('click', e => { if (e.target === back) close(); }); - back.querySelector('[data-sh="close"]').addEventListener('click', close); - back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); - back.querySelector('[data-sh="save"]').addEventListener('click', () => { - const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); - IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); - }); - // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) - back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { - try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } - catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } - window.open('https://massifly.com/account', '_blank', 'noopener'); - }); - const nat = back.querySelector('[data-sh="native"]'); - if (nat) nat.addEventListener('click', async () => { - try { - const file = new File([blob], 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); - if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); - else await navigator.share({ title: b.label + ' badge', text, url: page }); - } catch (e) {} - }); - } - - // milestone stepper under "Your next move": lit nodes for what's done, - // amber glow on the current target — the same ladder the contract pays - function renderSteps(d) { - const el = $('ncSteps'); - if (!el) return; - const b = d.buyerCount || 0; - const steps = [ - { label: 'Joined', sub: 'free account', hit: true }, - { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, - { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, - { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, - { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } - ]; - const cur = steps.findIndex(s => !s.hit); - el.innerHTML = steps.map((s, i) => - '
' - + '' + (s.hit ? '✓' : i + 1) + '' - + '' + s.label + '' + s.sub + '
').join(''); - } - // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - - // Paged lists (Marty, 2026-09-19): 25 rows, then a clearly marked next page, on every list - // that grows with the membership. Works on what is already rendered: rows past the page are - // hidden and a control bar goes under the list, so a row's buttons and bindings never change. - // key remembers the page across re-renders of the same list - // host the element the bar is appended to (a wrapper, never a ) - // rowSel the rows, queried inside host - // opts per (default 25); tail: a selector for a drawer that follows its row and pages - // with it; focus: a row predicate, opens on whichever page holds that row - const PAGE_SIZE = 25; - // My line is the longest page on the dashboard: its lists page at 10 (Marty, 2026-09-26) - const LINE_PER = 10; - // Sortable + filterable member lists (Marty, 2026-09-29): the holding tank, "Your line" and the three-level - // downline share one toolbar. Every row carries joined, last seen, surf earnings and wallet/payout state so a - // sponsor can spot "joined days ago, signed in today, earning on their own, wallet linked but payouts off". - const LIST_UI = {}; - const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; - const activeToday = m => (m.lastSeen || 0) >= dayStart(); - const LIST_SORTS = [ - { k: 'seen', label: 'Last seen', v: m => m.lastSeen || 0 }, - { k: 'joined', label: 'Joined', v: m => m.joined || 0 }, - { k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 }, - { k: 'balance', label: 'Earned balance', v: m => m.balance || 0 }, - { k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true }, - ]; - const LIST_FILTERS = [ - { k: 'today', label: 'Active today', t: m => activeToday(m) }, - { k: 'earning', label: 'Earning', t: m => (m.earned || 0) > 0 }, - { k: 'wallet', label: 'Wallet linked', t: m => !!m.wallet }, - { k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated }, - { k: 'payouts', label: 'Payouts on', t: m => !!m.activated }, - { k: 'nowallet', label: 'No wallet', t: m => !m.wallet }, - ]; - const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() }); - function listApply(key, rows) { - const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0]; - const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })); - out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; }); - return out; - } - function listBar(key, total, shown, rerender, opts) { - const st = listState(key); const hide = (opts && opts.hide) || []; - const bar = document.createElement('div'); bar.className = 'lst-bar'; - bar.innerHTML = '' - + '' - + '' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '').join('') + '' - + '' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + ''; - bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); }); - bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); }); - bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); })); - return bar; - } - const seenAgo = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' days ago'; }; - const seenChip = m => m.lastSeen ? '' + (activeToday(m) ? 'active today' : 'seen ' + seenAgo(m.lastSeen)) + '' : 'never signed in'; - const earnChip = m => '' + (m.earned || 0).toLocaleString() + ' cr earned'; - const walletChip = m => m.activated ? 'wallet · payouts on' : m.wallet ? 'wallet · payouts off' : 'no wallet'; - const memberChips = m => seenChip(m) + ' ' + earnChip(m) + ' ' + walletChip(m); - // Section pills at the top of My line: one per visible card marked data-jump, the one in view lit up. - // Cards that show or hide themselves (sponsor, upline messages) rebuild the row when they change. - let lineJumpObs = null; - function buildLineJump() { - const nav = document.getElementById('lineJump'); const pane = document.getElementById('pane-line'); if (!nav || !pane) return; - const cards = [...pane.querySelectorAll(':scope > .card[data-jump]')].filter(c => !c.hidden); - nav.innerHTML = cards.map(c => '').join(''); - nav.hidden = cards.length < 2; - const top = document.querySelector('.bo-top'); nav.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); pane.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); - nav.querySelectorAll('[data-jumpto]').forEach(b => b.addEventListener('click', () => { - const c = document.getElementById(b.dataset.jumpto); if (!c) return; - c.scrollIntoView({ behavior: 'smooth', block: 'start' }); - nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x === b)); - })); - if (lineJumpObs) lineJumpObs.disconnect(); - if ('IntersectionObserver' in window) { - const seen = new Map(); - lineJumpObs = new IntersectionObserver(ents => { - for (const e of ents) seen.set(e.target.id, e.isIntersecting ? e.boundingClientRect.top : null); - let best = null; for (const [id, t] of seen) if (t != null && (best == null || t < seen.get(best))) best = id; - if (best) { nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x.dataset.jumpto === best)); const on = nav.querySelector('.chip-t.on'); if (on && nav.scrollWidth > nav.clientWidth) nav.scrollLeft = on.offsetLeft - 16; } - }, { rootMargin: '-120px 0px -55% 0px' }); - cards.forEach(c => lineJumpObs.observe(c)); - } - } - { const pane = document.getElementById('pane-line'); - if (pane && 'MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(pane, { subtree: false, childList: false, attributes: true, attributeFilter: ['hidden'] }); - if (pane) pane.querySelectorAll(':scope > .card[data-jump]').forEach(c => { if ('MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(c, { attributes: true, attributeFilter: ['hidden'] }); }); } - const PAGE_AT = {}; - function pageList(key, host, rowSel, opts) { - if (!host) return; opts = opts || {}; const per = opts.per || PAGE_SIZE; - const rows = [...host.querySelectorAll(rowSel)]; - const old = host.querySelector(':scope > .pgr'); if (old) old.remove(); - if (rows.length <= per) { rows.forEach(r => { r.hidden = false; }); return; } - const pages = Math.ceil(rows.length / per); - let p = PAGE_AT[key] || 1; - if (opts.focus) { const i = rows.findIndex(opts.focus); if (i >= 0) p = Math.floor(i / per) + 1; } - p = Math.min(Math.max(1, p), pages); PAGE_AT[key] = p; - const start = (p - 1) * per; - rows.forEach((r, i) => { - const on = i >= start && i < start + per; r.hidden = !on; - if (opts.tail) { const t = r.nextElementSibling; if (t && t.matches(opts.tail) && !on && !t.hidden) { t.hidden = true; const b = r.querySelector('[aria-expanded]'); if (b) { b.setAttribute('aria-expanded', 'false'); b.textContent = 'Activity \u25BE'; } } } - }); - const bar = document.createElement('div'); bar.className = 'pgr'; - bar.innerHTML = 'Showing ' + (start + 1) + '\u2013' + Math.min(start + per, rows.length) + ' of ' + rows.length + '' - + '' - + 'Page ' + p + ' of ' + pages + '' - + ''; - bar.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => { - PAGE_AT[key] = Number(b.dataset.go); - pageList(key, host, rowSel, Object.assign({}, opts, { focus: null })); - host.scrollIntoView({ behavior: 'smooth', block: 'start' }); - })); - host.appendChild(bar); - } - const CH = { mint: '#43e8c3', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; - function bars(el, xel, data) { // data: [{v,label,tip,alt}] - if (!el) return; - const max = Math.max(1, ...data.map(d => d.v)); - el.innerHTML = data.length - ? data.map(d => '
').join('') - : '
'.repeat(8); - if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); - } - function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 - if (!el) return; - const total = segs.reduce((s, x) => s + x.v, 0); - let off = 25, out = ''; - if (total > 0) for (const s of segs) { - const len = s.v / total * 100; - if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } - out += ''; - off -= len; - } - out += '' + esc(center.big) + '' - + '' + esc(center.small) + ''; - el.innerHTML = out; - } - function legend(el, rows) { - if (el) el.innerHTML = rows.map(r => '
' - + esc(r.label) + ' ' + esc(r.v) + '
').join(''); - } - async function loadCharts(d) { - // credit composition donut + today's viewing ring (live balances) - try { - const st = await (await fetch('/api/my/earn')).json(); - if (!st.error) { - // one rule: a balance is what is NOT committed to a live campaign. Budgets are - // set aside when a campaign starts and spend down inside Campaigns, so these - // numbers only move when a campaign is created, topped up or paused - const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; - $('dbCredits').textContent = (purchased + earned).toLocaleString(); - // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) - if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; - $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (d.earnedReserved ? ' (+' + d.earnedReserved.toLocaleString() + ' earned and bonus credits working in your live campaigns)' : '') + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); - donut($('chDonut'), - [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], - { big: (purchased + earned).toLocaleString(), small: 'available' }); - legend($('chDonutLegend'), [ - { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, - { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, - { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); - const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); - donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], - { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); - legend($('chRingLegend'), [ - { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, - { color: CH.track, label: 'To go', v: left }, - { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); - } - } catch (e) {} - // recent on-chain payouts, sized to scale, oldest→newest - try { - let evs = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); - } - bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ - v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, - label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1), - tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); - if (!evs.length) $('chEarnSub').textContent = d.memberId - ? 'no payouts yet — share your link' : 'activate a package to start earning'; - } catch (e) {} - // campaign delivery: impressions per campaign - try { - const r = await (await fetch('/api/my/campaigns')).json(); - const cs = (r.campaigns || []).slice(0, 8); - bars($('chCampBars'), $('chCampX'), cs.map(c => ({ - v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), - tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', - alt: c.type === 'text' }))); - if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; - } catch (e) {} - } - // ── live updates: subscribe to the chain event stream so the members area - // reacts to on-chain changes (payouts, qualifications) without a refresh ── - let MYID = 0; - // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. - function playSound(kind) { - try { - const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; - const ctx = window.__iapAC || (window.__iapAC = new AC()); - if (ctx.state === 'suspended') ctx.resume(); - const now = ctx.currentTime; - const tone = (freq, at, dur, type, peak) => { - const o = ctx.createOscillator(), g = ctx.createGain(); - o.type = type || 'sine'; o.frequency.value = freq; - g.gain.setValueAtTime(0.0001, now + at); - g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); - g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); - o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); - }; - if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } - else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } - } catch (e) {} - } - function startLiveFeed() { - if (window.__iapFeed || !window.EventSource) return; - try { - const es = new EventSource('/api/feed/live'); - window.__iapFeed = es; - es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; - // browser auto-reconnects on error; nothing to do - } catch (e) {} - } - let liveRefreshT = null; - function liveRefresh() { // debounce a burst of events into one refresh - clearTimeout(liveRefreshT); - liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); - } - // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, - // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so - // they never replace a personal one. At most one every 4 s; a burst shows the latest. - let liveT = 0, liveQ = null; - function communityToast(msg) { - const now = Date.now(); - if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } - liveT = now; - let el = document.getElementById('liveToast'); - if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } - el.textContent = msg; el.hidden = false; el.style.opacity = '1'; - clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); - } - function handleLiveEvent(ev) { - if (!ev || !ev.type) return; - const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; - // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications - if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } - if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } - if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } - if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } - if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } - const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); - if (!mine) { - if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); - else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); - else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); - else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); - return; - } - if (!MYID) return; - let toast = null, kind = 'ok'; - let sound = null; - if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; - else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } - else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; - else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; - if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } - } - - // training center: videos + materials (admin-curated via data/training.json) - async function loadTraining() { - try { - const r = await (await fetch('/api/training')).json(); - const el = $('trainingList'); if (!el) return; - const items = r.items || []; - if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } - // section pills at the top: one per group, plus All; the active pill filters the list - const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; - const pills = $('trainingPills'); - const want = loadTraining.filter || 'all'; - if (pills) { - pills.hidden = groups.length < 2; - pills.innerHTML = ['all', ...groups].map(g => '').join(''); - pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); - } - const shown = want === 'all' ? items : items.filter(it => it.group === want); - let lastGroup = null; - el.innerHTML = shown.map(it => { - // optional section header: entries carry a `group`; a header renders when it changes - let head = ''; - if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } - const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); - // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) - const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); - const media = isVid ? '' : ''; - const links = []; - if (it.videoUrl && !isVid) links.push('Watch'); - if (it.docUrl) links.push('' + esc(it.docLabel || 'Open material') + ''); - return head + '

' + esc(it.title || 'Lesson') + '

' - + (it.desc ? '

' + esc(it.desc) + '

' : '') - + (media ? '

' + media + '

' : '') - + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; - }).join(''); - } catch (e) {} - } - // visual line tree on the Overview: YOU + three levels, qualified directs in gold - function renderRoster(wrap, all) { - const rows = listApply('roster', all); - wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove()); - wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all))); - if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '

Nobody in your line matches those filters.

'); return; } - const t = document.createElement('table'); t.className = 'roster'; - t.innerHTML = rows.map(r => '' - + '' - + '' - + '').join(''); - wrap.appendChild(t); - pageList('roster', wrap, 'table.roster tr', { per: LINE_PER }); - } - async function loadLineTree(buyerCount) { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineTree'); if (!el) return; - const levels = r.levels || []; - const total = levels.reduce((n, L) => n + L.members.length, 0); - if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; - const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; - const rowFor = lvl => { - const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; - // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") - let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy - if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; - if (!html) html = '+ open'; - return '
L' + lvl + '
' + html + '
'; - }; - el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); - // click a chip to drill down: My line opens with that person's Activity panel expanded (Marty, 2026-09-15) - const go = ref => { LINE_FOCUS_REF = ref; setPane('line'); }; - el.querySelectorAll('[data-goref]').forEach(n => { - n.addEventListener('click', () => go(n.dataset.goref)); - n.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(n.dataset.goref); } }); - }); - } catch (e) {} - } - let LINE_FOCUS_REF = null; // set by an Overview chip click; consumed once My line has rendered - // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) - let newsLoaded = false; - async function loadNews() { - if (newsLoaded || !$('newsCard')) return; newsLoaded = true; - try { - const r = await (await fetch('/api/releases')).json(); - if (!r.notes.length && !r.roadmap.length) return; - let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); - const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); - $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; - $('newsCard').hidden = false; - $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); - } catch (e) {} - } - // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) - async function loadLeaderboard() { - if (!$('lbCard')) return; - try { - const r = await (await fetch('/api/leaderboard?period=week')).json(); - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; - h += r.top.length ? '
' + esc(r.name || r.email || '') + 'joined ' + new Date(r.joined).toLocaleDateString() + '' + memberChips(r) + '' + esc(r.status) + '
' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' - : '

No packages sold yet this week. First sale takes the top spot.

'; - h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; - h += '

Full leaderboard: week, month, all time →

'; - $('lbList').innerHTML = h; $('lbCard').hidden = false; - } catch (e) {} - } - // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big - // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) - function renderSteps(d) { - const card = $('gsCard'); if (!card) return; - const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); - const steps = [ - { k: 'user', t: 'Pick a username', done: hasUser }, - { k: 'wallet', t: 'Link your wallet', done: hasWallet }, - { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, - { k: 'package', t: 'Your first package', done: hasPackage } - ]; - if (steps.every(x => x.done)) { card.hidden = true; return; } - const cur = steps.find(x => !x.done); - let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} - $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; - $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); - $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; - $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); - const copy = { - user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], - wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], - payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], - package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] - }[cur.k]; - $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; - $('gsGo').addEventListener('click', copy[3]); - card.hidden = false; - } - // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. - // We remember the game (through sign-in), tell the server once, and show the offer + the way back to the perk. - try { const fm = /[?&]from=([a-z]{3,20})/.exec(location.search); if (fm) { sessionStorage.setItem('iap.starterFrom', fm[1]); history.replaceState(null, '', '/my' + (location.hash || '')); } } catch (e) {} - async function starterBanner(me) { - let from = null; try { from = sessionStorage.getItem('iap.starterFrom'); } catch (e) {} - let v = null; - if (from) { try { sessionStorage.removeItem('iap.starterFrom'); } catch (e) {} v = await (await fetch('/api/starter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ game: from }) })).json(); } - else v = await (await fetch('/api/starter')).json(); - if (!v || !v.on || !v.game) return; - const pane = document.querySelector('#pane-buy .card'); if (!pane) return; - let box = document.getElementById('starterBox'); if (!box) { box = document.createElement('div'); box.id = 'starterBox'; pane.insertBefore(box, pane.children[1] || null); } - const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - box.style.cssText = 'border:1px solid var(--gold, #e2b04a);border-radius:12px;padding:12px 14px;margin:0 0 14px;background:rgba(226,176,74,.08)'; - box.innerHTML = v.eligible - ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' - : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; - if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card - } - function jumpTo(pane, id) { - setPane(pane); - setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); - } - async function loadDashboard() { - try { - loadNews(); loadLeaderboard(); - const d = await (await fetch('/api/my/dashboard')).json(); - if (d.error) return; - chatSync(d); - try { renderSteps(d); } catch (e) {} - MYID = d.memberId || MYID; - startLiveFeed(); - if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) - window.__lbChecked = true; - api('/api/my/login-bonus').then(r => { - if (r && r.comeback > 0) { IAP.status('🎉 Welcome back! +' + r.comeback + ' bonus credits for coming back, plus +' + r.granted + ' for signing in today.', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } - else if (r && r.granted > 0) { - IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); - playSound('chaching'); setTimeout(loadDashboard, 900); - } - }).catch(() => {}); - } - const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; - $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); - $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); - $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); - usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; }); - $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } - $('dbTeam').textContent = (d.referrals || []).length; - // trend chips: only real, computable facts - const ec = $('dbEarnedChip'); - if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } - const bc = $('dbBuyersChip'); - if (bc && d.memberId) { - bc.hidden = false; - bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; - } - const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; - if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } - setInboxBadge(d.inboxUnread || 0); - if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); - renderBadges(d); - loadFeatured(); - loadLineTree(d.buyerCount || 0); - loadCharts(d); - $('nextMove').textContent = nextMove(d); - renderSteps(d); - const wrap = $('rosterWrap'); - if ((d.referrals || []).length) { - $('rosterEmpty').hidden = true; - renderRoster(wrap, d.referrals); - } - // overview recent-activity widget: chain events + line joins, newest first - try { - const c = await IAP.getConfig(); - const ov = $('ovFeed'); - const rows = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - for (const ev of [...(a.earnings || []), ...(a.purchases || [])] - .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); - } - for (const r of (d.referrals || []).slice(0, 3)) { - const div = document.createElement('div'); - div.className = 'row'; - div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' - + new Date(r.joined).toLocaleDateString() + ''; - rows.push(div); - } - if (rows.length) { - ov.innerHTML = ''; - rows.slice(0, 6).forEach(r => ov.appendChild(r)); - } - } catch (e) {} - // ready-to-send share message + promo tools, personalized - await SHARE_READY; - const link = shareLink(d.username || d.refCode || d.memberId || ''); - fillPromo(link, d); - // founding-week readiness: shown until every item is done (or the launch moment is a week past) - try { - const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; - const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; - const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); - const lm = $('launchMark'); - if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } - } catch (e) {} - // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it - try { - const tw = d.tankWaiting, tn = $('tankNotice'); - if (tn) { - tn.hidden = !(tw && tw.count); - if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' - + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' - + (tw.eligible ? '.' : ' (you need your own $20 package first).'); - } - } catch (e) {} - // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join - { const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip'); - if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP); - $('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } } - if (d.username) { // wall link rides the username - const wl = location.origin + '/wall/' + d.username; - $('wallLine').textContent = wl; - if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link - $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; - $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; - } - $('wallCopy').hidden = false; - $('wallOpen').hidden = false; - $('wallOpen').href = '/wall/' + d.username; - $('wallCopy').onclick = async () => { - try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } - }; - } - if (d.refCode || d.memberId) { - const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' - + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' - + 'Free to join and look around: ' + link; - $('copyPitch').hidden = false; - $('pitchPreview').hidden = false; - $('pitchPreview').textContent = '"' + pitch + '"'; - $('copyPitch').onclick = async () => { - try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } - }; - } - } catch (e) {} - } - - // ── back-office menu: hash-routed panes ─────────────── - const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; - const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', - earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', - wallet: 'Wallet & account', profile: 'Profile' }; - function setPane(name) { - let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) - if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card - if (!PANES.includes(name)) name = 'overview'; - for (const p of PANES) { - const el = $('pane-' + p); - if (el) el.hidden = p !== name; - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.classList.toggle('on', b.dataset.pane === name)); - if ($('boTitle')) $('boTitle').textContent = TITLES[name]; - // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane - IAP.adSlot('text', 'adStripTop'); - if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); - if (name === 'earn') { setEarnSub(earnSub); loadPdCard(); } // refresh whichever sub-tab is active; PassiveDrip card (2026-10-01) - else if (vidState.token) stopVideo(); - if (name === 'profile') loadLineBanner(); - if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } - if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits - if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } - if (name === 'pipeline') loadPipeline(); - if (name === 'games') loadGames(paneQ); - if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) - document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer - const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket - if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.pane))); - document.querySelectorAll('.qa [data-goto]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.goto))); - const qaCopy = document.getElementById('qaCopyInvite'); - if (qaCopy) qaCopy.addEventListener('click', async () => { - const link = document.getElementById('inviteLine').textContent; - if (!link || !link.startsWith('http')) { setPane('line'); return; } - try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } - catch (e) { setPane('line'); } - }); - window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); - if ($('boBurger')) $('boBurger').addEventListener('click', () => - document.getElementById('memberArea').classList.toggle('side-open')); - - async function render() { - // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member - let me = null; - try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } - if ($('bootSpin')) $('bootSpin').hidden = true; - // one way in: email. A wallet-only session (no account) is sent back to the - // email card with a finish-setup note; verifying the code links that wallet. - const walletOnly = !!(me && me.signedIn && !me.email); - const signedIn = me && me.signedIn && !walletOnly; - $('authArea').hidden = !!signedIn; - $('memberArea').hidden = !signedIn; - if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; - if (!signedIn) return; - if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL - if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) - // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be - // skipped or dismissed; it resolves only when a username is saved, then the area renders. - if (!me.username) { - if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } - return; - } - // came from a Drip Runner share link: once they have a username, straight back into the game (2026-09-30) - if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; } - if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01) - if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; } - if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02) - if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13) - if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18) - if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05) - if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); - // x = not now: clears the bar cookie (the waiting mint order stays and a later package still completes it), Marty 2026-10-11 - const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.textContent = '×'; x.setAttribute('style', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;border:0;border-radius:50%;background:rgba(0,0,0,.28);color:#fff;font-size:20px;line-height:30px;cursor:pointer;padding:0'); - x.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); fetch('/pw/mint/dismiss', { method: 'POST' }).catch(() => {}); d.remove(); document.body.classList.remove('hasback'); if (me) me.pwMint = false; }); d.appendChild(x); } - if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; } - if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; document.body.classList.add('hasback'); d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } - if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; document.body.classList.add('hasback'); d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } - if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01) - // arrived from an invite page: run the welcome tour and login ad once - if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { - render.welcomed = true; - history.replaceState(null, '', '/my' + (location.hash || '')); - (async () => { - try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} - await render(); - })(); - } - starterBanner(me).catch(() => {}); - setPane(location.hash.slice(1) || 'overview'); - $('campGate').hidden = !!me.memberId; - $('earnGate').hidden = !!me.memberId; - if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } - loadDashboard(); - if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket - - const who = []; - if (me.email) who.push(me.email); - // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check - if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); - else who.push('No wallet connected yet (link one below)'); - if (me.memberId) who.push('on-chain member #' + me.memberId + '' - + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); - else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); - $('posLine').innerHTML = who.join('
'); - - $('creditLine').textContent = (me.credits || 0).toLocaleString(); - loadPositions(me); - $('linkCard').hidden = !!me.address; - $('activateCard').hidden = !(me.address && !me.memberId); - $('activityArea').hidden = !me.memberId; - $('campGate').hidden = true; // earned credits fund campaigns for everyone - $('campaignCard').hidden = false; - loadCampaigns(); - - // profile pane state - $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; - if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; - $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; - $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' - + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') - + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); - // the share link works from day one; usernames make it a vanity link - if (me.username || me.refCode || me.memberId) { - await SHARE_READY; - $('inviteLine').textContent = shareLink(me.username || me.refCode || me.memberId); - $('copyInvite').hidden = false; - } else { - $('inviteLine').textContent = 'Sign in with your email to get your link.'; - $('copyInvite').hidden = true; - } - if (me.memberId) { - const bc = me.buyerCount || 0; - $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' - + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' - : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' - : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); - loadActivity(); - } else { - $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' - + 'before your people start buying: the contract locks each buyer to their sponsor at ' - + 'their first purchase, and payments only route to wallets that are switched on.'; - } - } - - // Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here), - // shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day. - let USD = null; - async function usdRate() { - if (USD && Date.now() - USD.got < 120000) return USD; - try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; } - return USD; - } - function usdOf(wei, r) { - let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {} - const v = pol * ((r && r.usd) || 0); - return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); - } - function usdNote(r) { - if (!r || !(r.usd > 0)) return ''; - const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000)); - return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.'; - } - async function loadActivity() { - try { - const c = await IAP.getConfig(); - const a = await (await fetch('/api/my/activity')).json(); - const fill = (id, evs, empty) => { - const el = $(id); - el.innerHTML = ''; - if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } - for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); - }; - fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); - usdRate().then(r => { - const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r); - if (!(r.usd > 0)) return; - const rows = $('earnFeed').querySelectorAll('.row'); let i = 0; - for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); } - }); - fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); - fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); - } catch (e) {} - initTrace(); - } - // payment trace (2026-09-16): who was paid, who was skipped and why, per purchase - let traceInit = false; - function initTrace() { - if (traceInit || !$('trGo')) return; traceInit = true; - const run = async () => { - const who = ($('trWho').value || '').trim(); const out = $('trOut'); const msg = $('trMsg'); - msg.textContent = 'Reading the chain…'; out.innerHTML = ''; - try { - const c = await IAP.getConfig(); - const r = await (await fetch('/api/my/trace?who=' + encodeURIComponent(who))).json(); - if (r.error) { msg.textContent = r.error; return; } - msg.textContent = ''; - const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; - const pol = w => IAP.fmtPol(w) + ' POL'; - const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - let h = '

' + nm(r.memberId) + ' · ' + (r.activated ? 'activated under ' + nm(r.sponsorId) : 'not activated on the chain yet') + ' · ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' (level 2 needs 2, level 3 needs 5)

'; - if (!r.purchases.length) { out.innerHTML = h + '

No purchases involving ' + nm(r.memberId) + ' yet.

'; return; } - for (const p of r.purchases) { - const isBuyer = p.buyerId === r.memberId; - h += '
' - + '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought a $' + (p.priceCents / 100).toFixed(0) + ' package (' + pol(p.paidWei) + ')' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') - + (c.explorer ? ' · verify ↗' : '') + '
'; - for (const t of p.tiers) { - const me = t.paidTo === r.memberId, skippedMe = t.skipped.some(x => x.id === r.memberId); - let line = 'Level ' + t.tier + ' (' + t.pct + '%): '; - for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'not qualified: had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' qualifying buyers then' : esc(x.reason)) + ') → '; - line += t.paidTo ? '' + nm(t.paidTo) + ' paid ' + pol(t.amountWei) + '' : 'no eligible catcher within reach → company'; - h += '
' + line + '
'; - } - h += '
Platform (20%): ' + pol(p.adminWei) + (isBuyer ? '' : '') + '
'; - } - h += '

A skipped level means that person had not unlocked it when the purchase settled. Qualification never applies backwards; the next purchase after they qualify pays them.

'; - out.innerHTML = h; - } catch (e) { msg.textContent = 'Could not read the chain just now. Try again in a minute.'; } - }; - $('trGo').addEventListener('click', run); - $('trWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); run(); } }); - } - - // credit activity ledger under the campaign table (2026-09-16): every earn and spend with its reason - // Archived campaigns: everything they did, none of the clutter and none of the reservation. - function renderArchived(el, r) { - const rows = r.archived || []; - if (!rows.length) return; - const box = document.createElement('div'); - box.className = 'card'; - box.style.marginTop = '18px'; - // what each one gave back = budget not delivered (flat packs are charged in full when bought, so theirs is 0) - const leftOf = c => Math.max(0, Number(c.budget || 0) - Number(c.spent || 0) - Number(c.accrued || 0)); - const returned = rows.reduce((n, c) => n + leftOf(c), 0); - box.innerHTML = '

Archived

' + rows.length + ' finished campaign' + (rows.length === 1 ? '' : 's') + ' · ' + returned.toLocaleString() + ' unspent credit' + (returned === 1 ? '' : 's') + ' returned
' - + '
' - + rows.map(c => '' - + '' - + '' - + '' - + '' - + '' - + '').join('') - + '
NameTypeViews hereClicksSpentReturnedRan until
' + esc(c.name || ('#' + c.id)) + '' + esc(c.type) + '' + Number(c.imps || 0).toLocaleString() + '' + Number(c.clicks || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + leftOf(c).toLocaleString() + '' + (c.created ? new Date(c.created).toLocaleDateString() : '') + '
' - + '

Archived campaigns keep every number they earned. They serve nothing and reserve nothing, so any budget they had not delivered is back in your Available balance (the Returned column). A campaign that delivered its whole budget has nothing left to return, and visit packs, Golden Door, login and featured runs are paid in full when bought. Restore brings one back, paused.

'; - el.appendChild(box); - box.querySelectorAll('[data-unarch]').forEach(b => b.addEventListener('click', async () => { - b.disabled = true; - try { await api('/api/my/campaigns/' + b.dataset.unarch + '/unarchive'); IAP.status('Restored, and paused. Press Resume when you want it running.', 'ok'); await loadCampaigns(); loadDashboard(); } - catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - } - async function loadCreditActivity(el) { - try { - const r = await (await fetch('/api/my/credits/activity')).json(); - if (!r.items || !r.items.length) return; - const box = document.createElement('div'); box.id = 'creditActivity'; box.style.marginTop = '16px'; - const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - box.innerHTML = '

Credit activity

' - + '

Every credit that came in or went out, newest first. Earned credits are spent before purchased ones, so an earn followed by a buy shows as two lines here. Views a campaign delivers roll up into one line per day.

' - + '
' - + r.items.map(i => '').join('') - + '
' + when(i.ts) + '' + (i.delta > 0 ? '+' : '') + i.delta.toLocaleString() + '' + esc(i.note) + '
'; - el.appendChild(box); - pageList('credits', box, 'tbody tr'); - } catch (e) {} - } - async function loadCampaigns() { - try { - const r = await (await fetch('/api/my/campaigns')).json(); - if (r.error) return; - lastRates = r.rates; - lastLoginLine = r.loginLine || null; loginLineHint(); - if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; - // populate the banner-size dropdown once (ids map to NAS width/height) - if (r.bannerSizes && $('cSize') && !$('cSize').options.length) - $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); - applyType(); // the default type is banner: show its size + image rows now that the sizes exist - soloHint(); - if ($('spendBanner')) { - $('spendBanner').hidden = false; - $('spendBig').textContent = r.availableCredits.toLocaleString(); - $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.earnedReserved ? ' (' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits are already working inside your live campaigns)' : '') + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); - if ($('spendNote')) $('spendNote').textContent = r.inCampaigns - ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' - : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; - $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', Number(r.rates.loginSlotCredits || 1000).toLocaleString() + ' cr / ' + (r.rates.loginSlotDays || 30) + '-day slot'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); - } - $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() - + ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '') - + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') - + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch - + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch - + ' views, login ' + Number(r.rates.loginSlotCredits || 1000).toLocaleString() + 'cr per ' + (r.rates.loginSlotDays || 30) + '-day slot, solo ' - + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; - const el = $('campList'); - el.innerHTML = ''; - if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; loadCreditActivity(el); return; } - const tbl = document.createElement('div'); - tbl.className = 'tablewrap'; - tbl.innerHTML = '' - + '' - + r.campaigns.map(c => '' - + '' - + '' - + '' - + '' - + (c.type === 'visits' ? '' - : c.type === 'featured' ? '' - : '') - + '' - + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) - + (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' ' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '' : '') + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
paid up front' + c.imps.toLocaleString() + ' of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits') - + (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '
\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '
')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '
paid up front' + featRun(c) + '' + c.spent + '' + c.budget + '' + (c.status === 'queued' ? queuedCell(c) : c.status === 'cancelled' ? 'cancelled, refunded' : c.status === 'out' ? (c.type === 'visits' ? 'pack delivered' : 'budget spent') : c.status === 'done' ? '' + (c.type === 'featured' ? 'run ended' : 'ended') + '' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' - : c.status === 'paused' ? '' - : c.status === 'queued' ? ' ' : '') - + (['paused', 'out', 'done', 'cancelled'].includes(c.status) ? ' ' : '') - + (c.type === 'featured' ? ' ' - : c.type === 'visits' ? ' ' - : c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up - : ' ') - + '
'; - el.appendChild(tbl); - pageList('camps', tbl, 'tbody tr'); - renderArchived(el, r); - const note = document.createElement('p'); note.className = 'muted small'; - note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.'; - el.appendChild(note); - loadCreditActivity(el); - el.querySelectorAll('button[data-extend]').forEach(b => b.addEventListener('click', async () => { - const rr = r.rates || {}; const durs = rr.featuredDurations || [1, 2, 7]; const per = rr.featuredPerDay || 40; - const d = await IAP.ask({ title: 'Extend featured run', text: 'How many more days? Choose ' + durs.join(', ') + '. ' + per + ' credits a day, charged now. The days are added after the current run, or start today if it has ended.', type: 'number', placeholder: 'e.g. ' + durs[durs.length - 1], ok: 'Extend' }); - if (!d) return; - try { const x = await api('/api/my/campaigns/' + b.dataset.extend + '/extend', { days: Number(d) }); - IAP.status('Extended ' + x.days + ' day' + (x.days === 1 ? '' : 's') + ' for ' + x.cost + ' credits' + (x.resumed ? '. The run is live again.' : '.'), 'ok'); - await loadCampaigns(); loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('button[data-morevisits]').forEach(b => b.addEventListener('click', async () => { - const per = Number(b.dataset.vper) || (r.rates && r.rates.visitCostPerVisit) || 3; const door = b.dataset.vdoor; // door packs top up at their door price - const what = door === 'golden' ? 'Golden Doors' : door ? 'doors' : 'visits'; - const n = await IAP.ask({ title: 'Buy more ' + what, text: door ? 'How many more ' + what + '? ' + per + ' credits each, charged now like the original pack.' : 'How many more verified visits? ' + per + ' credits each, charged now like the original pack.', type: 'number', placeholder: 'e.g. 50', ok: 'Buy ' + what }); - if (!n) return; - try { const x = await api('/api/my/campaigns/' + b.dataset.morevisits + '/topup', { credits: Math.floor(Number(n)) * per }); - IAP.status('Added ' + x.visits + ' ' + what + ' (' + x.added + ' credits)' + (x.reactivated ? '. The pack is open again.' : '.'), 'ok'); - await loadCampaigns(); loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - })); - // prepaid login-ad line (2026-10-23): a reservation can be edited for free and cancelled for the full price back until it starts - el.querySelectorAll('button[data-qcancel]').forEach(b => b.addEventListener('click', async () => { - const paid = Number(b.dataset.qpaid) || 0; - const ok = await IAP.confirmBox('You give up your place in line and the full ' + paid.toLocaleString() + ' credits come back to your balance right away, as purchased credits. You can reserve again later, at the back of the line.', - { title: 'Cancel ' + b.dataset.qname + '?', ok: 'Cancel and refund', cancel: 'Keep my place' }); - if (!ok) return; - b.disabled = true; - try { const x = await api('/api/my/campaigns/' + b.dataset.qcancel + '/cancel-reservation'); IAP.status('Reservation cancelled. ' + Number(x.refunded || 0).toLocaleString() + ' credits are back in your balance.', 'ok'); await loadCampaigns(); loadDashboard(); } - catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; await loadCampaigns(); } - })); - el.querySelectorAll('button[data-qedit]').forEach(b => b.addEventListener('click', async () => { - const c = r.campaigns.find(x => x.id === Number(b.dataset.qedit)); if (!c) return; - const target = await IAP.ask({ title: 'Edit your reserved login ad', text: 'Target URL: the page members see when they sign in. Editing is free until the ad starts.', value: c.targetUrl || '', placeholder: 'https://', ok: 'Next' }); - if (target === null) return; - const image = await IAP.ask({ title: 'Image (optional)', text: 'A direct image link (.png or .jpg) shown as the clickable creative. Leave it empty for a plain link card.', value: c.imageUrl || '', placeholder: 'https://', ok: 'Next' }); - if (image === null) return; - const title = await IAP.ask({ title: 'Headline (optional)', text: 'Shown on the link card when there is no image. Up to 60 characters.', value: c.title || '', placeholder: 'Visit today\'s sponsor', ok: 'Save changes' }); - if (title === null) return; - try { await api('/api/my/campaigns/' + c.id + '/edit-reservation', { targetUrl: target.trim(), imageUrl: image.trim(), title: title.trim() }); IAP.status('Saved. Your place in line is unchanged.', 'ok'); await loadCampaigns(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('[data-arch]').forEach(b => b.addEventListener('click', async () => { - const left = Number(b.dataset.archleft) || 0; - const ok = await IAP.confirmBox( - 'It stops appearing in this list but keeps every number it earned, in the Archived section below.' - + (left ? ' Its ' + left.toLocaleString() + ' unspent credits go straight back to your Available balance.' : '') - + ' You can restore it at any time.', - { title: 'Archive ' + b.dataset.archname, ok: 'Archive it', cancel: 'Keep it here' }); - if (!ok) return; - b.disabled = true; - try { const x = await api('/api/my/campaigns/' + b.dataset.arch + '/archive'); - IAP.status('Archived.' + (x.freed ? ' ' + Number(x.freed).toLocaleString() + ' credits released.' : ''), 'ok'); - await loadCampaigns(); loadDashboard(); } - catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { - const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views. They are set aside now and spend as views are delivered; anything unspent comes back when the campaign ends.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); - if (!n) return; - const done = r => { IAP.status('Added ' + r.added + ' credits' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The campaign is live again.' : '.'), 'ok'); }; - try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) })); await loadCampaigns(); loadDashboard(); } - catch (e) { - // the ad's own position is short but another of yours has the credits: offer to pay from that one - const opt = e.data && e.data.switchOptions && e.data.switchOptions[0]; - if (!opt) { IAP.status(e.message, 'bad'); return; } - const yes = await IAP.confirmBox('This ad pays from your position #' + e.data.fundId + ', which has ' + e.data.free + ' credits free. Your position #' + opt.memberId + ' has ' + opt.free + ' free. Pay for this top-up from #' + opt.memberId + '? From now on this ad spends from #' + opt.memberId + '.', { title: 'Pay from another position?', ok: 'Pay from #' + opt.memberId, cancel: 'Cancel' }); - if (!yes) return; - try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n), switchTo: opt.memberId })); await loadCampaigns(); loadDashboard(); } - catch (e2) { IAP.status(e2.message, 'bad'); } - } - })); - } catch (e) {} - } - let lastRates = null; - let lastLoginLine = null; // { max, used, queued, free, credits, days, nextPlace, nextEstStart, mine: [{ id, place, estStart }] } - // every date about the login-ad line is shown in Central time, Marty's clock - function ctWhen(ts) { return new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; } - function queuedCell(c) { - const m = lastLoginLine && (lastLoginLine.mine || []).find(x => x.id === c.id); - return 'In line' + (m ? ' #' + m.place : '') + '' - + '
' + (m && m.estStart ? 'Estimated start ' + esc(ctWhen(m.estStart)) : 'Start date not known yet') + '
'; - } - // the Login ad form: open slots, or the paid line with this buyer's place and estimated start - function loginLineHint() { - const el = $('cLoginLine'); const isLogin = $('cType') && $('cType').value === 'login'; - if (el) el.hidden = !isLogin || !lastLoginLine; - if ($('createCampBtn')) $('createCampBtn').textContent = isLogin && lastLoginLine && !lastLoginLine.free ? 'Reserve the next slot' : 'Launch campaign'; - if (!el || !isLogin || !lastLoginLine) return; - const L = lastLoginLine; - el.textContent = L.free - ? L.free + ' of ' + L.max + ' login-ad slots open now. Yours goes live the moment you launch: ' + Number(L.credits).toLocaleString() + ' purchased credits for ' + L.days + ' days.' - : 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ' and ' + L.queued + ' paid ' + (L.queued === 1 ? 'reservation is' : 'reservations are') + ' in line' : '') + '. You can reserve the next slot: you pay the same ' - + Number(L.credits).toLocaleString() + ' purchased credits now and take place #' + L.nextPlace + ' in line. Your ' + L.days + ' days start when your turn comes, not before.' - + (L.nextEstStart ? ' Estimated start: ' + ctWhen(L.nextEstStart) + '. That is an estimate: a slot can end early if its owner archives it, which moves the line forward.' : '') - + ' Until it starts you can edit it for free, or cancel it for every credit back.'; - } - function soloHint() { - if (!lastRates || $('cType').value !== 'solo') return; - const cost = lastRates.soloCostPerRecipient || 5; - const n = Math.floor((Number($('cBudget').value) || 0) / cost); - $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' - + (n ? ' — this budget reaches ' + n + ' members' : '') - + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; - } - $('cBudget').addEventListener('input', soloHint); - // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); - // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort - document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); - document.querySelectorAll('.ed-bar [data-block]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); - $('edLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection - const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (!url) return; - $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } - document.execCommand('createLink', false, url); - }); - // inline media: upload, then drop the element at the cursor (BV-style) - let mediaMode = 'image'; - function insertHtmlAtCursor(html) { - const ed = $('cSoloEd'); - ed.focus(); - if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); - } - $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); - $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); - $('cSoloFile').addEventListener('change', async () => { - const f = $('cSoloFile').files[0]; - if (!f) return; - $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } - insertHtmlAtCursor(r.type === 'video' - ? '


' - : '


'); - $('edMediaInfo').textContent = f.name + ' inserted'; - } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } - $('cSoloFile').value = ''; - }); - // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back - $('edRawBtn').addEventListener('click', () => { - const ed = $('cSoloEd'), raw = $('cSoloRaw'); - if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } - else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } - }); - const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', - text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', - login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', - solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', - video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', - featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', - visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; - const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; - whereHint(); - // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately - function applyType() { // hoisted: loadCampaigns may run before this line is reached - whereHint(); - loginLineHint(); - const t = $('cType').value; - $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL - if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner'; - $('cSizeRow').hidden = t !== 'banner'; - $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; - $('cBodyRow').hidden = t !== 'text'; - $('cSoloRow').hidden = t !== 'solo'; - $('cSoloHint').hidden = t !== 'solo'; - $('cVideoRow').hidden = t !== 'video'; - $('cFeaturedRow').hidden = t !== 'featured'; - $('cVisitsRow').hidden = t !== 'visits'; - if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; - $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } - // fixed-cost types derive their spend (featured = day slots, visits = flat pack), - // so hide the free-form Budget field for them to avoid confusion - $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); - if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); - // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected - if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; - if (t === 'visits') visitHint(); - $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; - soloHint(); - if (t === 'video') videoHint(); - if (t === 'featured') featHint(); - } - $('cType').addEventListener('change', applyType); - let featStartDay = 0; // selected start-day offset (0 = today) - async function featHint() { - if (!lastRates || !lastRates.featuredDurations) return; - if ($('cFeatDays') && !$('cFeatDays').options.length) - $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => - '').join(''); - let s = null; - try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} - if (s && s.occupancy) { - const grid = $('cFeatDaysGrid'); - grid.innerHTML = s.occupancy.map(d => { - const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); - const full = d.open <= 0; - return '
' - + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; - }).join(''); - grid.querySelectorAll('.feat-day:not(.full)').forEach(el => - el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); - } - const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); - const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; - $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel - + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); - // where a visits pack runs (Spooky Doors, 2026-10-02): everywhere, behind the doors, or a Golden Door, each with its own price - // function declarations (hoisted): loadCampaigns can run before this point is reached - function visitPlace() { const x = document.querySelector('input[name="cVisitPlace"]:checked'); return x ? x.value : 'all'; } - function placeCost(pl, rr) { rr = rr || lastRates || {}; return pl === 'golden' ? (rr.goldenDoorCost || 6) : pl === 'doors' ? (rr.doorPackCost || 4) : (rr.visitCostPerVisit || 3); } - function sdSeasonOpen(rr) { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < String((rr && rr.sdSeasonEnd) || '2026-11-01'); } - function sdLastDay(rr) { const t = new Date(String((rr && rr.sdSeasonEnd) || '2026-11-01') + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); } - function visitHint() { - if (!lastRates) return; - const open = sdSeasonOpen(lastRates); - document.querySelectorAll('#cVisitPlaceRow .sd-place').forEach(el => { el.hidden = !open; }); - if (!open && visitPlace() !== 'all') { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; } - document.querySelectorAll('[data-vpcost]').forEach(el => { const p = el.dataset.vpcost; el.textContent = '(' + placeCost(p) + ' credits a ' + (p === 'all' ? 'visit' : 'door') + ')'; }); - const pl = visitPlace(), per = placeCost(pl), min = lastRates.visitMinPack || 20; - const n = Number($('cVisitCount').value) || 0; - const unit = pl === 'golden' ? 'Golden Door' : pl === 'doors' ? 'door' : 'verified visit'; - $('cVisitCount').placeholder = pl === 'all' ? 'How many verified visits?' : pl === 'golden' ? 'How many Golden Doors?' : 'How many doors?'; - $('cVisitHint').textContent = per + ' credits per ' + unit - + (n >= min ? ': ' + n + ' = ' + (n * per).toLocaleString() + ' credits, paid up front' : ' (min ' + min + ')') - + (pl === 'all' ? '. Each is a unique member, dwell + human-check verified.' - : '. Each door is a dwell + human-check verified visit by a Spooky Doors player, at most once a day per player' - + (pl === 'golden' ? '; Golden Doors open before every other door and give the player bonus candy' : '; door packs open before ordinary visits') - + '. They run only in Spooky Doors until the season ends on ' + sdLastDay(lastRates) + ', then any doors left run as normal visits.'); - } - $('cVisitCount').addEventListener('input', visitHint); - document.querySelectorAll('input[name="cVisitPlace"]').forEach(x => x.addEventListener('change', visitHint)); - // video composer: tier dropdown + upload + price hint - function videoHint() { - if (!lastRates || !lastRates.videoTiers) return; - if ($('cWatchSecs') && !$('cWatchSecs').options.length) - $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => - '').join(''); - const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; - const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; - $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' - + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); - $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); - $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); - $('cVideoUrl').addEventListener('change', async () => { - const url = $('cVideoUrl').value.trim(); - $('cVideoInfo').textContent = url ? 'checking video…' : ''; - cVidDims = url ? await probeVideoDims(url) : null; - if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; - else { $('cVideoInfo').textContent = ''; showVidOrient(); } - }); - $('cVideoFile').addEventListener('change', async () => { - const f = $('cVideoFile').files[0]; - if (!f) return; - $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } - $('cVideoUrl').value = r.url; - $('cVideoInfo').textContent = f.name + ' uploaded'; - $('cVideoPrev').hidden = false; - $('cVideoPrev').innerHTML = ''; - cVidDims = await probeVideoDims(r.url); showVidOrient(); - } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } - $('cVideoFile').value = ''; - }); - $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { - // in raw mode the source of truth is the textarea; sync it back first - let soloBody = $('cSoloEd').innerHTML; - if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; - const t = $('cType').value; - const isVideo = t === 'video', isFeat = t === 'featured'; - if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); - // login ad with every slot taken: pay now for a place in line (Marty, 2026-10-23), after one plain confirmation - const confirmReserve = async (place, est) => IAP.confirmBox('Every login-ad slot is taken right now. Reserving charges the full ' + Number((lastLoginLine && lastLoginLine.credits) || (lastRates && lastRates.loginSlotCredits) || 0).toLocaleString() - + ' purchased credits now and puts you at place #' + place + ' in line. Your ad starts on its own when a slot frees, and runs its full ' + ((lastLoginLine && lastLoginLine.days) || 30) + ' days from then.' - + (est ? '\n\nEstimated start: ' + ctWhen(est) + '. That is an estimate: a slot can end early if its owner archives it.' : '') - + '\n\nUntil it starts you can edit it for free, or cancel it and get every credit back.', { title: 'Reserve the next login-ad slot?', ok: 'Pay now and reserve', cancel: 'Not now' }); - let reserve = false; - if (t === 'login' && lastLoginLine && !lastLoginLine.free) { if (!(await confirmReserve(lastLoginLine.nextPlace, lastLoginLine.nextEstStart))) return; reserve = true; } - const sendCamp = extra => api('/api/my/campaigns', Object.assign({ type: t, name: $('cName').value, - targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, - title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, - body: t === 'solo' ? soloBody : $('cBody').value, - videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), - videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, - days: Number($('cFeatDays').value), startDay: featStartDay, - count: Number($('cVisitCount').value), placement: t === 'visits' ? visitPlace() : undefined, - dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, - geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), - startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, - endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, - ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, - budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }, extra || {})); - let res; - try { res = await sendCamp({ reserve }); } - catch (e) { // the last slot went while the form was open: offer the line instead of a dead end - if (!(t === 'login' && e.data && e.data.full)) throw e; - if (!(await confirmReserve(e.data.place, e.data.estStart))) { await loadCampaigns(); return; } - res = await sendCamp({ reserve: true }); - } - const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; - if (res && res.queued) IAP.status('Reserved and paid. You are #' + res.place + ' in line' + (res.estStart ? ', estimated start ' + ctWhen(res.estStart) : '') + '. We will tell you on site and by email the moment it goes live.', 'ok'); - else if (t === 'login' && reserve) IAP.status('A slot opened up while you were deciding, so your login ad is live now.', 'ok'); - else IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); - // clear EVERY field so no target/creative carries into the next campaign - ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', - 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] - .forEach(id => { if ($(id)) $(id).value = ''; }); - document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); - { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; if (t === 'visits') visitHint(); } - $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; - $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; - if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; - cVidDims = null; - await loadCampaigns(); - })); - // defers the busy() lookup to click time (busy is declared below) - function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } - - // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── - const visState = { token: null, id: null, dwell: 8 }; - async function loadVisitStatus() { - try { - const st = await (await fetch('/api/my/visits')).json(); - if (st.error) return; - $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; - $('vsStartBtn').hidden = st.status.count >= st.status.cap; - if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; - } catch (e) {} - } - async function loadVisit() { - $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; - let r = null; - try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} - if (!r || !r.ad) { - $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap - ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; - return; - } - visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; - $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; - const visit = $('vsVisit'); - visit.href = r.ad.url; visit.hidden = false; - $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; - // opening the site starts the dwell; then we ask the human-check - visit.onclick = () => { - let left = visState.dwell; - $('vsHint').textContent = 'Counting your visit: ' + left + 's'; - const t = setInterval(async () => { - left--; - if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } - clearInterval(t); - $('vsHint').textContent = 'One quick check to count the visit:'; - let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); - if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } - if (c.error) { $('vsHint').textContent = c.error; return; } - renderVisitCheck(c); - }, 1000); - }; - $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; - } - function renderVisitCheck(c) { - $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; - const w = $('vsOpts'); w.innerHTML = ''; - c.options.forEach((em, i) => { - const b = document.createElement('button'); - b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; - b.addEventListener('click', () => answerVisit(i)); - w.appendChild(b); - }); - $('vsCheck').hidden = false; - } - async function answerVisit(i) { - const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); - if (r.error) { - if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } - $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; - } - $('vsCheck').hidden = true; - $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; - $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; - IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); - loadDashboard(); - } - $('vsStartBtn').addEventListener('click', () => loadVisit()); - - // ── watch-to-earn videos: escape-proof player, server-clock reward ── - const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; - // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos - let cVidDims = null; - function probeVideoDims(url) { - return new Promise(resolve => { - if (!url) return resolve(null); - const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; - let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; - v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); - v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; - }); - } - function showVidOrient() { - const el = $('cVideoInfo'); if (!el) return; - if (!cVidDims) return; - const portrait = cVidDims.h > cVidDims.w; - el.textContent = (el.textContent ? el.textContent + ' · ' : '') - + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); - } - async function loadVideoStatus() { - try { - const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); - if (st.error) return; - $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; - if (st.status.left <= 0) { - $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; - $('vidStartBtn').hidden = true; - return; - } - $('vidStartBtn').hidden = false; - } catch (e) {} - } - // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) - function stopVideo() { - const p = $('vidPlayer'); if (!p) return; - const was = !!vidState.token && !vidState.done; - try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} - vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; vidState.needsTap = false; - if ($('vidWrap')) $('vidWrap').hidden = true; - if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } - if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } - } - document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); - async function loadVideoAd() { - let r = null; - try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} - if (!r || !r.ad) { - // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) - const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); - // the tab can run dry while Shorts still has clips, and both count toward the same - // daily total, so say so instead of sending them away (Marty, 2026-09-22) - const toShorts = !capHit && r && r.otherFormat === 'shorts'; - $('vidBox').innerHTML = toShorts - ? '
✓That is every video on this tab' - + 'You have watched all ' + r.status.count + ' of today’s landscape videos. The rest are upright clips that play in Shorts, and they count toward the same daily ' + r.status.cap + '. You have ' + r.status.left + ' left.' - + 'Open Shorts
' - : (capHit || allWatched) - ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' - : 'No member videos are live right now. Check back when a campaign is running.'; - if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched || toShorts; - $('vidBox').hidden = false; - $('vidWrap').hidden = true; - return; - } - const ad = r.ad; - vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; - $('vidBox').hidden = true; - $('vidWrap').hidden = false; - $('vidCta').hidden = true; - $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; - const p = $('vidPlayer'); - p.src = ad.videoUrl; - p.currentTime = 0; - // escape-proof: no seeking past what's been watched; track max reached - p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; - p.ontimeupdate = () => { - if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; - const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); - $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; - if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } - }; - $('vidStartBtn').textContent = 'Playing…'; - $('vidStartBtn').disabled = true; - vidState.needsTap = false; - // a browser that refuses to autoplay leaves the clip loaded and paused; the button then has to - // START it. Wired to loadVideoAd it threw the clip away and fetched another, so on a phone the - // video could never be played at all (Marty, 2026-09-22) - try { await p.play(); } catch (e) { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } - $('vidCta').href = ad.ctaUrl; - $('vidCta').textContent = ad.ctaLabel || 'Learn more'; - $('vidCta').hidden = false; - } - async function completeVideo(ad) { - if (vidState.credited) return; - vidState.credited = true; - try { - const r = await (await fetch('/api/my/videowatch', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } - else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } - else $('vidHint').textContent = 'That video just ran out of budget — load another.'; - if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; - } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } - $('vidStartBtn').disabled = false; - $('vidStartBtn').textContent = 'Next video'; - } - $('vidStartBtn').addEventListener('click', () => { - const p = $('vidPlayer'); - if (vidState.needsTap && p && p.src && !vidState.done) { // a clip is loaded and waiting on a tap: start it, never replace it - vidState.needsTap = false; - $('vidStartBtn').textContent = 'Playing…'; $('vidStartBtn').disabled = true; - p.play().catch(() => { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }); - return; - } - loadVideoAd(); - }); - // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, - // resume when it comes back — the viewer must stay on the page for the watch to complete - document.addEventListener('visibilitychange', () => { - const p = $('vidPlayer'); if (!p || !p.src) return; - if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); - }); - window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); - window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); - - // ── unmissable sponsor-message modal on sign-in ── - // Only a message a PERSON wrote reaches here; system notices (payouts, purchase - // confirmations) are kind 'notice' and go straight to the inbox. - // - // loadDashboard() runs on far more than sign-in — it refreshes after every ad view, every - // campaign edit, every chat close. So the modal is shown at most once per page load and - // never twice for the same message, otherwise a member earning credits gets interrupted - // after every single view. - const msgModalShown = new Set(); - function showSponsorModal(msg) { - if (!$('msgModal') || !msg || msgModalShown.has(msg.id)) return; - if (!$('msgModal').hidden) return; // one already open - msgModalShown.add(msg.id); - // An alert is generated by the system, so crediting it to a person ("A message from - // @martbost") is both wrong and misleading about what the member is looking at. - $('mmFrom').textContent = msg.kind === 'alert' - ? 'Action needed on your account' - : 'A message from ' + (msg.fromName || 'your sponsor'); - $('mmSubject').textContent = msg.subject || ''; - $('mmBody').innerHTML = msg.body || ''; // server-sanitized - $('msgModal').hidden = false; - $('mmAck').onclick = async () => { - $('msgModal').hidden = true; - try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} - setInboxBadge(Math.max(0, (Number($('inboxBadge') && $('inboxBadge').textContent) || 1) - 1)); - }; - } - - // ── coaching: every direct's rung, stalled flag, one-click nudge ── - // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── - async function pif(email, name, address) { - // Marty, 2026-09-27: the member must see the risk before every PIF. The platform holds no funds; this is a - // wallet-to-wallet gift in good faith, and nothing the site does can recover it. - const ok = await IAP.confirmBox('You are about to send POL from your own wallet directly to ' + name + '\'s wallet, in good faith, so they can buy their first package.\n\nInstantAdPay never holds or moves these funds and cannot reverse or recover them. Nothing obliges ' + name + ' to make a purchase. Only send what you are willing to give.', { title: 'Before you pay it forward', ok: 'I understand, continue', cancel: 'Cancel' }); - if (!ok) return; - let suggest = 25; - try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} - const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); - if (amt === null) return; - const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } - try { - IAP.status('Confirm the transfer in your wallet…', 'ok'); - const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); - const hash = await IAPWallet.sendPol(address, wei); - await api('/api/my/gift', { email, tx: hash, pol }); - IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); - playSound && playSound('chaching'); - } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } - } - // ── holding tank: waiting members, adopt, my open adoptions ── - const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; - async function loadTank() { - const el = $('tankList'); if (!el) return; - try { - const r = await (await fetch('/api/my/tank')).json(); - if (r.error) { el.innerHTML = ''; return; } - $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; - $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; - const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); - $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' - + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' - + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' - + '' - + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; - $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); - $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } - renderTank(el, r); - } catch (e) {} - } - function renderTank(el, r) { - const rows = listApply('tank', r.waiting); - el.innerHTML = ''; - el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on - el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + '' - + 'joined ' + ago(w.joined) + '' + memberChips(w) + '' - + 'last sign-in: ' + ago(w.lastSeen) + '' - + (r.eligible ? '' : '') + '
').join('') - : '

Nobody in the tank matches those filters.

'); - pageList('tank', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { - const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the InstantAdPay holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); - if (note === null) return; - try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } - // The announcement cards at the top of the Overview are repeated on a timer, so a member who has read - // one can put it away: dismissed for 24 hours on this browser (Marty, 2026-10-03; it used to come back - // at every sign-in and the cards stacked up), then it shows again so it is never gone for good. - const CARD_SNOOZE_MS = 24 * 3600 * 1000; - function cardHidden(key) { try { const t = Number(localStorage.getItem('iap-hide-' + key)); return t > 0 && Date.now() - t < CARD_SNOOZE_MS; } catch (e) { return false; } } - function cardDismiss(card, key) { - if (!card || card.querySelector('.card-x')) return; - const x = document.createElement('button'); - x.type = 'button'; x.className = 'card-x'; x.innerHTML = '×'; - x.title = 'Hide this for 24 hours'; - x.setAttribute('aria-label', 'Hide this message for 24 hours'); - x.addEventListener('click', () => { try { localStorage.setItem('iap-hide-' + key, String(Date.now())); } catch (e) {} card.hidden = true; }); - (card.querySelector('.card-head') || card).appendChild(x); - } - // Five Dollar Friday card on the Overview: the live wave on Fridays, the date the rest of the week - async function loadFridayCard() { - const card = $('fdfCard'); if (!card) return; - if (cardHidden('fdf')) { card.hidden = true; return; } - try { - const f = await (await fetch('/api/friday')).json(); if (!f.on) { card.hidden = true; return; } - card.hidden = false; - if (f.live && f.today) card.innerHTML = '

\u{1F4B5} It\u2019s Five Dollar Friday

+' + f.pct + '% credits on any pack today
' - + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Every $5+ package bought before midnight Central earns +' + f.pct + '% bonus credits the moment it settles. Your pack pays your sponsor line instantly; your line\u2019s packs pay you.

' - + ' Watch the wave'; - else card.innerHTML = '

\u{1F4B5} Five Dollar Friday

every Friday
' - + '

Every Friday (Central time), any ad package from $5 up earns +' + f.pct + '% bonus credits, added the moment it settles. The whole network buys on the same day, so every line gets paid at once. Next one: ' + (f.nextLabel || 'soon') + '.

' - + ''; - const b = $('fdfBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); - cardDismiss(card, 'fdf'); - } catch (e) {} - } - loadFridayCard(); setInterval(loadFridayCard, 120000); - // Wired Wednesday card on the Overview: the live wave on Wednesdays, the date the rest of the week - async function loadWednesdayCard() { - const card = $('wwCard'); if (!card) return; - if (cardHidden('ww')) { card.hidden = true; return; } - try { - const f = await (await fetch('/api/wednesday')).json(); if (!f.on) { card.hidden = true; return; } - card.hidden = false; - if (f.live && f.today) card.innerHTML = '

⚡ It’s Wired Wednesday

+' + f.pct + '% credits on any $' + f.minUsd + '+ pack today
' - + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in, ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Buy any $' + f.minUsd + '+ package before midnight Central and +' + f.pct + '% is wired into your balance the moment it settles, good for any format.

' - + ' How it works'; - else card.innerHTML = '

⚡ Wired Wednesday

every Wednesday
' - + '

Every Wednesday (Central time), any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles, purchased-grade so they run on any format, login ads included. Next one: ' + (f.nextLabel || 'soon') + '.

' - + ''; - const b = $('wwBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); - cardDismiss(card, 'ww'); - } catch (e) {} - } - loadWednesdayCard(); setInterval(loadWednesdayCard, 120000); - - // ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ---- - const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }); - const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, ''); - // Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add - // islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time. - // 2026-10-22 (Dallas's structure): + Sovereign (monthly) and Legend (yearly). Names and what each includes come from the server - // (gamepass.js TIER_DEFS, row.perks); GP_TIER_PERKS is only the fallback for an older server answer. - const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)'; - const GP_TIER_PERKS = { - weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'], - explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'], - champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'], - }; - const gpLen = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days'; - function renderPassTiers(card, gp, highlight) { - const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier); - const state = top ? '' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '' - : 'No pass active'; - const caps = gp.caps || {}; - const capsLine = caps.enforced ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : ''; - const box = r => { - const btn = r.waiting ? '' - : r.open ? '' - : 'Not on sale right now. Your pass keeps running.'; - return '

' + esc(r.name) + '

' - + '

$' + r.usd + ' for ' + gpLen(r.days) + '

' - + '
    ' + (r.perks || GP_TIER_PERKS[r.tier] || []).map(x => '
  • ' + esc(x) + '
  • ').join('') + '
' - + '

' + (r.active ? 'Active until ' + esc(gpCT(r.until)) + '' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '

' - + btn + '
'; - }; - card.hidden = false; card.classList.toggle('gp-hl', !!highlight); - card.innerHTML = '

\u{1F39F}️ Game Passes

weekly, monthly or yearly · every game
' - + (gp.tierPreview ? '

Admin preview. The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings.

' : '') - + '

' + state + '

' - + '

Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. Each higher pass includes everything below it and adds more of Shards of Valor: weapons, gear, bonus islands, heroes and a higher level cap. Paid passes add heroes, islands, a higher level cap and new looks. Pass gear is never better than gear players can earn, and passes never pay more POL.

' - + '
' + rows.map(box).join('') + '
' - + (capsLine ? '

' + capsLine + '

' : '') - + '

Every pass is paid by a new package purchase of at least its price, so your sponsor and team are paid; you keep the package credits for your ads. Credits you already hold never buy a pass. Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.

'; - card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => { - const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return; - const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + gpLen(r.days) : 'Get ' + r.name + ' for ' + gpLen(r.days)) + ' ($' + r.usd + ')? Every pass is paid by a new package purchase of $' + r.package + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the pass starts the moment it settles. Credits you already hold never buy a pass. The same POL caps as every pass: no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' }); - if (!yes) return; - b.disabled = true; - try { - const x = await api('/api/my/gamepass/buy', { tier: r.tier }); - if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'ok'); setPane('buy'); return; } - IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok'); - await loadGamePassCard(true); - } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - })); - card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy'))); - if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } - } - // What the Pass adds in each game (Marty, 2026-10-22: members must see what they are buying). Keep in step with the games' perks. - const GP_PERKS = [ - ['PolHunter', '5 missions a day instead of 3, plus 2 Ad Detective cases a day'], - ['Gem Kingdom', 'one free continue every day'], - ['Spooky Doors', 'one extra door every day'], - ['ClutterHunt', '2 bonus hints every day'], - ['SpellWheel', 'daily streak pays 0.30 POL instead of 0.15, plus 1 free hint a day'], - ['PolyBreak', 'daily gem limit 1.5 POL instead of 0.5, plus an extra paddle every round'], - ['PolyWarriors', 'a 4th daily mission, and defense pays 25 Circuits instead of 15'], - ['Drip Runner', 'a free shield at the start of every run'], - ['Road Agent', '2 patrols a day and 25% more scrap'] - ]; - function gpPerksHtml() { - return '

What you get

' - + '' - + '' - + '
Every gameDaily POL caps of 1.50 a day on repeatable rewards (free play 0.30) and 5 a day in all (free play 2), counted across all nine games
WeeklyA seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays
BadgeThe gold Game Pass badge with your name, to share or post
' - + '

In each game

' - + GP_PERKS.map(p => '').join('') + '
' + p[0] + '' + p[1] + '
' - + '

The Pass never changes how much a reward pays: it lets you play and collect more each day.

'; - } - async function loadGamePassCard(highlight) { - const card = $('gpCard'); if (!card) return; - let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} - if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; } - if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); - // Five Dollar Friday + the pass (Marty 2026-10-23): the package that starts the pass also gets the Friday bonus, so say so on Fridays - let fdf = ''; try { const f = await (await fetch('/api/friday')).json(); if (f && f.on && f.live) { const base = gp.price || 500, got = Math.round(base * (1 + (Number(f.pct) || 20) / 100)); - fdf = '

\u{1F383} It\u2019s Five Dollar Friday. The $' + (gp.usd || 5) + ' package that starts your pass gets +' + (Number(f.pct) || 20) + '% too, so you get the ' + (gp.days || 7) + '-day pass and keep ' + got.toLocaleString() + ' ad credits. Tap Get the Pass first, then buy the package.

'; } } catch (e) {} // a tier above weekly on sale (or admin preview, or a holder) - const caps = gp.caps || {}; const price = gp.price || 500; - const state = gp.active ? 'Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '' - : gp.waiting ? 'Waiting for a $' + (gp.usd || 5) + ' package' : 'Not active'; - const capsLine = caps.enforced - ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' - : gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.' - : 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.'; - card.hidden = false; card.classList.toggle('gp-hl', !!highlight); - card.innerHTML = '

\u{1F39F}\uFE0F Game Pass

$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games
' - + '

' + state + '

' - + fdf - + '

Free play pays real POL every day. The Pass plays more: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly Pass Tournament with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.

' - + gpPerksHtml() - + '

' + capsLine + '

' - + (gp.waiting ? '

Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.

' : '') - + '

' - + (gp.waiting ? '' : '') - + 'Paid by a new $' + (gp.usd || 5) + ' or bigger package, so your sponsor and team are paid. You keep the package credits for your ads; credits you already hold never buy a pass.

'; - const b = $('gpBuy'); if (b) b.addEventListener('click', async () => { - const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + '? The Pass is paid by a new package purchase of $' + (gp.usd || 5) + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the Pass starts the moment it settles. Credits you already hold never buy a pass.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' }); - if (!yes) return; - b.disabled = true; - try { - const r = await api('/api/my/gamepass/buy'); - if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'ok'); setPane('buy'); return; } - IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok'); - await loadGamePassCard(true); - try { await loadDashboard(); } catch (e) {} // unlocks the Game Pass badge at once (toast + team post) - } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } - }); - const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy')); - if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } - } - // Overview nudge: a game reported this member hit the free cap (polgrant lastCapHit). Shown once a day per browser, never to pass holders. - async function loadGpNudge() { - const card = $('gpNudge'); if (!card) return; - if (cardHidden('gpnudge')) { card.hidden = true; return; } - let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} - if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; } - const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' }; - card.hidden = false; - card.innerHTML = '

\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '

free play keeps paying; the Pass plays more
' - + '

Every member earns real POL in the games up to the daily cap. The Game Pass raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with a new package), adds the weekly Pass Tournament and a perk in every game.

' - + ''; - $('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1')); - try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day - cardDismiss(card, 'gpnudge'); - } - loadGpNudge(); - // launch-day surprise (Marty, 2026-09-20): PolHunter appears at siteConfig.launchAt, not a minute before. - // The card and the menu entry flip on their own if the dashboard is already open. - let phShown = false; - const LAUNCH_CARD_DAYS = 7; - async function launchReveal() { - try { - const nav = $('polhunterNav'); if (nav) nav.hidden = false; // listed in the menu from launch morning (Marty, 2026-09-21); the card below is the announcement and waits for launchAt - const cfg = await IAP.getConfig(); const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; - if (!at || Date.now() < at) return; - // launch cards retire 7 days after launch (Marty, 2026-10-03: old announcements kept stacking up) - if (Date.now() > at + LAUNCH_CARD_DAYS * 86400000) { const c = $('phLaunch'); if (c) c.hidden = true; return; } - const card = $('phLaunch'); if (!card || phShown) return; - if (cardHidden('phLaunch')) { card.hidden = true; return; } - phShown = true; card.hidden = false; - card.innerHTML = '

\u{1F3AF} New today: PolHunter

Launch-day surprise
' - + '

Missions across our sites. Visit the site, find your personal code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in the wallet on this account, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly POL prizes, and badge cards you can share. Your PolHunter share link puts sign-ups on your InstantAdPay line.

' - + 'Open my PolHunter board The teaser'; - const tb = $('phTrain'); if (tb) tb.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="training"]'); if (m) m.click(); }); - cardDismiss(card, 'phLaunch'); - } catch (e) {} - } - launchReveal(); setInterval(launchReveal, 30000); - // came from PolHunter (iap.return cookie): one card at the top of the Overview that sends them back - // Games hub (2026-10-01): one card per game, the player's own progress where the game reports it - // PassiveDrip, our earning site: a card on the Earn tab (not a game, Marty 2026-10-01) - async function loadPdCard() { - const card = $('pdCard'); if (!card) return; - let j = null; try { j = await (await fetch('/api/my/passivedrip/card')).json(); } catch (e) {} - if (!j || !j.show) { card.hidden = true; return; } - card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || ''; - } - async function loadGames(q) { - const el = $('gamesGrid'); if (!el) return; - loadGamePassCard(/(^|&)pass=1(&|$)/.test(q || '')).catch(() => {}); - let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {} - const list = (g && g.games) || []; - if (!list.length) { el.innerHTML = '

No games are open yet. Check back soon.

'; return; } - // a seasonal card (x.season, 2026-10-02) wears the pink limited-time ribbon from the Spooky Doors UI kit - el.innerHTML = list.map(x => '
' + (x.soon ? '' : x.season && x.season.ends ? 'Limited time \u00b7 ends ' + esc(x.season.ends) + '' : '') + '
' + esc(x.tag || '') + '

' + esc(x.name) + (x.preview ? '' + esc(x.previewNote || 'preview, not live') + '' : '') + '

' + esc(x.blurb) + '

' + (x.progress && x.progress.line ? '
' + esc(x.progress.line) + '
' : '') + '

Pays: ' + esc(x.pays || 'POL') + '

' + (x.perk ? '

Members get ' + esc(x.perk) + '

' : '') + (x.soon ? '' + esc(x.soon) + '' : '' + esc(x.cta || 'Play') + '') + '
').join(''); - } - async function loadReturnCard() { - const card = $('phReturn'); if (!card) return; - if (cardHidden('phReturn')) { card.hidden = true; return; } - try { - const me = await (await fetch('/api/me')).json(); - if (me.returnTo !== 'polhunter') { card.hidden = true; return; } - card.hidden = false; - card.innerHTML = '

You came from PolHunter

' + (me.address - ? '

Your wallet is linked, so your board is ready.

Back to PolHunter' - : '

One step left: link the wallet your POL drips will be paid to. The moment it is linked you go straight back.

'); - const b = $('phGoWallet'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="wallet"]'); if (m) m.click(); }); - cardDismiss(card, 'phReturn'); - } catch (e) {} - } - async function loadCoach() { - loadReturnCard(); - loadTank(); - try { - const r = await (await fetch('/api/my/coach')).json(); - const el = $('coachList'); if (!el || r.error) return; - const d = r.directs || []; - $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; - if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } - el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') - + (x.polWaiting ? ' ' + x.polWaiting.toFixed(2) + ' POL waiting · no wallet' : '') - + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' - + '' + esc(x.label) + ' → ' + esc(x.next) + '' - + 'rung ' + x.rung + '/6' - + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' - + '' - + (x.address ? ' ' : '') - + (x.free && x.rescue ? ' ' : '') - + (x.free ? ' ' : '') + '
').join(''); - pageList('coach', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { - await openConvo(b.dataset.nudge, b.dataset.nname); - const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } - })); - el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; - try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - // schedule chips on the campaign table (local time) + by-hour view bars - const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - // featured run column: days left of the booked total (Hugh, 2026-09-16: "says 14 but it's actually 7") - function featRun(c) { - const total = Number(c.body || 0), now = Date.now(); - if (c.status === 'done' || !c.expires || c.expires <= now) return '' + total + ' day' + (total === 1 ? '' : 's') + ' done'; - const left = Math.max(1, Math.ceil((c.expires - now) / 86400000)); - return '' + left + ' of ' + total + ' day' + (total === 1 ? '' : 's') + ' left'; - } - function schedChips(c) { - const now = Date.now(); let s = ''; - if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; - if (c.expires && c.type === 'featured') { const day = new Date(c.expires - 1).toLocaleDateString([], { month: 'short', day: 'numeric' }); s += ' ' + (c.expires > now ? 'runs through ' : 'ran through ') + day + ''; } - else if (c.expires) s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; - return s; - } - function geoLine(rows) { - if (!rows || !rows.length) return ''; - return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; - } - function hourBars(utc) { - if (!utc || !utc.some(n => n)) return ''; - // rotate the 24 UTC buckets into the viewer's local hours - const local = new Array(24).fill(0); - for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; - const max = Math.max(...local); - const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); - return '
' + local.map((n, h) => - '').join('') - + '
views by hour · last 7 days · your time
'; - } - // ── link stats: views, joins, buyers per angle ── - async function loadLinkStats() { - try { - const r = await (await fetch('/api/my/linkstats')).json(); - const t = $('linkStatsTable'); if (!t || r.error) return; - const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); - if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } - t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' - + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : a.angle === 'page' ? 'any page (viral link)' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); - const st = $('linkSrcTable'); - if (st) { - const src = (r.sources || []).filter(x => x.views || x.joins); - st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' - + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') - : 'Sources appear as visits arrive.'; - pageList('linksrc', st.parentElement, 'table tr:has(td)', { per: LINE_PER }); - } - pageList('linkangles', t.parentElement, 'table tr:has(td)', { per: LINE_PER }); - } catch (e) {} - } - // ── prospects: the member's own follow-up list ── - let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; - // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── - let PIPE = null, PIPE_KEY = null; - const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; - const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; - function pipeCardHtml(c, showStage) { - const today = new Date(); today.setHours(23, 59, 59, 999); - const due = c.followUp && c.followUp <= today.getTime(); - const chips = []; - if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); - if (due) chips.push('follow up'); - else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); - if (c.tag) chips.push('' + esc(c.tag) + ''); - if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); - const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; - return '
' - + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' - + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' - + (c.note ? '
' + esc(c.note) + '
' : '') - + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; - } - async function loadPipeline() { - try { - const r = await (await fetch('/api/my/pipeline')).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - if (!r.live) { - $('pipeSoon').hidden = false; $('pipeLive').hidden = true; - $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; - return; - } - PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; - const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } - $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; - $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; - $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; - $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); - $('pipeBoard').querySelectorAll('.pipe-col').forEach((col, i) => pageList('pipe-' + i, col, ':scope > [data-pk]')); - $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { - el.addEventListener('click', () => openPipeCard(el.dataset.pk)); - el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); - }); - if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } - } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } - } - function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } - function fillPipeCard(c) { - $('pipeCardName').textContent = c.name; - const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; - $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); - $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); - const say = (c.say || '').replace('{{link}}', pipeInvite()); - $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; - $('pipeSend').hidden = c.kind !== 'member' || !c.email; - $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; - const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); - $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; - $('pipeCard').hidden = false; - } - function openPipeCard(key) { - const c = allPipeCards().find(x => x.key === key); if (!c) return; - PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); - fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); - } - if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); - if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { - if (!PIPE_KEY) return; - try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } - catch (e) { IAP.status(e.message, 'bad'); } - }); - if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); - if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { - const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; - openConvo(c.email, c.name); - const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } - }); - async function loadProspects() { - try { - const r = await (await fetch('/api/my/prospects')).json(); - if (r.error) return; - PP_STATUSES = r.statuses || PP_STATUSES; - const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); - const list = r.prospects || []; const el = $('prospectList'); if (!el) return; - if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } - const today = new Date(); today.setHours(0, 0, 0, 0); - el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' - + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' - + '' - + '' - + '
'; }).join(''); - const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; - pageList('prospects', el, ':scope > .lin-row', { per: LINE_PER }); - el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); - el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); - el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); - } catch (e) {} - } - if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { - e.preventDefault(); - try { - await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); - $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); - } catch (err) { IAP.status(err.message, 'bad'); } - }); - // ── broadcast templates ── - const BC_TEMPLATES = [ - { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, - { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, - { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, - { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, - { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } - ]; - (function () { - const w = $('bcTemplates'); if (!w) return; - w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); - w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); - })(); - // ── Qualified Start calculator ── - (function () { - const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; - const CR = { 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 }; - const calc = () => { - const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 20; - const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); - const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; - out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' - + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; - }; - n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); - })(); - - // ── downline lineage + sponsor broadcast + upline messages ── - async function loadLineage() { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineageWrap'); - if (r.error || !r.levels || !r.levels.every) return; - if (!r.levels.length || !r.levels.some(L => L.members.length)) { - el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; - return; - } - LINE_DATA = r; renderLineage(el); - } catch (e) {} - } - let LINE_DATA = null; - function renderLineage(el) { - const r = LINE_DATA; if (!r) return; - try { - const all = r.levels.reduce((n, L) => n + L.members.length, 0); - const shown = r.levels.map(L => ({ level: L.level, members: listApply('line', L.members) })); - const kept = shown.reduce((n, L) => n + L.members.length, 0); - el.innerHTML = ''; - el.appendChild(listBar('line', all, kept, () => renderLineage(el))); - el.insertAdjacentHTML('beforeend', !kept ? '

Nobody in your downline matches those filters.

' : shown.map(L => !L.members.length ? '' : - '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' - + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' - + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '' + memberChips(m) + '') + '' - + '' - + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' - + '' + new Date(m.joined).toLocaleDateString() + '' - + (m.email ? '' : '') - + (m.ref && !m.own ? '' : '') - + '
' + (m.ref && !m.own ? '' : '')).join('') - + '
').join('')); - el.querySelectorAll('[data-cemail]').forEach(b => - b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); - el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); - const focusRef = LINE_FOCUS_REF ? LINE_FOCUS_REF.replace(/"/g, '') : null; - el.querySelectorAll('.lin-lvl').forEach((lv, i) => pageList('line-' + i, lv, ':scope > .lin-row', { per: LINE_PER, tail: '.lin-act', focus: focusRef ? row => !!row.querySelector('[data-act="' + focusRef + '"]') : null })); - if (LINE_FOCUS_REF) { - const ref = LINE_FOCUS_REF; LINE_FOCUS_REF = null; - const b = el.querySelector('[data-act="' + ref.replace(/"/g, '') + '"]'); - if (b) { const row = b.closest('.lin-row'); if (row) { row.classList.add('lin-focus'); setTimeout(() => row.classList.remove('lin-focus'), 4000); } toggleLineActivity(b); setTimeout(() => (row || b).scrollIntoView({ behavior: 'smooth', block: 'center' }), 150); } - } - } catch (e) {} - } - // who is working: per-member activity drop-down under the row (any of the three levels) - const lineActCache = {}; - async function toggleLineActivity(btn) { - const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; - const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; - if (!open) return; - if (!lineActCache[btn.dataset.act]) { - box.innerHTML = 'Loading…'; - try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } - } - const a = lineActCache[btn.dataset.act]; - if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } - const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; - const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; - const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); - box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) - + chip('Joined', new Date(a.joined).toLocaleDateString()) - + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') - + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') - + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') - + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') - + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') - + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') - + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') - + '' + (working ? 'Working' : 'Quiet') + ''; - } - async function loadUplineMessages() { - try { - const r = await (await fetch('/api/my/messages')).json(); - if (r.error) return; - const card = $('upMsgCard'), list = $('upList'); - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - list.innerHTML = r.items.map(i => '
' - + '
' + esc(i.subject) + '' - + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' - + '
' + (i.body || '') + '
').join(''); - pageList('upmsg', list, ':scope > .promo-block', { per: 5 }); - // opening the pane marks them read - for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); - } catch (e) {} - } - // broadcast composer editor (its own small rich editor, server sanitizes) - document.querySelectorAll('[data-bc]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); - document.querySelectorAll('[data-bcblock]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); - if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; - const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } - }); - // broadcast send (2026-10-05, Brian: "clicking send didn't give me anything to feel it was sent"): a pop-up either way, - // and an expired sign-in keeps the draft so nothing typed is lost - const BC_DRAFT = 'iap.bcDraft'; - try { const d = JSON.parse(localStorage.getItem(BC_DRAFT) || 'null'); if (d && $('bcSubject') && !$('bcSubject').value) { $('bcSubject').value = d.subject || ''; $('bcEd').innerHTML = d.body || ''; if ($('bcScope') && d.scope) $('bcScope').value = d.scope; localStorage.removeItem(BC_DRAFT); } } catch (e) {} - if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', async () => { - const btn = $('bcSendBtn'); btn.disabled = true; const label = btn.textContent; btn.textContent = 'Sending…'; - try { - const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); - $('bcSubject').value = ''; $('bcEd').innerHTML = ''; - $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; - await IAP.confirmBox('Your broadcast was delivered to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + ' in your line. They see it in their Messages, and get a copy by email. You can send your next broadcast in 24 hours.', { title: '✅ Broadcast sent', ok: 'Done', noCancel: true }); - } catch (e) { - const msg = (e && e.message) || String(e); - if (/sign in/i.test(msg)) { - try { localStorage.setItem(BC_DRAFT, JSON.stringify({ subject: $('bcSubject').value, body: $('bcEd').innerHTML, scope: $('bcScope').value })); } catch (x) {} - if (await IAP.confirmBox('Your sign-in expired, so the broadcast was NOT sent. Your message is saved: sign in again and it will be waiting for you here.', { title: 'Not sent yet', ok: 'Sign in again', cancel: 'Close' })) location.href = '/my#line'; - } else { - await IAP.confirmBox(msg + ' Your message is still in the box.', { title: 'Broadcast not sent', ok: 'OK', noCancel: true }); - } - } finally { btn.disabled = false; btn.textContent = label; } - }); - - // ── solo-ads inbox: list, read view, dwell-gated read reward ── - let ibTimer = null; - function setInboxBadge(n) { - for (const id of ['inboxBadge', 'inboxBadge2']) { - const b = $(id); - if (b) { b.hidden = !n; b.textContent = n; } - } - } - // Earn credits sub-tabs: Watch ads | Inbox - let earnSub = 'watch'; - function setEarnSub(which) { - earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; - if (earnSub !== 'videos' && vidState.token) stopVideo(); - const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); - if (w) w.hidden = earnSub !== 'watch'; - if (i) i.hidden = earnSub !== 'inbox'; - if (v) v.hidden = earnSub !== 'videos'; - if (vs) vs.hidden = earnSub !== 'visits'; - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.classList.toggle('on', b.dataset.earn === earnSub)); - if (earnSub === 'inbox') loadInbox(); - else if (earnSub === 'videos') loadVideoStatus(); - else if (earnSub === 'visits') loadVisitStatus(); - else earnRefresh(); - } - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.addEventListener('click', () => setEarnSub(b.dataset.earn))); - // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) - let tkState = null; - async function loadToolkit() { - try { - const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; - $('tkTierLine').textContent = 'you are at ' + names[r.tier]; - $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); - $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; - if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } - $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; - $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; - if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } - renderTkTools(r); - $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; - } catch (e) { console.error('toolkit', e); } - } - // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops - const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; - async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } - function renderTkTools(r) { - const at = tkRank[r.tier] || 0; - // Spark - const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; - if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; - else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } - // Circuit - const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; - if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; - else { loadTkVideos(r); loadTkSplit(); } - // Nexus - const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; - if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; - else { loadTkTeam(); renderTkPartner(r); } - } - let tkVidTimer = null; - async function loadTkVideos(r) { - const box = $('tkVideos'); - if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } - if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } - try { - const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; - box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); - clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); - } catch (e) {} - } - async function loadTkSplit() { - try { - const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; - const rows = sp.rows.filter(x => x.views || x.joins); - $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' - : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; - } catch (e) {} - } - let tkTeamData = null; - async function loadTkTeam() { - try { - const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; - $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; - const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); - $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') - + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); - $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); - } catch (e) {} - } - function renderTkPartner(r) { - const pk = r.partner; - $('tkPartner').innerHTML = pk - ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' - : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; - } - document.addEventListener('click', async ev => { - const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; - if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } - if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } - if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } - if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } - if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } - if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } - if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } - if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } - }); - $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); - async function tkSendBroadcast() { - const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); - const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); - if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; - const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); - if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); - } - async function tkGenerate() { - const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; - try { - const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; - IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); - loadToolkit(); loadDashboard(); - } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } - finally { btn.disabled = false; btn.textContent = 'Write it'; } - } - if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } - // promo tools: pill menu switches between posts / swipes / banners / wall / videos - function setPromoSub(name) { - const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'games']; - if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06) - if (name === 'toolkit') loadToolkit(); - const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]'); - if (!ids.includes(name) || !pill || pill.hidden) name = 'posts'; - ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { - b.classList.toggle('on', b.dataset.promo === name); - b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); - }); - try { localStorage.setItem('iap.promoSub', name); } catch (e) {} - } - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => - b.addEventListener('click', () => setPromoSub(b.dataset.promo))); - try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } - async function loadInbox() { - try { - const r = await (await fetch('/api/my/inbox')).json(); - if (r.error) return; - $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' - + r.readCap + ' rewarded reads a day)'; - const el = $('ibList'); - $('inboxReadCard').hidden = true; - $('inboxListCard').hidden = false; - setInboxBadge(r.unread); - if (!r.items.length) { - el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; - return; - } - el.innerHTML = ''; - for (const i of r.items) { - const d = document.createElement('div'); - d.className = 'ib-row' + (i.read ? '' : ' unread'); - d.innerHTML = '' - + (i.rewarded ? 'claimed' : i.read ? '' : 'new') - + '' + new Date(i.delivered).toLocaleDateString() + ''; - d.querySelector('.sub').textContent = i.subject || '(no subject)'; - d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); - d.addEventListener('click', () => openInboxItem(i.id)); - el.appendChild(d); - } - } catch (e) {} - } - async function openInboxItem(id) { - try { - const r = await (await fetch('/api/my/inbox/' + id)).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('inboxListCard').hidden = true; - $('inboxReadCard').hidden = false; - $('ibSubject').textContent = r.subject || '(no subject)'; - $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); - $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit - const mv = $('ibMedia'); - mv.hidden = !r.mediaUrl; - mv.innerHTML = !r.mediaUrl ? '' - : r.mediaType === 'video' - ? '' - : 'attachment'; - // the read reward needs BOTH the dwell AND an actual click-through to the - // advertiser — the visit is what makes the ad worth the sender's credits - const visit = $('ibVisit'); - visit.href = r.url; - visit.textContent = r.ctaLabel || 'Learn more'; - visit.target = '_blank'; - const btn = $('ibClaimBtn'); - clearInterval(ibTimer); - if (r.rewarded) { - btn.hidden = true; - visit.classList.remove('cta-need'); - $('ibHint').textContent = 'Read reward already claimed for this one.'; - return; - } - let dwellDone = false; - let visited = !!r.visited; - btn.hidden = false; - btn.disabled = true; - visit.classList.toggle('cta-need', !visited); - let left = r.dwell; - const refresh = () => { - if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } - if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } - btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; - }; - $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; - refresh(); - // countdown pauses off-tab; the server separately enforces the dwell on its own clock - ibTimer = setInterval(() => { - if (!tabActive()) return; - left -= 1; - if (left > 0) { refresh(); return; } - clearInterval(ibTimer); - dwellDone = true; - refresh(); - }, 1000); - // clicking the CTA records the visit (and counts the advertiser's click) - visit.onclick = async () => { - visited = true; - visit.classList.remove('cta-need'); - try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} - refresh(); - }; - btn.onclick = async () => { - try { - const c = await api('/api/my/inbox/' + id + '/claim'); - IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); - btn.hidden = true; - $('ibHint').textContent = 'Claimed. Head back for the next one.'; - loadDashboard(); - } catch (e2) { IAP.status(e2.message, 'bad'); } - }; - } catch (e) {} - } - $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); - - // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── - function fillPromo(link, me) { - if (window.IAPPromo) IAPPromo.fill(link, me || {}); - // banner kit - const bwrap = $('promoBanners'); - if (bwrap && !bwrap.dataset.filled) { - bwrap.dataset.filled = '1'; - // one collapsed accordion per size / use, so the kit stays scannable as it grows - const GROUPS = [ - { title: 'Stop chasing shiny objects · share the article with your link', bridge: { page: 'blog/stop-chasing-shiny-objects', name: 'shiny-objects article', short: 'article' }, items: [ - { file: 'iap-shiny-objects-wide-1200x630.jpg', size: '1200×630 · the article cover (widescreen art) · Facebook, X, link previews' }, - { file: 'iap-shiny-objects-wide-1600x896.jpg', size: '1600×896 · full widescreen art · YouTube community, LinkedIn, blogs' }, - { file: 'iap-shiny-objects-1200x630.jpg', size: '1200×630 · tight crop of the portrait art' }, - { file: 'iap-shiny-objects-1080x1080.jpg', size: '1080×1080 · square · Instagram, Facebook, Telegram' }, - { file: 'iap-shiny-objects-1080x1349.jpg', size: '1080×1349 · portrait · Instagram feed, Pinterest' } ] }, - { title: 'Wired Wednesday · share with your /wednesday link', bridge: { page: 'wednesday', name: 'Wired Wednesday', short: 'Wednesday' }, items: [ - { file: 'iap-wired-wednesday-1200x630.jpg', size: '1200×630 · Wired Wednesday · social card, link previews, Daily News' }, - { file: 'iap-wired-wednesday-1080x1080.jpg', size: '1080×1080 · Wired Wednesday · Instagram, Facebook, Telegram' }, - { file: 'iap-wired-wednesday-728x90.png', size: '728×90 · Wired Wednesday · leaderboard' }, - { file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' } ] }, - { title: 'Five Dollar Friday · share with your /friday link', friday: true, items: [ - { file: 'iap-five-dollar-friday-october-1200x630.jpg', size: '1200×630 · Five Dollar Friday · October porch, bright' }, - { file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' }, - { file: 'iap-five-dollar-friday-v2-1200x630.jpg', size: '1200×630 · Five Dollar Friday · loft, Central-time window' }, - { file: 'iap-five-dollar-friday-dark-1200x630.jpg', size: '1200×630 · Five Dollar Friday · dark studio' }, - { file: 'iap-five-dollar-friday-v2-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · square for Instagram and feeds' } ] }, - { title: '600×300 · traffic exchanges and splash pages', items: [ - { file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' } ] }, - { title: '1200×630 · social posts, link previews, Daily News covers', items: [ - { file: 'iap-hero-1200x630.png', size: '1200×630 · hero · advertise and earn' }, - { file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' }, - { file: 'iap-team-build-tiers-1200x630.jpg', size: '1200×630 · team build and instant payments · 50 / 20 / 10 tiers' }, - { file: 'iap-team-build-tiers-v2-1200x630.jpg', size: '1200×630 · team build and instant payments · variant 2' }, - { file: 'iap-instant-payments-tiers-1200x630.jpg', size: '1200×630 · instant payments, direct commissions · tiers' }, - { file: 'iap-instant-payments-tiers-v2-1200x630.jpg', size: '1200×630 · instant payments · variant 2' }, - { file: 'iap-multistream-info-1200x630.jpg', size: '1200×630 · multi-stream revenue · "INFO or message me" CTA' }, - { file: 'iap-multistream-info-v2-1200x630.jpg', size: '1200×630 · multi-stream revenue · variant 2' }, - { file: 'iap-success-path-info-1200x630.jpg', size: '1200×630 · success path, training and coaching · "INFO or message me" CTA' }, - { file: 'iap-success-path-link-1200x630.jpg', size: '1200×630 · success path · "link in the description" (feed posts, Daily News)' }, - { file: 'iap-success-path-coaching-1200x630.jpg', size: '1200×630 · success path · quality network traffic' } ] }, - { title: 'Five Dollar Friday · every Friday, +20% credits on any $5+ pack', items: [ - { file: 'iap-five-dollar-friday-1200x630.jpg', size: '1200×630 · social card, Daily News, feed posts' }, - { file: 'iap-five-dollar-friday-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' }, - { file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' }, - { file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' } ] }, - { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ - { file: 'iap-1080x1080.png', size: '1080×1080 · square' }, - { file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] }, - { title: '1280×720 · Telegram and group posts', items: [ - { file: 'iap-1280x720.png', size: '1280×720 · group post' } ] }, - { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ - { file: 'iap-728x90.png', size: '728×90 · leaderboard' }, - { file: 'iap-advertise-earn-728x90.png', size: '728×90 · advertise and earn instantly · Join free' }, - { file: 'iap-ledger-728x90.png', size: '728×90 · advertising that pays you on-chain · See the ledger' }, - { file: 'iap-468x60.png', size: '468×60 · banner' }, - { file: 'iap-ledger-468x60.png', size: '468×60 · advertising that pays you on-chain · See the ledger' }, - { file: 'iap-320x50.svg', size: '320×50 · mobile leaderboard' } ] }, - { title: 'Rectangles and buttons · 336×280, 300×250, 125×125', items: [ - { file: 'iap-336x280.png', size: '336×280 · large rectangle' }, - { file: 'iap-advertise-earn-336x280.png', size: '336×280 · advertise and earn instantly' }, - { file: 'iap-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' }, - { file: 'iap-300x250.png', size: '300×250 · rectangle' }, - { file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' }, - { file: 'iap-team-build-link-300x250.jpg', size: '300×250 · team build and instant payments · "link in the description"' }, - { file: 'iap-125x125.png', size: '125×125 · square button' } ] }, - { title: 'Skyscrapers · 160×600, 120×600', items: [ - { file: 'iap-160x600.png', size: '160×600 · wide skyscraper' }, - { file: 'iap-120x600.png', size: '120×600 · skyscraper' } ] } - ]; - bwrap.innerHTML = ''; - for (const g of GROUPS) { - const det = document.createElement('details'); - det.className = 'pb-acc'; - det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; - const grid = det.querySelector('.pb-grid'); - const bridge = g.bridge || (g.friday ? { page: 'friday', name: 'Five Dollar Friday', short: 'Friday' } : null); - if (bridge) { - // the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie - const inv = (document.getElementById('inviteLine') || {}).textContent || ''; - const fl = inv.replace(/\/join\/([^/?#]+).*$/, '/' + bridge.page + '?ref=$1'); - const note = document.createElement('div'); - note.className = 'pb-note'; - note.innerHTML = 'Post any of these with your ' + esc(bridge.name) + ' link: '; - note.querySelector('b').textContent = fl; - const cp = document.createElement('button'); cp.className = 'btn small'; cp.textContent = 'Copy my ' + bridge.short + ' link'; - cp.addEventListener('click', async () => { try { await navigator.clipboard.writeText(fl); IAP.status(bridge.short + ' link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } }); - note.appendChild(cp); - grid.before(note); - } - for (const b of g.items) { - const url = location.origin + '/banners/' + b.file; - const d = document.createElement('div'); - d.className = 'pb-item'; - d.innerHTML = 'InstantAdPay banner ' + b.size + '' - + '
' + b.size + '
'; - const dl = document.createElement('a'); - dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/banners/' + b.file; dl.setAttribute('download', b.file); - d.querySelector('.pb-row').appendChild(dl); - const btn = document.createElement('button'); - btn.className = 'btn small sec'; - btn.textContent = 'Copy image URL'; - btn.addEventListener('click', async () => { - try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } - catch (e) { IAP.status('Copy failed.', 'bad'); } - }); - d.querySelector('.pb-row').appendChild(btn); - grid.appendChild(d); - } - bwrap.appendChild(det); - } - } - } - - // ── profile ── (busy2 defers the busy lookup past its TDZ) - $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { - const r = await api('/api/my/profile', { username: $('pfUsername').value }); - IAP.status('You are @' + r.account.username + ' now.', 'ok'); - await render(); - })); - - // ── in-dashboard package buying ── - const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' }; - // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own - // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page - // otherwise. The site never touches funds — MoonPay is merchant of record. - async function openMoonpay(pol) { - try { - let addr = ''; - try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} - const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); - const r = await (await fetch(q)).json(); - if (r && r.url) { - window.open(r.url, '_blank', 'noopener'); - IAP.status(r.signed - ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' - : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); - } - } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } - } - // ── linked positions (Qualified Start) ── - const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; - let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) - async function loadPositions(me) { - try { - const r = await (await fetch('/api/my/positions')).json(); - if (r.error) return; - const list = r.positions || []; - const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' - + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' - + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' - + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' - + (!p.memberId ? '' : '') - + '
').join(''); - const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' - + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' - + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' - + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; - const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); - if ($('qsList')) $('qsList').innerHTML = html; - // Wallet tab: live POL balance of the linked wallet, and which package it covers - const wb = $('walletBal'); - if (wb && r.main && r.main.address && r.main.balanceWei != null) { - const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; - const usd = r.polUsd ? polN * r.polUsd : 0; - const pkgs = [5, 20, 50, 100, 250]; - const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; - wb.hidden = false; - wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') - + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); - } - if ($('posList')) $('posList').innerHTML = html; - if ($('posCard')) $('posCard').hidden = !list.length; - // "Buy from" picker: main + every position - const sel = $('buyFrom'); - if (sel) { - const keep = sel.value; - sel.innerHTML = '' - + list.map((p, i) => '').join(''); - noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); - if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; - $('buyFromWrap').hidden = !list.length; - } - document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; - try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); - if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); - if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; - IAP.status('Pick the new account in your wallet, then sign once…'); - const r = await IAPWallet.signIn({ asPosition: true, pick: true }); - $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; - IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); - await loadPositions(); - const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); - try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} - })); - async function loadBuyTiles() { - try { - const { products } = await (await fetch('/api/catalog')).json(); - const wrap = $('boTiles'); - wrap.innerHTML = ''; - products.sort((a, b) => a.priceCents - b.priceCents); - for (const p of products) { - const bonus = p.creditAmount - p.priceCents; - const div = document.createElement('div'); - div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); - div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' - + '
$' + Math.round(p.priceCents / 100) + '
' - + '
' + p.creditAmount.toLocaleString() + ' credits
' - + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' - + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' - + ''; - wrap.appendChild(div); - } - wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { - try { - b.disabled = true; - // the buyer's credits are read by the member id of their LINKED wallet. - // If they only connected a wallet (e.g. for the faucet) but never linked - // it, link it first (one signature) so the purchase's credits show up. - // retry these through transient failures — mobile drops in-flight - // fetches when the page returns from the wallet app-switch - const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; - const meNow = await jretry('/api/me'); - // which of the member's wallets is buying: the main wallet (default) or a - // linked position (Qualified Start). A position registers under the main - // member id on its first buy, so its sponsor is always this member. - const fromSel = $('buyFrom'); - const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; - if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } - if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } - if (!fromPos && !meNow.address) { - IAP.status('Link your wallet first — one quick signature…'); - await IAPWallet.signIn(); - } - const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); - if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member - await IAPWallet.connect(); - let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); - if (cur !== wantAddr) { - IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); - cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); - } - if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); - } - const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); - if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company - if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok'); - // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any - // transaction that spends most of the balance ("drain your wallet"), so Trust users - // get a heads-up first; other wallets go straight to the confirmation. - try { - const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() - const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); - if (bal < need) { - IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); - return; - } - const pct = Number(need * 100n / bal); - const isTrust = /trust/i.test(IAPWallet.walletName() || ''); - if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { - IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); - return; - } - } catch (e) { /* balance read failed: let the wallet decide */ } - IAP.status('Confirm the purchase in your wallet…'); - const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); - if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); - // a game sent them here to pay (PolyWarriors mint, Gem Kingdom Crowns, Spooky Doors costume): go straight back once it settles (Marty 2026-10-08) - const back = document.getElementById('pwBack') ? ['/pw/mint/resume', 'PolyWarriors'] : document.getElementById('gkBack') ? ['/gk/shop/resume', 'Gem Kingdom'] : document.getElementById('sdBack') ? ['/sd/shop/resume', 'Spooky Doors'] : null; - if (back) { IAP.status('Purchase settled on-chain. Taking you back to ' + back[1] + '…', 'ok'); setTimeout(() => { location.href = back[0]; }, 1800); return; } - IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); - await render(); - loadBuyTiles(); - } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } - finally { b.disabled = false; } - })); - // brand new to crypto? buy POL with a card, sent straight to the wallet - const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; - const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; - const cta = document.createElement('div'); - cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; - cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' - + ' Wallet and MoonPay guide'; - wrap.appendChild(cta); - const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); - } catch (e) {} - } - loadBuyTiles(); - - // ── earn-by-viewing: daily ad set with dwell, then claim ── - const earnState = { types: ['banner', 'text'], i: 0, timer: null }; - async function earnRefresh() { - try { - const st = await (await fetch('/api/my/earn')).json(); - if (st.error) return null; - $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; - loadFridayBank(); - $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); - if ($('earnActLink')) $('earnActLink').onclick = e => { e.preventDefault(); jumpTo('campaigns', 'creditActivity'); }; - const done = st.views >= st.target; - $('earnClaimBtn').hidden = !(done && !st.claimed); - if (st.claimed) { - $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; - // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign - const box = $('earnAdBox'); - if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' - + '
' - + (st.visitsLeft ? '' : '') - + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 - ? '' - : '') + '
'; - if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); - if ($('earnStartBtn')) $('earnStartBtn').hidden = true; - } else { - if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over - $('earnHint').textContent = done - ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' - : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); - } - return st; - } catch (e) { return null; } - } - async function earnShowAd() { - // each view happens full screen in its own tab: /view/ frames the - // advertiser's site, runs the countdown, then a human check credits it - const type = earnState.types[earnState.i++ % earnState.types.length]; - let r = null; - try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} - const box = $('earnAdBox'); - if (!r || !r.ad || !r.viewUrl) { - await earnRefresh(); - box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target - ? 'Set complete for today.' - : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; - return; - } - openAdOverlay(r.viewUrl); - box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; - $('earnStartBtn').textContent = 'View next ad'; - } - // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs - // badly), no window.close needed. The /view page runs the dwell + check inside, - // messages back when it credits or when the user is done. - function openAdOverlay(url) { - closeAdOverlay(); - const back = document.createElement('div'); - back.id = 'adOverlay'; - back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; - const x = document.createElement('button'); - x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); - x.textContent = '✕'; - x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; - x.addEventListener('click', closeAdOverlay); - const ifr = document.createElement('iframe'); - ifr.src = url; - ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; - back.appendChild(ifr); back.appendChild(x); - document.body.appendChild(back); - document.body.style.overflow = 'hidden'; - } - function closeAdOverlay() { - const m = $('adOverlay'); if (m) m.remove(); - document.body.style.overflow = ''; - earnRefresh(); loadDashboard(); - } - window.addEventListener('message', e => { - if (e.origin !== location.origin || !e.data) return; - if (e.data.t === 'iap-view-close') closeAdOverlay(); - else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - $('earnStartBtn').addEventListener('click', () => earnShowAd()); - // the viewer tab pings localStorage when a view credits; refresh instantly - window.addEventListener('storage', e => { - if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); - }); - $('earnClaimBtn').addEventListener('click', async () => { - try { - const r = await api('/api/my/claim'); - IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); - await earnRefresh(); - loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - }); - - const busy = (btn, fn) => async () => { - try { btn.disabled = true; await fn(); } - catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } - finally { btn.disabled = false; } - }; - - // passwordless (feature-flagged on config.emailAuth): code replaces passwords - (async () => { - const cfg = await IAP.getConfig(); - if (!cfg.emailAuth) return; - $('passCards').hidden = true; - $('magicCard').hidden = false; - const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); - const start = busy($('mcSendBtn'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - $('mcCodeRow').hidden = false; - $('mcVerifyBtn').hidden = false; - $('mcSendBtn').hidden = true; - $('mcResend').hidden = false; - if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } - else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); - $('mcCode').focus(); - }); - $('mcSendBtn').addEventListener('click', start); - $('mcResend').addEventListener('click', busy($('mcResend'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - if (r.devCode) $('mcCode').value = r.devCode; - IAP.status('Fresh code sent.', 'ok'); - })); - $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { - const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('You are in.', 'ok'); - if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game - if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - })(); - - // new-member onboarding: choose a username (required), optionally a bio. - // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. - function showOnboard(required) { - return new Promise(resolve => { - const m = $('onboardModal'); if (!m) return resolve(); - m.hidden = false; $('obErr').hidden = true; - $('obSkip').hidden = !!required; - if (required && !$('obUsername').value) { - fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); - } - setTimeout(() => $('obUsername').focus(), 50); - const done = () => { m.hidden = true; resolve(); }; - $('obSkip').onclick = required ? null : done; - $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; - $('obSave').onclick = async () => { - const u = $('obUsername').value.trim(); - if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } - try { - if (u) await api('/api/my/profile', { username: u }); - const bio = $('obBio').value.trim(); - if (bio) await api('/api/my/profile-details', { bio }); - done(); - } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } - }; - }); - } - - $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { - const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('Welcome aboard. You are in.', 'ok'); - if (!(r.account && r.account.username)) await showOnboard(); - await render(); - })); - $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { - await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); - IAP.status('Logged in.', 'ok'); - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { - IAP.status('Check your wallet for the free link signature…'); - const lr = await IAPWallet.signIn(); // server binds the wallet to the signed-in email account - if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to PolHunter…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter: close the loop - IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); - await render(); - })); - if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { - IAP.status('Connect your wallet first…'); - const addr = await IAPWallet.connect(); - let copied = false; - try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} - window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); - $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' - + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; - IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); - })); - if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { - // fire-and-forget: don't gate the reload on disconnect resolving (it can - // stall). The reload drops all in-memory wallet state and the picker returns. - IAPWallet.disconnect().catch(() => {}); - $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; - IAP.status('Disconnecting — reloading…', 'ok'); - setTimeout(() => location.reload(), 900); - })); - // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) - function sponsorHoldText(sp) { - const who = sp.sponsorName || 'your sponsor'; - if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; - if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; - return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; - } - $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } - IAP.status('Confirm the free activation in your wallet…'); - const r = await IAPWallet.activate(me.sponsorId || 0); - if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); - IAP.status('Payouts are on. Your invite link is live.', 'ok'); - await render(); - })); - $('copyInvite').addEventListener('click', async () => { - try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } - }); - $('logoutLink').addEventListener('click', async e => { - e.preventDefault(); - await fetch('/api/auth/logout', { method: 'POST' }); - IAP.status('Logged out.', 'ok'); - await render(); - }); - - // ── welcome tour (viral banner gauntlet): a new member meets their 3-level - // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. - // Same three levels the contract pays — the tour IS the org chart. - async function showGauntlet() { - try { - const g = await (await fetch('/api/my/gauntlet')).json(); - if (!g.pending || !g.slides || !g.slides.length) return false; - const gate = $('gauntGate'); - gate.hidden = false; - for (let i = 0; i < g.slides.length; i++) { - const s = g.slides[i]; - $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); - $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; - $('ggFrame').hidden = false; - $('ggFrame').src = s.targetUrl; - let left = g.dwell || 10; - $('ggTimer').textContent = left + 's'; - await new Promise(done => { - const t = setInterval(() => { - if (!tabActive()) return; - left -= 1; - $('ggTimer').textContent = Math.max(0, left) + 's'; - if (left <= 0) { clearInterval(t); done(); } - }, 1000); - }); - } - $('ggFrame').src = 'about:blank'; - $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done - $('ggTimer').textContent = '✓'; - $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; - $('ggClaim').hidden = false; - await new Promise(done => { - $('ggClaim').onclick = async () => { - try { - const r = await api('/api/my/gauntlet/complete', { token: g.token }); - IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); - } catch (e) { IAP.status(e.message, 'bad'); } - done(); - }; - }); - gate.hidden = true; - $('ggClaim').hidden = true; - return true; - } catch (e) { return false; } - } - - // ── line banner (profile): the member's slot on welcome tours + their wall ── - function fillLineBanner(a) { - if (!a) return; - if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; - if (a.lineBannerUrl) { - $('lbBanner').value = a.lineBannerUrl; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } - $('lbCurrent').textContent = a.lineTargetUrl - ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' - : 'Not set yet. Until you set one, your tour slot is skipped.'; - } - async function loadLineBanner() { - try { - const a = await (await fetch('/api/me')).json(); - fillLineBanner(a); - fillProfileDetails(a); - // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me - let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} - fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); - } catch (e) {} - } - // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── - function fillWallOffers(a) { - if (!a || !$('wallOffersCard')) return; - const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; - const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; - const NEED = [2, 5]; - for (let i = 0; i < 2; i++) { - const o = offers[i] || {}; - const open = unlocked >= i + 2; - $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; - $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; - $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; - $('woSlot' + i).classList.toggle('locked', !open); - } - $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' - : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' - : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; - } - document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); - document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { - const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; - $('woInfo' + i).textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('woInfo' + i).textContent = r.error; } - else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } - } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } - inp.value = ''; - })); - if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { - const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); - const r = await api('/api/my/wall-offers', { offers }); - IAP.status('Wall positions saved.', 'ok'); - await loadLineBanner(); - })); - const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link - function fillProfileDetails(a) { - if (!a) return; - if (a.bio) $('pfBio').value = a.bio; - if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } - let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} - for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; - if (a.username) { - const link = location.origin + '/wall/' + a.username; - $('pfBioLink').textContent = link; - $('pfViewBio').hidden = false; - $('pfViewBio').href = '/wall/' + a.username; - } - } - let pfAvatar; // pending avatar url - $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); - $('pfAvatarFile').addEventListener('change', async () => { - const f = $('pfAvatarFile').files[0]; - if (!f) return; - $('pfAvatarInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } - pfAvatar = r.url; - $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; - const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; - } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } - $('pfAvatarFile').value = ''; - }); - $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { - const body = { bio: $('pfBio').value, socials: {} }; - for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; - if (pfAvatar) body.avatarUrl = pfAvatar; - const r = await api('/api/my/profile-details', body); - IAP.status('Profile saved.', 'ok'); - if (r.account) fillProfileDetails(r.account); - })); - $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); - $('lbFile').addEventListener('change', async () => { - const f = $('lbFile').files[0]; - if (!f) return; - $('lbUpInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } - $('lbBanner').value = r.url; - $('lbUpInfo').textContent = 'Uploaded.'; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } - $('lbFile').value = ''; - }); - $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { - const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); - IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); - if (r.account) fillLineBanner(r.account); - })); - - // ── login ad interstitial: after a successful sign-in the sponsor card - // appears; "Open Ad" loads the sponsor's page INSIDE the gate, under our bar - // (countdown, open-in-new-tab, dashboard button), so the timer and the way - // out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X"). - // Sites that refuse framing open in a new tab instead, with the bar saying - // so; the timer is not paused, the member is expected to be on the ad. - async function showLoginAd() { - try { - const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); - if (!ad || !ad.targetUrl) return; - const gate = $('loginGate'); - const openBtn = $('lgOpen'); - const goBtn = $('lgContinue'); - const timer = $('lgTimer'); - const frame = $('lgFrame'); - const tab = $('lgOpenTab'); - const body = gate.querySelector('.lgate-body'); - const framed = !!(ad.frameable && frame); - $('lgCreative').innerHTML = ad.imageUrl - ? 'sponsor ad' - : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; - $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; - const how = $('lgHow'); - if (how) how.textContent = framed - ? 'The sponsor\'s page opens right here under this bar. The timer counts down at the top; when it hits zero, your dashboard button appears beside it.' - : 'This sponsor\'s site does not allow loading inside a frame, so it opens in a new tab. The timer counts down here; come back to this tab when it hits zero for your dashboard button.'; - timer.hidden = true; - goBtn.hidden = true; - if (tab) tab.hidden = true; - if (frame) { frame.hidden = true; frame.src = 'about:blank'; } - if (body) body.hidden = false; - openBtn.disabled = false; - gate.hidden = false; - await new Promise(done => { - openBtn.onclick = () => { - openBtn.disabled = true; - if (framed) { - frame.src = ad.targetUrl; // the click relay counts it, then redirects inside the frame - frame.hidden = false; - if (body) body.hidden = true; - if (tab) { tab.href = ad.siteUrl || ad.targetUrl; tab.hidden = false; } - $('lgStatus').textContent = 'Today\'s sponsor. Have a look; your dashboard button appears when the timer ends.'; - } else { - window.open(ad.targetUrl, '_blank'); // the click relay counts it - $('lgStatus').textContent = 'The sponsor opened in a new tab (that site does not allow framing). View it and come back; the timer runs here.'; - } - let left = ad.dwell || 10; - timer.hidden = false; - timer.textContent = 'Time remaining: ' + left + 's'; - const t = setInterval(() => { - left -= 1; - if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } - clearInterval(t); - timer.textContent = 'Time is up'; - timer.classList.add('done'); - $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; - goBtn.hidden = false; - }, 1000); - goBtn.onclick = () => done(); - }; - }); - gate.hidden = true; - if (frame) { frame.src = 'about:blank'; frame.hidden = true; } - if (body) body.hidden = false; - $('lgTimer').classList.remove('done'); - } catch (e) {} - } - - // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── - let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; - function chatSync(d) { - CHAT_ME = d.email || CHAT_ME; - CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; - const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; - setChatBadge(d.chatUnread || 0); - CHAT_LAST_UNREAD = d.chatUnread || 0; - const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; - // Overview quick action + My line card: message-your-sponsor entry points - const qs = $('qaMsgSponsor'); - if (qs) { - if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } - else qs.hidden = true; - } - const card = $('sponsorMsgCard'); - if (card) { - card.hidden = !CHAT_SPONSOR; - if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; - } - } - function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } - function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } - function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } - // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) - function autoGrow(el) { - const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); - const dragged = Number(el.dataset.dragged || 0); - el.style.height = 'auto'; - el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; - } - function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } - - async function openThreads() { - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; - $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; - $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; - stopPoll(); CHAT_OTHER = null; - $('chatThreads').innerHTML = '

Loading…

'; - try { - const r = await (await fetch('/api/my/chat/threads')).json(); - const list = r.threads || []; - // always offer "message your sponsor" up top when they have one and no thread yet - const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); - const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) - ? '
' - + '' - + '
' + esc(CHAT_SPONSOR.name) + '
' - + '
Your sponsor · tap to message
' - : ''; - if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } - $('chatThreads').innerHTML = sponsorRow + list.map(t => - '
' - + '' - + '
' + esc(t.name) + '
' - + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' - + (t.unread ? '' + t.unread + '' : '') + '
').join(''); - $('chatThreads').querySelectorAll('.chat-thread').forEach(el => - el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); - pageList('chat', $('chatThreads'), '.chat-thread'); - } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } - } - - async function openConvo(email, name) { - if (!email) return; - CHAT_OTHER = email; CHAT_LASTID = 0; - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; - $('chatBack').hidden = false; $('chatDot').hidden = false; - $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; - $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; - $('chatInput').disabled = false; $('chatSend').disabled = false; - await pullThread(true); startPoll(); - setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); - } - - function renderMsgs(msgs) { - const box = $('chatMsgs'); if (!box) return; - const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; - for (const m of msgs) { - if (m.id <= CHAT_LASTID) continue; - CHAT_LASTID = Math.max(CHAT_LASTID, m.id); - const d = document.createElement('div'); - d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); - d.textContent = m.body; - const t = document.createElement('span'); t.className = 'ct-time'; - t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); - d.appendChild(t); box.appendChild(d); - } - if (atBottom) box.scrollTop = box.scrollHeight; - } - - async function pullThread(reset) { - if (!CHAT_OTHER) return; - try { - const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); - if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } - if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } - renderMsgs(r.messages || []); - $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); - $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); - CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; - const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; - const blocked = !!r.blocked; - $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; - if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } - else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } - else $('chatBanner').hidden = true; - } catch (e) {} - } - - async function chatSend() { - const inp = $('chatInput'); if (!inp) return; - const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; - $('chatSend').disabled = true; - try { - const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); - inp.value = ''; autoGrow(inp); renderMsgs([r.message]); - const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; - } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } - finally { $('chatSend').disabled = false; inp.focus(); } - } - - async function toggleMute() { - if (!CHAT_OTHER) return; - try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } - catch (e) { IAP.status(e.message, 'bad'); } - } - - (function chatInit() { - if (!$('chatDrawer')) return; - const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; - on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); - on('chatClose', 'click', closeDrawer); - on('chatBack', 'click', openThreads); - on('chatMute', 'click', toggleMute); - on('chatSend', 'click', chatSend); - const inp = $('chatInput'); - if (inp) { - inp.addEventListener('input', () => autoGrow(inp)); - inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); - inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); - } - on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); - on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); - on('chatAvailToggle', 'change', async () => { - const t = $('chatAvailToggle'); - try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } - catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } - }); - // presence heartbeat + new-message notifier: pop + toast when unread rises - setInterval(async () => { - try { - const r = await (await fetch('/api/my/ping')).json(); - const n = r.chatUnread || 0; - if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } - CHAT_LAST_UNREAD = n; setChatBadge(n); - } catch (e) {} - }, 20000); - })(); - - // ad surfaces: a banner greets the sign-in screen; members see live - // banner + text placements inside the back office (they ARE the audience) - IAP.adSlot('banner', 'adSlotLogin'); - IAP.adSlot('banner', 'adSlotOverview'); - IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar - - render(); -})(); - -// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── -(function () { - const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); - if (!btn || !inp) return; - const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; - const go = async () => { - const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } - btn.disabled = true; - try { - const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); - if (r.error) { say(r.error, false); return; } - say(r.step - ? Number(r.now || 0).toLocaleString() + ' credits added now' + (r.partner ? ' from ' + r.partner : '') + '. The rest of the ' + Number(r.credits).toLocaleString() + ' arrive ' + r.step + ' at a time, one for each day you finish your daily ads, for the next 30 days.' - : 'Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); - inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); - } catch (e) { say('Could not apply that code. Try again.', false); } - finally { btn.disabled = false; } - }; - btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); -})(); - -// Friday Bonus Hunts card on the Earn tab (2026-09-26). Hoisted so the Earn loader can call it. -async function loadFridayBank() { - const card = document.getElementById('fbankCard'); if (!card) return; - let b; try { const r = await fetch('/api/my/friday-bank', { credentials: 'same-origin' }); if (!r.ok) return; b = await r.json(); } catch (e) { return; } - const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - const wd = d => WD[new Date(d + 'T12:00:00Z').getUTCDay()]; - document.getElementById('fbankCount').textContent = b.banked + ' banked'; - document.getElementById('fbankDays').innerHTML = (b.days || []).map(d => { - const st = d.banked ? ['#43e8c3', '✓'] : d.future ? ['var(--line-strong)', '·'] : d.day === b.today ? ['#ffb238', '○'] : ['var(--line-strong)', '×']; - return '' + st[1] + '' + wd(d.day) + ''; - }).join('') + 'Fri: +' + b.banked + ' hunts'; - const t = (b.days || []).find(d => d.day === b.today); - let msg = ''; - if (b.isFriday) msg = b.banked ? 'It\'s Friday. Your ' + b.banked + ' banked hunt' + (b.banked === 1 ? '' : 's') + ' are live on PolHunter today.' : 'It\'s Friday. Bank hunts Saturday through Thursday for next Friday.'; - else if (t && t.banked) msg = '✓ Today is banked. Come back tomorrow to bank another.'; - else if (t && t.video && t.soloNeeded && !t.solo) msg = '✓ Video watched. Not banked yet: an inbox ad is waiting for you today, and a day only counts once it is opened. Open the inbox ad and today is banked. (On days when nothing is waiting in your inbox, the video alone counts, which is why some days banked without one.)'; - else if (t) msg = 'To bank today: ' + (t.video ? '✓ video watched' : 'watch one video') + (t.soloNeeded ? ' and ' + (t.solo ? '✓ inbox ad opened' : 'open one inbox ad') : ' (no inbox ad waiting, so the video alone counts)') + '.'; - const el = document.getElementById('fbankToday'); el.innerHTML = msg; - el.querySelectorAll('[data-earn-go]').forEach(a => a.addEventListener('click', ev => { ev.preventDefault(); const tab = document.querySelector('[data-earn="' + a.dataset.earnGo + '"]'); if (tab) tab.click(); })); - card.hidden = false; -} +// member share links go out on the share domain (2026-10-20): https://ctbgo.com/ -> /join/ on InstantAdPay. +// The domain comes from site config (shareDomain); empty falls back to this site's own /join link. +let SHARE_DOMAIN = ''; +const SHARE_READY = fetch('/api/config').then(r => r.json()).then(c => { SHARE_DOMAIN = String((c && c.shareDomain) || '').trim(); }).catch(() => {}); +function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(String(ref)) ? 'https://' + SHARE_DOMAIN + '/' + ref : location.origin + '/join/' + ref; } +// My account: email-first join/login, wallet link at purchase time, +// free payout activation, invite link, on-chain activity. +(async function () { + // back-office shell: no marketing nav here; rehearsal notice lives in the top bar + const $ = IAP.$; + // dwell timers pause when the tab is away; a focused ad frame or a touch device counts as active (phones never report hasFocus reliably) + const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches)); + try { + const c = await IAP.getConfig(); + if (c.rehearsal && $('boRehearsal')) { + $('boRehearsal').hidden = false; + $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; + } + if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; + } catch (e) {} + // if they arrived through a sponsor's link, show who they're joining under + (async () => { + try { + const sp = await (await fetch('/api/sponsor?intent=view')).json(); // display only: never an alert + if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } + } catch (e) {} + })(); + + async function api(path, body) { + const r = await (await fetch(path, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); + if (r.error) { const e = new Error(r.error); e.data = r; throw e; } // e.data: the full answer (e.g. top-up switch options) + return r; + } + + function nextMove(d) { + if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; + if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; + if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.'; + if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $20+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; + if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; + return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; + } + // featured rotation strip on the overview + let featItems = [], featIdx = 0, featTimer = null; + function renderOneFeatured() { + if (!featItems.length) return; + const i = featItems[featIdx % featItems.length]; + $('featStrip').innerHTML = '' + esc(i.title) + '' + + (i.by ? '' + esc(i.by) + '' : '') + ''; + } + async function loadFeatured() { + try { + const r = await (await fetch('/api/featured')).json(); + const card = $('featuredCard'); if (!card) return; + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); + $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; + renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one + clearInterval(featTimer); + if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); + // self-sell: today's open slots + a CTA to feature your own link + try { + const st = await (await fetch('/api/featured/stats')).json(); + const today = (st.occupancy || []).find(d => d.offset === 0); + const cta = $('featCta'); + if (cta) { + cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') + + 'Feature your link →'; + const fb = $('featBuy'); + if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); + } + } catch (e) {} + } catch (e) {} + } + + // achievement badges: the milestone ladder as unlockable medals + share-to-image + const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) + { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, + { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, + { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, + { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 }, + { key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }, + { key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 } + ]; + let lastMilestones = []; + function renderBadges(d) { + const reached = d.milestonesReached || []; + lastMilestones = reached; + const strip = $('badgeStrip'); + if (!strip) return; + $('badgeCard').hidden = false; + strip.innerHTML = BADGES.map(b => { + const got = reached.includes(b.key); + return '
' + + '' + b.label + ' badge' + + '
' + b.label + '
' + b.sub + '
' + + (got ? ' ' : '
🔒 locked
') + '
'; + }).join(''); + strip.querySelectorAll('[data-badge]').forEach(btn => + btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); + strip.querySelectorAll('[data-badgepost]').forEach(btn => + btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); + fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) + if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); + (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); + }).catch(() => {}); + // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) + if (d.milestonesGranted && d.milestonesGranted.length) { + const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); + const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); + IAP.status('🏆 Achievement unlocked: ' + names + (total > 0 ? ': +' + total + ' bonus credits!' : '! See it in your badges.'), 'ok'); + d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); + } + } + // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) + function composeBadge(key, d, cb) { + const b = BADGES.find(x => x.key === key); if (!b) return cb(null); + const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; + const img = new Image(); + img.onload = () => { + const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; + const x = c.getContext('2d'); + x.drawImage(img, 0, 0); + if (who) { + x.textAlign = 'center'; x.textBaseline = 'middle'; + x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; + const y = c.height * (b.ribbonY || 0.75); + x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); + x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); + x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); + } + cb(c); + }; + img.onerror = () => cb(null); + img.src = b.img; + } + async function postBadge(key, d, btn, manual) { + if (btn && btn.disabled) return; + if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } + composeBadge(key, d, c => { + if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } + c.toBlob(async bl => { + try { + const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); + if (r.error) throw new Error(r.error); + if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } + if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); + } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } + }, 'image/jpeg', 0.86); + }); + } + // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at + // /b// carries it as the preview image; every network gets that link. + function shareBadge(key, d) { + const b = BADGES.find(x => x.key === key); if (!b) return; + if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } + IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); + composeBadge(key, d, c => { + if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } + c.toBlob(async bl => { + let page = null; + try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } + catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } + openShareSheet(b, d, bl, page); + }, 'image/jpeg', 0.9); + }); + } + function openShareSheet(b, d, blob, page) { + const text = 'I just unlocked the ' + b.label + ' badge on InstantAdPay (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; + const enc = encodeURIComponent; + const links = [ + ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], + ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], + ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], + ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], + ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] + ]; + const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; + back.innerHTML = ''; + document.body.appendChild(back); + const close = () => back.remove(); + back.addEventListener('click', e => { if (e.target === back) close(); }); + back.querySelector('[data-sh="close"]').addEventListener('click', close); + back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); + back.querySelector('[data-sh="save"]').addEventListener('click', () => { + const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); + IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); + }); + // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) + back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { + try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } + catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } + window.open('https://massifly.com/account', '_blank', 'noopener'); + }); + const nat = back.querySelector('[data-sh="native"]'); + if (nat) nat.addEventListener('click', async () => { + try { + const file = new File([blob], 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); + if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); + else await navigator.share({ title: b.label + ' badge', text, url: page }); + } catch (e) {} + }); + } + + // milestone stepper under "Your next move": lit nodes for what's done, + // amber glow on the current target — the same ladder the contract pays + function renderSteps(d) { + const el = $('ncSteps'); + if (!el) return; + const b = d.buyerCount || 0; + const steps = [ + { label: 'Joined', sub: 'free account', hit: true }, + { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, + { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, + { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, + { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } + ]; + const cur = steps.findIndex(s => !s.hit); + el.innerHTML = steps.map((s, i) => + '
' + + '' + (s.hit ? '✓' : i + 1) + '' + + '' + s.label + '' + s.sub + '
').join(''); + } + // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + + // Paged lists (Marty, 2026-09-19): 25 rows, then a clearly marked next page, on every list + // that grows with the membership. Works on what is already rendered: rows past the page are + // hidden and a control bar goes under the list, so a row's buttons and bindings never change. + // key remembers the page across re-renders of the same list + // host the element the bar is appended to (a wrapper, never a ) + // rowSel the rows, queried inside host + // opts per (default 25); tail: a selector for a drawer that follows its row and pages + // with it; focus: a row predicate, opens on whichever page holds that row + const PAGE_SIZE = 25; + // My line is the longest page on the dashboard: its lists page at 10 (Marty, 2026-09-26) + const LINE_PER = 10; + // Sortable + filterable member lists (Marty, 2026-09-29): the holding tank, "Your line" and the three-level + // downline share one toolbar. Every row carries joined, last seen, surf earnings and wallet/payout state so a + // sponsor can spot "joined days ago, signed in today, earning on their own, wallet linked but payouts off". + const LIST_UI = {}; + const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; + const activeToday = m => (m.lastSeen || 0) >= dayStart(); + const LIST_SORTS = [ + { k: 'seen', label: 'Last seen', v: m => m.lastSeen || 0 }, + { k: 'joined', label: 'Joined', v: m => m.joined || 0 }, + { k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 }, + { k: 'balance', label: 'Earned balance', v: m => m.balance || 0 }, + { k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true }, + ]; + const LIST_FILTERS = [ + { k: 'today', label: 'Active today', t: m => activeToday(m) }, + { k: 'earning', label: 'Earning', t: m => (m.earned || 0) > 0 }, + { k: 'wallet', label: 'Wallet linked', t: m => !!m.wallet }, + { k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated }, + { k: 'payouts', label: 'Payouts on', t: m => !!m.activated }, + { k: 'nowallet', label: 'No wallet', t: m => !m.wallet }, + ]; + const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() }); + function listApply(key, rows) { + const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0]; + const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })); + out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; }); + return out; + } + function listBar(key, total, shown, rerender, opts) { + const st = listState(key); const hide = (opts && opts.hide) || []; + const bar = document.createElement('div'); bar.className = 'lst-bar'; + bar.innerHTML = '' + + '' + + '' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '').join('') + '' + + '' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + ''; + bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); }); + bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); }); + bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); })); + return bar; + } + const seenAgo = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' days ago'; }; + const seenChip = m => m.lastSeen ? '' + (activeToday(m) ? 'active today' : 'seen ' + seenAgo(m.lastSeen)) + '' : 'never signed in'; + const earnChip = m => '' + (m.earned || 0).toLocaleString() + ' cr earned'; + const walletChip = m => m.activated ? 'wallet · payouts on' : m.wallet ? 'wallet · payouts off' : 'no wallet'; + const memberChips = m => seenChip(m) + ' ' + earnChip(m) + ' ' + walletChip(m); + // Section pills at the top of My line: one per visible card marked data-jump, the one in view lit up. + // Cards that show or hide themselves (sponsor, upline messages) rebuild the row when they change. + let lineJumpObs = null; + function buildLineJump() { + const nav = document.getElementById('lineJump'); const pane = document.getElementById('pane-line'); if (!nav || !pane) return; + const cards = [...pane.querySelectorAll(':scope > .card[data-jump]')].filter(c => !c.hidden); + nav.innerHTML = cards.map(c => '').join(''); + nav.hidden = cards.length < 2; + const top = document.querySelector('.bo-top'); nav.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); pane.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); + nav.querySelectorAll('[data-jumpto]').forEach(b => b.addEventListener('click', () => { + const c = document.getElementById(b.dataset.jumpto); if (!c) return; + c.scrollIntoView({ behavior: 'smooth', block: 'start' }); + nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x === b)); + })); + if (lineJumpObs) lineJumpObs.disconnect(); + if ('IntersectionObserver' in window) { + const seen = new Map(); + lineJumpObs = new IntersectionObserver(ents => { + for (const e of ents) seen.set(e.target.id, e.isIntersecting ? e.boundingClientRect.top : null); + let best = null; for (const [id, t] of seen) if (t != null && (best == null || t < seen.get(best))) best = id; + if (best) { nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x.dataset.jumpto === best)); const on = nav.querySelector('.chip-t.on'); if (on && nav.scrollWidth > nav.clientWidth) nav.scrollLeft = on.offsetLeft - 16; } + }, { rootMargin: '-120px 0px -55% 0px' }); + cards.forEach(c => lineJumpObs.observe(c)); + } + } + { const pane = document.getElementById('pane-line'); + if (pane && 'MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(pane, { subtree: false, childList: false, attributes: true, attributeFilter: ['hidden'] }); + if (pane) pane.querySelectorAll(':scope > .card[data-jump]').forEach(c => { if ('MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(c, { attributes: true, attributeFilter: ['hidden'] }); }); } + const PAGE_AT = {}; + function pageList(key, host, rowSel, opts) { + if (!host) return; opts = opts || {}; const per = opts.per || PAGE_SIZE; + const rows = [...host.querySelectorAll(rowSel)]; + const old = host.querySelector(':scope > .pgr'); if (old) old.remove(); + if (rows.length <= per) { rows.forEach(r => { r.hidden = false; }); return; } + const pages = Math.ceil(rows.length / per); + let p = PAGE_AT[key] || 1; + if (opts.focus) { const i = rows.findIndex(opts.focus); if (i >= 0) p = Math.floor(i / per) + 1; } + p = Math.min(Math.max(1, p), pages); PAGE_AT[key] = p; + const start = (p - 1) * per; + rows.forEach((r, i) => { + const on = i >= start && i < start + per; r.hidden = !on; + if (opts.tail) { const t = r.nextElementSibling; if (t && t.matches(opts.tail) && !on && !t.hidden) { t.hidden = true; const b = r.querySelector('[aria-expanded]'); if (b) { b.setAttribute('aria-expanded', 'false'); b.textContent = 'Activity \u25BE'; } } } + }); + const bar = document.createElement('div'); bar.className = 'pgr'; + bar.innerHTML = 'Showing ' + (start + 1) + '\u2013' + Math.min(start + per, rows.length) + ' of ' + rows.length + '' + + '' + + 'Page ' + p + ' of ' + pages + '' + + ''; + bar.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => { + PAGE_AT[key] = Number(b.dataset.go); + pageList(key, host, rowSel, Object.assign({}, opts, { focus: null })); + host.scrollIntoView({ behavior: 'smooth', block: 'start' }); + })); + host.appendChild(bar); + } + const CH = { mint: '#43e8c3', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; + function bars(el, xel, data) { // data: [{v,label,tip,alt}] + if (!el) return; + const max = Math.max(1, ...data.map(d => d.v)); + el.innerHTML = data.length + ? data.map(d => '
').join('') + : '
'.repeat(8); + if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); + } + function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 + if (!el) return; + const total = segs.reduce((s, x) => s + x.v, 0); + let off = 25, out = ''; + if (total > 0) for (const s of segs) { + const len = s.v / total * 100; + if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } + out += ''; + off -= len; + } + out += '' + esc(center.big) + '' + + '' + esc(center.small) + ''; + el.innerHTML = out; + } + function legend(el, rows) { + if (el) el.innerHTML = rows.map(r => '
' + + esc(r.label) + ' ' + esc(r.v) + '
').join(''); + } + async function loadCharts(d) { + // credit composition donut + today's viewing ring (live balances) + try { + const st = await (await fetch('/api/my/earn')).json(); + if (!st.error) { + // one rule: a balance is what is NOT committed to a live campaign. Budgets are + // set aside when a campaign starts and spend down inside Campaigns, so these + // numbers only move when a campaign is created, topped up or paused + const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; + $('dbCredits').textContent = (purchased + earned).toLocaleString(); + // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) + if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; + $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (d.earnedReserved ? ' (+' + d.earnedReserved.toLocaleString() + ' earned and bonus credits working in your live campaigns)' : '') + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); + donut($('chDonut'), + [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], + { big: (purchased + earned).toLocaleString(), small: 'available' }); + legend($('chDonutLegend'), [ + { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, + { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, + { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); + const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); + donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], + { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); + legend($('chRingLegend'), [ + { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, + { color: CH.track, label: 'To go', v: left }, + { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); + } + } catch (e) {} + // recent on-chain payouts, sized to scale, oldest→newest + try { + let evs = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); + } + bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ + v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, + label: e.type === 'AwardPaid' ? (e.override ? 'L4' : 'award') : 'L' + (e.tier || 1), + tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); + if (!evs.length) $('chEarnSub').textContent = d.memberId + ? 'no payouts yet — share your link' : 'activate a package to start earning'; + } catch (e) {} + // campaign delivery: impressions per campaign + try { + const r = await (await fetch('/api/my/campaigns')).json(); + const cs = (r.campaigns || []).slice(0, 8); + bars($('chCampBars'), $('chCampX'), cs.map(c => ({ + v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), + tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', + alt: c.type === 'text' }))); + if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; + } catch (e) {} + } + // ── live updates: subscribe to the chain event stream so the members area + // reacts to on-chain changes (payouts, qualifications) without a refresh ── + let MYID = 0; + // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. + function playSound(kind) { + try { + const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; + const ctx = window.__iapAC || (window.__iapAC = new AC()); + if (ctx.state === 'suspended') ctx.resume(); + const now = ctx.currentTime; + const tone = (freq, at, dur, type, peak) => { + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = type || 'sine'; o.frequency.value = freq; + g.gain.setValueAtTime(0.0001, now + at); + g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); + g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); + o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); + }; + if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } + else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } + } catch (e) {} + } + function startLiveFeed() { + if (window.__iapFeed || !window.EventSource) return; + try { + const es = new EventSource('/api/feed/live'); + window.__iapFeed = es; + es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; + // browser auto-reconnects on error; nothing to do + } catch (e) {} + } + let liveRefreshT = null; + function liveRefresh() { // debounce a burst of events into one refresh + clearTimeout(liveRefreshT); + liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); + } + // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, + // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so + // they never replace a personal one. At most one every 4 s; a burst shows the latest. + let liveT = 0, liveQ = null; + function communityToast(msg) { + const now = Date.now(); + if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } + liveT = now; + let el = document.getElementById('liveToast'); + if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } + el.textContent = msg; el.hidden = false; el.style.opacity = '1'; + clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); + } + function handleLiveEvent(ev) { + if (!ev || !ev.type) return; + const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; + // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications + if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } + if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } + if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } + if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } + if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } + const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); + if (!mine) { + if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); + else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); + else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); + else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); + return; + } + if (!MYID) return; + let toast = null, kind = 'ok'; + let sound = null; + if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; + else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } + else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; + else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; + if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } + } + + // training center: videos + materials (admin-curated via data/training.json) + async function loadTraining() { + try { + const r = await (await fetch('/api/training')).json(); + const el = $('trainingList'); if (!el) return; + const items = r.items || []; + if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } + // section pills at the top: one per group, plus All; the active pill filters the list + const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; + const pills = $('trainingPills'); + const want = loadTraining.filter || 'all'; + if (pills) { + pills.hidden = groups.length < 2; + pills.innerHTML = ['all', ...groups].map(g => '').join(''); + pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); + } + const shown = want === 'all' ? items : items.filter(it => it.group === want); + let lastGroup = null; + el.innerHTML = shown.map(it => { + // optional section header: entries carry a `group`; a header renders when it changes + let head = ''; + if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } + const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); + // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) + const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); + const media = isVid ? '' : ''; + const links = []; + if (it.videoUrl && !isVid) links.push('Watch'); + if (it.docUrl) links.push('' + esc(it.docLabel || 'Open material') + ''); + return head + '

' + esc(it.title || 'Lesson') + '

' + + (it.desc ? '

' + esc(it.desc) + '

' : '') + + (media ? '

' + media + '

' : '') + + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; + }).join(''); + } catch (e) {} + } + // visual line tree on the Overview: YOU + three levels, qualified directs in gold + function renderRoster(wrap, all) { + const rows = listApply('roster', all); + wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove()); + wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all))); + if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '

Nobody in your line matches those filters.

'); return; } + const t = document.createElement('table'); t.className = 'roster'; + t.innerHTML = rows.map(r => '' + + '' + + '' + + '').join(''); + wrap.appendChild(t); + pageList('roster', wrap, 'table.roster tr', { per: LINE_PER }); + } + async function loadLineTree(buyerCount) { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineTree'); if (!el) return; + const levels = r.levels || []; + const total = levels.reduce((n, L) => n + L.members.length, 0); + if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; + const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; + const rowFor = lvl => { + const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; + // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") + let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy + if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; + if (!html) html = '+ open'; + return '
L' + lvl + '
' + html + '
'; + }; + el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); + // click a chip to drill down: My line opens with that person's Activity panel expanded (Marty, 2026-09-15) + const go = ref => { LINE_FOCUS_REF = ref; setPane('line'); }; + el.querySelectorAll('[data-goref]').forEach(n => { + n.addEventListener('click', () => go(n.dataset.goref)); + n.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(n.dataset.goref); } }); + }); + } catch (e) {} + } + let LINE_FOCUS_REF = null; // set by an Overview chip click; consumed once My line has rendered + // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) + let newsLoaded = false; + async function loadNews() { + if (newsLoaded || !$('newsCard')) return; newsLoaded = true; + try { + const r = await (await fetch('/api/releases')).json(); + if (!r.notes.length && !r.roadmap.length) return; + let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); + const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); + $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; + $('newsCard').hidden = false; + $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); + } catch (e) {} + } + // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) + async function loadLeaderboard() { + if (!$('lbCard')) return; + try { + const r = await (await fetch('/api/leaderboard?period=week')).json(); + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; + h += r.top.length ? '
' + esc(r.name || r.email || '') + 'joined ' + new Date(r.joined).toLocaleDateString() + '' + memberChips(r) + '' + esc(r.status) + '
' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' + : '

No packages sold yet this week. First sale takes the top spot.

'; + h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; + h += '

Full leaderboard: week, month, all time →

'; + $('lbList').innerHTML = h; $('lbCard').hidden = false; + } catch (e) {} + } + // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big + // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) + function renderSteps(d) { + const card = $('gsCard'); if (!card) return; + const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); + const steps = [ + { k: 'user', t: 'Pick a username', done: hasUser }, + { k: 'wallet', t: 'Link your wallet', done: hasWallet }, + { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, + { k: 'package', t: 'Your first package', done: hasPackage } + ]; + if (steps.every(x => x.done)) { card.hidden = true; return; } + const cur = steps.find(x => !x.done); + let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} + $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; + $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); + $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; + $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); + const copy = { + user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], + wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], + payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], + package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] + }[cur.k]; + $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; + $('gsGo').addEventListener('click', copy[3]); + card.hidden = false; + } + // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. + // We remember the game (through sign-in), tell the server once, and show the offer + the way back to the perk. + try { const fm = /[?&]from=([a-z]{3,20})/.exec(location.search); if (fm) { sessionStorage.setItem('iap.starterFrom', fm[1]); history.replaceState(null, '', '/my' + (location.hash || '')); } } catch (e) {} + async function starterBanner(me) { + let from = null; try { from = sessionStorage.getItem('iap.starterFrom'); } catch (e) {} + let v = null; + if (from) { try { sessionStorage.removeItem('iap.starterFrom'); } catch (e) {} v = await (await fetch('/api/starter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ game: from }) })).json(); } + else v = await (await fetch('/api/starter')).json(); + if (!v || !v.on || !v.game) return; + const pane = document.querySelector('#pane-buy .card'); if (!pane) return; + let box = document.getElementById('starterBox'); if (!box) { box = document.createElement('div'); box.id = 'starterBox'; pane.insertBefore(box, pane.children[1] || null); } + const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + box.style.cssText = 'border:1px solid var(--gold, #e2b04a);border-radius:12px;padding:12px 14px;margin:0 0 14px;background:rgba(226,176,74,.08)'; + box.innerHTML = v.eligible + ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' + : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; + if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card + } + function jumpTo(pane, id) { + setPane(pane); + setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); + } + async function loadDashboard() { + try { + loadNews(); loadLeaderboard(); + const d = await (await fetch('/api/my/dashboard')).json(); + if (d.error) return; + chatSync(d); + try { renderSteps(d); } catch (e) {} + MYID = d.memberId || MYID; + startLiveFeed(); + if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) + window.__lbChecked = true; + api('/api/my/login-bonus').then(r => { + if (r && r.comeback > 0) { IAP.status('🎉 Welcome back! +' + r.comeback + ' bonus credits for coming back, plus +' + r.granted + ' for signing in today.', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } + else if (r && r.granted > 0) { + IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); + playSound('chaching'); setTimeout(loadDashboard, 900); + } + }).catch(() => {}); + } + const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; + $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); + $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); + $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); + usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; }); + $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } + $('dbTeam').textContent = (d.referrals || []).length; + // trend chips: only real, computable facts + const ec = $('dbEarnedChip'); + if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } + const bc = $('dbBuyersChip'); + if (bc && d.memberId) { + bc.hidden = false; + bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; + } + const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; + if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } + setInboxBadge(d.inboxUnread || 0); + if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); + renderBadges(d); + loadFeatured(); + loadLineTree(d.buyerCount || 0); + loadCharts(d); + $('nextMove').textContent = nextMove(d); + renderSteps(d); + const wrap = $('rosterWrap'); + if ((d.referrals || []).length) { + $('rosterEmpty').hidden = true; + renderRoster(wrap, d.referrals); + } + // overview recent-activity widget: chain events + line joins, newest first + try { + const c = await IAP.getConfig(); + const ov = $('ovFeed'); + const rows = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + for (const ev of [...(a.earnings || []), ...(a.purchases || [])] + .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); + } + for (const r of (d.referrals || []).slice(0, 3)) { + const div = document.createElement('div'); + div.className = 'row'; + div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' + + new Date(r.joined).toLocaleDateString() + ''; + rows.push(div); + } + if (rows.length) { + ov.innerHTML = ''; + rows.slice(0, 6).forEach(r => ov.appendChild(r)); + } + } catch (e) {} + // ready-to-send share message + promo tools, personalized + await SHARE_READY; + const link = shareLink(d.username || d.refCode || d.memberId || ''); + fillPromo(link, d); + // founding-week readiness: shown until every item is done (or the launch moment is a week past) + try { + const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; + const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; + const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); + const lm = $('launchMark'); + if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } + } catch (e) {} + // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it + try { + const tw = d.tankWaiting, tn = $('tankNotice'); + if (tn) { + tn.hidden = !(tw && tw.count); + if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' + + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' + + (tw.eligible ? '.' : ' (you need your own $20 package first).'); + } + } catch (e) {} + // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join + { const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip'); + if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP); + $('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } } + if (d.username) { // wall link rides the username + const wl = location.origin + '/wall/' + d.username; + $('wallLine').textContent = wl; + if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link + $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; + $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; + } + $('wallCopy').hidden = false; + $('wallOpen').hidden = false; + $('wallOpen').href = '/wall/' + d.username; + $('wallCopy').onclick = async () => { + try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } + }; + } + if (d.refCode || d.memberId) { + const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' + + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' + + 'Free to join and look around: ' + link; + $('copyPitch').hidden = false; + $('pitchPreview').hidden = false; + $('pitchPreview').textContent = '"' + pitch + '"'; + $('copyPitch').onclick = async () => { + try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } + }; + } + } catch (e) {} + } + + // ── back-office menu: hash-routed panes ─────────────── + const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; + const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', + earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', + wallet: 'Wallet & account', profile: 'Profile' }; + function setPane(name) { + let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) + if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card + if (!PANES.includes(name)) name = 'overview'; + for (const p of PANES) { + const el = $('pane-' + p); + if (el) el.hidden = p !== name; + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.classList.toggle('on', b.dataset.pane === name)); + if ($('boTitle')) $('boTitle').textContent = TITLES[name]; + // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane + IAP.adSlot('text', 'adStripTop'); + if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); + if (name === 'earn') { setEarnSub(earnSub); loadPdCard(); } // refresh whichever sub-tab is active; PassiveDrip card (2026-10-01) + else if (vidState.token) stopVideo(); + if (name === 'profile') loadLineBanner(); + if (name === 'line') { buildLineJump(); loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } + if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits + if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } + if (name === 'pipeline') loadPipeline(); + if (name === 'games') loadGames(paneQ); + if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) + document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer + const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket + if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.pane))); + document.querySelectorAll('.qa [data-goto]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.goto))); + const qaCopy = document.getElementById('qaCopyInvite'); + if (qaCopy) qaCopy.addEventListener('click', async () => { + const link = document.getElementById('inviteLine').textContent; + if (!link || !link.startsWith('http')) { setPane('line'); return; } + try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } + catch (e) { setPane('line'); } + }); + window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); + if ($('boBurger')) $('boBurger').addEventListener('click', () => + document.getElementById('memberArea').classList.toggle('side-open')); + + async function render() { + // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member + let me = null; + try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } + if ($('bootSpin')) $('bootSpin').hidden = true; + // one way in: email. A wallet-only session (no account) is sent back to the + // email card with a finish-setup note; verifying the code links that wallet. + const walletOnly = !!(me && me.signedIn && !me.email); + const signedIn = me && me.signedIn && !walletOnly; + $('authArea').hidden = !!signedIn; + $('memberArea').hidden = !signedIn; + if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; + if (!signedIn) return; + if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL + if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) + // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be + // skipped or dismissed; it resolves only when a username is saved, then the area renders. + if (!me.username) { + if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } + return; + } + // came from a Drip Runner share link: once they have a username, straight back into the game (2026-09-30) + if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; } + if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01) + if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; } + if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02) + if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13) + if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18) + if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05) + if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); + // x = not now: clears the bar cookie (the waiting mint order stays and a later package still completes it), Marty 2026-10-11 + const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.textContent = '×'; x.setAttribute('style', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;border:0;border-radius:50%;background:rgba(0,0,0,.28);color:#fff;font-size:20px;line-height:30px;cursor:pointer;padding:0'); + x.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); fetch('/pw/mint/dismiss', { method: 'POST' }).catch(() => {}); d.remove(); document.body.classList.remove('hasback'); if (me) me.pwMint = false; }); d.appendChild(x); } + if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; } + if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; document.body.classList.add('hasback'); d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } + if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; document.body.classList.add('hasback'); d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } + if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01) + // arrived from an invite page: run the welcome tour and login ad once + if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { + render.welcomed = true; + history.replaceState(null, '', '/my' + (location.hash || '')); + (async () => { + try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} + await render(); + })(); + } + starterBanner(me).catch(() => {}); + setPane(location.hash.slice(1) || 'overview'); + $('campGate').hidden = !!me.memberId; + $('earnGate').hidden = !!me.memberId; + if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } + loadDashboard(); + if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket + + const who = []; + if (me.email) who.push(me.email); + // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check + if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); + else who.push('No wallet connected yet (link one below)'); + if (me.memberId) who.push('on-chain member #' + me.memberId + '' + + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); + else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); + $('posLine').innerHTML = who.join('
'); + + $('creditLine').textContent = (me.credits || 0).toLocaleString(); + loadPositions(me); + $('linkCard').hidden = !!me.address; + $('activateCard').hidden = !(me.address && !me.memberId); + $('activityArea').hidden = !me.memberId; + $('campGate').hidden = true; // earned credits fund campaigns for everyone + $('campaignCard').hidden = false; + loadCampaigns(); + + // profile pane state + $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; + if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; + $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; + $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' + + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') + + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); + // the share link works from day one; usernames make it a vanity link + if (me.username || me.refCode || me.memberId) { + await SHARE_READY; + $('inviteLine').textContent = shareLink(me.username || me.refCode || me.memberId); + $('copyInvite').hidden = false; + } else { + $('inviteLine').textContent = 'Sign in with your email to get your link.'; + $('copyInvite').hidden = true; + } + if (me.memberId) { + const bc = me.buyerCount || 0; + $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' + + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' + : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' + : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); + loadActivity(); + } else { + $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' + + 'before your people start buying: the contract locks each buyer to their sponsor at ' + + 'their first purchase, and payments only route to wallets that are switched on.'; + } + } + + // Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here), + // shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day. + let USD = null; + async function usdRate() { + if (USD && Date.now() - USD.got < 120000) return USD; + try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; } + return USD; + } + function usdOf(wei, r) { + let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {} + const v = pol * ((r && r.usd) || 0); + return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + } + function usdNote(r) { + if (!r || !(r.usd > 0)) return ''; + const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000)); + return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.'; + } + async function loadActivity() { + try { + const c = await IAP.getConfig(); + const a = await (await fetch('/api/my/activity')).json(); + const fill = (id, evs, empty) => { + const el = $(id); + el.innerHTML = ''; + if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } + for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); + }; + fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); + usdRate().then(r => { + const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r); + if (!(r.usd > 0)) return; + const rows = $('earnFeed').querySelectorAll('.row'); let i = 0; + for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); } + }); + fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); + fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); + } catch (e) {} + initTrace(); + } + // payment trace (2026-09-16): who was paid, who was skipped and why, per purchase + let traceInit = false; + function initTrace() { + if (traceInit || !$('trGo')) return; traceInit = true; + const run = async () => { + const who = ($('trWho').value || '').trim(); const out = $('trOut'); const msg = $('trMsg'); + msg.textContent = 'Reading the chain…'; out.innerHTML = ''; + try { + const c = await IAP.getConfig(); + const r = await (await fetch('/api/my/trace?who=' + encodeURIComponent(who))).json(); + if (r.error) { msg.textContent = r.error; return; } + msg.textContent = ''; + const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; + const pol = w => IAP.fmtPol(w) + ' POL'; + const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + let h = '

' + nm(r.memberId) + ' · ' + (r.activated ? 'activated under ' + nm(r.sponsorId) : 'not activated on the chain yet') + ' · ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' (level 2 needs 2, level 3 needs 5)

'; + if (!r.purchases.length) { out.innerHTML = h + '

No purchases involving ' + nm(r.memberId) + ' yet.

'; return; } + for (const p of r.purchases) { + const isBuyer = p.buyerId === r.memberId; + h += '
' + + '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought a $' + (p.priceCents / 100).toFixed(0) + ' package (' + pol(p.paidWei) + ')' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + + (c.explorer ? ' · verify ↗' : '') + '
'; + for (const t of p.tiers) { + const me = t.paidTo === r.memberId, skippedMe = t.skipped.some(x => x.id === r.memberId); + let line = 'Level ' + t.tier + ' (' + t.pct + '%): '; + for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'not qualified: had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' qualifying buyers then' : esc(x.reason)) + ') → '; + line += t.paidTo ? '' + nm(t.paidTo) + ' paid ' + pol(t.amountWei) + '' : 'no eligible catcher within reach → company'; + h += '
' + line + '
'; + } + h += '
Platform (20%): ' + pol(p.adminWei) + (isBuyer ? '' : '') + '
'; + } + h += '

A skipped level means that person had not unlocked it when the purchase settled. Qualification never applies backwards; the next purchase after they qualify pays them.

'; + out.innerHTML = h; + } catch (e) { msg.textContent = 'Could not read the chain just now. Try again in a minute.'; } + }; + $('trGo').addEventListener('click', run); + $('trWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); run(); } }); + } + + // credit activity ledger under the campaign table (2026-09-16): every earn and spend with its reason + // Archived campaigns: everything they did, none of the clutter and none of the reservation. + function renderArchived(el, r) { + const rows = r.archived || []; + if (!rows.length) return; + const box = document.createElement('div'); + box.className = 'card'; + box.style.marginTop = '18px'; + // what each one gave back = budget not delivered (flat packs are charged in full when bought, so theirs is 0) + const leftOf = c => Math.max(0, Number(c.budget || 0) - Number(c.spent || 0) - Number(c.accrued || 0)); + const returned = rows.reduce((n, c) => n + leftOf(c), 0); + box.innerHTML = '

Archived

' + rows.length + ' finished campaign' + (rows.length === 1 ? '' : 's') + ' · ' + returned.toLocaleString() + ' unspent credit' + (returned === 1 ? '' : 's') + ' returned
' + + '
' + + rows.map(c => '' + + '' + + '' + + '' + + '' + + '' + + '').join('') + + '
NameTypeViews hereClicksSpentReturnedRan until
' + esc(c.name || ('#' + c.id)) + '' + esc(c.type) + '' + Number(c.imps || 0).toLocaleString() + '' + Number(c.clicks || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + leftOf(c).toLocaleString() + '' + (c.created ? new Date(c.created).toLocaleDateString() : '') + '
' + + '

Archived campaigns keep every number they earned. They serve nothing and reserve nothing, so any budget they had not delivered is back in your Available balance (the Returned column). A campaign that delivered its whole budget has nothing left to return, and visit packs, Golden Door, login and featured runs are paid in full when bought. Restore brings one back, paused.

'; + el.appendChild(box); + box.querySelectorAll('[data-unarch]').forEach(b => b.addEventListener('click', async () => { + b.disabled = true; + try { await api('/api/my/campaigns/' + b.dataset.unarch + '/unarchive'); IAP.status('Restored, and paused. Press Resume when you want it running.', 'ok'); await loadCampaigns(); loadDashboard(); } + catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + } + async function loadCreditActivity(el) { + try { + const r = await (await fetch('/api/my/credits/activity')).json(); + if (!r.items || !r.items.length) return; + const box = document.createElement('div'); box.id = 'creditActivity'; box.style.marginTop = '16px'; + const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + box.innerHTML = '

Credit activity

' + + '

Every credit that came in or went out, newest first. Earned credits are spent before purchased ones, so an earn followed by a buy shows as two lines here. Views a campaign delivers roll up into one line per day.

' + + '
' + + r.items.map(i => '').join('') + + '
' + when(i.ts) + '' + (i.delta > 0 ? '+' : '') + i.delta.toLocaleString() + '' + esc(i.note) + '
'; + el.appendChild(box); + pageList('credits', box, 'tbody tr'); + } catch (e) {} + } + async function loadCampaigns() { + try { + const r = await (await fetch('/api/my/campaigns')).json(); + if (r.error) return; + lastRates = r.rates; + lastLoginLine = r.loginLine || null; loginLineHint(); + if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; + // populate the banner-size dropdown once (ids map to NAS width/height) + if (r.bannerSizes && $('cSize') && !$('cSize').options.length) + $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); + applyType(); // the default type is banner: show its size + image rows now that the sizes exist + soloHint(); + if ($('spendBanner')) { + $('spendBanner').hidden = false; + $('spendBig').textContent = r.availableCredits.toLocaleString(); + $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.earnedReserved ? ' (' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits are already working inside your live campaigns)' : '') + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); + if ($('spendNote')) $('spendNote').textContent = r.inCampaigns + ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' + : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; + $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', Number(r.rates.loginSlotCredits || 1000).toLocaleString() + ' cr / ' + (r.rates.loginSlotDays || 30) + '-day slot'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); + } + $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() + + ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '') + + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') + + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch + + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch + + ' views, login ' + Number(r.rates.loginSlotCredits || 1000).toLocaleString() + 'cr per ' + (r.rates.loginSlotDays || 30) + '-day slot, solo ' + + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; + const el = $('campList'); + el.innerHTML = ''; + if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; loadCreditActivity(el); return; } + const tbl = document.createElement('div'); + tbl.className = 'tablewrap'; + tbl.innerHTML = '' + + '' + + r.campaigns.map(c => '' + + '' + + '' + + '' + + '' + + (c.type === 'visits' ? '' + : c.type === 'featured' ? '' + : '') + + '' + + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) + + (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' ' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '' : '') + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
paid up front' + c.imps.toLocaleString() + ' of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits') + + (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '
\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '
')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '
paid up front' + featRun(c) + '' + c.spent + '' + c.budget + '' + (c.status === 'queued' ? queuedCell(c) : c.status === 'cancelled' ? 'cancelled, refunded' : c.status === 'out' ? (c.type === 'visits' ? 'pack delivered' : 'budget spent') : c.status === 'done' ? '' + (c.type === 'featured' ? 'run ended' : 'ended') + '' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' + : c.status === 'paused' ? '' + : c.status === 'queued' ? ' ' : '') + + (['paused', 'out', 'done', 'cancelled'].includes(c.status) ? ' ' : '') + + (c.type === 'featured' ? ' ' + : c.type === 'visits' ? ' ' + : c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up + : ' ') + + '
'; + el.appendChild(tbl); + pageList('camps', tbl, 'tbody tr'); + renderArchived(el, r); + const note = document.createElement('p'); note.className = 'muted small'; + note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.'; + el.appendChild(note); + loadCreditActivity(el); + el.querySelectorAll('button[data-extend]').forEach(b => b.addEventListener('click', async () => { + const rr = r.rates || {}; const durs = rr.featuredDurations || [1, 2, 7]; const per = rr.featuredPerDay || 40; + const d = await IAP.ask({ title: 'Extend featured run', text: 'How many more days? Choose ' + durs.join(', ') + '. ' + per + ' credits a day, charged now. The days are added after the current run, or start today if it has ended.', type: 'number', placeholder: 'e.g. ' + durs[durs.length - 1], ok: 'Extend' }); + if (!d) return; + try { const x = await api('/api/my/campaigns/' + b.dataset.extend + '/extend', { days: Number(d) }); + IAP.status('Extended ' + x.days + ' day' + (x.days === 1 ? '' : 's') + ' for ' + x.cost + ' credits' + (x.resumed ? '. The run is live again.' : '.'), 'ok'); + await loadCampaigns(); loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('button[data-morevisits]').forEach(b => b.addEventListener('click', async () => { + const per = Number(b.dataset.vper) || (r.rates && r.rates.visitCostPerVisit) || 3; const door = b.dataset.vdoor; // door packs top up at their door price + const what = door === 'golden' ? 'Golden Doors' : door ? 'doors' : 'visits'; + const n = await IAP.ask({ title: 'Buy more ' + what, text: door ? 'How many more ' + what + '? ' + per + ' credits each, charged now like the original pack.' : 'How many more verified visits? ' + per + ' credits each, charged now like the original pack.', type: 'number', placeholder: 'e.g. 50', ok: 'Buy ' + what }); + if (!n) return; + try { const x = await api('/api/my/campaigns/' + b.dataset.morevisits + '/topup', { credits: Math.floor(Number(n)) * per }); + IAP.status('Added ' + x.visits + ' ' + what + ' (' + x.added + ' credits)' + (x.reactivated ? '. The pack is open again.' : '.'), 'ok'); + await loadCampaigns(); loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + })); + // prepaid login-ad line (2026-10-23): a reservation can be edited for free and cancelled for the full price back until it starts + el.querySelectorAll('button[data-qcancel]').forEach(b => b.addEventListener('click', async () => { + const paid = Number(b.dataset.qpaid) || 0; + const ok = await IAP.confirmBox('You give up your place in line and the full ' + paid.toLocaleString() + ' credits come back to your balance right away, as purchased credits. You can reserve again later, at the back of the line.', + { title: 'Cancel ' + b.dataset.qname + '?', ok: 'Cancel and refund', cancel: 'Keep my place' }); + if (!ok) return; + b.disabled = true; + try { const x = await api('/api/my/campaigns/' + b.dataset.qcancel + '/cancel-reservation'); IAP.status('Reservation cancelled. ' + Number(x.refunded || 0).toLocaleString() + ' credits are back in your balance.', 'ok'); await loadCampaigns(); loadDashboard(); } + catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; await loadCampaigns(); } + })); + el.querySelectorAll('button[data-qedit]').forEach(b => b.addEventListener('click', async () => { + const c = r.campaigns.find(x => x.id === Number(b.dataset.qedit)); if (!c) return; + const target = await IAP.ask({ title: 'Edit your reserved login ad', text: 'Target URL: the page members see when they sign in. Editing is free until the ad starts.', value: c.targetUrl || '', placeholder: 'https://', ok: 'Next' }); + if (target === null) return; + const image = await IAP.ask({ title: 'Image (optional)', text: 'A direct image link (.png or .jpg) shown as the clickable creative. Leave it empty for a plain link card.', value: c.imageUrl || '', placeholder: 'https://', ok: 'Next' }); + if (image === null) return; + const title = await IAP.ask({ title: 'Headline (optional)', text: 'Shown on the link card when there is no image. Up to 60 characters.', value: c.title || '', placeholder: 'Visit today\'s sponsor', ok: 'Save changes' }); + if (title === null) return; + try { await api('/api/my/campaigns/' + c.id + '/edit-reservation', { targetUrl: target.trim(), imageUrl: image.trim(), title: title.trim() }); IAP.status('Saved. Your place in line is unchanged.', 'ok'); await loadCampaigns(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('[data-arch]').forEach(b => b.addEventListener('click', async () => { + const left = Number(b.dataset.archleft) || 0; + const ok = await IAP.confirmBox( + 'It stops appearing in this list but keeps every number it earned, in the Archived section below.' + + (left ? ' Its ' + left.toLocaleString() + ' unspent credits go straight back to your Available balance.' : '') + + ' You can restore it at any time.', + { title: 'Archive ' + b.dataset.archname, ok: 'Archive it', cancel: 'Keep it here' }); + if (!ok) return; + b.disabled = true; + try { const x = await api('/api/my/campaigns/' + b.dataset.arch + '/archive'); + IAP.status('Archived.' + (x.freed ? ' ' + Number(x.freed).toLocaleString() + ' credits released.' : ''), 'ok'); + await loadCampaigns(); loadDashboard(); } + catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { + const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views. They are set aside now and spend as views are delivered; anything unspent comes back when the campaign ends.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); + if (!n) return; + const done = r => { IAP.status('Added ' + r.added + ' credits' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The campaign is live again.' : '.'), 'ok'); }; + try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) })); await loadCampaigns(); loadDashboard(); } + catch (e) { + // the ad's own position is short but another of yours has the credits: offer to pay from that one + const opt = e.data && e.data.switchOptions && e.data.switchOptions[0]; + if (!opt) { IAP.status(e.message, 'bad'); return; } + const yes = await IAP.confirmBox('This ad pays from your position #' + e.data.fundId + ', which has ' + e.data.free + ' credits free. Your position #' + opt.memberId + ' has ' + opt.free + ' free. Pay for this top-up from #' + opt.memberId + '? From now on this ad spends from #' + opt.memberId + '.', { title: 'Pay from another position?', ok: 'Pay from #' + opt.memberId, cancel: 'Cancel' }); + if (!yes) return; + try { done(await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n), switchTo: opt.memberId })); await loadCampaigns(); loadDashboard(); } + catch (e2) { IAP.status(e2.message, 'bad'); } + } + })); + } catch (e) {} + } + let lastRates = null; + let lastLoginLine = null; // { max, used, queued, free, credits, days, nextPlace, nextEstStart, mine: [{ id, place, estStart }] } + // every date about the login-ad line is shown in Central time, Marty's clock + function ctWhen(ts) { return new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; } + function queuedCell(c) { + const m = lastLoginLine && (lastLoginLine.mine || []).find(x => x.id === c.id); + return 'In line' + (m ? ' #' + m.place : '') + '' + + '
' + (m && m.estStart ? 'Estimated start ' + esc(ctWhen(m.estStart)) : 'Start date not known yet') + '
'; + } + // the Login ad form: open slots, or the paid line with this buyer's place and estimated start + function loginLineHint() { + const el = $('cLoginLine'); const isLogin = $('cType') && $('cType').value === 'login'; + if (el) el.hidden = !isLogin || !lastLoginLine; + if ($('createCampBtn')) $('createCampBtn').textContent = isLogin && lastLoginLine && !lastLoginLine.free ? 'Reserve the next slot' : 'Launch campaign'; + if (!el || !isLogin || !lastLoginLine) return; + const L = lastLoginLine; + el.textContent = L.free + ? L.free + ' of ' + L.max + ' login-ad slots open now. Yours goes live the moment you launch: ' + Number(L.credits).toLocaleString() + ' purchased credits for ' + L.days + ' days.' + : 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ' and ' + L.queued + ' paid ' + (L.queued === 1 ? 'reservation is' : 'reservations are') + ' in line' : '') + '. You can reserve the next slot: you pay the same ' + + Number(L.credits).toLocaleString() + ' purchased credits now and take place #' + L.nextPlace + ' in line. Your ' + L.days + ' days start when your turn comes, not before.' + + (L.nextEstStart ? ' Estimated start: ' + ctWhen(L.nextEstStart) + '. That is an estimate: a slot can end early if its owner archives it, which moves the line forward.' : '') + + ' Until it starts you can edit it for free, or cancel it for every credit back.'; + } + function soloHint() { + if (!lastRates || $('cType').value !== 'solo') return; + const cost = lastRates.soloCostPerRecipient || 5; + const n = Math.floor((Number($('cBudget').value) || 0) / cost); + $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' + + (n ? ' — this budget reaches ' + n + ' members' : '') + + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; + } + $('cBudget').addEventListener('input', soloHint); + // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); + // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort + document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); + document.querySelectorAll('.ed-bar [data-block]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); + $('edLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection + const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (!url) return; + $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } + document.execCommand('createLink', false, url); + }); + // inline media: upload, then drop the element at the cursor (BV-style) + let mediaMode = 'image'; + function insertHtmlAtCursor(html) { + const ed = $('cSoloEd'); + ed.focus(); + if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); + } + $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); + $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); + $('cSoloFile').addEventListener('change', async () => { + const f = $('cSoloFile').files[0]; + if (!f) return; + $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } + insertHtmlAtCursor(r.type === 'video' + ? '


' + : '


'); + $('edMediaInfo').textContent = f.name + ' inserted'; + } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } + $('cSoloFile').value = ''; + }); + // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back + $('edRawBtn').addEventListener('click', () => { + const ed = $('cSoloEd'), raw = $('cSoloRaw'); + if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } + else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } + }); + const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', + text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', + login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', + solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', + video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', + featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', + visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; + const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; + whereHint(); + // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately + function applyType() { // hoisted: loadCampaigns may run before this line is reached + whereHint(); + loginLineHint(); + const t = $('cType').value; + $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL + if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner'; + $('cSizeRow').hidden = t !== 'banner'; + $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; + $('cBodyRow').hidden = t !== 'text'; + $('cSoloRow').hidden = t !== 'solo'; + $('cSoloHint').hidden = t !== 'solo'; + $('cVideoRow').hidden = t !== 'video'; + $('cFeaturedRow').hidden = t !== 'featured'; + $('cVisitsRow').hidden = t !== 'visits'; + if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; + $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } + // fixed-cost types derive their spend (featured = day slots, visits = flat pack), + // so hide the free-form Budget field for them to avoid confusion + $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); + if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); + // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected + if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; + if (t === 'visits') visitHint(); + $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; + soloHint(); + if (t === 'video') videoHint(); + if (t === 'featured') featHint(); + } + $('cType').addEventListener('change', applyType); + let featStartDay = 0; // selected start-day offset (0 = today) + async function featHint() { + if (!lastRates || !lastRates.featuredDurations) return; + if ($('cFeatDays') && !$('cFeatDays').options.length) + $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => + '').join(''); + let s = null; + try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} + if (s && s.occupancy) { + const grid = $('cFeatDaysGrid'); + grid.innerHTML = s.occupancy.map(d => { + const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); + const full = d.open <= 0; + return '
' + + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; + }).join(''); + grid.querySelectorAll('.feat-day:not(.full)').forEach(el => + el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); + } + const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); + const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; + $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel + + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); + // where a visits pack runs (Spooky Doors, 2026-10-02): everywhere, behind the doors, or a Golden Door, each with its own price + // function declarations (hoisted): loadCampaigns can run before this point is reached + function visitPlace() { const x = document.querySelector('input[name="cVisitPlace"]:checked'); return x ? x.value : 'all'; } + function placeCost(pl, rr) { rr = rr || lastRates || {}; return pl === 'golden' ? (rr.goldenDoorCost || 6) : pl === 'doors' ? (rr.doorPackCost || 4) : (rr.visitCostPerVisit || 3); } + function sdSeasonOpen(rr) { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < String((rr && rr.sdSeasonEnd) || '2026-11-01'); } + function sdLastDay(rr) { const t = new Date(String((rr && rr.sdSeasonEnd) || '2026-11-01') + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); } + function visitHint() { + if (!lastRates) return; + const open = sdSeasonOpen(lastRates); + document.querySelectorAll('#cVisitPlaceRow .sd-place').forEach(el => { el.hidden = !open; }); + if (!open && visitPlace() !== 'all') { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; } + document.querySelectorAll('[data-vpcost]').forEach(el => { const p = el.dataset.vpcost; el.textContent = '(' + placeCost(p) + ' credits a ' + (p === 'all' ? 'visit' : 'door') + ')'; }); + const pl = visitPlace(), per = placeCost(pl), min = lastRates.visitMinPack || 20; + const n = Number($('cVisitCount').value) || 0; + const unit = pl === 'golden' ? 'Golden Door' : pl === 'doors' ? 'door' : 'verified visit'; + $('cVisitCount').placeholder = pl === 'all' ? 'How many verified visits?' : pl === 'golden' ? 'How many Golden Doors?' : 'How many doors?'; + $('cVisitHint').textContent = per + ' credits per ' + unit + + (n >= min ? ': ' + n + ' = ' + (n * per).toLocaleString() + ' credits, paid up front' : ' (min ' + min + ')') + + (pl === 'all' ? '. Each is a unique member, dwell + human-check verified.' + : '. Each door is a dwell + human-check verified visit by a Spooky Doors player, at most once a day per player' + + (pl === 'golden' ? '; Golden Doors open before every other door and give the player bonus candy' : '; door packs open before ordinary visits') + + '. They run only in Spooky Doors until the season ends on ' + sdLastDay(lastRates) + ', then any doors left run as normal visits.'); + } + $('cVisitCount').addEventListener('input', visitHint); + document.querySelectorAll('input[name="cVisitPlace"]').forEach(x => x.addEventListener('change', visitHint)); + // video composer: tier dropdown + upload + price hint + function videoHint() { + if (!lastRates || !lastRates.videoTiers) return; + if ($('cWatchSecs') && !$('cWatchSecs').options.length) + $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => + '').join(''); + const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; + const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; + $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' + + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); + $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); + $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); + $('cVideoUrl').addEventListener('change', async () => { + const url = $('cVideoUrl').value.trim(); + $('cVideoInfo').textContent = url ? 'checking video…' : ''; + cVidDims = url ? await probeVideoDims(url) : null; + if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; + else { $('cVideoInfo').textContent = ''; showVidOrient(); } + }); + $('cVideoFile').addEventListener('change', async () => { + const f = $('cVideoFile').files[0]; + if (!f) return; + $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } + $('cVideoUrl').value = r.url; + $('cVideoInfo').textContent = f.name + ' uploaded'; + $('cVideoPrev').hidden = false; + $('cVideoPrev').innerHTML = ''; + cVidDims = await probeVideoDims(r.url); showVidOrient(); + } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } + $('cVideoFile').value = ''; + }); + $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { + // in raw mode the source of truth is the textarea; sync it back first + let soloBody = $('cSoloEd').innerHTML; + if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; + const t = $('cType').value; + const isVideo = t === 'video', isFeat = t === 'featured'; + if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); + // login ad with every slot taken: pay now for a place in line (Marty, 2026-10-23), after one plain confirmation + const confirmReserve = async (place, est) => IAP.confirmBox('Every login-ad slot is taken right now. Reserving charges the full ' + Number((lastLoginLine && lastLoginLine.credits) || (lastRates && lastRates.loginSlotCredits) || 0).toLocaleString() + + ' purchased credits now and puts you at place #' + place + ' in line. Your ad starts on its own when a slot frees, and runs its full ' + ((lastLoginLine && lastLoginLine.days) || 30) + ' days from then.' + + (est ? '\n\nEstimated start: ' + ctWhen(est) + '. That is an estimate: a slot can end early if its owner archives it.' : '') + + '\n\nUntil it starts you can edit it for free, or cancel it and get every credit back.', { title: 'Reserve the next login-ad slot?', ok: 'Pay now and reserve', cancel: 'Not now' }); + let reserve = false; + if (t === 'login' && lastLoginLine && !lastLoginLine.free) { if (!(await confirmReserve(lastLoginLine.nextPlace, lastLoginLine.nextEstStart))) return; reserve = true; } + const sendCamp = extra => api('/api/my/campaigns', Object.assign({ type: t, name: $('cName').value, + targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, + title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, + body: t === 'solo' ? soloBody : $('cBody').value, + videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), + videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, + days: Number($('cFeatDays').value), startDay: featStartDay, + count: Number($('cVisitCount').value), placement: t === 'visits' ? visitPlace() : undefined, + dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, + geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), + startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, + endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, + ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, + budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }, extra || {})); + let res; + try { res = await sendCamp({ reserve }); } + catch (e) { // the last slot went while the form was open: offer the line instead of a dead end + if (!(t === 'login' && e.data && e.data.full)) throw e; + if (!(await confirmReserve(e.data.place, e.data.estStart))) { await loadCampaigns(); return; } + res = await sendCamp({ reserve: true }); + } + const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; + if (res && res.queued) IAP.status('Reserved and paid. You are #' + res.place + ' in line' + (res.estStart ? ', estimated start ' + ctWhen(res.estStart) : '') + '. We will tell you on site and by email the moment it goes live.', 'ok'); + else if (t === 'login' && reserve) IAP.status('A slot opened up while you were deciding, so your login ad is live now.', 'ok'); + else IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); + // clear EVERY field so no target/creative carries into the next campaign + ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', + 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] + .forEach(id => { if ($(id)) $(id).value = ''; }); + document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); + { const a = document.querySelector('input[name="cVisitPlace"][value="all"]'); if (a) a.checked = true; if (t === 'visits') visitHint(); } + $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; + $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; + if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; + cVidDims = null; + await loadCampaigns(); + })); + // defers the busy() lookup to click time (busy is declared below) + function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } + + // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── + const visState = { token: null, id: null, dwell: 8 }; + async function loadVisitStatus() { + try { + const st = await (await fetch('/api/my/visits')).json(); + if (st.error) return; + $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; + $('vsStartBtn').hidden = st.status.count >= st.status.cap; + if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; + } catch (e) {} + } + async function loadVisit() { + $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; + let r = null; + try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} + if (!r || !r.ad) { + $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap + ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; + return; + } + visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; + $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; + const visit = $('vsVisit'); + visit.href = r.ad.url; visit.hidden = false; + $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; + // opening the site starts the dwell; then we ask the human-check + visit.onclick = () => { + let left = visState.dwell; + $('vsHint').textContent = 'Counting your visit: ' + left + 's'; + const t = setInterval(async () => { + left--; + if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } + clearInterval(t); + $('vsHint').textContent = 'One quick check to count the visit:'; + let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); + if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } + if (c.error) { $('vsHint').textContent = c.error; return; } + renderVisitCheck(c); + }, 1000); + }; + $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; + } + function renderVisitCheck(c) { + $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; + const w = $('vsOpts'); w.innerHTML = ''; + c.options.forEach((em, i) => { + const b = document.createElement('button'); + b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; + b.addEventListener('click', () => answerVisit(i)); + w.appendChild(b); + }); + $('vsCheck').hidden = false; + } + async function answerVisit(i) { + const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); + if (r.error) { + if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } + $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; + } + $('vsCheck').hidden = true; + $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; + $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; + IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); + loadDashboard(); + } + $('vsStartBtn').addEventListener('click', () => loadVisit()); + + // ── watch-to-earn videos: escape-proof player, server-clock reward ── + const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; + // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos + let cVidDims = null; + function probeVideoDims(url) { + return new Promise(resolve => { + if (!url) return resolve(null); + const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; + let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; + v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); + v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; + }); + } + function showVidOrient() { + const el = $('cVideoInfo'); if (!el) return; + if (!cVidDims) return; + const portrait = cVidDims.h > cVidDims.w; + el.textContent = (el.textContent ? el.textContent + ' · ' : '') + + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); + } + async function loadVideoStatus() { + try { + const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); + if (st.error) return; + $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; + if (st.status.left <= 0) { + $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; + $('vidStartBtn').hidden = true; + return; + } + $('vidStartBtn').hidden = false; + } catch (e) {} + } + // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) + function stopVideo() { + const p = $('vidPlayer'); if (!p) return; + const was = !!vidState.token && !vidState.done; + try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} + vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; vidState.needsTap = false; + if ($('vidWrap')) $('vidWrap').hidden = true; + if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } + if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } + } + document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); + async function loadVideoAd() { + let r = null; + try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} + if (!r || !r.ad) { + // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) + const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); + // the tab can run dry while Shorts still has clips, and both count toward the same + // daily total, so say so instead of sending them away (Marty, 2026-09-22) + const toShorts = !capHit && r && r.otherFormat === 'shorts'; + $('vidBox').innerHTML = toShorts + ? '
✓That is every video on this tab' + + 'You have watched all ' + r.status.count + ' of today’s landscape videos. The rest are upright clips that play in Shorts, and they count toward the same daily ' + r.status.cap + '. You have ' + r.status.left + ' left.' + + 'Open Shorts
' + : (capHit || allWatched) + ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' + : 'No member videos are live right now. Check back when a campaign is running.'; + if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched || toShorts; + $('vidBox').hidden = false; + $('vidWrap').hidden = true; + return; + } + const ad = r.ad; + vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; + $('vidBox').hidden = true; + $('vidWrap').hidden = false; + $('vidCta').hidden = true; + $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; + const p = $('vidPlayer'); + p.src = ad.videoUrl; + p.currentTime = 0; + // escape-proof: no seeking past what's been watched; track max reached + p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; + p.ontimeupdate = () => { + if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; + const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); + $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; + if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } + }; + $('vidStartBtn').textContent = 'Playing…'; + $('vidStartBtn').disabled = true; + vidState.needsTap = false; + // a browser that refuses to autoplay leaves the clip loaded and paused; the button then has to + // START it. Wired to loadVideoAd it threw the clip away and fetched another, so on a phone the + // video could never be played at all (Marty, 2026-09-22) + try { await p.play(); } catch (e) { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } + $('vidCta').href = ad.ctaUrl; + $('vidCta').textContent = ad.ctaLabel || 'Learn more'; + $('vidCta').hidden = false; + } + async function completeVideo(ad) { + if (vidState.credited) return; + vidState.credited = true; + try { + const r = await (await fetch('/api/my/videowatch', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } + else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } + else $('vidHint').textContent = 'That video just ran out of budget — load another.'; + if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; + } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } + $('vidStartBtn').disabled = false; + $('vidStartBtn').textContent = 'Next video'; + } + $('vidStartBtn').addEventListener('click', () => { + const p = $('vidPlayer'); + if (vidState.needsTap && p && p.src && !vidState.done) { // a clip is loaded and waiting on a tap: start it, never replace it + vidState.needsTap = false; + $('vidStartBtn').textContent = 'Playing…'; $('vidStartBtn').disabled = true; + p.play().catch(() => { vidState.needsTap = true; $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }); + return; + } + loadVideoAd(); + }); + // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, + // resume when it comes back — the viewer must stay on the page for the watch to complete + document.addEventListener('visibilitychange', () => { + const p = $('vidPlayer'); if (!p || !p.src) return; + if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); + }); + window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); + window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); + + // ── unmissable sponsor-message modal on sign-in ── + // Only a message a PERSON wrote reaches here; system notices (payouts, purchase + // confirmations) are kind 'notice' and go straight to the inbox. + // + // loadDashboard() runs on far more than sign-in — it refreshes after every ad view, every + // campaign edit, every chat close. So the modal is shown at most once per page load and + // never twice for the same message, otherwise a member earning credits gets interrupted + // after every single view. + const msgModalShown = new Set(); + function showSponsorModal(msg) { + if (!$('msgModal') || !msg || msgModalShown.has(msg.id)) return; + if (!$('msgModal').hidden) return; // one already open + msgModalShown.add(msg.id); + // An alert is generated by the system, so crediting it to a person ("A message from + // @martbost") is both wrong and misleading about what the member is looking at. + $('mmFrom').textContent = msg.kind === 'alert' + ? 'Action needed on your account' + : 'A message from ' + (msg.fromName || 'your sponsor'); + $('mmSubject').textContent = msg.subject || ''; + $('mmBody').innerHTML = msg.body || ''; // server-sanitized + $('msgModal').hidden = false; + $('mmAck').onclick = async () => { + $('msgModal').hidden = true; + try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} + setInboxBadge(Math.max(0, (Number($('inboxBadge') && $('inboxBadge').textContent) || 1) - 1)); + }; + } + + // ── coaching: every direct's rung, stalled flag, one-click nudge ── + // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── + async function pif(email, name, address) { + // Marty, 2026-09-27: the member must see the risk before every PIF. The platform holds no funds; this is a + // wallet-to-wallet gift in good faith, and nothing the site does can recover it. + const ok = await IAP.confirmBox('You are about to send POL from your own wallet directly to ' + name + '\'s wallet, in good faith, so they can buy their first package.\n\nInstantAdPay never holds or moves these funds and cannot reverse or recover them. Nothing obliges ' + name + ' to make a purchase. Only send what you are willing to give.', { title: 'Before you pay it forward', ok: 'I understand, continue', cancel: 'Cancel' }); + if (!ok) return; + let suggest = 25; + try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} + const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); + if (amt === null) return; + const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } + try { + IAP.status('Confirm the transfer in your wallet…', 'ok'); + const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); + const hash = await IAPWallet.sendPol(address, wei); + await api('/api/my/gift', { email, tx: hash, pol }); + IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); + playSound && playSound('chaching'); + } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } + } + // ── holding tank: waiting members, adopt, my open adoptions ── + const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; + async function loadTank() { + const el = $('tankList'); if (!el) return; + try { + const r = await (await fetch('/api/my/tank')).json(); + if (r.error) { el.innerHTML = ''; return; } + $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; + $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; + const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); + $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' + + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' + + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' + + '' + + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; + $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); + $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } + renderTank(el, r); + } catch (e) {} + } + function renderTank(el, r) { + const rows = listApply('tank', r.waiting); + el.innerHTML = ''; + el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on + el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + '' + + 'joined ' + ago(w.joined) + '' + memberChips(w) + '' + + 'last sign-in: ' + ago(w.lastSeen) + '' + + (r.eligible ? '' : '') + '
').join('') + : '

Nobody in the tank matches those filters.

'); + pageList('tank', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { + const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the InstantAdPay holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); + if (note === null) return; + try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } + // The announcement cards at the top of the Overview are repeated on a timer, so a member who has read + // one can put it away: dismissed for 24 hours on this browser (Marty, 2026-10-03; it used to come back + // at every sign-in and the cards stacked up), then it shows again so it is never gone for good. + const CARD_SNOOZE_MS = 24 * 3600 * 1000; + function cardHidden(key) { try { const t = Number(localStorage.getItem('iap-hide-' + key)); return t > 0 && Date.now() - t < CARD_SNOOZE_MS; } catch (e) { return false; } } + function cardDismiss(card, key) { + if (!card || card.querySelector('.card-x')) return; + const x = document.createElement('button'); + x.type = 'button'; x.className = 'card-x'; x.innerHTML = '×'; + x.title = 'Hide this for 24 hours'; + x.setAttribute('aria-label', 'Hide this message for 24 hours'); + x.addEventListener('click', () => { try { localStorage.setItem('iap-hide-' + key, String(Date.now())); } catch (e) {} card.hidden = true; }); + (card.querySelector('.card-head') || card).appendChild(x); + } + // Five Dollar Friday card on the Overview: the live wave on Fridays, the date the rest of the week + async function loadFridayCard() { + const card = $('fdfCard'); if (!card) return; + if (cardHidden('fdf')) { card.hidden = true; return; } + try { + const f = await (await fetch('/api/friday')).json(); if (!f.on) { card.hidden = true; return; } + card.hidden = false; + if (f.live && f.today) card.innerHTML = '

\u{1F4B5} It\u2019s Five Dollar Friday

+' + f.pct + '% credits on any pack today
' + + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Every $5+ package bought before midnight Central earns +' + f.pct + '% bonus credits the moment it settles. Your pack pays your sponsor line instantly; your line\u2019s packs pay you.

' + + ' Watch the wave'; + else card.innerHTML = '

\u{1F4B5} Five Dollar Friday

every Friday
' + + '

Every Friday (Central time), any ad package from $5 up earns +' + f.pct + '% bonus credits, added the moment it settles. The whole network buys on the same day, so every line gets paid at once. Next one: ' + (f.nextLabel || 'soon') + '.

' + + ''; + const b = $('fdfBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); + cardDismiss(card, 'fdf'); + } catch (e) {} + } + loadFridayCard(); setInterval(loadFridayCard, 120000); + // Wired Wednesday card on the Overview: the live wave on Wednesdays, the date the rest of the week + async function loadWednesdayCard() { + const card = $('wwCard'); if (!card) return; + if (cardHidden('ww')) { card.hidden = true; return; } + try { + const f = await (await fetch('/api/wednesday')).json(); if (!f.on) { card.hidden = true; return; } + card.hidden = false; + if (f.live && f.today) card.innerHTML = '

⚡ It’s Wired Wednesday

+' + f.pct + '% credits on any $' + f.minUsd + '+ pack today
' + + '

' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' so far today from ' + f.today.buyers + ' buyer' + (f.today.buyers === 1 ? '' : 's') + ', ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in, ' + f.today.polPaid.toFixed(2) + ' POL paid to members in the same transactions. Buy any $' + f.minUsd + '+ package before midnight Central and +' + f.pct + '% is wired into your balance the moment it settles, good for any format.

' + + ' How it works'; + else card.innerHTML = '

⚡ Wired Wednesday

every Wednesday
' + + '

Every Wednesday (Central time), any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles, purchased-grade so they run on any format, login ads included. Next one: ' + (f.nextLabel || 'soon') + '.

' + + ''; + const b = $('wwBuy'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); }); + cardDismiss(card, 'ww'); + } catch (e) {} + } + loadWednesdayCard(); setInterval(loadWednesdayCard, 120000); + + // ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ---- + const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }); + const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, ''); + // Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add + // islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time. + // 2026-10-22 (Dallas's structure): + Sovereign (monthly) and Legend (yearly). Names and what each includes come from the server + // (gamepass.js TIER_DEFS, row.perks); GP_TIER_PERKS is only the fallback for an older server answer. + const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)'; + const GP_TIER_PERKS = { + weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'], + explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'], + champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'], + }; + const gpLen = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days'; + function renderPassTiers(card, gp, highlight) { + const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier); + const state = top ? '' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '' + : 'No pass active'; + const caps = gp.caps || {}; + const capsLine = caps.enforced ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : ''; + const box = r => { + const btn = r.waiting ? '' + : r.open ? '' + : 'Not on sale right now. Your pass keeps running.'; + return '

' + esc(r.name) + '

' + + '

$' + r.usd + ' for ' + gpLen(r.days) + '

' + + '
    ' + (r.perks || GP_TIER_PERKS[r.tier] || []).map(x => '
  • ' + esc(x) + '
  • ').join('') + '
' + + '

' + (r.active ? 'Active until ' + esc(gpCT(r.until)) + '' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '

' + + btn + '
'; + }; + card.hidden = false; card.classList.toggle('gp-hl', !!highlight); + card.innerHTML = '

\u{1F39F}️ Game Passes

weekly, monthly or yearly · every game
' + + (gp.tierPreview ? '

Admin preview. The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings.

' : '') + + '

' + state + '

' + + '

Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. Each higher pass includes everything below it and adds more of Shards of Valor: weapons, gear, bonus islands, heroes and a higher level cap. Paid passes add heroes, islands, a higher level cap and new looks. Pass gear is never better than gear players can earn, and passes never pay more POL.

' + + '
' + rows.map(box).join('') + '
' + + (capsLine ? '

' + capsLine + '

' : '') + + '

Every pass is paid by a new package purchase of at least its price, so your sponsor and team are paid; you keep the package credits for your ads. Credits you already hold never buy a pass. Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.

'; + card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => { + const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return; + const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + gpLen(r.days) : 'Get ' + r.name + ' for ' + gpLen(r.days)) + ' ($' + r.usd + ')? Every pass is paid by a new package purchase of $' + r.package + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the pass starts the moment it settles. Credits you already hold never buy a pass. The same POL caps as every pass: no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' }); + if (!yes) return; + b.disabled = true; + try { + const x = await api('/api/my/gamepass/buy', { tier: r.tier }); + if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'ok'); setPane('buy'); return; } + IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok'); + await loadGamePassCard(true); + } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy'))); + if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } + } + // What the Pass adds in each game (Marty, 2026-10-22: members must see what they are buying). Keep in step with the games' perks. + const GP_PERKS = [ + ['PolHunter', '5 missions a day instead of 3, plus 2 Ad Detective cases a day'], + ['Gem Kingdom', 'one free continue every day'], + ['Spooky Doors', 'one extra door every day'], + ['ClutterHunt', '2 bonus hints every day'], + ['SpellWheel', 'daily streak pays 0.30 POL instead of 0.15, plus 1 free hint a day'], + ['PolyBreak', 'daily gem limit 1.5 POL instead of 0.5, plus an extra paddle every round'], + ['PolyWarriors', 'a 4th daily mission, and defense pays 25 Circuits instead of 15'], + ['Drip Runner', 'a free shield at the start of every run'], + ['Road Agent', '2 patrols a day and 25% more scrap'] + ]; + function gpPerksHtml() { + return '

What you get

' + + '' + + '' + + '
Every gameDaily POL caps of 1.50 a day on repeatable rewards (free play 0.30) and 5 a day in all (free play 2), counted across all nine games
WeeklyA seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays
BadgeThe gold Game Pass badge with your name, to share or post
' + + '

In each game

' + + GP_PERKS.map(p => '').join('') + '
' + p[0] + '' + p[1] + '
' + + '

The Pass never changes how much a reward pays: it lets you play and collect more each day.

'; + } + async function loadGamePassCard(highlight) { + const card = $('gpCard'); if (!card) return; + let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} + if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; } + if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); + // Five Dollar Friday + the pass (Marty 2026-10-23): the package that starts the pass also gets the Friday bonus, so say so on Fridays + let fdf = ''; try { const f = await (await fetch('/api/friday')).json(); if (f && f.on && f.live) { const base = gp.price || 500, got = Math.round(base * (1 + (Number(f.pct) || 20) / 100)); + fdf = '

\u{1F383} It\u2019s Five Dollar Friday. The $' + (gp.usd || 5) + ' package that starts your pass gets +' + (Number(f.pct) || 20) + '% too, so you get the ' + (gp.days || 7) + '-day pass and keep ' + got.toLocaleString() + ' ad credits. Tap Get the Pass first, then buy the package.

'; } } catch (e) {} // a tier above weekly on sale (or admin preview, or a holder) + const caps = gp.caps || {}; const price = gp.price || 500; + const state = gp.active ? 'Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '' + : gp.waiting ? 'Waiting for a $' + (gp.usd || 5) + ' package' : 'Not active'; + const capsLine = caps.enforced + ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' + : gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.' + : 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.'; + card.hidden = false; card.classList.toggle('gp-hl', !!highlight); + card.innerHTML = '

\u{1F39F}\uFE0F Game Pass

$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games
' + + '

' + state + '

' + + fdf + + '

Free play pays real POL every day. The Pass plays more: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly Pass Tournament with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.

' + + gpPerksHtml() + + '

' + capsLine + '

' + + (gp.waiting ? '

Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.

' : '') + + '

' + + (gp.waiting ? '' : '') + + 'Paid by a new $' + (gp.usd || 5) + ' or bigger package, so your sponsor and team are paid. You keep the package credits for your ads; credits you already hold never buy a pass.

'; + const b = $('gpBuy'); if (b) b.addEventListener('click', async () => { + const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + '? The Pass is paid by a new package purchase of $' + (gp.usd || 5) + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the Pass starts the moment it settles. Credits you already hold never buy a pass.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' }); + if (!yes) return; + b.disabled = true; + try { + const r = await api('/api/my/gamepass/buy'); + if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'ok'); setPane('buy'); return; } + IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok'); + await loadGamePassCard(true); + try { await loadDashboard(); } catch (e) {} // unlocks the Game Pass badge at once (toast + team post) + } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + }); + const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy')); + if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } + } + // Overview nudge: a game reported this member hit the free cap (polgrant lastCapHit). Shown once a day per browser, never to pass holders. + async function loadGpNudge() { + const card = $('gpNudge'); if (!card) return; + if (cardHidden('gpnudge')) { card.hidden = true; return; } + let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} + if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; } + const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' }; + card.hidden = false; + card.innerHTML = '

\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '

free play keeps paying; the Pass plays more
' + + '

Every member earns real POL in the games up to the daily cap. The Game Pass raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with a new package), adds the weekly Pass Tournament and a perk in every game.

' + + ''; + $('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1')); + try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day + cardDismiss(card, 'gpnudge'); + } + loadGpNudge(); + // launch-day surprise (Marty, 2026-09-20): PolHunter appears at siteConfig.launchAt, not a minute before. + // The card and the menu entry flip on their own if the dashboard is already open. + let phShown = false; + const LAUNCH_CARD_DAYS = 7; + async function launchReveal() { + try { + const nav = $('polhunterNav'); if (nav) nav.hidden = false; // listed in the menu from launch morning (Marty, 2026-09-21); the card below is the announcement and waits for launchAt + const cfg = await IAP.getConfig(); const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; + if (!at || Date.now() < at) return; + // launch cards retire 7 days after launch (Marty, 2026-10-03: old announcements kept stacking up) + if (Date.now() > at + LAUNCH_CARD_DAYS * 86400000) { const c = $('phLaunch'); if (c) c.hidden = true; return; } + const card = $('phLaunch'); if (!card || phShown) return; + if (cardHidden('phLaunch')) { card.hidden = true; return; } + phShown = true; card.hidden = false; + card.innerHTML = '

\u{1F3AF} New today: PolHunter

Launch-day surprise
' + + '

Missions across our sites. Visit the site, find your personal code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in the wallet on this account, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly POL prizes, and badge cards you can share. Your PolHunter share link puts sign-ups on your InstantAdPay line.

' + + 'Open my PolHunter board The teaser'; + const tb = $('phTrain'); if (tb) tb.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="training"]'); if (m) m.click(); }); + cardDismiss(card, 'phLaunch'); + } catch (e) {} + } + launchReveal(); setInterval(launchReveal, 30000); + // came from PolHunter (iap.return cookie): one card at the top of the Overview that sends them back + // Games hub (2026-10-01): one card per game, the player's own progress where the game reports it + // PassiveDrip, our earning site: a card on the Earn tab (not a game, Marty 2026-10-01) + async function loadPdCard() { + const card = $('pdCard'); if (!card) return; + let j = null; try { j = await (await fetch('/api/my/passivedrip/card')).json(); } catch (e) {} + if (!j || !j.show) { card.hidden = true; return; } + card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || ''; + } + async function loadGames(q) { + const el = $('gamesGrid'); if (!el) return; + loadGamePassCard(/(^|&)pass=1(&|$)/.test(q || '')).catch(() => {}); + let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {} + const list = (g && g.games) || []; + if (!list.length) { el.innerHTML = '

No games are open yet. Check back soon.

'; return; } + // a seasonal card (x.season, 2026-10-02) wears the pink limited-time ribbon from the Spooky Doors UI kit + el.innerHTML = list.map(x => '
' + (x.soon ? '' : x.season && x.season.ends ? 'Limited time \u00b7 ends ' + esc(x.season.ends) + '' : '') + '
' + esc(x.tag || '') + '

' + esc(x.name) + (x.preview ? '' + esc(x.previewNote || 'preview, not live') + '' : '') + '

' + esc(x.blurb) + '

' + (x.progress && x.progress.line ? '
' + esc(x.progress.line) + '
' : '') + '

Pays: ' + esc(x.pays || 'POL') + '

' + (x.perk ? '

Members get ' + esc(x.perk) + '

' : '') + (x.soon ? '' + esc(x.soon) + '' : '' + esc(x.cta || 'Play') + '') + '
').join(''); + } + async function loadReturnCard() { + const card = $('phReturn'); if (!card) return; + if (cardHidden('phReturn')) { card.hidden = true; return; } + try { + const me = await (await fetch('/api/me')).json(); + if (me.returnTo !== 'polhunter') { card.hidden = true; return; } + card.hidden = false; + card.innerHTML = '

You came from PolHunter

' + (me.address + ? '

Your wallet is linked, so your board is ready.

Back to PolHunter' + : '

One step left: link the wallet your POL drips will be paid to. The moment it is linked you go straight back.

'); + const b = $('phGoWallet'); if (b) b.addEventListener('click', () => { const m = document.querySelector('.bo-menu [data-pane="wallet"]'); if (m) m.click(); }); + cardDismiss(card, 'phReturn'); + } catch (e) {} + } + async function loadCoach() { + loadReturnCard(); + loadTank(); + try { + const r = await (await fetch('/api/my/coach')).json(); + const el = $('coachList'); if (!el || r.error) return; + const d = r.directs || []; + $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; + if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } + el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') + + (x.polWaiting ? ' ' + x.polWaiting.toFixed(2) + ' POL waiting · no wallet' : '') + + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' + + '' + esc(x.label) + ' → ' + esc(x.next) + '' + + 'rung ' + x.rung + '/6' + + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' + + '' + + (x.address ? ' ' : '') + + (x.free && x.rescue ? ' ' : '') + + (x.free ? ' ' : '') + '
').join(''); + pageList('coach', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { + await openConvo(b.dataset.nudge, b.dataset.nname); + const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } + })); + el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; + try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + // schedule chips on the campaign table (local time) + by-hour view bars + const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + // featured run column: days left of the booked total (Hugh, 2026-09-16: "says 14 but it's actually 7") + function featRun(c) { + const total = Number(c.body || 0), now = Date.now(); + if (c.status === 'done' || !c.expires || c.expires <= now) return '' + total + ' day' + (total === 1 ? '' : 's') + ' done'; + const left = Math.max(1, Math.ceil((c.expires - now) / 86400000)); + return '' + left + ' of ' + total + ' day' + (total === 1 ? '' : 's') + ' left'; + } + function schedChips(c) { + const now = Date.now(); let s = ''; + if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; + if (c.expires && c.type === 'featured') { const day = new Date(c.expires - 1).toLocaleDateString([], { month: 'short', day: 'numeric' }); s += ' ' + (c.expires > now ? 'runs through ' : 'ran through ') + day + ''; } + else if (c.expires) s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; + return s; + } + function geoLine(rows) { + if (!rows || !rows.length) return ''; + return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; + } + function hourBars(utc) { + if (!utc || !utc.some(n => n)) return ''; + // rotate the 24 UTC buckets into the viewer's local hours + const local = new Array(24).fill(0); + for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; + const max = Math.max(...local); + const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); + return '
' + local.map((n, h) => + '').join('') + + '
views by hour · last 7 days · your time
'; + } + // ── link stats: views, joins, buyers per angle ── + async function loadLinkStats() { + try { + const r = await (await fetch('/api/my/linkstats')).json(); + const t = $('linkStatsTable'); if (!t || r.error) return; + const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); + if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } + t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' + + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : a.angle === 'page' ? 'any page (viral link)' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); + const st = $('linkSrcTable'); + if (st) { + const src = (r.sources || []).filter(x => x.views || x.joins); + st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' + + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') + : 'Sources appear as visits arrive.'; + pageList('linksrc', st.parentElement, 'table tr:has(td)', { per: LINE_PER }); + } + pageList('linkangles', t.parentElement, 'table tr:has(td)', { per: LINE_PER }); + } catch (e) {} + } + // ── prospects: the member's own follow-up list ── + let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; + // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── + let PIPE = null, PIPE_KEY = null; + const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; + const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; + function pipeCardHtml(c, showStage) { + const today = new Date(); today.setHours(23, 59, 59, 999); + const due = c.followUp && c.followUp <= today.getTime(); + const chips = []; + if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); + if (due) chips.push('follow up'); + else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); + if (c.tag) chips.push('' + esc(c.tag) + ''); + if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); + const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; + return '
' + + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' + + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' + + (c.note ? '
' + esc(c.note) + '
' : '') + + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; + } + async function loadPipeline() { + try { + const r = await (await fetch('/api/my/pipeline')).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + if (!r.live) { + $('pipeSoon').hidden = false; $('pipeLive').hidden = true; + $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; + return; + } + PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; + const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } + $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; + $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; + $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; + $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); + $('pipeBoard').querySelectorAll('.pipe-col').forEach((col, i) => pageList('pipe-' + i, col, ':scope > [data-pk]')); + $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { + el.addEventListener('click', () => openPipeCard(el.dataset.pk)); + el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); + }); + if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } + } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } + } + function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } + function fillPipeCard(c) { + $('pipeCardName').textContent = c.name; + const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; + $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); + $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); + const say = (c.say || '').replace('{{link}}', pipeInvite()); + $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; + $('pipeSend').hidden = c.kind !== 'member' || !c.email; + $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; + const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); + $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; + $('pipeCard').hidden = false; + } + function openPipeCard(key) { + const c = allPipeCards().find(x => x.key === key); if (!c) return; + PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); + fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); + } + if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); + if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { + if (!PIPE_KEY) return; + try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } + catch (e) { IAP.status(e.message, 'bad'); } + }); + if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); + if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { + const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; + openConvo(c.email, c.name); + const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } + }); + async function loadProspects() { + try { + const r = await (await fetch('/api/my/prospects')).json(); + if (r.error) return; + PP_STATUSES = r.statuses || PP_STATUSES; + const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); + const list = r.prospects || []; const el = $('prospectList'); if (!el) return; + if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } + const today = new Date(); today.setHours(0, 0, 0, 0); + el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' + + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' + + '' + + '' + + '
'; }).join(''); + const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; + pageList('prospects', el, ':scope > .lin-row', { per: LINE_PER }); + el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); + el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); + el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); + } catch (e) {} + } + if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { + e.preventDefault(); + try { + await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); + $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); + } catch (err) { IAP.status(err.message, 'bad'); } + }); + // ── broadcast templates ── + const BC_TEMPLATES = [ + { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, + { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, + { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, + { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, + { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } + ]; + (function () { + const w = $('bcTemplates'); if (!w) return; + w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); + w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); + })(); + // ── Qualified Start calculator ── + (function () { + const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; + const CR = { 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 }; + const calc = () => { + const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 20; + const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); + const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; + out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' + + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; + }; + n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); + })(); + + // ── downline lineage + sponsor broadcast + upline messages ── + async function loadLineage() { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineageWrap'); + if (r.error || !r.levels || !r.levels.every) return; + if (!r.levels.length || !r.levels.some(L => L.members.length)) { + el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; + return; + } + LINE_DATA = r; renderLineage(el); + } catch (e) {} + } + let LINE_DATA = null; + function renderLineage(el) { + const r = LINE_DATA; if (!r) return; + try { + const all = r.levels.reduce((n, L) => n + L.members.length, 0); + const shown = r.levels.map(L => ({ level: L.level, members: listApply('line', L.members) })); + const kept = shown.reduce((n, L) => n + L.members.length, 0); + el.innerHTML = ''; + el.appendChild(listBar('line', all, kept, () => renderLineage(el))); + el.insertAdjacentHTML('beforeend', !kept ? '

Nobody in your downline matches those filters.

' : shown.map(L => !L.members.length ? '' : + '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' + + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' + + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '' + memberChips(m) + '') + '' + + '' + + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' + + '' + new Date(m.joined).toLocaleDateString() + '' + + (m.email ? '' : '') + + (m.ref && !m.own ? '' : '') + + '
' + (m.ref && !m.own ? '' : '')).join('') + + '
').join('')); + el.querySelectorAll('[data-cemail]').forEach(b => + b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); + el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); + const focusRef = LINE_FOCUS_REF ? LINE_FOCUS_REF.replace(/"/g, '') : null; + el.querySelectorAll('.lin-lvl').forEach((lv, i) => pageList('line-' + i, lv, ':scope > .lin-row', { per: LINE_PER, tail: '.lin-act', focus: focusRef ? row => !!row.querySelector('[data-act="' + focusRef + '"]') : null })); + if (LINE_FOCUS_REF) { + const ref = LINE_FOCUS_REF; LINE_FOCUS_REF = null; + const b = el.querySelector('[data-act="' + ref.replace(/"/g, '') + '"]'); + if (b) { const row = b.closest('.lin-row'); if (row) { row.classList.add('lin-focus'); setTimeout(() => row.classList.remove('lin-focus'), 4000); } toggleLineActivity(b); setTimeout(() => (row || b).scrollIntoView({ behavior: 'smooth', block: 'center' }), 150); } + } + } catch (e) {} + } + // who is working: per-member activity drop-down under the row (any of the three levels) + const lineActCache = {}; + async function toggleLineActivity(btn) { + const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; + const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; + if (!open) return; + if (!lineActCache[btn.dataset.act]) { + box.innerHTML = 'Loading…'; + try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } + } + const a = lineActCache[btn.dataset.act]; + if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } + const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; + const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; + const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); + box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) + + chip('Joined', new Date(a.joined).toLocaleDateString()) + + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') + + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') + + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') + + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') + + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') + + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') + + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') + + '' + (working ? 'Working' : 'Quiet') + ''; + } + async function loadUplineMessages() { + try { + const r = await (await fetch('/api/my/messages')).json(); + if (r.error) return; + const card = $('upMsgCard'), list = $('upList'); + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + list.innerHTML = r.items.map(i => '
' + + '
' + esc(i.subject) + '' + + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' + + '
' + (i.body || '') + '
').join(''); + pageList('upmsg', list, ':scope > .promo-block', { per: 5 }); + // opening the pane marks them read + for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); + } catch (e) {} + } + // broadcast composer editor (its own small rich editor, server sanitizes) + document.querySelectorAll('[data-bc]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); + document.querySelectorAll('[data-bcblock]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); + if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; + const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } + }); + // broadcast send (2026-10-05, Brian: "clicking send didn't give me anything to feel it was sent"): a pop-up either way, + // and an expired sign-in keeps the draft so nothing typed is lost + const BC_DRAFT = 'iap.bcDraft'; + try { const d = JSON.parse(localStorage.getItem(BC_DRAFT) || 'null'); if (d && $('bcSubject') && !$('bcSubject').value) { $('bcSubject').value = d.subject || ''; $('bcEd').innerHTML = d.body || ''; if ($('bcScope') && d.scope) $('bcScope').value = d.scope; localStorage.removeItem(BC_DRAFT); } } catch (e) {} + if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', async () => { + const btn = $('bcSendBtn'); btn.disabled = true; const label = btn.textContent; btn.textContent = 'Sending…'; + try { + const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); + $('bcSubject').value = ''; $('bcEd').innerHTML = ''; + $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; + await IAP.confirmBox('Your broadcast was delivered to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + ' in your line. They see it in their Messages, and get a copy by email. You can send your next broadcast in 24 hours.', { title: '✅ Broadcast sent', ok: 'Done', noCancel: true }); + } catch (e) { + const msg = (e && e.message) || String(e); + if (/sign in/i.test(msg)) { + try { localStorage.setItem(BC_DRAFT, JSON.stringify({ subject: $('bcSubject').value, body: $('bcEd').innerHTML, scope: $('bcScope').value })); } catch (x) {} + if (await IAP.confirmBox('Your sign-in expired, so the broadcast was NOT sent. Your message is saved: sign in again and it will be waiting for you here.', { title: 'Not sent yet', ok: 'Sign in again', cancel: 'Close' })) location.href = '/my#line'; + } else { + await IAP.confirmBox(msg + ' Your message is still in the box.', { title: 'Broadcast not sent', ok: 'OK', noCancel: true }); + } + } finally { btn.disabled = false; btn.textContent = label; } + }); + + // ── solo-ads inbox: list, read view, dwell-gated read reward ── + let ibTimer = null; + function setInboxBadge(n) { + for (const id of ['inboxBadge', 'inboxBadge2']) { + const b = $(id); + if (b) { b.hidden = !n; b.textContent = n; } + } + } + // Earn credits sub-tabs: Watch ads | Inbox + let earnSub = 'watch'; + function setEarnSub(which) { + earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; + if (earnSub !== 'videos' && vidState.token) stopVideo(); + const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); + if (w) w.hidden = earnSub !== 'watch'; + if (i) i.hidden = earnSub !== 'inbox'; + if (v) v.hidden = earnSub !== 'videos'; + if (vs) vs.hidden = earnSub !== 'visits'; + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.classList.toggle('on', b.dataset.earn === earnSub)); + if (earnSub === 'inbox') loadInbox(); + else if (earnSub === 'videos') loadVideoStatus(); + else if (earnSub === 'visits') loadVisitStatus(); + else earnRefresh(); + } + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.addEventListener('click', () => setEarnSub(b.dataset.earn))); + // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) + let tkState = null; + async function loadToolkit() { + try { + const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; + $('tkTierLine').textContent = 'you are at ' + names[r.tier]; + $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); + $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; + if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } + $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; + $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; + if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } + renderTkTools(r); + $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; + } catch (e) { console.error('toolkit', e); } + } + // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops + const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; + async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } + function renderTkTools(r) { + const at = tkRank[r.tier] || 0; + // Spark + const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; + if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; + else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } + // Circuit + const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; + if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; + else { loadTkVideos(r); loadTkSplit(); } + // Nexus + const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; + if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; + else { loadTkTeam(); renderTkPartner(r); } + } + let tkVidTimer = null; + async function loadTkVideos(r) { + const box = $('tkVideos'); + if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } + if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } + try { + const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; + box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); + clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); + } catch (e) {} + } + async function loadTkSplit() { + try { + const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; + const rows = sp.rows.filter(x => x.views || x.joins); + $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' + : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; + } catch (e) {} + } + let tkTeamData = null; + async function loadTkTeam() { + try { + const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; + $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; + const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); + $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') + + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); + $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); + } catch (e) {} + } + function renderTkPartner(r) { + const pk = r.partner; + $('tkPartner').innerHTML = pk + ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' + : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; + } + document.addEventListener('click', async ev => { + const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; + if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } + if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } + if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } + if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } + if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } + if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } + if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } + if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } + }); + $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); + async function tkSendBroadcast() { + const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); + const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); + if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; + const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); + if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); + } + async function tkGenerate() { + const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; + try { + const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; + IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); + loadToolkit(); loadDashboard(); + } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } + finally { btn.disabled = false; btn.textContent = 'Write it'; } + } + if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } + // promo tools: pill menu switches between posts / swipes / banners / wall / videos + function setPromoSub(name) { + const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'games']; + if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06) + if (name === 'toolkit') loadToolkit(); + const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]'); + if (!ids.includes(name) || !pill || pill.hidden) name = 'posts'; + ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { + b.classList.toggle('on', b.dataset.promo === name); + b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); + }); + try { localStorage.setItem('iap.promoSub', name); } catch (e) {} + } + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => + b.addEventListener('click', () => setPromoSub(b.dataset.promo))); + try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } + async function loadInbox() { + try { + const r = await (await fetch('/api/my/inbox')).json(); + if (r.error) return; + $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' + + r.readCap + ' rewarded reads a day)'; + const el = $('ibList'); + $('inboxReadCard').hidden = true; + $('inboxListCard').hidden = false; + setInboxBadge(r.unread); + if (!r.items.length) { + el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; + return; + } + el.innerHTML = ''; + for (const i of r.items) { + const d = document.createElement('div'); + d.className = 'ib-row' + (i.read ? '' : ' unread'); + d.innerHTML = '' + + (i.rewarded ? 'claimed' : i.read ? '' : 'new') + + '' + new Date(i.delivered).toLocaleDateString() + ''; + d.querySelector('.sub').textContent = i.subject || '(no subject)'; + d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); + d.addEventListener('click', () => openInboxItem(i.id)); + el.appendChild(d); + } + } catch (e) {} + } + async function openInboxItem(id) { + try { + const r = await (await fetch('/api/my/inbox/' + id)).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('inboxListCard').hidden = true; + $('inboxReadCard').hidden = false; + $('ibSubject').textContent = r.subject || '(no subject)'; + $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); + $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit + const mv = $('ibMedia'); + mv.hidden = !r.mediaUrl; + mv.innerHTML = !r.mediaUrl ? '' + : r.mediaType === 'video' + ? '' + : 'attachment'; + // the read reward needs BOTH the dwell AND an actual click-through to the + // advertiser — the visit is what makes the ad worth the sender's credits + const visit = $('ibVisit'); + visit.href = r.url; + visit.textContent = r.ctaLabel || 'Learn more'; + visit.target = '_blank'; + const btn = $('ibClaimBtn'); + clearInterval(ibTimer); + if (r.rewarded) { + btn.hidden = true; + visit.classList.remove('cta-need'); + $('ibHint').textContent = 'Read reward already claimed for this one.'; + return; + } + let dwellDone = false; + let visited = !!r.visited; + btn.hidden = false; + btn.disabled = true; + visit.classList.toggle('cta-need', !visited); + let left = r.dwell; + const refresh = () => { + if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } + if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } + btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; + }; + $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; + refresh(); + // countdown pauses off-tab; the server separately enforces the dwell on its own clock + ibTimer = setInterval(() => { + if (!tabActive()) return; + left -= 1; + if (left > 0) { refresh(); return; } + clearInterval(ibTimer); + dwellDone = true; + refresh(); + }, 1000); + // clicking the CTA records the visit (and counts the advertiser's click) + visit.onclick = async () => { + visited = true; + visit.classList.remove('cta-need'); + try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} + refresh(); + }; + btn.onclick = async () => { + try { + const c = await api('/api/my/inbox/' + id + '/claim'); + IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); + btn.hidden = true; + $('ibHint').textContent = 'Claimed. Head back for the next one.'; + loadDashboard(); + } catch (e2) { IAP.status(e2.message, 'bad'); } + }; + } catch (e) {} + } + $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); + + // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── + function fillPromo(link, me) { + if (window.IAPPromo) IAPPromo.fill(link, me || {}); + // banner kit + const bwrap = $('promoBanners'); + if (bwrap && !bwrap.dataset.filled) { + bwrap.dataset.filled = '1'; + // one collapsed accordion per size / use, so the kit stays scannable as it grows + const GROUPS = [ + { title: 'Stop chasing shiny objects · share the article with your link', bridge: { page: 'blog/stop-chasing-shiny-objects', name: 'shiny-objects article', short: 'article' }, items: [ + { file: 'iap-shiny-objects-wide-1200x630.jpg', size: '1200×630 · the article cover (widescreen art) · Facebook, X, link previews' }, + { file: 'iap-shiny-objects-wide-1600x896.jpg', size: '1600×896 · full widescreen art · YouTube community, LinkedIn, blogs' }, + { file: 'iap-shiny-objects-1200x630.jpg', size: '1200×630 · tight crop of the portrait art' }, + { file: 'iap-shiny-objects-1080x1080.jpg', size: '1080×1080 · square · Instagram, Facebook, Telegram' }, + { file: 'iap-shiny-objects-1080x1349.jpg', size: '1080×1349 · portrait · Instagram feed, Pinterest' } ] }, + { title: 'Wired Wednesday · share with your /wednesday link', bridge: { page: 'wednesday', name: 'Wired Wednesday', short: 'Wednesday' }, items: [ + { file: 'iap-wired-wednesday-1200x630.jpg', size: '1200×630 · Wired Wednesday · social card, link previews, Daily News' }, + { file: 'iap-wired-wednesday-1080x1080.jpg', size: '1080×1080 · Wired Wednesday · Instagram, Facebook, Telegram' }, + { file: 'iap-wired-wednesday-728x90.png', size: '728×90 · Wired Wednesday · leaderboard' }, + { file: 'iap-wired-wednesday-300x250.png', size: '300×250 · Wired Wednesday · rectangle' } ] }, + { title: 'Five Dollar Friday · share with your /friday link', friday: true, items: [ + { file: 'iap-five-dollar-friday-october-1200x630.jpg', size: '1200×630 · Five Dollar Friday · October porch, bright' }, + { file: 'iap-five-dollar-friday-october-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · October porch, square' }, + { file: 'iap-five-dollar-friday-v2-1200x630.jpg', size: '1200×630 · Five Dollar Friday · loft, Central-time window' }, + { file: 'iap-five-dollar-friday-dark-1200x630.jpg', size: '1200×630 · Five Dollar Friday · dark studio' }, + { file: 'iap-five-dollar-friday-v2-1080x1080.jpg', size: '1080×1080 · Five Dollar Friday · square for Instagram and feeds' } ] }, + { title: '600×300 · traffic exchanges and splash pages', items: [ + { file: 'iap-advertise-earn-600x300.png', size: '600×300 · advertise and earn · traffic exchanges, splash pages, safelist mailers' } ] }, + { title: '1200×630 · social posts, link previews, Daily News covers', items: [ + { file: 'iap-hero-1200x630.png', size: '1200×630 · hero · advertise and earn' }, + { file: 'iap-advertise-earn-1200x630.jpg', size: '1200×630 · advertise and earn instantly, locked in code' }, + { file: 'iap-team-build-tiers-1200x630.jpg', size: '1200×630 · team build and instant payments · 50 / 20 / 10 tiers' }, + { file: 'iap-team-build-tiers-v2-1200x630.jpg', size: '1200×630 · team build and instant payments · variant 2' }, + { file: 'iap-instant-payments-tiers-1200x630.jpg', size: '1200×630 · instant payments, direct commissions · tiers' }, + { file: 'iap-instant-payments-tiers-v2-1200x630.jpg', size: '1200×630 · instant payments · variant 2' }, + { file: 'iap-multistream-info-1200x630.jpg', size: '1200×630 · multi-stream revenue · "INFO or message me" CTA' }, + { file: 'iap-multistream-info-v2-1200x630.jpg', size: '1200×630 · multi-stream revenue · variant 2' }, + { file: 'iap-success-path-info-1200x630.jpg', size: '1200×630 · success path, training and coaching · "INFO or message me" CTA' }, + { file: 'iap-success-path-link-1200x630.jpg', size: '1200×630 · success path · "link in the description" (feed posts, Daily News)' }, + { file: 'iap-success-path-coaching-1200x630.jpg', size: '1200×630 · success path · quality network traffic' } ] }, + { title: 'Five Dollar Friday · every Friday, +20% credits on any $5+ pack', items: [ + { file: 'iap-five-dollar-friday-1200x630.jpg', size: '1200×630 · social card, Daily News, feed posts' }, + { file: 'iap-five-dollar-friday-1080x1080.jpg', size: '1080×1080 · Instagram, Facebook, Telegram' }, + { file: 'iap-five-dollar-friday-728x90.png', size: '728×90 · leaderboard' }, + { file: 'iap-five-dollar-friday-300x250.png', size: '300×250 · rectangle' } ] }, + { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ + { file: 'iap-1080x1080.png', size: '1080×1080 · square' }, + { file: 'iap-1080x1920.png', size: '1080×1920 · story / reel' } ] }, + { title: '1280×720 · Telegram and group posts', items: [ + { file: 'iap-1280x720.png', size: '1280×720 · group post' } ] }, + { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ + { file: 'iap-728x90.png', size: '728×90 · leaderboard' }, + { file: 'iap-advertise-earn-728x90.png', size: '728×90 · advertise and earn instantly · Join free' }, + { file: 'iap-ledger-728x90.png', size: '728×90 · advertising that pays you on-chain · See the ledger' }, + { file: 'iap-468x60.png', size: '468×60 · banner' }, + { file: 'iap-ledger-468x60.png', size: '468×60 · advertising that pays you on-chain · See the ledger' }, + { file: 'iap-320x50.svg', size: '320×50 · mobile leaderboard' } ] }, + { title: 'Rectangles and buttons · 336×280, 300×250, 125×125', items: [ + { file: 'iap-336x280.png', size: '336×280 · large rectangle' }, + { file: 'iap-advertise-earn-336x280.png', size: '336×280 · advertise and earn instantly' }, + { file: 'iap-advertise-earn-v2-336x280.png', size: '336×280 · advertise and earn · variant 2' }, + { file: 'iap-300x250.png', size: '300×250 · rectangle' }, + { file: 'iap-advertise-earn-300x250.png', size: '300×250 · advertise and earn instantly' }, + { file: 'iap-team-build-link-300x250.jpg', size: '300×250 · team build and instant payments · "link in the description"' }, + { file: 'iap-125x125.png', size: '125×125 · square button' } ] }, + { title: 'Skyscrapers · 160×600, 120×600', items: [ + { file: 'iap-160x600.png', size: '160×600 · wide skyscraper' }, + { file: 'iap-120x600.png', size: '120×600 · skyscraper' } ] } + ]; + bwrap.innerHTML = ''; + for (const g of GROUPS) { + const det = document.createElement('details'); + det.className = 'pb-acc'; + det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; + const grid = det.querySelector('.pb-grid'); + const bridge = g.bridge || (g.friday ? { page: 'friday', name: 'Five Dollar Friday', short: 'Friday' } : null); + if (bridge) { + // the bridge page with this member's referral: any public page + ?ref sets the sponsor cookie + const inv = (document.getElementById('inviteLine') || {}).textContent || ''; + const fl = inv.replace(/\/join\/([^/?#]+).*$/, '/' + bridge.page + '?ref=$1'); + const note = document.createElement('div'); + note.className = 'pb-note'; + note.innerHTML = 'Post any of these with your ' + esc(bridge.name) + ' link: '; + note.querySelector('b').textContent = fl; + const cp = document.createElement('button'); cp.className = 'btn small'; cp.textContent = 'Copy my ' + bridge.short + ' link'; + cp.addEventListener('click', async () => { try { await navigator.clipboard.writeText(fl); IAP.status(bridge.short + ' link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } }); + note.appendChild(cp); + grid.before(note); + } + for (const b of g.items) { + const url = location.origin + '/banners/' + b.file; + const d = document.createElement('div'); + d.className = 'pb-item'; + d.innerHTML = 'InstantAdPay banner ' + b.size + '' + + '
' + b.size + '
'; + const dl = document.createElement('a'); + dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/banners/' + b.file; dl.setAttribute('download', b.file); + d.querySelector('.pb-row').appendChild(dl); + const btn = document.createElement('button'); + btn.className = 'btn small sec'; + btn.textContent = 'Copy image URL'; + btn.addEventListener('click', async () => { + try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } + catch (e) { IAP.status('Copy failed.', 'bad'); } + }); + d.querySelector('.pb-row').appendChild(btn); + grid.appendChild(d); + } + bwrap.appendChild(det); + } + } + } + + // ── profile ── (busy2 defers the busy lookup past its TDZ) + $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { + const r = await api('/api/my/profile', { username: $('pfUsername').value }); + IAP.status('You are @' + r.account.username + ' now.', 'ok'); + await render(); + })); + + // ── in-dashboard package buying ── + const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' }; + // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own + // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page + // otherwise. The site never touches funds — MoonPay is merchant of record. + async function openMoonpay(pol) { + try { + let addr = ''; + try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} + const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); + const r = await (await fetch(q)).json(); + if (r && r.url) { + window.open(r.url, '_blank', 'noopener'); + IAP.status(r.signed + ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' + : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); + } + } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } + } + // ── linked positions (Qualified Start) ── + const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; + let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) + async function loadPositions(me) { + try { + const r = await (await fetch('/api/my/positions')).json(); + if (r.error) return; + const list = r.positions || []; + const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' + + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' + + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' + + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' + + (!p.memberId ? '' : '') + + '
').join(''); + const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' + + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' + + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' + + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; + const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); + if ($('qsList')) $('qsList').innerHTML = html; + // Wallet tab: live POL balance of the linked wallet, and which package it covers + const wb = $('walletBal'); + if (wb && r.main && r.main.address && r.main.balanceWei != null) { + const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; + const usd = r.polUsd ? polN * r.polUsd : 0; + const pkgs = [5, 20, 50, 100, 250]; + const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; + wb.hidden = false; + wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') + + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); + } + if ($('posList')) $('posList').innerHTML = html; + if ($('posCard')) $('posCard').hidden = !list.length; + // "Buy from" picker: main + every position + const sel = $('buyFrom'); + if (sel) { + const keep = sel.value; + sel.innerHTML = '' + + list.map((p, i) => '').join(''); + noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); + if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; + $('buyFromWrap').hidden = !list.length; + } + document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; + try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { + const me = await (await fetch('/api/me')).json(); + if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); + if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); + if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; + IAP.status('Pick the new account in your wallet, then sign once…'); + const r = await IAPWallet.signIn({ asPosition: true, pick: true }); + $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; + IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); + await loadPositions(); + const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); + try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} + })); + async function loadBuyTiles() { + try { + const { products } = await (await fetch('/api/catalog')).json(); + const wrap = $('boTiles'); + wrap.innerHTML = ''; + products.sort((a, b) => a.priceCents - b.priceCents); + for (const p of products) { + const bonus = p.creditAmount - p.priceCents; + const div = document.createElement('div'); + div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); + div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' + + '
$' + Math.round(p.priceCents / 100) + '
' + + '
' + p.creditAmount.toLocaleString() + ' credits
' + + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' + + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' + + ''; + wrap.appendChild(div); + } + wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { + try { + b.disabled = true; + // the buyer's credits are read by the member id of their LINKED wallet. + // If they only connected a wallet (e.g. for the faucet) but never linked + // it, link it first (one signature) so the purchase's credits show up. + // retry these through transient failures — mobile drops in-flight + // fetches when the page returns from the wallet app-switch + const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; + const meNow = await jretry('/api/me'); + // which of the member's wallets is buying: the main wallet (default) or a + // linked position (Qualified Start). A position registers under the main + // member id on its first buy, so its sponsor is always this member. + const fromSel = $('buyFrom'); + const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; + if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } + if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } + if (!fromPos && !meNow.address) { + IAP.status('Link your wallet first — one quick signature…'); + await IAPWallet.signIn(); + } + const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); + if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member + await IAPWallet.connect(); + let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); + if (cur !== wantAddr) { + IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); + cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); + } + if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); + } + const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); + if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company + if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok'); + // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any + // transaction that spends most of the balance ("drain your wallet"), so Trust users + // get a heads-up first; other wallets go straight to the confirmation. + try { + const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() + const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); + if (bal < need) { + IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); + return; + } + const pct = Number(need * 100n / bal); + const isTrust = /trust/i.test(IAPWallet.walletName() || ''); + if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { + IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); + return; + } + } catch (e) { /* balance read failed: let the wallet decide */ } + IAP.status('Confirm the purchase in your wallet…'); + const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); + if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); + // a game sent them here to pay (PolyWarriors mint, Gem Kingdom Crowns, Spooky Doors costume): go straight back once it settles (Marty 2026-10-08) + const back = document.getElementById('pwBack') ? ['/pw/mint/resume', 'PolyWarriors'] : document.getElementById('gkBack') ? ['/gk/shop/resume', 'Gem Kingdom'] : document.getElementById('sdBack') ? ['/sd/shop/resume', 'Spooky Doors'] : null; + if (back) { IAP.status('Purchase settled on-chain. Taking you back to ' + back[1] + '…', 'ok'); setTimeout(() => { location.href = back[0]; }, 1800); return; } + IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); + await render(); + loadBuyTiles(); + } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } + finally { b.disabled = false; } + })); + // brand new to crypto? buy POL with a card, sent straight to the wallet + const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; + const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; + const cta = document.createElement('div'); + cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; + cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' + + ' Wallet and MoonPay guide'; + wrap.appendChild(cta); + const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); + } catch (e) {} + } + loadBuyTiles(); + + // ── earn-by-viewing: daily ad set with dwell, then claim ── + const earnState = { types: ['banner', 'text'], i: 0, timer: null }; + async function earnRefresh() { + try { + const st = await (await fetch('/api/my/earn')).json(); + if (st.error) return null; + $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; + loadFridayBank(); + $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); + if ($('earnActLink')) $('earnActLink').onclick = e => { e.preventDefault(); jumpTo('campaigns', 'creditActivity'); }; + const done = st.views >= st.target; + $('earnClaimBtn').hidden = !(done && !st.claimed); + if (st.claimed) { + $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; + // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign + const box = $('earnAdBox'); + if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' + + '
' + + (st.visitsLeft ? '' : '') + + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 + ? '' + : '') + '
'; + if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); + if ($('earnStartBtn')) $('earnStartBtn').hidden = true; + } else { + if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over + $('earnHint').textContent = done + ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' + : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); + } + return st; + } catch (e) { return null; } + } + async function earnShowAd() { + // each view happens full screen in its own tab: /view/ frames the + // advertiser's site, runs the countdown, then a human check credits it + const type = earnState.types[earnState.i++ % earnState.types.length]; + let r = null; + try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} + const box = $('earnAdBox'); + if (!r || !r.ad || !r.viewUrl) { + await earnRefresh(); + box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target + ? 'Set complete for today.' + : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; + return; + } + openAdOverlay(r.viewUrl); + box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; + $('earnStartBtn').textContent = 'View next ad'; + } + // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs + // badly), no window.close needed. The /view page runs the dwell + check inside, + // messages back when it credits or when the user is done. + function openAdOverlay(url) { + closeAdOverlay(); + const back = document.createElement('div'); + back.id = 'adOverlay'; + back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; + const x = document.createElement('button'); + x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); + x.textContent = '✕'; + x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; + x.addEventListener('click', closeAdOverlay); + const ifr = document.createElement('iframe'); + ifr.src = url; + ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; + back.appendChild(ifr); back.appendChild(x); + document.body.appendChild(back); + document.body.style.overflow = 'hidden'; + } + function closeAdOverlay() { + const m = $('adOverlay'); if (m) m.remove(); + document.body.style.overflow = ''; + earnRefresh(); loadDashboard(); + } + window.addEventListener('message', e => { + if (e.origin !== location.origin || !e.data) return; + if (e.data.t === 'iap-view-close') closeAdOverlay(); + else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + $('earnStartBtn').addEventListener('click', () => earnShowAd()); + // the viewer tab pings localStorage when a view credits; refresh instantly + window.addEventListener('storage', e => { + if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); + }); + $('earnClaimBtn').addEventListener('click', async () => { + try { + const r = await api('/api/my/claim'); + IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); + await earnRefresh(); + loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + }); + + const busy = (btn, fn) => async () => { + try { btn.disabled = true; await fn(); } + catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } + finally { btn.disabled = false; } + }; + + // passwordless (feature-flagged on config.emailAuth): code replaces passwords + (async () => { + const cfg = await IAP.getConfig(); + if (!cfg.emailAuth) return; + $('passCards').hidden = true; + $('magicCard').hidden = false; + const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); + const start = busy($('mcSendBtn'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + $('mcCodeRow').hidden = false; + $('mcVerifyBtn').hidden = false; + $('mcSendBtn').hidden = true; + $('mcResend').hidden = false; + if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } + else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); + $('mcCode').focus(); + }); + $('mcSendBtn').addEventListener('click', start); + $('mcResend').addEventListener('click', busy($('mcResend'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + if (r.devCode) $('mcCode').value = r.devCode; + IAP.status('Fresh code sent.', 'ok'); + })); + $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { + const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('You are in.', 'ok'); + if (r.next && !r.created) { location.href = r.next; return; } // came from Drip Runner: straight back into the game + if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + })(); + + // new-member onboarding: choose a username (required), optionally a bio. + // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. + function showOnboard(required) { + return new Promise(resolve => { + const m = $('onboardModal'); if (!m) return resolve(); + m.hidden = false; $('obErr').hidden = true; + $('obSkip').hidden = !!required; + if (required && !$('obUsername').value) { + fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); + } + setTimeout(() => $('obUsername').focus(), 50); + const done = () => { m.hidden = true; resolve(); }; + $('obSkip').onclick = required ? null : done; + $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; + $('obSave').onclick = async () => { + const u = $('obUsername').value.trim(); + if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } + try { + if (u) await api('/api/my/profile', { username: u }); + const bio = $('obBio').value.trim(); + if (bio) await api('/api/my/profile-details', { bio }); + done(); + } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } + }; + }); + } + + $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { + const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('Welcome aboard. You are in.', 'ok'); + if (!(r.account && r.account.username)) await showOnboard(); + await render(); + })); + $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { + await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); + IAP.status('Logged in.', 'ok'); + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { + IAP.status('Check your wallet for the free link signature…'); + const lr = await IAPWallet.signIn(); // server binds the wallet to the signed-in email account + if (lr && lr.next) { IAP.status('Wallet linked. Taking you back to PolHunter…', 'ok'); setTimeout(() => { location.href = lr.next; }, 700); return; } // they came from PolHunter: close the loop + IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); + await render(); + })); + if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { + IAP.status('Connect your wallet first…'); + const addr = await IAPWallet.connect(); + let copied = false; + try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} + window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); + $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' + + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; + IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); + })); + if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { + // fire-and-forget: don't gate the reload on disconnect resolving (it can + // stall). The reload drops all in-memory wallet state and the picker returns. + IAPWallet.disconnect().catch(() => {}); + $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; + IAP.status('Disconnecting — reloading…', 'ok'); + setTimeout(() => location.reload(), 900); + })); + // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) + function sponsorHoldText(sp) { + const who = sp.sponsorName || 'your sponsor'; + if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; + if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; + return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; + } + $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { + const me = await (await fetch('/api/me')).json(); + if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } + IAP.status('Confirm the free activation in your wallet…'); + const r = await IAPWallet.activate(me.sponsorId || 0); + if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); + IAP.status('Payouts are on. Your invite link is live.', 'ok'); + await render(); + })); + $('copyInvite').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } + }); + $('logoutLink').addEventListener('click', async e => { + e.preventDefault(); + await fetch('/api/auth/logout', { method: 'POST' }); + IAP.status('Logged out.', 'ok'); + await render(); + }); + + // ── welcome tour (viral banner gauntlet): a new member meets their 3-level + // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. + // Same three levels the contract pays — the tour IS the org chart. + async function showGauntlet() { + try { + const g = await (await fetch('/api/my/gauntlet')).json(); + if (!g.pending || !g.slides || !g.slides.length) return false; + const gate = $('gauntGate'); + gate.hidden = false; + for (let i = 0; i < g.slides.length; i++) { + const s = g.slides[i]; + $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); + $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; + $('ggFrame').hidden = false; + $('ggFrame').src = s.targetUrl; + let left = g.dwell || 10; + $('ggTimer').textContent = left + 's'; + await new Promise(done => { + const t = setInterval(() => { + if (!tabActive()) return; + left -= 1; + $('ggTimer').textContent = Math.max(0, left) + 's'; + if (left <= 0) { clearInterval(t); done(); } + }, 1000); + }); + } + $('ggFrame').src = 'about:blank'; + $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done + $('ggTimer').textContent = '✓'; + $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; + $('ggClaim').hidden = false; + await new Promise(done => { + $('ggClaim').onclick = async () => { + try { + const r = await api('/api/my/gauntlet/complete', { token: g.token }); + IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); + } catch (e) { IAP.status(e.message, 'bad'); } + done(); + }; + }); + gate.hidden = true; + $('ggClaim').hidden = true; + return true; + } catch (e) { return false; } + } + + // ── line banner (profile): the member's slot on welcome tours + their wall ── + function fillLineBanner(a) { + if (!a) return; + if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; + if (a.lineBannerUrl) { + $('lbBanner').value = a.lineBannerUrl; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } + $('lbCurrent').textContent = a.lineTargetUrl + ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' + : 'Not set yet. Until you set one, your tour slot is skipped.'; + } + async function loadLineBanner() { + try { + const a = await (await fetch('/api/me')).json(); + fillLineBanner(a); + fillProfileDetails(a); + // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me + let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} + fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); + } catch (e) {} + } + // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── + function fillWallOffers(a) { + if (!a || !$('wallOffersCard')) return; + const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; + const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; + const NEED = [2, 5]; + for (let i = 0; i < 2; i++) { + const o = offers[i] || {}; + const open = unlocked >= i + 2; + $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; + $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; + $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; + $('woSlot' + i).classList.toggle('locked', !open); + } + $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' + : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' + : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; + } + document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); + document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { + const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; + $('woInfo' + i).textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('woInfo' + i).textContent = r.error; } + else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } + } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } + inp.value = ''; + })); + if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { + const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); + const r = await api('/api/my/wall-offers', { offers }); + IAP.status('Wall positions saved.', 'ok'); + await loadLineBanner(); + })); + const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link + function fillProfileDetails(a) { + if (!a) return; + if (a.bio) $('pfBio').value = a.bio; + if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } + let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} + for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; + if (a.username) { + const link = location.origin + '/wall/' + a.username; + $('pfBioLink').textContent = link; + $('pfViewBio').hidden = false; + $('pfViewBio').href = '/wall/' + a.username; + } + } + let pfAvatar; // pending avatar url + $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); + $('pfAvatarFile').addEventListener('change', async () => { + const f = $('pfAvatarFile').files[0]; + if (!f) return; + $('pfAvatarInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } + pfAvatar = r.url; + $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; + const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; + } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } + $('pfAvatarFile').value = ''; + }); + $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { + const body = { bio: $('pfBio').value, socials: {} }; + for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; + if (pfAvatar) body.avatarUrl = pfAvatar; + const r = await api('/api/my/profile-details', body); + IAP.status('Profile saved.', 'ok'); + if (r.account) fillProfileDetails(r.account); + })); + $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); + $('lbFile').addEventListener('change', async () => { + const f = $('lbFile').files[0]; + if (!f) return; + $('lbUpInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } + $('lbBanner').value = r.url; + $('lbUpInfo').textContent = 'Uploaded.'; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } + $('lbFile').value = ''; + }); + $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { + const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); + IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); + if (r.account) fillLineBanner(r.account); + })); + + // ── login ad interstitial: after a successful sign-in the sponsor card + // appears; "Open Ad" loads the sponsor's page INSIDE the gate, under our bar + // (countdown, open-in-new-tab, dashboard button), so the timer and the way + // out sit on the ad itself (Brian Holland, 2026-10-09: "no timer, no X"). + // Sites that refuse framing open in a new tab instead, with the bar saying + // so; the timer is not paused, the member is expected to be on the ad. + async function showLoginAd() { + try { + const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); + if (!ad || !ad.targetUrl) return; + const gate = $('loginGate'); + const openBtn = $('lgOpen'); + const goBtn = $('lgContinue'); + const timer = $('lgTimer'); + const frame = $('lgFrame'); + const tab = $('lgOpenTab'); + const body = gate.querySelector('.lgate-body'); + const framed = !!(ad.frameable && frame); + $('lgCreative').innerHTML = ad.imageUrl + ? 'sponsor ad' + : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; + $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; + const how = $('lgHow'); + if (how) how.textContent = framed + ? 'The sponsor\'s page opens right here under this bar. The timer counts down at the top; when it hits zero, your dashboard button appears beside it.' + : 'This sponsor\'s site does not allow loading inside a frame, so it opens in a new tab. The timer counts down here; come back to this tab when it hits zero for your dashboard button.'; + timer.hidden = true; + goBtn.hidden = true; + if (tab) tab.hidden = true; + if (frame) { frame.hidden = true; frame.src = 'about:blank'; } + if (body) body.hidden = false; + openBtn.disabled = false; + gate.hidden = false; + await new Promise(done => { + openBtn.onclick = () => { + openBtn.disabled = true; + if (framed) { + frame.src = ad.targetUrl; // the click relay counts it, then redirects inside the frame + frame.hidden = false; + if (body) body.hidden = true; + if (tab) { tab.href = ad.siteUrl || ad.targetUrl; tab.hidden = false; } + $('lgStatus').textContent = 'Today\'s sponsor. Have a look; your dashboard button appears when the timer ends.'; + } else { + window.open(ad.targetUrl, '_blank'); // the click relay counts it + $('lgStatus').textContent = 'The sponsor opened in a new tab (that site does not allow framing). View it and come back; the timer runs here.'; + } + let left = ad.dwell || 10; + timer.hidden = false; + timer.textContent = 'Time remaining: ' + left + 's'; + const t = setInterval(() => { + left -= 1; + if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } + clearInterval(t); + timer.textContent = 'Time is up'; + timer.classList.add('done'); + $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; + goBtn.hidden = false; + }, 1000); + goBtn.onclick = () => done(); + }; + }); + gate.hidden = true; + if (frame) { frame.src = 'about:blank'; frame.hidden = true; } + if (body) body.hidden = false; + $('lgTimer').classList.remove('done'); + } catch (e) {} + } + + // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── + let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; + function chatSync(d) { + CHAT_ME = d.email || CHAT_ME; + CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; + const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; + setChatBadge(d.chatUnread || 0); + CHAT_LAST_UNREAD = d.chatUnread || 0; + const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; + // Overview quick action + My line card: message-your-sponsor entry points + const qs = $('qaMsgSponsor'); + if (qs) { + if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } + else qs.hidden = true; + } + const card = $('sponsorMsgCard'); + if (card) { + card.hidden = !CHAT_SPONSOR; + if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; + } + } + function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } + function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } + function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } + // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) + function autoGrow(el) { + const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); + const dragged = Number(el.dataset.dragged || 0); + el.style.height = 'auto'; + el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; + } + function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } + + async function openThreads() { + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; + $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; + $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; + stopPoll(); CHAT_OTHER = null; + $('chatThreads').innerHTML = '

Loading…

'; + try { + const r = await (await fetch('/api/my/chat/threads')).json(); + const list = r.threads || []; + // always offer "message your sponsor" up top when they have one and no thread yet + const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); + const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) + ? '
' + + '' + + '
' + esc(CHAT_SPONSOR.name) + '
' + + '
Your sponsor · tap to message
' + : ''; + if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } + $('chatThreads').innerHTML = sponsorRow + list.map(t => + '
' + + '' + + '
' + esc(t.name) + '
' + + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' + + (t.unread ? '' + t.unread + '' : '') + '
').join(''); + $('chatThreads').querySelectorAll('.chat-thread').forEach(el => + el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); + pageList('chat', $('chatThreads'), '.chat-thread'); + } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } + } + + async function openConvo(email, name) { + if (!email) return; + CHAT_OTHER = email; CHAT_LASTID = 0; + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; + $('chatBack').hidden = false; $('chatDot').hidden = false; + $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; + $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; + $('chatInput').disabled = false; $('chatSend').disabled = false; + await pullThread(true); startPoll(); + setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); + } + + function renderMsgs(msgs) { + const box = $('chatMsgs'); if (!box) return; + const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; + for (const m of msgs) { + if (m.id <= CHAT_LASTID) continue; + CHAT_LASTID = Math.max(CHAT_LASTID, m.id); + const d = document.createElement('div'); + d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); + d.textContent = m.body; + const t = document.createElement('span'); t.className = 'ct-time'; + t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); + d.appendChild(t); box.appendChild(d); + } + if (atBottom) box.scrollTop = box.scrollHeight; + } + + async function pullThread(reset) { + if (!CHAT_OTHER) return; + try { + const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); + if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } + if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } + renderMsgs(r.messages || []); + $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); + $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); + CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; + const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; + const blocked = !!r.blocked; + $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; + if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } + else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } + else $('chatBanner').hidden = true; + } catch (e) {} + } + + async function chatSend() { + const inp = $('chatInput'); if (!inp) return; + const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; + $('chatSend').disabled = true; + try { + const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); + inp.value = ''; autoGrow(inp); renderMsgs([r.message]); + const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; + } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } + finally { $('chatSend').disabled = false; inp.focus(); } + } + + async function toggleMute() { + if (!CHAT_OTHER) return; + try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } + catch (e) { IAP.status(e.message, 'bad'); } + } + + (function chatInit() { + if (!$('chatDrawer')) return; + const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; + on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); + on('chatClose', 'click', closeDrawer); + on('chatBack', 'click', openThreads); + on('chatMute', 'click', toggleMute); + on('chatSend', 'click', chatSend); + const inp = $('chatInput'); + if (inp) { + inp.addEventListener('input', () => autoGrow(inp)); + inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); + inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); + } + on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); + on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); + on('chatAvailToggle', 'change', async () => { + const t = $('chatAvailToggle'); + try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } + catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } + }); + // presence heartbeat + new-message notifier: pop + toast when unread rises + setInterval(async () => { + try { + const r = await (await fetch('/api/my/ping')).json(); + const n = r.chatUnread || 0; + if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } + CHAT_LAST_UNREAD = n; setChatBadge(n); + } catch (e) {} + }, 20000); + })(); + + // ad surfaces: a banner greets the sign-in screen; members see live + // banner + text placements inside the back office (they ARE the audience) + IAP.adSlot('banner', 'adSlotLogin'); + IAP.adSlot('banner', 'adSlotOverview'); + IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar + + render(); +})(); + +// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── +(function () { + const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); + if (!btn || !inp) return; + const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; + const go = async () => { + const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } + btn.disabled = true; + try { + const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); + if (r.error) { say(r.error, false); return; } + say(r.step + ? Number(r.now || 0).toLocaleString() + ' credits added now' + (r.partner ? ' from ' + r.partner : '') + '. The rest of the ' + Number(r.credits).toLocaleString() + ' arrive ' + r.step + ' at a time, one for each day you finish your daily ads, for the next 30 days.' + : 'Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); + inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); + } catch (e) { say('Could not apply that code. Try again.', false); } + finally { btn.disabled = false; } + }; + btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); +})(); + +// Friday Bonus Hunts card on the Earn tab (2026-09-26). Hoisted so the Earn loader can call it. +async function loadFridayBank() { + const card = document.getElementById('fbankCard'); if (!card) return; + let b; try { const r = await fetch('/api/my/friday-bank', { credentials: 'same-origin' }); if (!r.ok) return; b = await r.json(); } catch (e) { return; } + const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + const wd = d => WD[new Date(d + 'T12:00:00Z').getUTCDay()]; + document.getElementById('fbankCount').textContent = b.banked + ' banked'; + document.getElementById('fbankDays').innerHTML = (b.days || []).map(d => { + const st = d.banked ? ['#43e8c3', '✓'] : d.future ? ['var(--line-strong)', '·'] : d.day === b.today ? ['#ffb238', '○'] : ['var(--line-strong)', '×']; + return '' + st[1] + '' + wd(d.day) + ''; + }).join('') + 'Fri: +' + b.banked + ' hunts'; + const t = (b.days || []).find(d => d.day === b.today); + let msg = ''; + if (b.isFriday) msg = b.banked ? 'It\'s Friday. Your ' + b.banked + ' banked hunt' + (b.banked === 1 ? '' : 's') + ' are live on PolHunter today.' : 'It\'s Friday. Bank hunts Saturday through Thursday for next Friday.'; + else if (t && t.banked) msg = '✓ Today is banked. Come back tomorrow to bank another.'; + else if (t && t.video && t.soloNeeded && !t.solo) msg = '✓ Video watched. Not banked yet: an inbox ad is waiting for you today, and a day only counts once it is opened. Open the inbox ad and today is banked. (On days when nothing is waiting in your inbox, the video alone counts, which is why some days banked without one.)'; + else if (t) msg = 'To bank today: ' + (t.video ? '✓ video watched' : 'watch one video') + (t.soloNeeded ? ' and ' + (t.solo ? '✓ inbox ad opened' : 'open one inbox ad') : ' (no inbox ad waiting, so the video alone counts)') + '.'; + const el = document.getElementById('fbankToday'); el.innerHTML = msg; + el.querySelectorAll('[data-earn-go]').forEach(a => a.addEventListener('click', ev => { ev.preventDefault(); const tab = document.querySelector('[data-earn="' + a.dataset.earnGo + '"]'); if (tab) tab.click(); })); + card.hidden = false; +} diff --git a/public/contract.html b/public/contract.html index 23c3225..edc0464 100644 --- a/public/contract.html +++ b/public/contract.html @@ -1,149 +1,149 @@ - - - - -The contract | InstantAdPay - - - - - - - - - - - - - - - - - -
-
-

The contract, in plain language.

-

Every dollar on this platform moves through one smart contract. This page explains - what it does, what nobody can change, and exactly what powers we kept. Verify every claim - yourself. That is the point.

-

- address: … - … -

-

- Raw contract on the explorer ↗ - Verified source code ↗ -

-
- -
-

The six laws the code enforces

-
    -
  • It never holds funds. Every purchase is fully paid out in the same transaction. The contract balance is zero after every sale. There is nothing to freeze, drain, or run away with.
  • -
  • The compensation rules are constants. 50 percent, 20 percent, 10 percent, 20 percent platform. They are compiled into the bytecode. No function exists to change them.
  • -
  • No upgrade path, no pause switch, no self-destruct. The deployed bytecode is the program forever.
  • -
  • Purchased credits only ever go down by delivering your ads. No function reduces them for any other reason, and nothing can mint them except a purchase.
  • -
  • Qualification is earned, never bought. Deeper levels unlock only by referring real buyers of $20 or more. No spend-based shortcuts exist.
  • -
  • Everything is observable. Every state change emits a public event. The website is a mirror of the chain, never the source of truth for money.
  • -
-
- -
-
-

What the operator CAN do

-
    -
  • Add ad packages to the catalog (price floor $1, ceiling $500)
  • -
  • Queue a price change, which waits behind a public 24-hour timelock before anyone can apply it
  • -
  • Retire a package from sale, and reactivate it later
  • -
  • Rotate the fee-receiver, ad-engine, and owner addresses (key-loss insurance)
  • -
  • The ad engine can burn credits, but only as your campaigns consume delivery
  • -
-
-
-

What the operator CANNOT do

-
    -
  • Change any split percentage or qualification threshold
  • -
  • Pause, upgrade, or replace the contract
  • -
  • Hold, redirect, or claw back anyone's payout
  • -
  • Mint credits, take credits, or touch anyone's membership record
  • -
  • Move a price outside the $1 to $500 bounds, or skip the 24-hour notice
  • -
-
-
- -
-

Where every purchase goes

-
-
50%
direct sponsor
-
20%
level 2
-
10%
level 3
-
20%
platform
-
-

On a $20 package: $10.00 to the direct sponsor, $4.00 to level 2, $2.00 to level 3, - $4.00 to the platform. Rounding dust of a few billionths of a cent goes to the platform wallet so the - books always balance to zero. When a level has no qualified recipient, that share visibly passes up - to the next qualified person; if none exists within 25 candidates, it goes to the platform. Every one - of these movements is an event on the live ledger.

-
- -
-
-

Dollar prices, POL settlement

-

Packages are priced in dollars and settled in POL using the Chainlink POL/USD - oracle at the moment of purchase. If you send slightly too much because the rate moved, the excess - refunds to you in the same transaction. If the oracle ever goes quiet, the contract keeps selling - at its last fresh price for up to 24 hours, then new purchases pause until the feed returns. - Settled money, credits, and memberships are never affected by an oracle outage.

-
-
-

Nobody can stall it

-

Payouts are pushed with a strict gas allowance. A wallet that refuses to - accept payment is simply treated as unqualified and its share passes up. No escrow forms, no - purchase reverts, nobody waits on anybody. One practical note: use a normal wallet address for - payouts. Some exotic smart-contract wallets cost more gas to receive than the allowance and would - be passed over.

-
-
- -
-

How it was tested

-

Before deployment the contract passed a suite of 24 tests covering every split - scenario, the pass-up walk to its exact 25-candidate boundary, oracle outages and price swings, - refunds, hostile recipient wallets, and catalog rules. On top of that, an invariant fuzzer ran - 128,000 randomized transactions and confirmed after every single one: the contract balance stayed - zero, every wei in equaled every wei out, credits equaled purchases minus delivery, and nobody was - qualified without earning it. The full specification was then audited line by line against the code. - The source you see at the verified-source link is byte-for-byte what runs on chain.

-
- -
-
-

Do not trust this page. Check it.

-

The whole reason this platform exists is that you should - not have to take anyone's word, including ours. Open the source, open the ledger, click a - transaction.

- Read the verified source - Open the live ledger -
-
-
contract
-
-
compiler checkexact match
-
bytecode checkexact match
-
upgrade pathnone
-
pause switchnone
-
-
-
- -
-
InstantAdPay · how it works · live ledger
-
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
-
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
-
-
- - - - - + + + + +The contract | InstantAdPay + + + + + + + + + + + + + + + + + +
+
+

The contract, in plain language.

+

Every dollar on this platform moves through one smart contract. This page explains + what it does, what nobody can change, and exactly what powers we kept. Verify every claim + yourself. That is the point.

+

+ address: … + … +

+

+ Raw contract on the explorer ↗ + Verified source code ↗ +

+
+ +
+

The six laws the code enforces

+
    +
  • It never holds funds. Every purchase is fully paid out in the same transaction. The contract balance is zero after every sale. There is nothing to freeze, drain, or run away with.
  • +
  • The compensation rules are constants. 50 percent, 20 percent, 10 percent, 20 percent platform. They are compiled into the bytecode. No function exists to change them.
  • +
  • No upgrade path, no pause switch, no self-destruct. The deployed bytecode is the program forever.
  • +
  • Purchased credits only ever go down by delivering your ads. No function reduces them for any other reason, and nothing can mint them except a purchase.
  • +
  • Qualification is earned, never bought. Deeper levels unlock only by referring real buyers of $20 or more. No spend-based shortcuts exist.
  • +
  • Everything is observable. Every state change emits a public event. The website is a mirror of the chain, never the source of truth for money.
  • +
+
+ +
+
+

What the operator CAN do

+
    +
  • Add ad packages to the catalog (price floor $1, ceiling $500)
  • +
  • Queue a price change, which waits behind a public 24-hour timelock before anyone can apply it
  • +
  • Retire a package from sale, and reactivate it later
  • +
  • Rotate the fee-receiver, ad-engine, and owner addresses (key-loss insurance)
  • +
  • The ad engine can burn credits, but only as your campaigns consume delivery
  • +
+
+
+

What the operator CANNOT do

+
    +
  • Change any split percentage or qualification threshold
  • +
  • Pause, upgrade, or replace the contract
  • +
  • Hold, redirect, or claw back anyone's payout
  • +
  • Mint credits, take credits, or touch anyone's membership record
  • +
  • Move a price outside the $1 to $500 bounds, or skip the 24-hour notice
  • +
+
+
+ +
+

Where every purchase goes

+
+
50%
direct sponsor
+
20%
level 2
+
10%
level 3
+
20%
platform
+
+

On a $20 package: $10.00 to the direct sponsor, $4.00 to level 2, $2.00 to level 3, + $4.00 to the platform. Rounding dust of a few billionths of a cent goes to the platform wallet so the + books always balance to zero. When a level has no qualified recipient, that share visibly passes up + to the next qualified person; if none exists within 25 candidates, it goes to the platform. Every one + of these movements is an event on the live ledger.

+
+ +
+
+

Dollar prices, POL settlement

+

Packages are priced in dollars and settled in POL using the Chainlink POL/USD + oracle at the moment of purchase. If you send slightly too much because the rate moved, the excess + refunds to you in the same transaction. If the oracle ever goes quiet, the contract keeps selling + at its last fresh price for up to 24 hours, then new purchases pause until the feed returns. + Settled money, credits, and memberships are never affected by an oracle outage.

+
+
+

Nobody can stall it

+

Payouts are pushed with a strict gas allowance. A wallet that refuses to + accept payment is simply treated as unqualified and its share passes up. No escrow forms, no + purchase reverts, nobody waits on anybody. One practical note: use a normal wallet address for + payouts. Some exotic smart-contract wallets cost more gas to receive than the allowance and would + be passed over.

+
+
+ +
+

How it was tested

+

Before deployment the contract passed a suite of 24 tests covering every split + scenario, the pass-up walk to its exact 25-candidate boundary, oracle outages and price swings, + refunds, hostile recipient wallets, and catalog rules. On top of that, an invariant fuzzer ran + 128,000 randomized transactions and confirmed after every single one: the contract balance stayed + zero, every wei in equaled every wei out, credits equaled purchases minus delivery, and nobody was + qualified without earning it. The full specification was then audited line by line against the code. + The source you see at the verified-source link is byte-for-byte what runs on chain.

+
+ +
+
+

Do not trust this page. Check it.

+

The whole reason this platform exists is that you should + not have to take anyone's word, including ours. Open the source, open the ledger, click a + transaction.

+ Read the verified source + Open the live ledger +
+
+
contract
+
+
compiler checkexact match
+
bytecode checkexact match
+
upgrade pathnone
+
pause switchnone
+
+
+
+ +
+
InstantAdPay · how it works · live ledger
+
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
+
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/disclaimer.html b/public/disclaimer.html index f7f5db9..05059d6 100644 --- a/public/disclaimer.html +++ b/public/disclaimer.html @@ -1,32 +1,32 @@ - - - - -Disclaimer | InstantAdPay - - - - - - -
-

Risk & Earnings Disclaimer

Last updated: September 2026

-
-

No income guarantee

-

InstantAdPay is an advertising service with a referral program. It is not an investment, a security, or a passive-income scheme. We do not promise, project, or guarantee any earnings. Any figures shown in examples or sample creatives are illustrations only, not typical or expected results. Most participants should expect to earn little or nothing unless real advertising is purchased in their line.

-

Not financial or legal advice

-

Nothing on the Platform is investment, financial, tax, or legal advice. Do your own research and consult a professional before spending money.

-

Crypto risk

-

Purchases settle on a public blockchain using a volatile network token. On-chain transactions are final and irreversible: there are no refunds, chargebacks, or reversals. You are responsible for your wallet, your keys, network fees, and the tax treatment of your activity.

-

Live on Polygon

-

The Platform is live on the Polygon mainnet. Purchases and payouts use POL, a real cryptocurrency with real monetary value. Every transaction is real and final — this is not a simulation or test environment.

-

Advertising

-

Ads are member-created and auto-approved for speed. InstantAdPay does not endorse and is not responsible for advertised products, sites, or claims. Use your judgment, and report anything broken or inappropriate.

-

Your responsibility

-

You decide whether, and how much, to spend. Never spend more than you can afford to lose.

-
-
- - - - + + + + +Disclaimer | InstantAdPay + + + + + + +
+

Risk & Earnings Disclaimer

Last updated: September 2026

+
+

No income guarantee

+

InstantAdPay is an advertising service with a referral program. It is not an investment, a security, or a passive-income scheme. We do not promise, project, or guarantee any earnings. Any figures shown in examples or sample creatives are illustrations only, not typical or expected results. Most participants should expect to earn little or nothing unless real advertising is purchased in their line.

+

Not financial or legal advice

+

Nothing on the Platform is investment, financial, tax, or legal advice. Do your own research and consult a professional before spending money.

+

Crypto risk

+

Purchases settle on a public blockchain using a volatile network token. On-chain transactions are final and irreversible: there are no refunds, chargebacks, or reversals. You are responsible for your wallet, your keys, network fees, and the tax treatment of your activity.

+

Live on Polygon

+

The Platform is live on the Polygon mainnet. Purchases and payouts use POL, a real cryptocurrency with real monetary value. Every transaction is real and final — this is not a simulation or test environment.

+

Advertising

+

Ads are member-created and auto-approved for speed. InstantAdPay does not endorse and is not responsible for advertised products, sites, or claims. Use your judgment, and report anything broken or inappropriate.

+

Your responsibility

+

You decide whether, and how much, to spend. Never spend more than you can afford to lose.

+
+
+ + + + diff --git a/public/earning.html b/public/earning.html index db8000f..afe67d8 100644 --- a/public/earning.html +++ b/public/earning.html @@ -1,89 +1,101 @@ - - - - -How earning works: credits and POL payouts | InstantAdPay - - - - - - - - - -
-
-

Member guide

-

How earning works: credits, and POL to your wallet.

-

Every free way to earn ad credits, the claim streak, and the one thing that makes the credits worth anything: spending them on a campaign.

-
- -
This page is about credits, which every member earns. POL, the crypto the contract pays to your wallet when your referrals buy packages, is separate: activate with the $20 starter package and switch on payouts, and level 1 pays 50 percent of every package your directs buy.
-
One credit is one cent of ad delivery. Credits are not money and cannot be withdrawn. They buy impressions, clicks and visits for your own campaigns across InstantAdPay and the partner network. Payouts in POL come only from packages people in your line buy.
- -

1. The daily set

-

Earn credits › Watch ads. Five ads a day. Each one opens full screen, a 10-second countdown runs while you look, you pass a quick click-the-icon check, and you earn 1 credit. Finish all five and the Claim button appears.

- -

2. The claim streak

-

The claim pays more the more days in a row you claim it. Miss a day and it restarts at day 1.

- - - - - - -
Consecutive dayClaim pays
Day 15 credits
Day 27 credits
Day 3 and on10 credits
Every 7th day in a row25 credits
-

The hint under the set always tells you which day you are on and what tomorrow's claim pays. Days are counted in UTC, so the set resets at 7 PM Central.

- -

3. After the set: verified visits

-

When the set is claimed, the done screen offers verified visits: up to 20 a day, 1 credit each. You open a member's site in a new tab, stay for the dwell, and the visit counts. Each visit is unique per site per day, so it is 20 different sites, not one site 20 times.

- -

4. Videos and inbox ads

-
    -
  • Videos. Earn credits › Watch videos. You are credited only when the video plays to the end. Up to 6 a day, and the reward depends on the video's length.
  • -
  • Inbox solo ads. Earn credits › Inbox Ads. Open the message, visit the advertiser's link, then claim 2 credits. Once per message.
  • -
- -

5. The sign-in bonus and milestones

-

Signing in pays 5 credits a day, rising by one for each consecutive day up to 10. Milestone badges pay too: Spark when payouts are on, Surge at your first qualifying buyer, Circuit at two, Nexus at five.

- -

6. Now spend it

-

Credits sitting in your balance do nothing. Campaigns › New campaign: pick a banner or a text ad, give it a name and a budget in credits, point it at your own invite link or wall, and launch. Banner and text ads also push out to the partner network, so a 100-credit campaign is a hundred cents of real delivery. The done screen has a one-tap button for this after every claim.

-

Two things to know: a campaign reserves its whole budget the moment you start it, so your available balance drops right away and never surprises you later, and login ads are the one format that needs purchased credits.

- -

7. The other earning: POL paid to your wallet

-

Everything above is about credits, the currency that runs your advertising. The second kind of earning is POL, real money sent to your own wallet, and it comes from one place: ad packages bought by people in your line.

-

When anyone buys a package, the smart contract splits the price in the same transaction: 50% to the buyer's sponsor (level 1), 20% to the sponsor's sponsor (level 2), 10% to the one above that (level 3), and 20% to the platform. There is no balance to withdraw and no request to make. The POL lands in the wallet on your account before the buyer's page has finished refreshing, and every payout carries a link you can open on Polygon.

-

What has to be true for a share to reach you

-
    -
  • Payouts are switched on. Wallet tab: link your wallet and switch on payouts, which puts your member number on the contract. Until then a share meant for you passes up to the next payable person above you, and it is never paid to you later.
  • -
  • Level 1 pays from the moment payouts are on. Every direct referral's package pays you 50%, whatever the size.
  • -
  • Level 2 opens at two qualifying buyers, level 3 at five. A qualifying buyer is a direct referral who bought a package of $20 or more. Qualification never expires and cannot be bought. It is counted at the block the purchase happens in, so a buy that lands forty minutes before you qualify is passed up, not held.
  • -
  • Passed-up shares go to the next qualified person above. That is why the people who qualify early collect what the people below them are not yet set up to receive.
  • -
-

Who is your sponsor

-

The invite link you opened most recently before creating your account sets your sponsor, and it locks the moment the account exists. Linked positions from Qualified Start count toward your badges, and their purchases pay your main position at level 1.

-

Where to see it

-

Earnings shows three cards: payouts sent to your wallet, referral events in your line, and your purchases, every row with its Polygon link. If a share you expected is missing, use Trace a payment on that tab: it shows, purchase by purchase, who was paid at each level and why a level was skipped. The usual answers are not yet qualified at that block, a Qualified Start position buying under its own main wallet, or payouts not switched on. The live ledger shows the whole network's payouts as they happen.

- -

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

- -
- - - + + + + +How earning works: credits and POL payouts | InstantAdPay + + + + + + + + + +
+
+

Member guide

+

How earning works: credits, and POL to your wallet.

+

Every free way to earn ad credits, the claim streak, and the one thing that makes the credits worth anything: spending them on a campaign.

+
+ +
This page is about credits, which every member earns. POL, the crypto the contract pays to your wallet when your referrals buy packages, is separate: activate with the $20 starter package and switch on payouts, and level 1 pays 50 percent of every package your directs buy.
+
One credit is one cent of ad delivery. Credits are not money and cannot be withdrawn. They buy impressions, clicks and visits for your own campaigns across InstantAdPay and the partner network. Payouts in POL come only from packages people in your line buy.
+ +

1. The daily set

+

Earn credits › Watch ads. Five ads a day. Each one opens full screen, a 10-second countdown runs while you look, you pass a quick click-the-icon check, and you earn 1 credit. Finish all five and the Claim button appears.

+ +

2. The claim streak

+

The claim pays more the more days in a row you claim it. Miss a day and it restarts at day 1.

+ + + + + + +
Consecutive dayClaim pays
Day 15 credits
Day 27 credits
Day 3 and on10 credits
Every 7th day in a row25 credits
+

The hint under the set always tells you which day you are on and what tomorrow's claim pays. Days are counted in UTC, so the set resets at 7 PM Central.

+ +

3. After the set: verified visits

+

When the set is claimed, the done screen offers verified visits: up to 20 a day, 1 credit each. You open a member's site in a new tab, stay for the dwell, and the visit counts. Each visit is unique per site per day, so it is 20 different sites, not one site 20 times.

+ +

4. Videos and inbox ads

+
    +
  • Videos. Earn credits › Watch videos. You are credited only when the video plays to the end. Up to 6 a day, and the reward depends on the video's length.
  • +
  • Inbox solo ads. Earn credits › Inbox Ads. Open the message, visit the advertiser's link, then claim 2 credits. Once per message.
  • +
+ +

5. The sign-in bonus and milestones

+

Signing in pays 5 credits a day, rising by one for each consecutive day up to 10. Milestone badges pay too: Spark when payouts are on, Surge at your first qualifying buyer, Circuit at two, Nexus at five.

+ +

6. Now spend it

+

Credits sitting in your balance do nothing. Campaigns › New campaign: pick a banner or a text ad, give it a name and a budget in credits, point it at your own invite link or wall, and launch. Banner and text ads also push out to the partner network, so a 100-credit campaign is a hundred cents of real delivery. The done screen has a one-tap button for this after every claim.

+

Two things to know: a campaign reserves its whole budget the moment you start it, so your available balance drops right away and never surprises you later, and login ads are the one format that needs purchased credits.

+ +

7. The other earning: POL paid to your wallet

+

Everything above is about credits, the currency that runs your advertising. The second kind of earning is POL, real money sent to your own wallet, and it comes from one place: ad packages bought by people in your line.

+

When anyone buys a package, the smart contract splits the price in the same transaction: 50% to the buyer's sponsor (level 1), 20% to the sponsor's sponsor (level 2), 10% to the one above that (level 3), and 20% to the platform. There is no balance to withdraw and no request to make. The POL lands in the wallet on your account before the buyer's page has finished refreshing, and every payout carries a link you can open on Polygon.

+

What has to be true for a share to reach you

+
    +
  • Payouts are switched on. Wallet tab: link your wallet and switch on payouts, which puts your member number on the contract. Until then a share meant for you passes up to the next payable person above you, and it is never paid to you later.
  • +
  • Level 1 pays from the moment payouts are on. Every direct referral's package pays you 50%, whatever the size.
  • +
  • Level 2 opens at two qualifying buyers, level 3 at five. A qualifying buyer is a direct referral who bought a package of $20 or more. Qualification never expires and cannot be bought. It is counted at the block the purchase happens in, so a buy that lands forty minutes before you qualify is passed up, not held.
  • +
  • Passed-up shares go to the next qualified person above. That is why the people who qualify early collect what the people below them are not yet set up to receive.
  • +
+ +

Who is your sponsor

+

The invite link you opened most recently before creating your account sets your sponsor, and it locks the moment the account exists. Linked positions from Qualified Start count toward your badges, and their purchases pay your main position at level 1.

+

Where to see it

+

Earnings shows three cards: payouts sent to your wallet, referral events in your line, and your purchases, every row with its Polygon link. If a share you expected is missing, use Trace a payment on that tab: it shows, purchase by purchase, who was paid at each level and why a level was skipped. The usual answers are not yet qualified at that block, a Qualified Start position buying under its own main wallet, or payouts not switched on. The live ledger shows the whole network's payouts as they happen.

+ +

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

+ +
+ + + diff --git a/public/facts.html b/public/facts.html index 1e8a596..2d5bd30 100644 --- a/public/facts.html +++ b/public/facts.html @@ -1,127 +1,132 @@ - - - - -Platform Facts | InstantAdPay - - - - - - - - - - -
-

Platform Facts

-

The reference description of how InstantAdPay works, checked against the deployed contract and the live site. Last verified: October 6, 2026. A plain-text copy for AI systems is at instantadpay.com/llms.txt.

- -
-

What InstantAdPay is

-

InstantAdPay is an advertising platform with a referral program, live on the Polygon blockchain. Members buy advertising credit packages in POL and spend the credits on ads shown to other members. Each purchase is settled by a public smart contract that pays a fixed share to the buyer's referral line and to two platform wallets in the same transaction. It is not an investment, a security or a passive-income scheme, and it makes no earnings promises (see the Disclaimer).

-

InstantAdPay is part of the Crypto Team Build Network and has its own contract, rules and membership.

-
- -
-

1. The smart contract

-
- - - - - -
ItemFact
NetworkPolygon mainnet (chain id 137)
Contract0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 (view on Polygonscan)
Changeable split?No. The percentages and qualification rules are constants in the code. There is no function that changes them.
CustodyNone. The contract forwards every payment in the same transaction. It holds no member funds.
-

More detail, including what the operator can and cannot do, is on The contract page.

-
- -
-

2. Where each purchase goes

-
- - - - - - -
ShareRecipientRule
50%Level 1 (direct sponsor)Any activated member qualifies.
20%Level 2Paid to a member who has referred at least 2 members whose first purchase was $20 or more.
10%Level 3Paid to a member who has referred at least 5 members whose first purchase was $20 or more.
10%Platform wallet AFixed platform fee.
10%Platform wallet BFixed platform fee.
-
    -
  • Pass-up: if the member at a level is not qualified for that level, that share moves up the sponsor line to the next qualified member (up to 25 steps). If nobody in range qualifies, it goes to platform wallet A. Every pass-up is recorded on-chain with the reason.
  • -
  • Qualification is earned only by referring real buyers. It cannot be bought.
  • -
  • Platform wallets: A is 0x7627fc78876948ac9d95c1c9eb061e7d6d647b70, B is 0x8b7d33849a2c4d92c985be31e46dc564ba901ad2. Platform income pays for operations, development, marketing and the game rewards described below.
  • -
  • Overpayment is returned to the buyer in the same transaction.
  • -
-
- -
-

3. Pricing and ad credits

-
    -
  • Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers.
  • -
  • Base rate: 1 credit = $0.01. Current packages: $5 = 500 credits, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000 (larger packages include bonus credits). Package prices are bounded in the contract between $1 and $500, and any price change waits 24 hours before it takes effect.
  • -
  • Purchased credits are recorded on-chain. A purchase adds credits to the member's balance inside the contract. As campaigns run, the platform's engine wallet burns the spent credits on-chain in batches, each burn tagged with its campaign reference, so the public ledger shows credits in and credits used. Only the engine wallet can reduce a balance, and only by burning.
  • -
  • Earned credits are kept by the site, not on-chain. Welcome credits, surfing and viewing rewards, promo codes and other bonuses are tracked in the site's database and labeled separately from purchased credits.
  • -
  • Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash.
  • -
-
- -
-

4. Refunds

-

Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in the member's balance until spent. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to the member's balance, labeled as returned purchased credits.

-
- -
-

5. Ad formats

-

Seven formats: banner ads, text ads, login ads, video ads, solo ads (a message sent to members), featured rotation, and verified visits (a member opens the advertiser's page and stays on it for a set time before the visit counts).

-
- -
-

6. Attention and anti-fraud

-
    -
  • Active viewing: video ads pause when the viewer switches tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early.
  • -
  • One account per person: required by the Terms. Sign-ups are checked with device and network signals; a second account from the same device is refused, and suspicious matches are flagged for review. Accounts sign in with a one-time email code.
  • -
  • Extra positions, openly: a member who wants more than one position adds extra wallets to their one account ("Qualified Start"). They are the member's own wallets and own purchases, shown openly in the account.
  • -
  • PolHunter codes: each hunt code is generated per member and per visit, is only released after the required time on the page, and its hiding place rotates daily, so codes cannot be shared or scraped ahead of time.
  • -
-
- -
-

7. Network games

-

Free browser games in the network bring players to member ads and pay small POL rewards for gameplay milestones. Rewards come from game wallets that the company tops up from platform income, and every top-up is recorded in the company's accounts as a marketing cost. Rewards are per action and not guaranteed. Players sign in to the games with their InstantAdPay account, so a player's sponsor carries across them.

-
- - - - - - - - -
GameWhat it isStatus
PolHunterScavenger hunts across network sites: find a per-visit code after a 45-second visit, plus advertiser missions.Live
Gem KingdomFantasy match-3 with boss battles and a village to rebuild.Live
Drip RunnerArcade runner: dodge drones, clear chapters, refuel at verified ad visits.Live
ClutterHuntSeasonal hidden-object game.Live
Spooky DoorsHalloween event: platform levels and door visits with candy milestones.Through October 31, 2026
SpellWheelLetter-wheel word puzzle.Opens October 10, 2026
PolyWarriorsCyberpunk turn-based battler with collectible warrior NFTs.Opens October 12, 2026
-
- -
-

What InstantAdPay is not

-
    -
  • Not an investment, token sale or security. Credits are not a token and have no cash value.
  • -
  • Not a holder of member money. Payments are split by the contract in the same transaction.
  • -
  • Not a guarantee of income. Referral payouts happen only when real advertising is purchased in a member's line.
  • -
-
-
- - - - + + + + +Platform Facts | InstantAdPay + + + + + + + + + + +
+

Platform Facts

+

The reference description of how InstantAdPay works, checked against the deployed contract and the live site. Last verified: October 6, 2026. A plain-text copy for AI systems is at instantadpay.com/llms.txt.

+ +
+

What InstantAdPay is

+

InstantAdPay is an advertising platform with a referral program, live on the Polygon blockchain. Members buy advertising credit packages in POL and spend the credits on ads shown to other members. Each purchase is settled by a public smart contract that pays a fixed share to the buyer's referral line and to two platform wallets in the same transaction. It is not an investment, a security or a passive-income scheme, and it makes no earnings promises (see the Disclaimer).

+

InstantAdPay is part of the Crypto Team Build Network and has its own contract, rules and membership.

+
+ +
+

1. The smart contract

+
+ + + + + +
ItemFact
NetworkPolygon mainnet (chain id 137)
Contract0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 (view on Polygonscan)
Changeable split?No. The percentages and qualification rules are constants in the code. There is no function that changes them.
CustodyNone. The contract forwards every payment in the same transaction. It holds no member funds.
+

More detail, including what the operator can and cannot do, is on The contract page.

+
+ +
+

2. Where each purchase goes

+
+ + + + + + +
ShareRecipientRule
50%Level 1 (direct sponsor)Any activated member qualifies.
20%Level 2Paid to a member who has referred at least 2 members whose first purchase was $20 or more.
10%Level 3Paid to a member who has referred at least 5 members whose first purchase was $20 or more.
10%Platform wallet AFixed platform fee.
10%Platform wallet BFixed platform fee.
+
    +
  • Pass-up: if the member at a level is not qualified for that level, that share moves up the sponsor line to the next qualified member (up to 25 steps). If nobody in range qualifies, it goes to platform wallet A. Every pass-up is recorded on-chain with the reason.
  • +
  • Qualification is earned only by referring real buyers. It cannot be bought.
  • +
  • Platform wallets: A is 0x7627fc78876948ac9d95c1c9eb061e7d6d647b70, B is 0x8b7d33849a2c4d92c985be31e46dc564ba901ad2. Platform income pays for operations, development, marketing and the game rewards described below.
  • +
  • Overpayment is returned to the buyer in the same transaction.
  • +
+
+ +
+

3. Pricing and ad credits

+
    +
  • Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers.
  • +
  • Base rate: 1 credit = $0.01. Current packages: $5 = 500 credits, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000 (larger packages include bonus credits). Package prices are bounded in the contract between $1 and $500, and any price change waits 24 hours before it takes effect.
  • +
  • Purchased credits are recorded on-chain. A purchase adds credits to the member's balance inside the contract. As campaigns run, the platform's engine wallet burns the spent credits on-chain in batches, each burn tagged with its campaign reference, so the public ledger shows credits in and credits used. Only the engine wallet can reduce a balance, and only by burning.
  • +
  • Earned credits are kept by the site, not on-chain. Welcome credits, surfing and viewing rewards, promo codes and other bonuses are tracked in the site's database and labeled separately from purchased credits.
  • +
  • Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash.
  • +
+
+ +
+

4. Refunds

+

Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in the member's balance until spent. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to the member's balance, labeled as returned purchased credits.

+
+ +
+

5. Ad formats

+

Seven formats: banner ads, text ads, login ads, video ads, solo ads (a message sent to members), featured rotation, and verified visits (a member opens the advertiser's page and stays on it for a set time before the visit counts).

+
+ +
+

6. Attention and anti-fraud

+
    +
  • Active viewing: video ads pause when the viewer switches tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early.
  • +
  • One account per person: required by the Terms. Sign-ups are checked with device and network signals; a second account from the same device is refused, and suspicious matches are flagged for review. Accounts sign in with a one-time email code.
  • +
  • Extra positions, openly: a member who wants more than one position adds extra wallets to their one account ("Qualified Start"). They are the member's own wallets and own purchases, shown openly in the account.
  • +
  • PolHunter codes: each hunt code is generated per member and per visit, is only released after the required time on the page, and its hiding place rotates daily, so codes cannot be shared or scraped ahead of time.
  • +
+
+ +
+

7. Network games

+

Free browser games in the network bring players to member ads and pay small POL rewards for gameplay milestones. Rewards come from game wallets that the company tops up from platform income, and every top-up is recorded in the company's accounts as a marketing cost. Rewards are per action and not guaranteed. Players sign in to the games with their InstantAdPay account, so a player's sponsor carries across them.

+
+ + + + + + + + +
GameWhat it isStatus
PolHunterScavenger hunts across network sites: find a per-visit code after a 45-second visit, plus advertiser missions.Live
Gem KingdomFantasy match-3 with boss battles and a village to rebuild.Live
Drip RunnerArcade runner: dodge drones, clear chapters, refuel at verified ad visits.Live
ClutterHuntSeasonal hidden-object game.Live
Spooky DoorsHalloween event: platform levels and door visits with candy milestones.Through October 31, 2026
SpellWheelLetter-wheel word puzzle.Opens October 10, 2026
PolyWarriorsCyberpunk turn-based battler with collectible warrior NFTs.Opens October 12, 2026
+
+ + + +
+

What InstantAdPay is not

+
    +
  • Not an investment, token sale or security. Credits are not a token and have no cash value.
  • +
  • Not a holder of member money. Payments are split by the contract in the same transaction.
  • +
  • Not a guarantee of income. Referral payouts happen only when real advertising is purchased in a member's line.
  • +
+
+
+ + + + diff --git a/public/friday.html b/public/friday.html index 34218ae..513227e 100644 --- a/public/friday.html +++ b/public/friday.html @@ -1,76 +1,76 @@ - - - - -Five Dollar Friday: 20% bonus credits on every $5+ ad package | InstantAdPay - - - - - - - - - - - - - - -
-
-

Every Friday · US Central time · midnight to midnight

-

Five Dollar Friday: 20% bonus credits on every $5+ ad package.

-

Buy any InstantAdPay ad package from $5 up on a Friday and 20% extra credits land the moment the purchase settles. No code, nothing to claim. And like every pack, it pays the sponsor line in the same transaction.

-
- - Five Dollar Friday: 20% bonus credits on every $5+ ad package. Fridays 12:00 AM to 11:59 PM US Central time. - -
CheckingLoading today’s status…
- - - -
-
Step 1

Join free, by email.

Email first, wallet later, inside your account. Nothing to install to look around.

-
Step 2

Buy any pack from $5 on a Friday.

Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log. You also get a free 7-day Game Pass for all nine games.

-
Step 3

Your pack pays the line above you. Theirs pays you.

Every package is one Polygon transaction that splits to the sponsor line instantly. Public ledger, nothing held, nothing pending.

-
- -
What a credit is. One credit is one cent of ad delivery across the network: banners, text ads, video, verified visits, solo ads and more. Credits are not money and cannot be withdrawn. They buy advertising for your own offers. The POL the contract pays to wallets is separate and comes only from packages bought in your line.
- -
Members: this page is your Friday promo tool. Add ?ref=yourusername to this address and anyone who joins from it is your referral, the same as your invite link. Banners, ready-made posts and your exact link are in Promo tools.
- -

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.

- -
- - - - + + + + +Five Dollar Friday: 20% bonus credits on every $5+ ad package | InstantAdPay + + + + + + + + + + + + + + +
+
+

Every Friday · US Central time · midnight to midnight

+

Five Dollar Friday: 20% bonus credits on every $5+ ad package.

+

Buy any InstantAdPay ad package from $5 up on a Friday and 20% extra credits land the moment the purchase settles. No code, nothing to claim. And like every pack, it pays the sponsor line in the same transaction.

+
+ + Five Dollar Friday: 20% bonus credits on every $5+ ad package. Fridays 12:00 AM to 11:59 PM US Central time. + +
CheckingLoading today’s status…
+ + + +
+
Step 1

Join free, by email.

Email first, wallet later, inside your account. Nothing to install to look around.

+
Step 2

Buy any pack from $5 on a Friday.

Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log. You also get a free 7-day Game Pass for all nine games.

+
Step 3

Your pack pays the line above you. Theirs pays you.

Every package is one Polygon transaction that splits to the sponsor line instantly. Public ledger, nothing held, nothing pending.

+
+ +
What a credit is. One credit is one cent of ad delivery across the network: banners, text ads, video, verified visits, solo ads and more. Credits are not money and cannot be withdrawn. They buy advertising for your own offers. The POL the contract pays to wallets is separate and comes only from packages bought in your line.
+ +
Members: this page is your Friday promo tool. Add ?ref=yourusername to this address and anyone who joins from it is your referral, the same as your invite link. Banners, ready-made posts and your exact link are in Promo tools.
+ +

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.

+ +
+ + + + diff --git a/public/games.html b/public/games.html index f542cf7..7f61cb6 100644 --- a/public/games.html +++ b/public/games.html @@ -1,83 +1,83 @@ - - - - -Games that pay POL | InstantAdPay - - - - - - - - - - - - - - - -
-
-

InstantAdPay games

-

Play free. Get paid in POL.

-

Every game in the network, on one page. Each one signs you in with your InstantAdPay account in one tap and pays POL to the wallet on that account for the things you do inside it: first clears, levels, chapters, finds, daily puzzles.

-
- -
How it worksCreate a free InstantAdPay account, link a Polygon wallet on your Wallet tab (one free signature), then open any game below. Rewards are small per action and paid automatically when your balance in that game reaches its payout amount. Every payout carries a transaction link.
- -
-
- - -
-

Not a member yet?

Join free, add a wallet, and every game on this page pays the same wallet. InstantAdPay itself is an advertising network: members run ads and get paid when the people they bring in buy packages.

- Join free -
- -

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment. Game rewards are a marketing cost paid from a funded pool while it lasts.

- -
- - - + + + + +Games that pay POL | InstantAdPay + + + + + + + + + + + + + + + +
+
+

InstantAdPay games

+

Play free. Get paid in POL.

+

Every game in the network, on one page. Each one signs you in with your InstantAdPay account in one tap and pays POL to the wallet on that account for the things you do inside it: first clears, levels, chapters, finds, daily puzzles.

+
+ +
How it worksCreate a free InstantAdPay account, link a Polygon wallet on your Wallet tab (one free signature), then open any game below. Rewards are small per action and paid automatically when your balance in that game reaches its payout amount. Every payout carries a transaction link.
+ +
+
+ + +
+

Not a member yet?

Join free, add a wallet, and every game on this page pays the same wallet. InstantAdPay itself is an advertising network: members run ads and get paid when the people they bring in buy packages.

+ Join free +
+ +

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment. Game rewards are a marketing cost paid from a funded pool while it lasts.

+ +
+ + + diff --git a/public/index.html b/public/index.html index 5290e84..465ec52 100644 --- a/public/index.html +++ b/public/index.html @@ -1,508 +1,508 @@ - - - - - -InstantAdPay: advertise and earn, locked in code - - - - - - - - - - - - - - - - - - - - - -
-
- -
- - - - - - -
-

Advertise and earn instantly.
Locked in code, not promises.

-

Buy real ad packages from 5 to 500 dollars. Every purchase settles through - a smart contract you can read yourself, and your earnings land in - your own wallet before the page even refreshes.

-

One crypto, one network: packages are paid in POL on Polygon and every payout arrives as POL in your wallet. Buy POL with a card inside if you have never held any.

- - -
-
–
On-chain members
-
–
Packages bought
-
–
POL settled
-
–
Instant payouts
-
-

every number above is read from the blockchain, not a marketing database

- - -
-
- - - -
-
-
-

The whole platform in four minutes

-

What it is, what you get free, how the ads run, how the money moves, and how a line gets built. Watch this first.

-
-
- -
-

No income is promised. Every figure in the video is a rule of the contract.

-
-
-
-
-
-

Instant payments without compromise

-

Most referral programs run on a database someone can change after you promote. - This one runs on Polygon, split by a contract nobody can touch. Not even us.

-
-
-
-
-

Paid in the same transaction

-

The purchase and every payout are one blockchain event. No balances held, no withdrawal - button, no company touching the money.

-
-
-
-

Rules that cannot move

-

50-20-10 across three levels plus a 20 percent platform fee, written as constants in an - immutable contract. There is no function to change them.

-
-
-
-

Verifiable by anyone

-

Every payment streams to a public ledger with a verify link straight to the block explorer. - If it is not there, it did not happen.

-
-
-
-
- -
-
-
-

Why this is not another ad site

-

You have seen traffic exchanges, click-to-earn sites and solo-ad sellers. Here is the honest side by side.

-
-
- - - - - - - - - - -
Typical advertising siteInstantAdPay
Referral commission5 to 15 percent, often only after a minimum balance50 percent to the direct sponsor, then 20 and 10 on the next two levels
When you get paidRequest a withdrawal, wait for approval, hopeIn the same transaction the package sells
Who holds the moneyThe site's balance, at the owner's discretionNobody. The contract splits it to real wallets. There is no balance to hold
Can the rules changeWhenever the owner edits a settingNever. 50 / 20 / 10 / 20 are constants in a verified, immutable contract
ProofA number on a dashboardEvery payout is a public transaction you can open yourself
Ad viewsTimers that run while nobody looksA 10-second dwell, a human check, and a server-side clock
CreditsPoints that expire or get devalued1 credit = 1 cent of delivery, recorded on-chain, spent only by your campaigns
JoiningInstall an app, connect a wallet, then maybe readEmail first. The wallet comes when you are ready to be paid
AdvertisingPay to be seen by people who are paid to clickSeven formats delivered to members who buy ads themselves, with verified visits and finished video views
-

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

-
-
- -
-
-
-

Watch the money move

-

This is a live view, not a brochure. Real purchases split into real payouts, - each one a click away from the raw transaction.

-
-
-
-
-
-

Buy a package

-

Priced in dollars, settled in POL at the live oracle rate. Overpayment refunds itself in the same transaction.

-
-
-
-

The contract splits it

-

Half to the direct sponsor, then levels 2 and 3, then the platform. Automatically, immediately, every time.

-
-
-
-
instantadpay.com/ledger
-
-
🧾 member #7 bought package #2 ($20.00)−213 POL
-
💸 level 1 payout → member #3+106.5 POL
-
💸 level 2 payout → member #2+42.6 POL
-
💸 level 3 payout → member #1+21.3 POL
-
🏛 platform fee settled42.6 POL
-
⭐ member #3 now has 2 qualifying buyerslevel 2 ✓
-
-
-
-
-
-

Straight to their wallets

-

Recipients get POL in their own wallets within seconds. Nothing to claim, nothing to request.

-
-
-
-

Credits mint on-chain

-

One credit is one cent of ad delivery across the network. Only your campaigns can ever spend them.

-
-
-
-

Amounts shown are the $20 worked example at the current oracle rate. Open the real ledger →

-
-
- -
-
-
-
- - - - - - - - - - - - - - - - - - - 50% - - - - - - - - - - - - - - - - - - - - - -
-
-

Earn deeper as your people buy

-

Levels unlock by performance, never by payment. Refer buyers, and their - shares of every future purchase route to you automatically.

-
- - - -
-

Activate with the $20 starter package and switch on payouts from your wallet. From then on your direct referrals each pay you 50 percent of every package they ever buy, in POL, straight to your wallet. Until you activate, you earn ad credits, not POL.

-
    -
  • No withdrawal requests, ever. Every payment sends straight to your wallet.
  • -
  • Unqualified shares visibly pass up to the next qualified person
  • -
  • Qualification never expires and can never be bought
  • -
-
-
-
-
- -
-
-
-

Real ad inventory. Real eyeballs.

-

This is not phantom traffic or empty impressions. Seven ad formats run right now, - reaching members who are themselves marketers buying traffic — and members earn credits back - for the attention they give.

-
-
-
-
-

Display banners live

-

All standard sizes, live across our network, priced per impression. You pay for views, not guesses.

-
-
-
-

Text ads live

-

A headline plus a support line, placed where members actually look. Also per impression, also live right now.

-
-
-
-

Login ads live

-

The moment a member signs in, your ad is the toll gate: they open your page in a fresh tab - while a countdown holds their dashboard. Just a link is enough — add a banner if you have - one. Priced per day.

-
-
-
-

Video ads live

-

Upload a video or drop a link, and pick how long members must watch — 10, 30 or 60 seconds. - They watch in a player that can't be skipped, the clock runs on our server, and you pay only - for completed views. There's a full-screen Shorts feed too.

-
-
-
-

Solo ads live

-

Your full message — rich text, an image or video, and a call-to-action button — delivered - straight into member inboxes on-site and by email. Priced per guaranteed delivery, and readers - earn credits for a real read, so your message gets opened, not skimmed past.

-
-
-
-

Featured rotation live

-

Book your link into the featured rotation by the day — 1, 2 or 7 days — with a hard cap on how - many links share a day and the occupancy shown before you buy. The only rotator that tells you - the dilution up front, because hiding it is a sucker move.

-
-
-
-

Verified visits live

-

Buy a pack of guaranteed unique human visits. Each one is a different member who stayed the - full dwell and passed a human check — no bots, no recycled clicks, no repeats, just real visits - you can count on.

-
-
-
-
- -
-
-
-

What you get as a member

-

Free membership gets you in the door with a working account and the ability to earn - from day one. Buy any package and the real firepower unlocks.

-
-
-
-

Credits: everyone earns these

-

Ad credits are the currency of the ad platform. One credit is one cent of ad delivery. They are not money and are never withdrawn.

-
    -
  • Earned free by viewing ads, watching videos, verified visits, inbox ads and the daily sign-in
  • -
  • Welcome credits on day one, badge bonuses as your team grows
  • -
  • Spent on your own banner, text, video and solo campaigns
  • -
-
-
-

POL: activated members earn this

-

POL is real crypto, paid to your own wallet by the contract in the same transaction someone in your line buys a package. Nobody holds it for you.

-
    -
  • Activate: the $20 starter package (2,000 credits to advertise with) and payouts switched on from your wallet
  • -
  • Level 1 pays 50 percent of every package your direct referrals buy, from the day you are activated
  • -
  • Levels 2 and 3 open when 2, then 5, of your referrals buy a $20 or larger package
  • -
  • If you are not activated when someone in your line buys, that share passes up to the next member above you who is
  • -
-
-
-
-
-

Free membership includes

-
    -
  • A member account and the live ledger
  • -
  • Welcome credits to taste real ad delivery
  • -
  • Earn more credits by viewing ads, watching videos, making verified visits and reading solo ads
  • -
  • Your line banner, shown to your next three levels as they join
  • -
  • Your own shareable profile page with a scannable join QR code
  • -
  • Achievement badges and credit bonuses as your team grows
  • -
  • Your personal referral link, working from day one
  • -
  • Your invite link and line from day one; activate with the $20 starter package to earn POL on your referrals' purchases
  • -
-
-
-

Any package adds

-
    -
  • On-chain ad credits minted the moment you buy
  • -
  • All seven ad formats, with live stats and a dashboard of charts per campaign
  • -
  • Top up any campaign anytime, and message your whole downline
  • -
  • A full arsenal of promotional tools and a ready-made banner kit, personalized with your link
  • -
  • Packages of $20 or more count toward qualification
  • -
-
-
-
-
- -
-
-
-

The ad packages

-

Priced in dollars, settled in POL at the moment you buy. Packages of $20 or more - count toward your sponsor's qualification.

-
-
Loading live prices from the contract…
-
-
50%
direct sponsor
-
20%
level 2
-
10%
level 3
-
20%
platform
-
-
-
- -
-
-
-

Run your what-if

-

Play with a scenario and see how the contract would split it. This is arithmetic on the - locked percentages, not a prediction and not a promise. Nobody earns a cent unless real - people really buy advertising.

-
-
-
-
-

Direct referrals who each buy a package

-

- 2

-

The package they buy

-

-

Referrals each of them brings who also buy

-

- 2

-

-
-
-
- - - - - - - -
LevelPeople buyingYour shareYou receive
Level 1 open–50%–
Level 2 locked–20%–
Level 3 locked–10%–
If every one of those purchases happens–
-

And that is one round of purchases. The same - split runs again on every future package the same people buy.

-
-
-

- The pass-up rule: a locked level's share does not disappear. - The contract climbs the sponsor line, checking up to 25 positions, and pays the first qualified - person it finds; only if nobody in those 25 qualifies does the share go to the platform. It cuts - both ways: stay qualified and you catch the shares that under-qualified positions below you let - slip. Every pass-up is a visible event on the ledger, so you can see - exactly where money climbed past someone and why.

-
-
-
- -
-
- -
-
- -
-
-
-

Questions people actually ask

-
-
Is this a pyramid or ponzi scheme? -

No, and here is the plain version of why. A pyramid scheme pays you just for recruiting, with no - real product behind it. Here every payment is for ad delivery, and the payouts only come from real - buyers who buy real ad packages. You earn from people actually advertising, not from building a chain - of signups. The whole thing runs on a public ledger you can verify yourself, so nothing stays hidden.

-
What happens if the company disappears? -

The important part is that there is no company holding the money. Every sale is split by the smart - contract itself, on the blockchain, in the same transaction. Nobody can pause it, change it, or run - off with the funds, because the code does the paying automatically. If the site vanished tomorrow, - the contract would keep paying exactly what it is set to pay.

-
Do I need crypto experience or a wallet to join? -

No. You can start with a free email signup and use the platform the same way you would use any ad - site. If you want payouts to a wallet, setting one up takes a few minutes and the platform walks you - through it. But you do not need to know anything about crypto to get in and get moving.

-
How fast do I really get paid? -

Payouts happen inside the very transaction that pays for the package. There is no approval step - and nobody holding funds. Your share lands in your own wallet the moment your referral's purchase - confirms. The public ledger lets you watch each one go through.

-
What am I actually buying? -

You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. - The 5 dollar package mints 500 credits, and the bigger packages mint bonus credits on top, up to - 70,000 on the 500 dollar package. That is the product, plain and simple. Your earnings come from - referring people who also buy real ad delivery, and the contract splits every purchase automatically.

- -
-
-

See a payment land before you decide.

-

The ledger is open to everyone. Watch real purchases - split and settle, then join free when you have seen enough.

- Join free - Open the live ledger -
-
-
live · polygon
-
-
💸 payout → member #3instant
-
💸 payout → member #2instant
-
🔍 verify on explorer↗
-
-
-
- -
-
InstantAdPay · every payment verifiable on-chain · live ledger · view the contract ↗ · support
-
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
-
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
- -
-
-
- - - - - - - + + + + + +InstantAdPay: advertise and earn, locked in code + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + + + + + +
+

Advertise and earn instantly.
Locked in code, not promises.

+

Buy real ad packages from 5 to 500 dollars. Every purchase settles through + a smart contract you can read yourself, and your earnings land in + your own wallet before the page even refreshes.

+

One crypto, one network: packages are paid in POL on Polygon and every payout arrives as POL in your wallet. Buy POL with a card inside if you have never held any.

+ + +
+
–
On-chain members
+
–
Packages bought
+
–
POL settled
+
–
Instant payouts
+
+

every number above is read from the blockchain, not a marketing database

+ + +
+
+ + + +
+
+
+

The whole platform in four minutes

+

What it is, what you get free, how the ads run, how the money moves, and how a line gets built. Watch this first.

+
+
+ +
+

No income is promised. Every figure in the video is a rule of the contract.

+
+
+
+
+
+

Instant payments without compromise

+

Most referral programs run on a database someone can change after you promote. + This one runs on Polygon, split by a contract nobody can touch. Not even us.

+
+
+
+
+

Paid in the same transaction

+

The purchase and every payout are one blockchain event. No balances held, no withdrawal + button, no company touching the money.

+
+
+
+

Rules that cannot move

+

50-20-10 across three levels plus a 20 percent platform fee, written as constants in an + immutable contract. There is no function to change them.

+
+
+
+

Verifiable by anyone

+

Every payment streams to a public ledger with a verify link straight to the block explorer. + If it is not there, it did not happen.

+
+
+
+
+ +
+
+
+

Why this is not another ad site

+

You have seen traffic exchanges, click-to-earn sites and solo-ad sellers. Here is the honest side by side.

+
+
+ + + + + + + + + + +
Typical advertising siteInstantAdPay
Referral commission5 to 15 percent, often only after a minimum balance50 percent to the direct sponsor, then 20 and 10 on the next two levels
When you get paidRequest a withdrawal, wait for approval, hopeIn the same transaction the package sells
Who holds the moneyThe site's balance, at the owner's discretionNobody. The contract splits it to real wallets. There is no balance to hold
Can the rules changeWhenever the owner edits a settingNever. 50 / 20 / 10 / 20 are constants in a verified, immutable contract
ProofA number on a dashboardEvery payout is a public transaction you can open yourself
Ad viewsTimers that run while nobody looksA 10-second dwell, a human check, and a server-side clock
CreditsPoints that expire or get devalued1 credit = 1 cent of delivery, recorded on-chain, spent only by your campaigns
JoiningInstall an app, connect a wallet, then maybe readEmail first. The wallet comes when you are ready to be paid
AdvertisingPay to be seen by people who are paid to clickSeven formats delivered to members who buy ads themselves, with verified visits and finished video views
+

No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

+
+
+ +
+
+
+

Watch the money move

+

This is a live view, not a brochure. Real purchases split into real payouts, + each one a click away from the raw transaction.

+
+
+
+
+
+

Buy a package

+

Priced in dollars, settled in POL at the live oracle rate. Overpayment refunds itself in the same transaction.

+
+
+
+

The contract splits it

+

Half to the direct sponsor, then levels 2 and 3, then the platform. Automatically, immediately, every time.

+
+
+
+
instantadpay.com/ledger
+
+
🧾 member #7 bought package #2 ($20.00)−213 POL
+
💸 level 1 payout → member #3+106.5 POL
+
💸 level 2 payout → member #2+42.6 POL
+
💸 level 3 payout → member #1+21.3 POL
+
🏛 platform fee settled42.6 POL
+
⭐ member #3 now has 2 qualifying buyerslevel 2 ✓
+
+
+
+
+
+

Straight to their wallets

+

Recipients get POL in their own wallets within seconds. Nothing to claim, nothing to request.

+
+
+
+

Credits mint on-chain

+

One credit is one cent of ad delivery across the network. Only your campaigns can ever spend them.

+
+
+
+

Amounts shown are the $20 worked example at the current oracle rate. Open the real ledger →

+
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + 50% + + + + + + + + + + + + + + + + + + + + + +
+
+

Earn deeper as your people buy

+

Levels unlock by performance, never by payment. Refer buyers, and their + shares of every future purchase route to you automatically.

+
+ + + +
+

Activate with the $20 starter package and switch on payouts from your wallet. From then on your direct referrals each pay you 50 percent of every package they ever buy, in POL, straight to your wallet. Until you activate, you earn ad credits, not POL.

+
    +
  • No withdrawal requests, ever. Every payment sends straight to your wallet.
  • +
  • Unqualified shares visibly pass up to the next qualified person
  • +
  • Qualification never expires and can never be bought
  • +
+
+
+
+
+ +
+
+
+

Real ad inventory. Real eyeballs.

+

This is not phantom traffic or empty impressions. Seven ad formats run right now, + reaching members who are themselves marketers buying traffic — and members earn credits back + for the attention they give.

+
+
+
+
+

Display banners live

+

All standard sizes, live across our network, priced per impression. You pay for views, not guesses.

+
+
+
+

Text ads live

+

A headline plus a support line, placed where members actually look. Also per impression, also live right now.

+
+
+
+

Login ads live

+

The moment a member signs in, your ad is the toll gate: they open your page in a fresh tab + while a countdown holds their dashboard. Just a link is enough — add a banner if you have + one. Priced per day.

+
+
+
+

Video ads live

+

Upload a video or drop a link, and pick how long members must watch — 10, 30 or 60 seconds. + They watch in a player that can't be skipped, the clock runs on our server, and you pay only + for completed views. There's a full-screen Shorts feed too.

+
+
+
+

Solo ads live

+

Your full message — rich text, an image or video, and a call-to-action button — delivered + straight into member inboxes on-site and by email. Priced per guaranteed delivery, and readers + earn credits for a real read, so your message gets opened, not skimmed past.

+
+
+
+

Featured rotation live

+

Book your link into the featured rotation by the day — 1, 2 or 7 days — with a hard cap on how + many links share a day and the occupancy shown before you buy. The only rotator that tells you + the dilution up front, because hiding it is a sucker move.

+
+
+
+

Verified visits live

+

Buy a pack of guaranteed unique human visits. Each one is a different member who stayed the + full dwell and passed a human check — no bots, no recycled clicks, no repeats, just real visits + you can count on.

+
+
+
+
+ +
+
+
+

What you get as a member

+

Free membership gets you in the door with a working account and the ability to earn + from day one. Buy any package and the real firepower unlocks.

+
+
+
+

Credits: everyone earns these

+

Ad credits are the currency of the ad platform. One credit is one cent of ad delivery. They are not money and are never withdrawn.

+
    +
  • Earned free by viewing ads, watching videos, verified visits, inbox ads and the daily sign-in
  • +
  • Welcome credits on day one, badge bonuses as your team grows
  • +
  • Spent on your own banner, text, video and solo campaigns
  • +
+
+
+

POL: activated members earn this

+

POL is real crypto, paid to your own wallet by the contract in the same transaction someone in your line buys a package. Nobody holds it for you.

+
    +
  • Activate: the $20 starter package (2,000 credits to advertise with) and payouts switched on from your wallet
  • +
  • Level 1 pays 50 percent of every package your direct referrals buy, from the day you are activated
  • +
  • Levels 2 and 3 open when 2, then 5, of your referrals buy a $20 or larger package
  • +
  • If you are not activated when someone in your line buys, that share passes up to the next member above you who is
  • +
+
+
+
+
+

Free membership includes

+
    +
  • A member account and the live ledger
  • +
  • Welcome credits to taste real ad delivery
  • +
  • Earn more credits by viewing ads, watching videos, making verified visits and reading solo ads
  • +
  • Your line banner, shown to your next three levels as they join
  • +
  • Your own shareable profile page with a scannable join QR code
  • +
  • Achievement badges and credit bonuses as your team grows
  • +
  • Your personal referral link, working from day one
  • +
  • Your invite link and line from day one; activate with the $20 starter package to earn POL on your referrals' purchases
  • +
+
+
+

Any package adds

+
    +
  • On-chain ad credits minted the moment you buy
  • +
  • All seven ad formats, with live stats and a dashboard of charts per campaign
  • +
  • Top up any campaign anytime, and message your whole downline
  • +
  • A full arsenal of promotional tools and a ready-made banner kit, personalized with your link
  • +
  • Packages of $20 or more count toward qualification
  • +
+
+
+
+
+ +
+
+
+

The ad packages

+

Priced in dollars, settled in POL at the moment you buy. Packages of $20 or more + count toward your sponsor's qualification.

+
+
Loading live prices from the contract…
+
+
50%
direct sponsor
+
20%
level 2
+
10%
level 3
+
20%
platform
+
+
+
+ +
+
+
+

Run your what-if

+

Play with a scenario and see how the contract would split it. This is arithmetic on the + locked percentages, not a prediction and not a promise. Nobody earns a cent unless real + people really buy advertising.

+
+
+
+
+

Direct referrals who each buy a package

+

+ 2

+

The package they buy

+

+

Referrals each of them brings who also buy

+

+ 2

+

+
+
+
+ + + + + + + +
LevelPeople buyingYour shareYou receive
Level 1 open–50%–
Level 2 locked–20%–
Level 3 locked–10%–
If every one of those purchases happens–
+

And that is one round of purchases. The same + split runs again on every future package the same people buy.

+
+
+

+ The pass-up rule: a locked level's share does not disappear. + The contract climbs the sponsor line, checking up to 25 positions, and pays the first qualified + person it finds; only if nobody in those 25 qualifies does the share go to the platform. It cuts + both ways: stay qualified and you catch the shares that under-qualified positions below you let + slip. Every pass-up is a visible event on the ledger, so you can see + exactly where money climbed past someone and why.

+
+
+
+ +
+
+ +
+
+ +
+
+
+

Questions people actually ask

+
+
Is this a pyramid or ponzi scheme? +

No, and here is the plain version of why. A pyramid scheme pays you just for recruiting, with no + real product behind it. Here every payment is for ad delivery, and the payouts only come from real + buyers who buy real ad packages. You earn from people actually advertising, not from building a chain + of signups. The whole thing runs on a public ledger you can verify yourself, so nothing stays hidden.

+
What happens if the company disappears? +

The important part is that there is no company holding the money. Every sale is split by the smart + contract itself, on the blockchain, in the same transaction. Nobody can pause it, change it, or run + off with the funds, because the code does the paying automatically. If the site vanished tomorrow, + the contract would keep paying exactly what it is set to pay.

+
Do I need crypto experience or a wallet to join? +

No. You can start with a free email signup and use the platform the same way you would use any ad + site. If you want payouts to a wallet, setting one up takes a few minutes and the platform walks you + through it. But you do not need to know anything about crypto to get in and get moving.

+
How fast do I really get paid? +

Payouts happen inside the very transaction that pays for the package. There is no approval step + and nobody holding funds. Your share lands in your own wallet the moment your referral's purchase + confirms. The public ledger lets you watch each one go through.

+
What am I actually buying? +

You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. + The 5 dollar package mints 500 credits, and the bigger packages mint bonus credits on top, up to + 70,000 on the 500 dollar package. That is the product, plain and simple. Your earnings come from + referring people who also buy real ad delivery, and the contract splits every purchase automatically.

+ +
+
+

See a payment land before you decide.

+

The ledger is open to everyone. Watch real purchases + split and settle, then join free when you have seen enough.

+ Join free + Open the live ledger +
+
+
live · polygon
+
+
💸 payout → member #3instant
+
💸 payout → member #2instant
+
🔍 verify on explorer↗
+
+
+
+ +
+
InstantAdPay · every payment verifiable on-chain · live ledger · view the contract ↗ · support
+
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
+
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/join.html b/public/join.html index 33cf94f..f4323d7 100644 --- a/public/join.html +++ b/public/join.html @@ -157,7 +157,7 @@ InstantAdPay · Contract · Terms · Privacy · Disclaimer - + diff --git a/public/launch.html b/public/launch.html index 632fdb7..2a033b6 100644 --- a/public/launch.html +++ b/public/launch.html @@ -1,111 +1,111 @@ - - - - -Founding week checklist | InstantAdPay - - - - - - - - - -
-
-

Leaders · founding week

-

Eight things before launch day.

-

Get these done this week, in this order, and your first commissions land in your wallet instead of climbing past you. Everything here reads from your live account.

-
- -

Members only

Sign in to your member area to open the checklist. Sign in

- -
-
-
0 of 8 ready
- - -
- -
- The one rule that makes this week matter: unqualified levels pass up. - Level 2 pays you only after two of your people have bought a $20 or more package. Level 3 only after five. If your team's team starts buying before you are qualified, those 20% and 10% payments climb to the next qualified member above you, or to the platform, and they never come back. Qualify first, then open the doors. -
- -
    - -

    The week, day by day

    -
    -
    Day 1
    • Items 1 to 3 done in one sitting.
    • Decide your play, and whether you are going for level 2 or all three.
    -
    Days 2 to 3
    • Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.
    • Line banner uploaded.
    -
    Days 4 to 6
    • Place your first two personally.
    • Walk them through items 1 to 3 on their accounts.
    -
    Launch day
    • Everyone releases links at the same time.
    • Watch the ledger and the Telegram proof feed fill.
    -
    - -

    What to send your two this week

    -
    Text or DM · before launchI'm bringing a small group in early on something before it opens publicly next week. Free to join, real advertising, and every payment lands in your own wallet the second it happens. I want you positioned before the doors open. Set up takes five minutes: your link
    -
    Text or DM · after they joinThree quick things before launch so your first commission lands with you and not past you: pick your username, link your wallet, switch on payouts. All on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.
    - -

    Launch graphics and posts

    -

    Two images, no text on them but the headline, so they work anywhere. Post one with the day's line below it; your link and the FOUNDER code are already in each line.

    -
    -
    Doors open Monday
    Wide, 1200x630 · for X, Facebook, LinkedIn, link previews Download
    -
    Doors open Monday
    Square, 1080x1080 · for Instagram, Telegram, WhatsApp Download
    -
    -
    - -

    Launch week swipes: four emails for your list

    -

    Send one a day to your own list or contacts, in this order. Your invite link and the FOUNDER code (500 free credits for anyone who joins before Monday 9 AM Central) are already filled in. Copy, paste, send from your own email. Edit anything you like.

    -
    - -

    No income is guaranteed. Results depend on your effort. Crypto carries risk of loss. InstantAdPay sells advertising; it is not an investment.

    -
    - - -
    - - - - + + + + +Founding week checklist | InstantAdPay + + + + + + + + + +
    +
    +

    Leaders · founding week

    +

    Eight things before launch day.

    +

    Get these done this week, in this order, and your first commissions land in your wallet instead of climbing past you. Everything here reads from your live account.

    +
    + +

    Members only

    Sign in to your member area to open the checklist. Sign in

    + +
    +
    +
    0 of 8 ready
    + + +
    + +
    + The one rule that makes this week matter: unqualified levels pass up. + Level 2 pays you only after two of your people have bought a $20 or more package. Level 3 only after five. If your team's team starts buying before you are qualified, those 20% and 10% payments climb to the next qualified member above you, or to the platform, and they never come back. Qualify first, then open the doors. +
    + +
      + +

      The week, day by day

      +
      +
      Day 1
      • Items 1 to 3 done in one sitting.
      • Decide your play, and whether you are going for level 2 or all three.
      +
      Days 2 to 3
      • Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.
      • Line banner uploaded.
      +
      Days 4 to 6
      • Place your first two personally.
      • Walk them through items 1 to 3 on their accounts.
      +
      Launch day
      • Everyone releases links at the same time.
      • Watch the ledger and the Telegram proof feed fill.
      +
      + +

      What to send your two this week

      +
      Text or DM · before launchI'm bringing a small group in early on something before it opens publicly next week. Free to join, real advertising, and every payment lands in your own wallet the second it happens. I want you positioned before the doors open. Set up takes five minutes: your link
      +
      Text or DM · after they joinThree quick things before launch so your first commission lands with you and not past you: pick your username, link your wallet, switch on payouts. All on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.
      + +

      Launch graphics and posts

      +

      Two images, no text on them but the headline, so they work anywhere. Post one with the day's line below it; your link and the FOUNDER code are already in each line.

      +
      +
      Doors open Monday
      Wide, 1200x630 · for X, Facebook, LinkedIn, link previews Download
      +
      Doors open Monday
      Square, 1080x1080 · for Instagram, Telegram, WhatsApp Download
      +
      +
      + +

      Launch week swipes: four emails for your list

      +

      Send one a day to your own list or contacts, in this order. Your invite link and the FOUNDER code (500 free credits for anyone who joins before Monday 9 AM Central) are already filled in. Copy, paste, send from your own email. Edit anything you like.

      +
      + +

      No income is guaranteed. Results depend on your effort. Crypto carries risk of loss. InstantAdPay sells advertising; it is not an investment.

      +
      + + +
      + + + + diff --git a/public/ledger.html b/public/ledger.html index f452b9f..a3d0d88 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -1,48 +1,48 @@ - - - - -Live ledger | InstantAdPay - - - - - - - - - - - - - - - - - -
      -
      -

      The ledger does not lie.

      -

      This page streams every payment the contract has ever made. If it is not here, - it did not happen. Every line carries a verify link straight to the block explorer. Go click one.

      -

      connecting… -

      -
      - -
      -
      -
      Loading recent history…
      -
      -
      - - -
      - - - - - - + + + + +Live ledger | InstantAdPay + + + + + + + + + + + + + + + + + +
      +
      +

      The ledger does not lie.

      +

      This page streams every payment the contract has ever made. If it is not here, + it did not happen. Every line carries a verify link straight to the block explorer. Go click one.

      +

      connecting… +

      +
      + +
      +
      +
      Loading recent history…
      +
      +
      + + +
      + + + + + + diff --git a/public/my.html b/public/my.html index fe45fd3..4ec1913 100644 --- a/public/my.html +++ b/public/my.html @@ -1185,11 +1185,11 @@ - + - + diff --git a/public/partners.html b/public/partners.html index 989fc5e..f9f08a1 100644 --- a/public/partners.html +++ b/public/partners.html @@ -1,136 +1,136 @@ - - - - -For site owners | InstantAdPay - - - - - - - - - -
      -
      -

      For site owners with a downline builder

      -

      I built the ad platform I always wanted to run. I want it in your builder.

      -

      A note from me, plus everything you need to list InstantAdPay in your builder and hand your members free ad credits with a code of your own.

      -
      - -

      - -
      -

      Watch first: the whole platform in about five minutes. Free and paid members, the seven ad formats, how people get paid, and the offer for your builder.

      - -

      Why I built it

      -

      You know I've been running ad sites for years, the kind your members already know: buy a package, run banners and text ads, click for credits. Two of mine, Faucet Wave and Tier One Ads, ran on a licensed script. The vendor went out of business, their license server went dark, and it crippled licenses that were fully paid. The sites died overnight and nothing I could do would bring them back.

      -

      So I built InstantAdPay from scratch as part of the Crypto Team Build Network. No vendor, no license server, and the part that always went wrong on ad sites, the money, is handled by a verified smart contract on Polygon instead of by me. When a package sells, the contract splits the payment and sends it in the same transaction. I never hold member funds, so there is no back office, no payday, and nothing anyone can switch off.

      -

      Marty Bostick · Crypto Team Build Network

      - -

      What InstantAdPay is

      -

      An advertising platform where the ad spend in your line pays you. Members join free with an email address, no password and no wallet on day one. They earn credits by viewing ads and can run their first campaign for zero dollars. When they want more reach they buy an ad package, and every package that sells is split by the contract the moment it sells.

      -
      -

      Seven ad formats

      Banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw the ad.

      -

      Beyond the site

      Banner and text ads also push out to Network Ad Space, a partner rotation across other member sites. Those impressions count in the member's stats.

      -

      WalletConnect built in

      Full WalletConnect integration: members link MetaMask, Trust, Phantom, SafePal or any WalletConnect wallet with one tap, sign once, and buy or get paid straight from that wallet. No custody on my side.

      -

      Public, verified, immutable

      Every payout is a public transaction on Polygon. The split percentages and qualification rules are constants in a verified contract that the operator cannot change.

      -
      - -

      How the money moves

      -

      Every ad package splits the same way, in the same transaction it sells in:

      -
      -
      50%
      direct sponsor
      -
      20%
      level 2
      -
      10%
      level 3
      -
      20%
      platform
      -
      -

      On a $20 package: $10 to the direct sponsor, $4 to level 2, $2 to level 3, $4 to the platform. If a level has no qualified member, that share passes up to the next qualified person above.

      -

      Qualification is earned, never bought. Every direct buyer pays their sponsor 50% from their very first package. Two qualifying buyers, people who bought a $20 or larger package, open level 2. Five open level 3. Until a level opens, its share climbs to the next qualified member above, which is why the plan rewards the people who actually build.

      - - - - - - - - - -
      PackagePriceCredits
      Micro$5500
      Starter$101,000
      Activation, the qualifying buy$202,000
      Builder$505,500
      Growth$10012,000
      Leader$25032,500
      Elite$50070,000
      - -

      What your members get

      -
        -
      • A free start. Join by email, view a few ads, earn credits, run a real banner or text campaign for nothing.
      • -
      • Your promo credits on top. Members who arrive with your code get free ad credits added the moment they join, in addition to everything else.
      • -
      • Instant, public payouts. When anyone in their line buys ads, the contract pays them in POL to their own wallet in the same transaction. They can check every payment on Polygonscan.
      • -
      • A seamless wallet step. Full WalletConnect integration means linking a wallet is one tap and one free signature from any major wallet app, and purchases confirm inside the wallet they already use.
      • -
      • Tools that do the work. A ready-to-send invite message, social posts, email swipes, a full banner kit, objection answers, and a public profile wall with their own banner slots.
      • -
      • Training that keeps growing. A video series that walks the whole member area, plus written plays for building a line.
      • -
      • A holding tank. Members who arrive without a sponsor are not lost. Qualified builders adopt them, first come, first served.
      • -
      • Coaching built in. A next-move card on every dashboard, nudges when a referral stalls, and a live payments topic on Telegram where every payout posts as it lands.
      • -
      - -
      -

      What you get for listing it in your builder

      -
        -
      • Your spot at the top. You join directly under the company at the top, no sponsor in between. All it takes to claim that spot is activating your account with at least the $20 package, and that locks you in at the top of your own line from day one.
      • -
      • Your own promo code. A reusable code that adds free ad credits for every member who redeems it, on your builder link or in the dashboard. I set the credit amount, an optional cap and an optional expiry. One redemption per account, every redemption logged, and you can see uses any time.
      • -
      • Your own line. Every member who comes through your builder link lands under you. Each one who buys pays you 50% of their first package and every package after it, and their buyers open your level 2 and level 3 shares.
      • -
      • Ready-made creatives. Banners in every builder size (468x60, 728x90, 300x250, 160x600, 120x600, 1200x630), text ad copy, email swipes and a program description you can paste into your listing.
      • -
      • A bridge page for your brand, on request. A landing page in this design that names your site, explains the connection, and carries your code.
      • -
      • Attribution you can check. Signups and buyers are tagged with the source they came from, and the promo code report shows exactly who redeemed yours.
      • -
      -
      - -

      Setting it up takes about fifteen minutes

      -
        -
      1. Claim your spot with the button below. It places you directly under the company at the top. Join with your email and pick your username; your own invite link is live immediately: instantadpay.com/join/yourname.
      2. -
      3. Send me your username and the site you are listing it on. I mint your code with the credit amount we agree on.
      4. -
      5. Add InstantAdPay to your downline builder with your link plus the code: https://instantadpay.com/join/yourname?promo=YOURCODE. Members who click it land under you and their credits apply the moment their account exists.
      6. -
      7. Use the banners and text ads from the kit. Members who already have an account can type the code into the "Have a promo code?" box on their Overview.
      8. -
      9. Link a wallet, switch on payouts, and activate with at least the $20 package. That claims your spot at the top and makes you a qualifying buyer in your own right.
      10. -
      - -
      - Claim your spot at the top -

      Free account by email. No password, no wallet today. The link below places you directly under the company.

      - Claim my spot -
      - -

      The honest part

      -

      InstantAdPay sells advertising. Members earn from the ad packages people in their line buy, and nothing else. There is no earn-without-referring option, on purpose, because sites that pay you just for buying in are the ones that collapse. No income is guaranteed, results depend on effort, and cryptocurrency involves risk of loss. The contract, the ledger and every payout are public, so you never have to take my word for any of it.

      -

      Marty Bostick · marty@marketingwithmarty.com · t.me/cryptoteambuild

      - -
      -
      InstantAdPay · home · live ledger · the contract
      -
      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.
      -
      -
      - - - - + + + + +For site owners | InstantAdPay + + + + + + + + + +
      +
      +

      For site owners with a downline builder

      +

      I built the ad platform I always wanted to run. I want it in your builder.

      +

      A note from me, plus everything you need to list InstantAdPay in your builder and hand your members free ad credits with a code of your own.

      +
      + +

      + +
      +

      Watch first: the whole platform in about five minutes. Free and paid members, the seven ad formats, how people get paid, and the offer for your builder.

      + +

      Why I built it

      +

      You know I've been running ad sites for years, the kind your members already know: buy a package, run banners and text ads, click for credits. Two of mine, Faucet Wave and Tier One Ads, ran on a licensed script. The vendor went out of business, their license server went dark, and it crippled licenses that were fully paid. The sites died overnight and nothing I could do would bring them back.

      +

      So I built InstantAdPay from scratch as part of the Crypto Team Build Network. No vendor, no license server, and the part that always went wrong on ad sites, the money, is handled by a verified smart contract on Polygon instead of by me. When a package sells, the contract splits the payment and sends it in the same transaction. I never hold member funds, so there is no back office, no payday, and nothing anyone can switch off.

      +

      Marty Bostick · Crypto Team Build Network

      + +

      What InstantAdPay is

      +

      An advertising platform where the ad spend in your line pays you. Members join free with an email address, no password and no wallet on day one. They earn credits by viewing ads and can run their first campaign for zero dollars. When they want more reach they buy an ad package, and every package that sells is split by the contract the moment it sells.

      +
      +

      Seven ad formats

      Banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw the ad.

      +

      Beyond the site

      Banner and text ads also push out to Network Ad Space, a partner rotation across other member sites. Those impressions count in the member's stats.

      +

      WalletConnect built in

      Full WalletConnect integration: members link MetaMask, Trust, Phantom, SafePal or any WalletConnect wallet with one tap, sign once, and buy or get paid straight from that wallet. No custody on my side.

      +

      Public, verified, immutable

      Every payout is a public transaction on Polygon. The split percentages and qualification rules are constants in a verified contract that the operator cannot change.

      +
      + +

      How the money moves

      +

      Every ad package splits the same way, in the same transaction it sells in:

      +
      +
      50%
      direct sponsor
      +
      20%
      level 2
      +
      10%
      level 3
      +
      20%
      platform
      +
      +

      On a $20 package: $10 to the direct sponsor, $4 to level 2, $2 to level 3, $4 to the platform. If a level has no qualified member, that share passes up to the next qualified person above.

      +

      Qualification is earned, never bought. Every direct buyer pays their sponsor 50% from their very first package. Two qualifying buyers, people who bought a $20 or larger package, open level 2. Five open level 3. Until a level opens, its share climbs to the next qualified member above, which is why the plan rewards the people who actually build.

      + + + + + + + + + +
      PackagePriceCredits
      Micro$5500
      Starter$101,000
      Activation, the qualifying buy$202,000
      Builder$505,500
      Growth$10012,000
      Leader$25032,500
      Elite$50070,000
      + +

      What your members get

      +
        +
      • A free start. Join by email, view a few ads, earn credits, run a real banner or text campaign for nothing.
      • +
      • Your promo credits on top. Members who arrive with your code get free ad credits added the moment they join, in addition to everything else.
      • +
      • Instant, public payouts. When anyone in their line buys ads, the contract pays them in POL to their own wallet in the same transaction. They can check every payment on Polygonscan.
      • +
      • A seamless wallet step. Full WalletConnect integration means linking a wallet is one tap and one free signature from any major wallet app, and purchases confirm inside the wallet they already use.
      • +
      • Tools that do the work. A ready-to-send invite message, social posts, email swipes, a full banner kit, objection answers, and a public profile wall with their own banner slots.
      • +
      • Training that keeps growing. A video series that walks the whole member area, plus written plays for building a line.
      • +
      • A holding tank. Members who arrive without a sponsor are not lost. Qualified builders adopt them, first come, first served.
      • +
      • Coaching built in. A next-move card on every dashboard, nudges when a referral stalls, and a live payments topic on Telegram where every payout posts as it lands.
      • +
      + +
      +

      What you get for listing it in your builder

      +
        +
      • Your spot at the top. You join directly under the company at the top, no sponsor in between. All it takes to claim that spot is activating your account with at least the $20 package, and that locks you in at the top of your own line from day one.
      • +
      • Your own promo code. A reusable code that adds free ad credits for every member who redeems it, on your builder link or in the dashboard. I set the credit amount, an optional cap and an optional expiry. One redemption per account, every redemption logged, and you can see uses any time.
      • +
      • Your own line. Every member who comes through your builder link lands under you. Each one who buys pays you 50% of their first package and every package after it, and their buyers open your level 2 and level 3 shares.
      • +
      • Ready-made creatives. Banners in every builder size (468x60, 728x90, 300x250, 160x600, 120x600, 1200x630), text ad copy, email swipes and a program description you can paste into your listing.
      • +
      • A bridge page for your brand, on request. A landing page in this design that names your site, explains the connection, and carries your code.
      • +
      • Attribution you can check. Signups and buyers are tagged with the source they came from, and the promo code report shows exactly who redeemed yours.
      • +
      +
      + +

      Setting it up takes about fifteen minutes

      +
        +
      1. Claim your spot with the button below. It places you directly under the company at the top. Join with your email and pick your username; your own invite link is live immediately: instantadpay.com/join/yourname.
      2. +
      3. Send me your username and the site you are listing it on. I mint your code with the credit amount we agree on.
      4. +
      5. Add InstantAdPay to your downline builder with your link plus the code: https://instantadpay.com/join/yourname?promo=YOURCODE. Members who click it land under you and their credits apply the moment their account exists.
      6. +
      7. Use the banners and text ads from the kit. Members who already have an account can type the code into the "Have a promo code?" box on their Overview.
      8. +
      9. Link a wallet, switch on payouts, and activate with at least the $20 package. That claims your spot at the top and makes you a qualifying buyer in your own right.
      10. +
      + +
      + Claim your spot at the top +

      Free account by email. No password, no wallet today. The link below places you directly under the company.

      + Claim my spot +
      + +

      The honest part

      +

      InstantAdPay sells advertising. Members earn from the ad packages people in their line buy, and nothing else. There is no earn-without-referring option, on purpose, because sites that pay you just for buying in are the ones that collapse. No income is guaranteed, results depend on effort, and cryptocurrency involves risk of loss. The contract, the ledger and every payout are public, so you never have to take my word for any of it.

      +

      Marty Bostick · marty@marketingwithmarty.com · t.me/cryptoteambuild

      + +
      +
      InstantAdPay · home · live ledger · the contract
      +
      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 dd76cac..32eca81 100644 --- a/public/plays.html +++ b/public/plays.html @@ -1,199 +1,199 @@ - - - - -Team-building plays | InstantAdPay - - - - - - - - - -
      -
      -

      Member training

      -

      Three ways to build a line.

      -

      Pick one and run it. Every number here comes from the live contract and the rate table, not from a slide.

      -
      - -

      Members only

      Sign in to your member area to read the plays. Sign in

      - -
      -
      - The one rule under all three plays: unqualified levels pass up. - If someone on your level 2 buys before you have two qualifying buyers, that 20% does not wait for you. It goes to the next qualified sponsor above you, or to the platform. Same for level 3 and five. Whatever play you run, the first job is the same: get qualified before your line gets busy. -
      - -

      How a package splits, the moment it sells

      -
      -
      50%
      Direct sponsor
      -
      20%
      Level 2 · needs 2
      -
      10%
      Level 3 · needs 5
      -
      20%
      Platform
      -
      -

      The ladder on your Overview, and what each rung unlocks

      -
      -
      Rung 1
      Joined
      Welcome tour: 25 credits
      -
      Rung 2
      Payouts on
      Spark badge · 10 credits
      -
      Rung 3
      First buyer
      Surge · 25 credits · 50% starts
      -
      Rung 4
      2 qualifying
      Circuit · 50 credits · level 2 · wall position 2
      -
      Rung 5
      5 qualifying
      Nexus · 100 credits · level 3 · wall position 3
      -
      - -
      -

      Opening move · Qualified Start

      works with any play
      -

      Fits: anyone who would rather start qualified than wait for their first two buyers.

      -

      Qualification is earned by buyers, never bought. But you can be your own first buyers, openly. Under Buy packages, link a second wallet you own as a position. When it buys a $20 package the contract counts it as a qualifying buyer, half the purchase comes straight back to your main wallet, and its credits pool with yours. Two positions open level 2 the same day; five open level 3. Then run whichever play fits you with the ladder already climbed. The three Qualified Start videos in Training show every click.

      -
      -
      Net cost
      Level 2: about $20 net for $40 of ad credits. Level 3: about $50 net for $100 of credits. Plus a little POL for gas in each wallet.
      -
      Say it plainly
      Your own money, your own wallets, a faster start. Never an income promise: qualification only pays on future purchases in your line.
      -
      -
      - -
      -

      Play 1 · Wide and teach

      the fifty play
      -

      Fits: someone with an audience, a list, a group, or traffic they can point somewhere.

      -

      Every direct who buys is 50% to you, instantly, forever. Directs are the only thing that qualifies you. The teaching is what fills levels 2 and 3 without extra work from you: your directs' buyers are your 20%, their buyers are your 10%.

      -
        -
      1. One new conversation a day, minimum. Text a friend and Social posts in Promo tools already carry your link.
      2. -
      3. Send paid traffic to an angle lander, not the bare link. Add ?v=adspend for advertisers, ?v=free for freebie seekers, ?v=instant for the crypto-curious.
      4. -
      5. Every new direct gets the same three sentences inside 24 hours (sponsor chat or the daily broadcast): pick your username, link your wallet and switch on payouts, send your link to one person today. That is the whole teaching. They pass it down.
      6. -
      7. Run the network's own ads at your link. Buy a package or claim the daily 5 credits, then spend credits on a Featured link (40 credits a day) or a text ad pointed at your angle lander.
      8. -
      -
      -
      Scoreboard
      Joined your line climbing daily · Qualifying buyers 2, then 5 · level 2 and 3 rows appearing in My line
      -
      Ceiling and weakness
      No ceiling on width. Shallow lines churn if you skip step 3.
      -
      -
      - -
      -

      Play 2 · Two, then down

      the depth play
      -

      Fits: someone with a small circle who would rather coach two people well than pitch twenty.

      -

      Two qualifying buyers open level 2, wall position 2, the Circuit badge and 50 bonus credits. From there every person your two bring in pays you 20%, and every person those people bring in pays you 10% once you reach five. Your effort goes into two relationships instead of a funnel.

      -
        -
      1. Get two directs to a $20+ package. Sit with them on the buy if you have to. Trust Wallet needs a POL cushion; SafePal or MetaMask are smoother.
      2. -
      3. Coach them to their two. Sponsor chat daily for the first week. One broadcast a day to your directs with a single ask each time.
      4. -
      5. Set your line banner to your team's meeting place (a Telegram group, a training page). Every new member three levels down meets it on their welcome tour.
      6. -
      7. Keep adding directs until you have five. This is the catch: level 3 only opens on five qualifying directs of your own. Two deep, coached well, earns a healthy 20% level. It does not open the 10% level.
      8. -
      -
      -
      Scoreboard
      Qualifying buyers 2 · level 2 count in My line rising · your directs' own qualifying counts
      -
      Ceiling and strength
      Level 2 income until you personally hit five. The stickiest lines come from this play.
      -
      -
      - -
      -

      Recommended default

      -

      Play 3 · Five and wide

      the combination
      -

      Fits: anyone willing to do both. This is the play the dashboard ladder is actually built for.

      -
        -
      1. Sprint to five qualifying directs. Nothing else matters until level 3 is open: Nexus, wall position 3 (your whole public page runs your own links), 100 bonus credits, and the full 50 / 20 / 10.
      2. -
      3. Then split the day. Mornings wide: one new conversation, one post, one ad running. Evenings deep: read My line, message the three newest directs, send the broadcast.
      4. -
      5. Coach the 2-then-5 rule down the line. Each of your five gets pushed to two (your level 2 fills), then to five (your level 3 fills). Use the achievements Share links; people copy what they see rewarded.
      6. -
      7. Book the featured strip for 7 days whenever you have 280 credits spare. Ten slots a day, every member sees it.
      8. -
      -
      -
      Scoreboard
      All four Overview tiles, plus Earning levels: buyers referred, level open, how many to next
      -
      Why it wins
      Width qualifies you. Depth pays you on other people's effort. Only this play does both on purpose.
      -
      -
      - -
      -

      Which play fits you

      -
      - - - - -
      You haveRunFirst target
      A list, a group, or ad budgetWide and teachFive qualifying directs in 30 days
      A few close people and patienceTwo, then downTwo qualifying directs in 14 days, both coached to their two
      An hour a day and a phoneFive and wideFive qualifying, then one wide and one deep action every day
      -
      - -
      -

      First 30 days, any play

      -
      -
      Day 1
      Username. Wallet linked. Payouts on. Welcome tour done (25 credits). Link sent to one person.
      -
      Days 2 to 7
      One conversation a day. Claim the daily 5 credits. First buyer (25 bonus credits).
      -
      Days 8 to 14
      Second qualifying buyer. Level 2 open. Line banner set. First broadcast sent.
      -
      Days 15 to 30
      Coach the two to their two. Add directs three, four, five. Level 3 open by day 30 is the stretch goal.
      -
      -
      - -
      -

      Messages that fit each play

      -
      WideI run ads anyway. This one pays me in the same transaction the buyer's package sells, on a public ledger. Free to join by email: your link
      -
      DepthI need two people who will actually do this with me, not twenty who will look at it. You are one of the two I thought of. your link
      -
      Combination · to a new directThree things today: username, wallet on, one person. I will check in tomorrow.
      -
      - -

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      -

      - -
      - -
      -

      InstantAdPay: Qualified Start checklist

      -
        -
      1. Username chosen (Profile tab). It is permanent: it becomes your invite link.
      2. -
      3. Main wallet linked (Wallet tab, one free signature).
      4. -
      5. Payouts switched on (Wallet tab, one free transaction).
      6. -
      7. Extra wallet accounts created in your wallet app: IAP Position 2, 3, 4, 5.
      8. -
      9. Each extra account funded with enough POL for a $20 package plus gas.
      10. -
      11. Buy packages: Add a position, tick only the new account, sign once.
      12. -
      13. Buy from: choose the position, Buy $20, confirm in the wallet.
      14. -
      15. Repeat. Two positions open level 2. Five open level 3 and the Nexus badge.
      16. -
      -

      First 30 days, any play

      -

      Day 1

      • Username, wallet linked, payouts on, welcome tour done.
      • Link sent to one person.
      -

      Days 2 to 7

      • One conversation a day.
      • Claim the daily 5 credits.
      • First buyer.
      -

      Days 8 to 14

      • Second qualifying buyer. Level 2 open.
      • Line banner set. First broadcast sent.
      -

      Days 15 to 30

      • Coach the two to their two.
      • Add directs three, four, five. Level 3 open by day 30 is the stretch goal.
      -

      My invite link: __________________________

      -

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      -
      - -
      -
      InstantAdPay · back to Training · live ledger
      -
      InstantAdPay is the Polygon hub of the Crypto Team Build Network.
      -
      Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
      -
      -
      - - - - + + + + +Team-building plays | InstantAdPay + + + + + + + + + +
      +
      +

      Member training

      +

      Three ways to build a line.

      +

      Pick one and run it. Every number here comes from the live contract and the rate table, not from a slide.

      +
      + +

      Members only

      Sign in to your member area to read the plays. Sign in

      + +
      +
      + The one rule under all three plays: unqualified levels pass up. + If someone on your level 2 buys before you have two qualifying buyers, that 20% does not wait for you. It goes to the next qualified sponsor above you, or to the platform. Same for level 3 and five. Whatever play you run, the first job is the same: get qualified before your line gets busy. +
      + +

      How a package splits, the moment it sells

      +
      +
      50%
      Direct sponsor
      +
      20%
      Level 2 · needs 2
      +
      10%
      Level 3 · needs 5
      +
      20%
      Platform
      +
      +

      The ladder on your Overview, and what each rung unlocks

      +
      +
      Rung 1
      Joined
      Welcome tour: 25 credits
      +
      Rung 2
      Payouts on
      Spark badge · 10 credits
      +
      Rung 3
      First buyer
      Surge · 25 credits · 50% starts
      +
      Rung 4
      2 qualifying
      Circuit · 50 credits · level 2 · wall position 2
      +
      Rung 5
      5 qualifying
      Nexus · 100 credits · level 3 · wall position 3
      +
      + +
      +

      Opening move · Qualified Start

      works with any play
      +

      Fits: anyone who would rather start qualified than wait for their first two buyers.

      +

      Qualification is earned by buyers, never bought. But you can be your own first buyers, openly. Under Buy packages, link a second wallet you own as a position. When it buys a $20 package the contract counts it as a qualifying buyer, half the purchase comes straight back to your main wallet, and its credits pool with yours. Two positions open level 2 the same day; five open level 3. Then run whichever play fits you with the ladder already climbed. The three Qualified Start videos in Training show every click.

      +
      +
      Net cost
      Level 2: about $20 net for $40 of ad credits. Level 3: about $50 net for $100 of credits. Plus a little POL for gas in each wallet.
      +
      Say it plainly
      Your own money, your own wallets, a faster start. Never an income promise: qualification only pays on future purchases in your line.
      +
      +
      + +
      +

      Play 1 · Wide and teach

      the fifty play
      +

      Fits: someone with an audience, a list, a group, or traffic they can point somewhere.

      +

      Every direct who buys is 50% to you, instantly, forever. Directs are the only thing that qualifies you. The teaching is what fills levels 2 and 3 without extra work from you: your directs' buyers are your 20%, their buyers are your 10%.

      +
        +
      1. One new conversation a day, minimum. Text a friend and Social posts in Promo tools already carry your link.
      2. +
      3. Send paid traffic to an angle lander, not the bare link. Add ?v=adspend for advertisers, ?v=free for freebie seekers, ?v=instant for the crypto-curious.
      4. +
      5. Every new direct gets the same three sentences inside 24 hours (sponsor chat or the daily broadcast): pick your username, link your wallet and switch on payouts, send your link to one person today. That is the whole teaching. They pass it down.
      6. +
      7. Run the network's own ads at your link. Buy a package or claim the daily 5 credits, then spend credits on a Featured link (40 credits a day) or a text ad pointed at your angle lander.
      8. +
      +
      +
      Scoreboard
      Joined your line climbing daily · Qualifying buyers 2, then 5 · level 2 and 3 rows appearing in My line
      +
      Ceiling and weakness
      No ceiling on width. Shallow lines churn if you skip step 3.
      +
      +
      + +
      +

      Play 2 · Two, then down

      the depth play
      +

      Fits: someone with a small circle who would rather coach two people well than pitch twenty.

      +

      Two qualifying buyers open level 2, wall position 2, the Circuit badge and 50 bonus credits. From there every person your two bring in pays you 20%, and every person those people bring in pays you 10% once you reach five. Your effort goes into two relationships instead of a funnel.

      +
        +
      1. Get two directs to a $20+ package. Sit with them on the buy if you have to. Trust Wallet needs a POL cushion; SafePal or MetaMask are smoother.
      2. +
      3. Coach them to their two. Sponsor chat daily for the first week. One broadcast a day to your directs with a single ask each time.
      4. +
      5. Set your line banner to your team's meeting place (a Telegram group, a training page). Every new member three levels down meets it on their welcome tour.
      6. +
      7. Keep adding directs until you have five. This is the catch: level 3 only opens on five qualifying directs of your own. Two deep, coached well, earns a healthy 20% level. It does not open the 10% level.
      8. +
      +
      +
      Scoreboard
      Qualifying buyers 2 · level 2 count in My line rising · your directs' own qualifying counts
      +
      Ceiling and strength
      Level 2 income until you personally hit five. The stickiest lines come from this play.
      +
      +
      + +
      +

      Recommended default

      +

      Play 3 · Five and wide

      the combination
      +

      Fits: anyone willing to do both. This is the play the dashboard ladder is actually built for.

      +
        +
      1. Sprint to five qualifying directs. Nothing else matters until level 3 is open: Nexus, wall position 3 (your whole public page runs your own links), 100 bonus credits, and the full 50 / 20 / 10.
      2. +
      3. Then split the day. Mornings wide: one new conversation, one post, one ad running. Evenings deep: read My line, message the three newest directs, send the broadcast.
      4. +
      5. Coach the 2-then-5 rule down the line. Each of your five gets pushed to two (your level 2 fills), then to five (your level 3 fills). Use the achievements Share links; people copy what they see rewarded.
      6. +
      7. Book the featured strip for 7 days whenever you have 280 credits spare. Ten slots a day, every member sees it.
      8. +
      +
      +
      Scoreboard
      All four Overview tiles, plus Earning levels: buyers referred, level open, how many to next
      +
      Why it wins
      Width qualifies you. Depth pays you on other people's effort. Only this play does both on purpose.
      +
      +
      + +
      +

      Which play fits you

      +
      + + + + +
      You haveRunFirst target
      A list, a group, or ad budgetWide and teachFive qualifying directs in 30 days
      A few close people and patienceTwo, then downTwo qualifying directs in 14 days, both coached to their two
      An hour a day and a phoneFive and wideFive qualifying, then one wide and one deep action every day
      +
      + +
      +

      First 30 days, any play

      +
      +
      Day 1
      Username. Wallet linked. Payouts on. Welcome tour done (25 credits). Link sent to one person.
      +
      Days 2 to 7
      One conversation a day. Claim the daily 5 credits. First buyer (25 bonus credits).
      +
      Days 8 to 14
      Second qualifying buyer. Level 2 open. Line banner set. First broadcast sent.
      +
      Days 15 to 30
      Coach the two to their two. Add directs three, four, five. Level 3 open by day 30 is the stretch goal.
      +
      +
      + +
      +

      Messages that fit each play

      +
      WideI run ads anyway. This one pays me in the same transaction the buyer's package sells, on a public ledger. Free to join by email: your link
      +
      DepthI need two people who will actually do this with me, not twenty who will look at it. You are one of the two I thought of. your link
      +
      Combination · to a new directThree things today: username, wallet on, one person. I will check in tomorrow.
      +
      + +

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      +

      + +
      + +
      +

      InstantAdPay: Qualified Start checklist

      +
        +
      1. Username chosen (Profile tab). It is permanent: it becomes your invite link.
      2. +
      3. Main wallet linked (Wallet tab, one free signature).
      4. +
      5. Payouts switched on (Wallet tab, one free transaction).
      6. +
      7. Extra wallet accounts created in your wallet app: IAP Position 2, 3, 4, 5.
      8. +
      9. Each extra account funded with enough POL for a $20 package plus gas.
      10. +
      11. Buy packages: Add a position, tick only the new account, sign once.
      12. +
      13. Buy from: choose the position, Buy $20, confirm in the wallet.
      14. +
      15. Repeat. Two positions open level 2. Five open level 3 and the Nexus badge.
      16. +
      +

      First 30 days, any play

      +

      Day 1

      • Username, wallet linked, payouts on, welcome tour done.
      • Link sent to one person.
      +

      Days 2 to 7

      • One conversation a day.
      • Claim the daily 5 credits.
      • First buyer.
      +

      Days 8 to 14

      • Second qualifying buyer. Level 2 open.
      • Line banner set. First broadcast sent.
      +

      Days 15 to 30

      • Coach the two to their two.
      • Add directs three, four, five. Level 3 open by day 30 is the stretch goal.
      +

      My invite link: __________________________

      +

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      +
      + +
      +
      InstantAdPay · back to Training · live ledger
      +
      InstantAdPay is the Polygon hub of the Crypto Team Build Network.
      +
      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/presentation.html b/public/presentation.html index 6b92108..53b4dd6 100644 --- a/public/presentation.html +++ b/public/presentation.html @@ -1,91 +1,91 @@ - - - - -Build wide. Get paid instantly. | InstantAdPay presentation - - - - - - - - - - - - - - - - - - -
      -
      -

      The InstantAdPay presentation

      -

      Build wide. Get paid instantly.

      -

      Six minutes, narrated start to finish: what InstantAdPay is, how far your ads reach, how one purchase pays three levels in the same transaction, and why five strong buyers unlock everything. Pick your language under the video.

      -
      - -
      - -
      -
      - -
      -
      ? -

      Ready to start?

      Ask the person who shared this with you, or join here. It is free to join by email.

      - Join free -
      - -
      -
      50% on every direct purchasePaid by the contract in the same transaction the package sells.
      -
      Two buyers, then fiveTwo qualifying buyers open level two, five open level three.
      -
      One wallet, every platformYour sponsor line carries across the network, LinkSpin included.
      -
      - -

      Examples in the presentation are illustrations, not promises of income. Whether anyone buys is their own choice, and results depend on your effort. Payments are made in POL at the rate at the time of each purchase. Crypto involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      - -
      - - - + + + + +Build wide. Get paid instantly. | InstantAdPay presentation + + + + + + + + + + + + + + + + + + +
      +
      +

      The InstantAdPay presentation

      +

      Build wide. Get paid instantly.

      +

      Six minutes, narrated start to finish: what InstantAdPay is, how far your ads reach, how one purchase pays three levels in the same transaction, and why five strong buyers unlock everything. Pick your language under the video.

      +
      + +
      + +
      +
      + +
      +
      ? +

      Ready to start?

      Ask the person who shared this with you, or join here. It is free to join by email.

      + Join free +
      + +
      +
      50% on every direct purchasePaid by the contract in the same transaction the package sells.
      +
      Two buyers, then fiveTwo qualifying buyers open level two, five open level three.
      +
      One wallet, every platformYour sponsor line carries across the network, LinkSpin included.
      +
      + +

      Examples in the presentation are illustrations, not promises of income. Whether anyone buys is their own choice, and results depend on your effort. Payments are made in POL at the rate at the time of each purchase. Crypto involves risk of loss. InstantAdPay sells advertising; it is not an investment.

      + +
      + + + diff --git a/public/privacy.html b/public/privacy.html index 82f36b7..394564d 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -1,35 +1,35 @@ - - - - -Privacy Policy | InstantAdPay - - - - - - -
      -

      Privacy Policy

      Last updated: September 2026

      -
      -

      What we collect

      -

      A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. Campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.

      -

      What we do not collect

      -

      We never take custody of your funds or private keys, and we do not sell your personal data.

      -

      How we use it

      -

      To run your account, deliver and measure ads, attribute referrals, send service and notification emails (payouts, messages, onboarding), and keep the Platform secure. You can set your email and chat notification preferences in your dashboard.

      -

      Cookies

      -

      We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, and a browser identifier cookie used only to enforce one account per person. No third-party ad-tracking cookies.

      -

      Abuse prevention. When you create an account and when you sign in we record your IP address, browser type and the browser identifier. We use them to detect duplicate accounts and self-referral, which the Terms prohibit, and for nothing else. They are visible to the site administrator only and are not sold or shared.

      -

      Sharing

      -

      Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.

      -

      Your choices

      -

      You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us through the support page or at support@instantadpay.com. Note that on-chain records cannot be deleted by anyone.

      -

      Security

      -

      We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.

      -
      -
      - - - - + + + + +Privacy Policy | InstantAdPay + + + + + + +
      +

      Privacy Policy

      Last updated: September 2026

      +
      +

      What we collect

      +

      A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. Campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.

      +

      What we do not collect

      +

      We never take custody of your funds or private keys, and we do not sell your personal data.

      +

      How we use it

      +

      To run your account, deliver and measure ads, attribute referrals, send service and notification emails (payouts, messages, onboarding), and keep the Platform secure. You can set your email and chat notification preferences in your dashboard.

      +

      Cookies

      +

      We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, and a browser identifier cookie used only to enforce one account per person. No third-party ad-tracking cookies.

      +

      Abuse prevention. When you create an account and when you sign in we record your IP address, browser type and the browser identifier. We use them to detect duplicate accounts and self-referral, which the Terms prohibit, and for nothing else. They are visible to the site administrator only and are not sold or shared.

      +

      Sharing

      +

      Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.

      +

      Your choices

      +

      You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us through the support page or at support@instantadpay.com. Note that on-chain records cannot be deleted by anyone.

      +

      Security

      +

      We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.

      +
      +
      + + + + diff --git a/public/support.html b/public/support.html index 51f5b03..8c13bd1 100644 --- a/public/support.html +++ b/public/support.html @@ -1,27 +1,27 @@ - - - - -Support | InstantAdPay - - - - - - - -
      -
      -

      Support

      -

      Ask for help

      -

      Tell us what is going on and Marty will reply by email. Members can also open Help in the dashboard, and you can email support@instantadpay.com. Quick answers to common questions are in the chat bubble and on the platform facts page.

      -
      -

      Loading…

      -

      We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.

      -
      - - - - - - + + + + +Support | InstantAdPay + + + + + + + +
      +
      +

      Support

      +

      Ask for help

      +

      Tell us what is going on and Marty will reply by email. Members can also open Help in the dashboard, and you can email support@instantadpay.com. Quick answers to common questions are in the chat bubble and on the platform facts page.

      +
      +

      Loading…

      +

      We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.

      +
      + + + + + + diff --git a/public/terms.html b/public/terms.html index 1ca67b0..5a562ff 100644 --- a/public/terms.html +++ b/public/terms.html @@ -1,44 +1,44 @@ - - - - -Terms of Service | InstantAdPay - - - - - - -
      -

      Terms of Service

      Last updated: September 2026

      -
      -

      Please read these Terms carefully. By creating an account or using InstantAdPay ("the Platform"), you agree to them. If you do not agree, do not use the Platform.

      -

      1. What InstantAdPay is

      -

      InstantAdPay is an advertising platform with a referral program. Members buy advertising packages that mint on-chain ad credits and are delivered as banner, text, video, solo, featured, and verified-visit placements. Payments between members are split by an immutable smart contract and settle directly to members' own wallets. InstantAdPay is not a bank, an investment product, a security, or a money-transmission service.

      -

      2. Eligibility

      -

      You must be at least 18 and legally able to enter contracts where you live. You are responsible for complying with the laws of your jurisdiction, including any that restrict crypto activity. You may not use the Platform where doing so is unlawful.

      -

      3. Accounts

      -

      You join free with an email. Keep your access secure; you are responsible for activity under your account. Your wallet is your own. We never hold, custody, or control your funds or private keys.

      -

      One account per person. Each person may hold exactly one InstantAdPay account. Opening or operating a second account, under any email, name or wallet, is not allowed, and neither is referring yourself through another account. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, where they are visible as yours. Duplicate accounts may be merged, suspended or closed at our discretion; credits, prizes and contest rankings earned through a duplicate account are forfeited. On-chain payments already made by the contract cannot be reversed by anyone, including us.

      -

      Usernames must not mislead. Your username, bio and public page may not suggest that you are InstantAdPay, part of our staff or team, an administrator, or connected to any of our sites or partner brands. Names such as "instantadpay", "admin", "support" or "official", and names built around our brand names, are reserved. We may change a misleading username without notice, clear profile text that repeats it, and return any holding-tank members adopted under it to the tank. Repeated or deliberate impersonation may lead to suspension.

      -

      4. Purchases and the smart contract

      -

      Package purchases execute on the blockchain. On-chain transactions are final and irreversible. Prices are shown in USD and settled in the network token at the live rate at the moment of purchase. The contract splits each purchase and pays members' wallets in the same transaction; InstantAdPay never touches the money. You are responsible for network fees.

      -

      5. Referrals and qualification

      -

      Referral earnings depend on real purchases in your line and on the qualification rules published on the site and enforced by the contract. Nobody earns unless real advertising is bought. We do not promise or guarantee any income.

      -

      6. Advertising rules

      -

      Ads you submit must be lawful and must not be deceptive, adult, hateful, malicious, or infringing. Ads are auto-approved for speed; we may remove or pause any ad or campaign at any time, and members can report ads for review. You are solely responsible for the ads you run and the sites they point to.

      -

      7. Acceptable use

      -

      No fraud, bots, fake traffic, self-dealing to farm rewards, multiple or duplicate accounts, self-referral through another account, attempts to manipulate the contract, or abuse of other members. We may suspend or terminate accounts that break these rules.

      -

      8. No warranty

      -

      The Platform is provided "as is," without warranties of any kind. Blockchains, wallets, oracles, and third-party sites can fail or behave unexpectedly. We do not guarantee uptime, delivery volumes, or results.

      -

      9. Limitation of liability

      -

      To the fullest extent permitted by law, InstantAdPay and its operators are not liable for indirect, incidental, or consequential damages, or for losses arising from crypto volatility, irreversible transactions, third-party sites, or your own decisions.

      -

      10. Changes and termination

      -

      We may update these Terms and the Platform, and continued use means you accept the changes. We may discontinue features. The immutable contract's rules cannot be changed by anyone, including us.

      -

      See also the Disclaimer and Privacy Policy. Questions: the support page or support@instantadpay.com.

      -
      -
      - - - - + + + + +Terms of Service | InstantAdPay + + + + + + +
      +

      Terms of Service

      Last updated: September 2026

      +
      +

      Please read these Terms carefully. By creating an account or using InstantAdPay ("the Platform"), you agree to them. If you do not agree, do not use the Platform.

      +

      1. What InstantAdPay is

      +

      InstantAdPay is an advertising platform with a referral program. Members buy advertising packages that mint on-chain ad credits and are delivered as banner, text, video, solo, featured, and verified-visit placements. Payments between members are split by an immutable smart contract and settle directly to members' own wallets. InstantAdPay is not a bank, an investment product, a security, or a money-transmission service.

      +

      2. Eligibility

      +

      You must be at least 18 and legally able to enter contracts where you live. You are responsible for complying with the laws of your jurisdiction, including any that restrict crypto activity. You may not use the Platform where doing so is unlawful.

      +

      3. Accounts

      +

      You join free with an email. Keep your access secure; you are responsible for activity under your account. Your wallet is your own. We never hold, custody, or control your funds or private keys.

      +

      One account per person. Each person may hold exactly one InstantAdPay account. Opening or operating a second account, under any email, name or wallet, is not allowed, and neither is referring yourself through another account. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, where they are visible as yours. Duplicate accounts may be merged, suspended or closed at our discretion; credits, prizes and contest rankings earned through a duplicate account are forfeited. On-chain payments already made by the contract cannot be reversed by anyone, including us.

      +

      Usernames must not mislead. Your username, bio and public page may not suggest that you are InstantAdPay, part of our staff or team, an administrator, or connected to any of our sites or partner brands. Names such as "instantadpay", "admin", "support" or "official", and names built around our brand names, are reserved. We may change a misleading username without notice, clear profile text that repeats it, and return any holding-tank members adopted under it to the tank. Repeated or deliberate impersonation may lead to suspension.

      +

      4. Purchases and the smart contract

      +

      Package purchases execute on the blockchain. On-chain transactions are final and irreversible. Prices are shown in USD and settled in the network token at the live rate at the moment of purchase. The contract splits each purchase and pays members' wallets in the same transaction; InstantAdPay never touches the money. You are responsible for network fees.

      +

      5. Referrals and qualification

      +

      Referral earnings depend on real purchases in your line and on the qualification rules published on the site and enforced by the contract. Nobody earns unless real advertising is bought. We do not promise or guarantee any income.

      +

      6. Advertising rules

      +

      Ads you submit must be lawful and must not be deceptive, adult, hateful, malicious, or infringing. Ads are auto-approved for speed; we may remove or pause any ad or campaign at any time, and members can report ads for review. You are solely responsible for the ads you run and the sites they point to.

      +

      7. Acceptable use

      +

      No fraud, bots, fake traffic, self-dealing to farm rewards, multiple or duplicate accounts, self-referral through another account, attempts to manipulate the contract, or abuse of other members. We may suspend or terminate accounts that break these rules.

      +

      8. No warranty

      +

      The Platform is provided "as is," without warranties of any kind. Blockchains, wallets, oracles, and third-party sites can fail or behave unexpectedly. We do not guarantee uptime, delivery volumes, or results.

      +

      9. Limitation of liability

      +

      To the fullest extent permitted by law, InstantAdPay and its operators are not liable for indirect, incidental, or consequential damages, or for losses arising from crypto volatility, irreversible transactions, third-party sites, or your own decisions.

      +

      10. Changes and termination

      +

      We may update these Terms and the Platform, and continued use means you accept the changes. We may discontinue features. The immutable contract's rules cannot be changed by anyone, including us.

      +

      See also the Disclaimer and Privacy Policy. Questions: the support page or support@instantadpay.com.

      +
      +
      + + + + diff --git a/public/tx.html b/public/tx.html index 865c4e7..c119a00 100644 --- a/public/tx.html +++ b/public/tx.html @@ -1,40 +1,40 @@ - - - - -Transaction | InstantAdPay - - - - - - -
      -
      -
      -

      One transaction, fully public

      -

      Pulled straight from the chain this site settles on. Every field below is read from the node, - not from our database.

      -
      -
      -

      looking it up… -

      -

      -
      - -
      - -
      - -

      ← Back to the live ledger · Read the contract review

      -
      -
      - - - - + + + + +Transaction | InstantAdPay + + + + + + +
      +
      +
      +

      One transaction, fully public

      +

      Pulled straight from the chain this site settles on. Every field below is read from the node, + not from our database.

      +
      +
      +

      looking it up… +

      +

      +
      + +
      + +
      + +

      ← Back to the live ledger · Read the contract review

      +
      +
      + + + + diff --git a/public/wall.html b/public/wall.html index 7a28073..2a62184 100644 --- a/public/wall.html +++ b/public/wall.html @@ -1,53 +1,53 @@ - - - - -Banner wall | InstantAdPay - - - - - - - -
      -
      -
      -

      InstantAdPay member wall

      -

      Advertise and earn. Paid on-chain, instantly.

      -

      Real ad packages from $5. Every payout arrives as POL on Polygon in your own wallet, in the same transaction the package sells, on a public ledger. Free to join by email, and this member is your sponsor if you join from here.

      -
      - - -
      -

      The line, three levels deep

      -

      Three positions, three levels — the exact levels the contract pays. Every banner here belongs - to a real member of this line, and every payment between them settles on-chain, instantly.

      -
      -
      - - -
      -

      Join this line

      -

      Free to join with just an email. Your wallet only comes out if you buy — - and payments go straight to member wallets, never through an admin.

      - -

      Join free through this wall

      -

      Watch the live ledger · Read the contract

      -
      -
      -
      - - - - + + + + +Banner wall | InstantAdPay + + + + + + + +
      +
      +
      +

      InstantAdPay member wall

      +

      Advertise and earn. Paid on-chain, instantly.

      +

      Real ad packages from $5. Every payout arrives as POL on Polygon in your own wallet, in the same transaction the package sells, on a public ledger. Free to join by email, and this member is your sponsor if you join from here.

      +
      + + +
      +

      The line, three levels deep

      +

      Three positions, three levels — the exact levels the contract pays. Every banner here belongs + to a real member of this line, and every payment between them settles on-chain, instantly.

      +
      +
      + + +
      +

      Join this line

      +

      Free to join with just an email. Your wallet only comes out if you buy — + and payments go straight to member wallets, never through an admin.

      + +

      Join free through this wall

      +

      Watch the live ledger · Read the contract

      +
      +
      +
      + + + + diff --git a/public/wallets.html b/public/wallets.html index 591e55d..54cff3f 100644 --- a/public/wallets.html +++ b/public/wallets.html @@ -1,128 +1,128 @@ - - - - -Wallets and buying POL | InstantAdPay - - - - - - - - - -
      -
      -

      Member training

      -

      Wallets, and buying POL.

      -

      Which wallet to use, how to set it up in five minutes, and how to buy POL with a debit or credit card through MoonPay so it lands in your own wallet.

      -
      - -

      Members only

      Sign in to your member area to read this guide. Sign in

      - -
      -
      - One coin, one network: POL on Polygon. - Packages are paid in POL and every payout arrives as POL in your own wallet. Nothing else is used. When you buy, choose POL on the Polygon network, never MATIC on Ethereum and never another chain. The site never holds your money: you pay the contract from your wallet and the contract pays your line in the same transaction. -
      - -

      Preferred wallets

      -

      Any wallet that supports the Polygon network works. These are the ones we have tested end to end.

      -
      -
      -

      MetaMask recommended

      -

      Browser extension on desktop, app on phone. The one to use for Qualified Start, because it lets you add extra accounts under the same wallet, one per position. Connects directly on desktop and through WalletConnect on mobile.

      - -
      -
      -

      Phantom

      -

      Clean phone and desktop apps, no purchase-size block. Good choice if you are new and only ever plan to run one position. One setup step: Phantom ships with Polygon switched off. Open Settings, then Active Networks (Developer Settings on some versions), and turn Polygon on before you connect. Until it is on, the connect and buy buttons here will fail or show the wrong network.

      - -
      -
      -

      SafePal

      -

      Phone app with a built-in card purchase option for POL. Connects through WalletConnect. Works well for members who do everything on a phone.

      - -
      -
      -

      Coinbase Wallet

      -

      The self-custody wallet from Coinbase, not the exchange account. Handy if you already buy crypto on Coinbase: buy POL there and send it to this wallet on the Polygon network.

      - -
      -
      -

      Trust Wallet works, with one catch

      -

      Trust Wallet blocks any purchase that would spend most of the POL in the wallet. You see a red "this transaction will drain your wallet" screen with no way past it. If you use Trust, keep about twice the package cost in POL, or buy a smaller package first. The extra POL stays yours. If a blocked attempt leaves the connection dead, open Wallet, tap Disconnect, then Connect again.

      - -
      -
      - -

      Set up a wallet in five minutes

      -
        -
      1. Install it from the official source only. MetaMask: metamask.io. Phantom: phantom.app. SafePal: safepal.io. Coinbase Wallet: wallet.coinbase.com. On a phone, use the app store listing those sites point to.
      2. -
      3. Create a new wallet and set a device password or PIN.
      4. -
      5. Write down the recovery phrase (12 or 24 words) on paper and keep it offline. Anyone who has those words has your money. Nobody from InstantAdPay will ever ask for them, and the site never sees them.
      6. -
      7. Make sure Polygon is available. MetaMask asks to switch to Polygon the first time InstantAdPay needs it; approve that. SafePal and Coinbase Wallet include Polygon already. Phantom has Polygon built in but switched off by default: Settings, then Active Networks, turn on Polygon.
      8. -
      9. Copy your address. It starts with 0x and is the same on every EVM network. This is where your POL goes and where your payouts arrive.
      10. -
      11. Link it in Members: open the Wallet tab, tap Connect, and sign the free message. Then Switch on payouts, one small transaction that registers your address with the contract. Do both before your people start buying, so their first purchase pays you.
      12. -
      - -

      Buy POL with a card through MoonPay

      -

      MoonPay is a licensed card-to-crypto service. You pay them, they send POL to your wallet. InstantAdPay is never in the middle of that payment.

      -

      Opens in a new tab with POL on Polygon selected.

      -
        -
      1. Have your wallet connected first (Wallet tab). Then open Buy packages and look at the live POL price for the package you want. Plan to buy that amount plus 2 or 3 POL for network fees. Trust Wallet users: buy about double.
      2. -
      3. Tap "Buy POL with a card" under the packages. MoonPay opens in a new tab with POL on Polygon selected and your own wallet address filled in. If for any reason it is not filled in, choose POL (Polygon) yourself and paste your address from step 5 above.
      4. -
      5. Enter the amount in dollars or POL and pay with a debit card, credit card, Apple Pay or Google Pay. MoonPay has a minimum order, usually around $30, so the $5 package on its own is below it. Buy enough for the package you actually want.
      6. -
      7. First time only: identity check. MoonPay asks for your email, phone and a photo ID. This is their legal requirement, not ours. It normally takes a few minutes; occasionally a review takes longer, and MoonPay emails you when it clears.
      8. -
      9. Wait for the POL to land. Usually a few minutes. Your wallet balance shows on the Wallet tab and next to your positions.
      10. -
      11. Go back to Buy packages and buy. The wallet asks you to confirm one transaction. The moment it settles, your credits are minted and your line is paid.
      12. -
      - -
      Already own crypto on an exchange? Coinbase, Kraken, Binance and most others sell POL. Withdraw it to your wallet address and pick the Polygon network on the withdrawal screen. Sending on the wrong network can lose the funds.
      -
      Prefer to buy inside the wallet? MetaMask, Trust, SafePal and Phantom all have a Buy button that uses MoonPay or a similar provider. Same rule: POL, Polygon network, your own address.
      - -

      Common questions

      -
      -
      Do I need a wallet to join?

      No. Join with your email. The wallet comes out only when you buy a package or switch on payouts.

      -
      How much POL do I need?

      The Buy packages tab shows the live POL cost of each package. Buy that plus 2 or 3 POL for fees. There is no other cost.

      -
      Why did MoonPay decline my card?

      Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy on an exchange and withdraw to your wallet on Polygon.

      -
      Can I use the same wallet for more than one position?

      One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.

      -
      Where do my payouts go?

      To the wallet address you switched payouts on with, in the same transaction as the purchase that earned them. Nothing is held on the site.

      -
      - -

      Advertising, not investing. No income is guaranteed; results depend on your effort. Crypto transactions are irreversible and carry risk of loss. MoonPay is an independent, licensed provider; its fees and limits are its own.

      -
      - -
      -
      InstantAdPay · back to Training · Buy packages · Wallet
      -
      InstantAdPay is the Polygon hub of the Crypto Team Build Network.
      -
      Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.
      -
      -
      - - - - + + + + +Wallets and buying POL | InstantAdPay + + + + + + + + + +
      +
      +

      Member training

      +

      Wallets, and buying POL.

      +

      Which wallet to use, how to set it up in five minutes, and how to buy POL with a debit or credit card through MoonPay so it lands in your own wallet.

      +
      + +

      Members only

      Sign in to your member area to read this guide. Sign in

      + +
      +
      + One coin, one network: POL on Polygon. + Packages are paid in POL and every payout arrives as POL in your own wallet. Nothing else is used. When you buy, choose POL on the Polygon network, never MATIC on Ethereum and never another chain. The site never holds your money: you pay the contract from your wallet and the contract pays your line in the same transaction. +
      + +

      Preferred wallets

      +

      Any wallet that supports the Polygon network works. These are the ones we have tested end to end.

      +
      +
      +

      MetaMask recommended

      +

      Browser extension on desktop, app on phone. The one to use for Qualified Start, because it lets you add extra accounts under the same wallet, one per position. Connects directly on desktop and through WalletConnect on mobile.

      + +
      +
      +

      Phantom

      +

      Clean phone and desktop apps, no purchase-size block. Good choice if you are new and only ever plan to run one position. One setup step: Phantom ships with Polygon switched off. Open Settings, then Active Networks (Developer Settings on some versions), and turn Polygon on before you connect. Until it is on, the connect and buy buttons here will fail or show the wrong network.

      + +
      +
      +

      SafePal

      +

      Phone app with a built-in card purchase option for POL. Connects through WalletConnect. Works well for members who do everything on a phone.

      + +
      +
      +

      Coinbase Wallet

      +

      The self-custody wallet from Coinbase, not the exchange account. Handy if you already buy crypto on Coinbase: buy POL there and send it to this wallet on the Polygon network.

      + +
      +
      +

      Trust Wallet works, with one catch

      +

      Trust Wallet blocks any purchase that would spend most of the POL in the wallet. You see a red "this transaction will drain your wallet" screen with no way past it. If you use Trust, keep about twice the package cost in POL, or buy a smaller package first. The extra POL stays yours. If a blocked attempt leaves the connection dead, open Wallet, tap Disconnect, then Connect again.

      + +
      +
      + +

      Set up a wallet in five minutes

      +
        +
      1. Install it from the official source only. MetaMask: metamask.io. Phantom: phantom.app. SafePal: safepal.io. Coinbase Wallet: wallet.coinbase.com. On a phone, use the app store listing those sites point to.
      2. +
      3. Create a new wallet and set a device password or PIN.
      4. +
      5. Write down the recovery phrase (12 or 24 words) on paper and keep it offline. Anyone who has those words has your money. Nobody from InstantAdPay will ever ask for them, and the site never sees them.
      6. +
      7. Make sure Polygon is available. MetaMask asks to switch to Polygon the first time InstantAdPay needs it; approve that. SafePal and Coinbase Wallet include Polygon already. Phantom has Polygon built in but switched off by default: Settings, then Active Networks, turn on Polygon.
      8. +
      9. Copy your address. It starts with 0x and is the same on every EVM network. This is where your POL goes and where your payouts arrive.
      10. +
      11. Link it in Members: open the Wallet tab, tap Connect, and sign the free message. Then Switch on payouts, one small transaction that registers your address with the contract. Do both before your people start buying, so their first purchase pays you.
      12. +
      + +

      Buy POL with a card through MoonPay

      +

      MoonPay is a licensed card-to-crypto service. You pay them, they send POL to your wallet. InstantAdPay is never in the middle of that payment.

      +

      Opens in a new tab with POL on Polygon selected.

      +
        +
      1. Have your wallet connected first (Wallet tab). Then open Buy packages and look at the live POL price for the package you want. Plan to buy that amount plus 2 or 3 POL for network fees. Trust Wallet users: buy about double.
      2. +
      3. Tap "Buy POL with a card" under the packages. MoonPay opens in a new tab with POL on Polygon selected and your own wallet address filled in. If for any reason it is not filled in, choose POL (Polygon) yourself and paste your address from step 5 above.
      4. +
      5. Enter the amount in dollars or POL and pay with a debit card, credit card, Apple Pay or Google Pay. MoonPay has a minimum order, usually around $30, so the $5 package on its own is below it. Buy enough for the package you actually want.
      6. +
      7. First time only: identity check. MoonPay asks for your email, phone and a photo ID. This is their legal requirement, not ours. It normally takes a few minutes; occasionally a review takes longer, and MoonPay emails you when it clears.
      8. +
      9. Wait for the POL to land. Usually a few minutes. Your wallet balance shows on the Wallet tab and next to your positions.
      10. +
      11. Go back to Buy packages and buy. The wallet asks you to confirm one transaction. The moment it settles, your credits are minted and your line is paid.
      12. +
      + +
      Already own crypto on an exchange? Coinbase, Kraken, Binance and most others sell POL. Withdraw it to your wallet address and pick the Polygon network on the withdrawal screen. Sending on the wrong network can lose the funds.
      +
      Prefer to buy inside the wallet? MetaMask, Trust, SafePal and Phantom all have a Buy button that uses MoonPay or a similar provider. Same rule: POL, Polygon network, your own address.
      + +

      Common questions

      +
      +
      Do I need a wallet to join?

      No. Join with your email. The wallet comes out only when you buy a package or switch on payouts.

      +
      How much POL do I need?

      The Buy packages tab shows the live POL cost of each package. Buy that plus 2 or 3 POL for fees. There is no other cost.

      +
      Why did MoonPay decline my card?

      Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy on an exchange and withdraw to your wallet on Polygon.

      +
      Can I use the same wallet for more than one position?

      One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.

      +
      Where do my payouts go?

      To the wallet address you switched payouts on with, in the same transaction as the purchase that earned them. Nothing is held on the site.

      +
      + +

      Advertising, not investing. No income is guaranteed; results depend on your effort. Crypto transactions are irreversible and carry risk of loss. MoonPay is an independent, licensed provider; its fees and limits are its own.

      +
      + +
      +
      InstantAdPay · back to Training · Buy packages · Wallet
      +
      InstantAdPay is the Polygon hub of the Crypto Team Build Network.
      +
      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/public/wednesday.html b/public/wednesday.html index 4e7d30d..e6b910a 100644 --- a/public/wednesday.html +++ b/public/wednesday.html @@ -1,69 +1,69 @@ - - - - -Wired Wednesday: 25% bonus credits, wired in the second your pack settles | InstantAdPay - - - - - - - - - - - - - - -
      -
      -

      Every Wednesday · US Central time · midnight to midnight

      -

      Wired Wednesday: 25% bonus credits, wired in the second your pack settles.

      -

      Buy any InstantAdPay ad package from $20 up on a Wednesday and 25% extra credits are wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format you choose: banners and text ads that go out across the network, video, solo ads, verified visits, even login ads. No code, nothing to claim. And like every pack, it pays the sponsor line above you in the same transaction.

      -
      - Wired Wednesday: 25% bonus credits wired in the second your pack settles. Wednesdays 12:00 AM to 11:59 PM US Central time. -
      CheckingLoading today’s status…
      - -
      -
      Step 1

      Join free, by email.

      Email first, wallet later, inside your account. Nothing to install to look around.

      -
      Step 2

      Buy any pack from $20 on a Wednesday.

      Central time, midnight to midnight. 25% extra credits are wired into your balance the moment the purchase settles, labelled in your credit log, ready to spend on any format.

      -
      Step 3

      Your pack pays the line above you. Theirs pays you.

      Every package is one Polygon transaction that splits to the sponsor line instantly. Public on the ledger, nothing held.

      -
      -
      What a credit is. One credit is one cent of ad delivery across the network: banners, text ads, video, verified visits, solo ads, login ads and more. Purchased-grade credits like this bonus can run on every format. Credits are not money and cannot be withdrawn.
      -
      Members: this page is your Wednesday promo tool. Add ?ref=yourusername to this address and anyone who joins from it is your referral, exactly like your invite link. Promo tools has the banners and posts ready with your link filled in.
      -

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.

      - -
      - - - - + + + + +Wired Wednesday: 25% bonus credits, wired in the second your pack settles | InstantAdPay + + + + + + + + + + + + + + +
      +
      +

      Every Wednesday · US Central time · midnight to midnight

      +

      Wired Wednesday: 25% bonus credits, wired in the second your pack settles.

      +

      Buy any InstantAdPay ad package from $20 up on a Wednesday and 25% extra credits are wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format you choose: banners and text ads that go out across the network, video, solo ads, verified visits, even login ads. No code, nothing to claim. And like every pack, it pays the sponsor line above you in the same transaction.

      +
      + Wired Wednesday: 25% bonus credits wired in the second your pack settles. Wednesdays 12:00 AM to 11:59 PM US Central time. +
      CheckingLoading today’s status…
      + +
      +
      Step 1

      Join free, by email.

      Email first, wallet later, inside your account. Nothing to install to look around.

      +
      Step 2

      Buy any pack from $20 on a Wednesday.

      Central time, midnight to midnight. 25% extra credits are wired into your balance the moment the purchase settles, labelled in your credit log, ready to spend on any format.

      +
      Step 3

      Your pack pays the line above you. Theirs pays you.

      Every package is one Polygon transaction that splits to the sponsor line instantly. Public on the ledger, nothing held.

      +
      +
      What a credit is. One credit is one cent of ad delivery across the network: banners, text ads, video, verified visits, solo ads, login ads and more. Purchased-grade credits like this bonus can run on every format. Credits are not money and cannot be withdrawn.
      +
      Members: this page is your Wednesday promo tool. Add ?ref=yourusername to this address and anyone who joins from it is your referral, exactly like your invite link. Promo tools has the banners and posts ready with your link filled in.
      +

      No income is guaranteed. Results depend on your effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.

      + +
      + + + + diff --git a/qa/override.test.cjs b/qa/override.test.cjs new file mode 100644 index 0000000..700825c --- /dev/null +++ b/qa/override.test.cjs @@ -0,0 +1,236 @@ +// Level-4 override payer tests (2026-10-23). 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 7ca7b54..9240c84 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -1,68 +1,71 @@ -#!/usr/bin/env bash -# InstantAdPay QA harness runner. From the site dir: -# bash qa/run.sh public # live public pages only (no local server) -# bash qa/run.sh member # local copy: member + admin walk -# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min) -# bash qa/run.sh all # public + member + earn -# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter -# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data) -# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) -# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) -# bash qa/run.sh sov-passes # pass tiers (Explorer/Champion/Sovereign/Legend): store unit checks + admin buys Explorer + Sovereign with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes) -# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data) -# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos) -# 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 -cd "$(dirname "$0")/.." -MODE="${1:-all}" -OUT="qa/out"; mkdir -p "$OUT" -TMP="${TMPDIR:-${TEMP:-/tmp}}/iap-qa-$$" -status=0 - -start_local() { # $1 = port - local port="$1" - rm -rf "$TMP-$port"; mkdir -p "$TMP-$port/uploads" - (PORT="$port" DATA_DIR="$TMP-$port" ADMIN_EMAIL="${ADMIN_EMAIL:-martybostick@gmail.com}" ADMIN_PASSWORD=localtest node server.js > "$OUT/server-$port.log" 2>&1 &) - for i in $(seq 1 20); do curl -s -m 2 "http://127.0.0.1:$port/api/config" >/dev/null && return 0; sleep 1; done - echo "local server on :$port did not come up"; return 1 -} -stop_local() { # $1 = port - for p in $(netstat -ano 2>/dev/null | grep ":$1 " | awk '{print $5}' | sort -u); do taskkill //F //PID "$p" >/dev/null 2>&1; done - rm -rf "$TMP-$1" -} - -if [ "$MODE" = "public" ]; then - node qa/walk.mjs public || status=1 - node qa/chatbot-sync.mjs || 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 - node qa/sponsorfollow.test.cjs || status=1 - node qa/sponsorfollow-e2e.mjs || status=1 -elif [ "$MODE" = "kb" ]; then - node qa/kb-retrieval.cjs || status=1 - node qa/kb-chat.mjs || status=1 -elif [ "$MODE" = "door" ]; then - node qa/door.mjs || status=1 -elif [ "$MODE" = "gamepass" ]; then - node qa/gamepass.mjs || status=1 -elif [ "$MODE" = "sov-passes" ]; then - node qa/sov-passes-store.cjs || status=1 - node qa/sov-passes-local.mjs || status=1 -elif [ "$MODE" = "login-queue" ]; then - node qa/login-queue.cjs || status=1 - node qa/login-queue-sql.cjs || status=1 -elif [ "$MODE" = "gamepass-games" ]; then - node qa/gamepass-games.cjs || status=1 -elif [ "$MODE" = "earn" ]; then - start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 -else - node qa/walk.mjs public || status=1 - node qa/chatbot-sync.mjs || status=1 - start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 - start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 -fi -echo -echo "reports: $OUT/walk-report.txt $OUT/earn-report.txt (screenshots alongside)" -exit $status +#!/usr/bin/env bash +# InstantAdPay QA harness runner. From the site dir: +# bash qa/run.sh public # live public pages only (no local server) +# bash qa/run.sh member # local copy: member + admin walk +# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min) +# bash qa/run.sh all # public + member + earn +# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter +# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data) +# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) +# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) +# bash qa/run.sh sov-passes # pass tiers (Explorer/Champion/Sovereign/Legend): store unit checks + admin buys Explorer + Sovereign with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes) +# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data) +# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos) +# 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 +cd "$(dirname "$0")/.." +MODE="${1:-all}" +OUT="qa/out"; mkdir -p "$OUT" +TMP="${TMPDIR:-${TEMP:-/tmp}}/iap-qa-$$" +status=0 + +start_local() { # $1 = port + local port="$1" + rm -rf "$TMP-$port"; mkdir -p "$TMP-$port/uploads" + (PORT="$port" DATA_DIR="$TMP-$port" ADMIN_EMAIL="${ADMIN_EMAIL:-martybostick@gmail.com}" ADMIN_PASSWORD=localtest node server.js > "$OUT/server-$port.log" 2>&1 &) + for i in $(seq 1 20); do curl -s -m 2 "http://127.0.0.1:$port/api/config" >/dev/null && return 0; sleep 1; done + echo "local server on :$port did not come up"; return 1 +} +stop_local() { # $1 = port + for p in $(netstat -ano 2>/dev/null | grep ":$1 " | awk '{print $5}' | sort -u); do taskkill //F //PID "$p" >/dev/null 2>&1; done + rm -rf "$TMP-$1" +} + +if [ "$MODE" = "public" ]; then + node qa/walk.mjs public || status=1 + node qa/chatbot-sync.mjs || 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 + node qa/sponsorfollow.test.cjs || status=1 + node qa/sponsorfollow-e2e.mjs || status=1 +elif [ "$MODE" = "kb" ]; then + node qa/kb-retrieval.cjs || status=1 + node qa/kb-chat.mjs || status=1 +elif [ "$MODE" = "door" ]; then + node qa/door.mjs || status=1 +elif [ "$MODE" = "gamepass" ]; then + node qa/gamepass.mjs || status=1 +elif [ "$MODE" = "sov-passes" ]; then + node qa/sov-passes-store.cjs || status=1 + node qa/sov-passes-local.mjs || status=1 +elif [ "$MODE" = "login-queue" ]; then + node qa/login-queue.cjs || status=1 + node qa/login-queue-sql.cjs || status=1 +elif [ "$MODE" = "override" ]; then + node qa/override.test.cjs || status=1 +elif [ "$MODE" = "gamepass-games" ]; then + node qa/gamepass-games.cjs || status=1 +elif [ "$MODE" = "earn" ]; then + start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 +else + node qa/walk.mjs public || status=1 + node qa/chatbot-sync.mjs || status=1 + start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 + start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 +fi +echo +echo "reports: $OUT/walk-report.txt $OUT/earn-report.txt (screenshots alongside)" +exit $status diff --git a/releases.js b/releases.js index 1e8d861..a4ecb16 100644 --- a/releases.js +++ b/releases.js @@ -64,7 +64,7 @@ function renderPage() { h += '

      Release notes

      '; h += v.notes.length ? v.notes.map(n => '

      ' + esc(n.title) + n.tags.map(tagChip).join('') + '

      ' + fmt(n.date) + '

      ' + bodyHtml(n.body) + '
      ').join('') : '

      No notes yet.

      '; h += '

      Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.

      '; - h += ''; + h += ''; return h; } module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES }; diff --git a/server.js b/server.js index 60fc65a..fb45e47 100644 --- a/server.js +++ b/server.js @@ -1,5443 +1,5466 @@ -// InstantAdPay — membership advertising with immutable on-chain settlement. -// Zero-dependency Node server (RM Circle pattern): static pages + JSON API, -// wallet sign-in (SIWE), live contract ledger, sponsor join links. -// -// Chain selection (Amoy rehearsal vs mainnet) lives in data/config.json — -// see chain.js. Wipe the volume's accounts/sessions + flip config = launch. -const http = require('http'); -const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09) -const https = require('https'); -const dns = require('dns'); -const fs = require('fs'); -const path = require('path'); -const crypto = require('crypto'); -const sendy = require('./sendy'); -const { URL } = require('url'); -const chain = require('./chain'); -const auth = require('./auth'); -const accounts = require('./accounts'); -const ads = require('./ads'); -const mailer = require('./mailer'); -const { emailIssue } = require('./emailcheck'); // typo / no-mail-domain check for NEW addresses (2026-10-22) -// only addresses we have never seen get the typo check; existing members always sign in with what they have. -// Skipped when this server cannot send mail (local QA copies sign in as @example.com via devCode). -const newEmailIssue = async e => (!mailer.hasKey() || (await accounts.byEmail(e)) ? null : emailIssue(e)); -const messages = require('./messages'); -const reports = require('./reports'); -const drip = require('./drip'); -const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) -let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } -const chatbot = require('./chatbot'); -const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20) -const fraud = require('./fraud'); -const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats -const tank = require('./tank'); -const walletnudge = require('./walletnudge'); -const milestone = require('./milestone'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward -const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails -const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) -const loginShows = require('./loginshows'); // login-ad showings per day, dashboard vs games (2026-10-18) -const promos = require('./promos'); -const missedNotice = require('./missed'); // the whole-chain missed-payout notice // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box) -const blog = require('./blog'); -const adminMember = require('./adminmember'); -const syndicate = require('./syndicate'); -const releases = require('./releases'); -const ledger = require('./ledger'); -const videosweep = require('./videosweep'); -const sbcheck = require('./sbcheck'); -const reach = require('./reach'); -const lssync = require('./lssync'); -const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) -const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22) -let follow = null, followStore = null; -const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''); -let activationCache = { at: 0, map: null }; -function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor) - if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map; - const m = new Map(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'MemberActivated' && ev.account) { const k = String(ev.account).toLowerCase(); if (!m.has(k)) m.set(k, { id: ev.id, sponsorId: ev.sponsorId, block: ev.block, tx: ev.tx }); } - activationCache = { at: Date.now(), map: m }; return m; -} -const gamestats = require('./gamestats'); -const marks = require('./marks'); -const gamepass = require('./gamepass'); // the $5 weekly Game Pass + the account-wide POL cap service the games call (2026-10-16) -const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations -const updates = require('./updates'); -const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14) -const leaderboard = require('./leaderboard'); -const toolkit = require('./toolkit'); -const badge = require('./badge'); // achievement badge image drawn on the server with ffmpeg (2026-09-16) -const friday = require('./friday'); -const starter = require('./starter'); // member welcome offer from the games (2026-10-05) -const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29) -const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26) -const refill = require('./refill'); -const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) -const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) -const override = require('./override'); // level-4 override, DRY RUN: weekly who-would-be-paid report, no money moves (2026-10-17) -const translate = require('./translate'); // help desk: member messages in other languages, replies back in theirs (2026-10-16) -const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16) -const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16) -const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16) -const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) -const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) -const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/presentation', '/support']); -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 PORT = Number(process.env.PORT || 3000); -const ROOT = __dirname; -const PUBLIC_DIR = path.join(ROOT, 'public'); -const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data'); -const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; -const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); -// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept -// in the volume so a restart doesn't log the admin out. Separate cookie and -// store from member sessions; the Bearer ADMIN_PASSWORD API path still works. -const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json'); -const ADMIN_TTL = 12 * 60 * 60 * 1000; -let adminSessions = {}; -try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } -function saveAdminSessions() { - const now = Date.now(); - for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k]; - try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {} -} -function mintAdminSession(email) { - const t = crypto.randomBytes(32).toString('hex'); - adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL }; - saveAdminSessions(); - return t; -} -function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; } -function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; } -function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } } -function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); } -function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; } -const IS_PROD = process.env.NODE_ENV === 'production'; -const todayCT = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Marty's day, never UTC -const SITE_FILE = path.join(DATA_DIR, 'site.json'); - -const db = require('./db'); -fs.mkdirSync(DATA_DIR, { recursive: true }); -const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume -fs.mkdirSync(UPLOADS_DIR, { recursive: true }); -const uploadCounts = new Map(); // email:day -> uploads today -// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a -// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart) -const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json'); -const persistedMaps = {}; -let tokenSaveTimer = null; -function saveOpenTokens() { - tokenSaveTimer = null; - try { - const out = {}; - for (const [name, m] of Object.entries(persistedMaps)) out[name] = Object.fromEntries(m); - fs.writeFileSync(OPEN_TOKENS_FILE(), JSON.stringify(out)); - } catch (e) {} -} -function persistedMap(name) { - const m = new Map(); - const touch = () => { if (!tokenSaveTimer) tokenSaveTimer = setTimeout(saveOpenTokens, 500); }; - const set = m.set.bind(m), del = m.delete.bind(m); - m.set = (k, v) => { set(k, v); touch(); return m; }; - m.delete = k => { const r = del(k); if (r) touch(); return r; }; - persistedMaps[name] = m; - return m; -} -function loadOpenTokens() { - let saved = null; try { saved = JSON.parse(fs.readFileSync(OPEN_TOKENS_FILE(), 'utf8')); } catch (e) { return; } - const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0; - // durable maps are balances and orders, not short-lived tokens: restore every entry whatever its age. Before 2026-10-10 the - // age filter silently dropped every PolyWarriors mint pass (no ts on the record) on each deploy; Orlando lost his. - const DURABLE = new Set(['pwpasses', 'pwprizes', 'pworders', 'gkorders', 'sdorders', 'gamepass', 'gporders', 'gpprizes']); - for (const [name, m] of Object.entries(persistedMaps)) { - for (const [k, v] of Object.entries(saved[name] || {})) if (v && (DURABLE.has(name) || Number(v.ts || 0) > cutoff)) { Map.prototype.set.call(m, k, v); n++; } - } - if (n) console.log('open earn tokens restored:', n); -} -const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor) -const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor) -const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit) -const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor) -// walk the referral chain upward via sponsorRef (code/username/member id) -async function uplineSlides(email, depth = 3) { - const out = []; - let cur = await accounts.byEmail(email); - for (let i = 0; i < depth && cur; i++) { - const ref = String(cur.sponsorRef || '').trim().toLowerCase(); - if (!ref) break; - let s = null; - if (/^\d+$/.test(ref)) s = await accounts.byMemberId(Number(ref)); - if (!s) s = await accounts.byCode(ref); - if (!s) s = await accounts.byUsername(ref); - if (!s || s.email === cur.email) break; - out.push(s); - cur = s; - } - return out; -} -// Wall ownership ladder: position 1 is always the member's own line banner; -// positions 2 and 3 become theirs at 2 and 5 qualifying buyers (the same -// thresholds that open payout levels 2 and 3). Until then, or while an unlocked -// slot is empty, the slot shows an upline's banner, then a house ad. -const catalogCache = { at: 0, products: null }; -const wallUnlockedFor = bc => (bc >= 5 ? 3 : bc >= 2 ? 2 : 1); -// every on-chain member id this session controls: the main wallet plus linked -// positions (Qualified Start). Credits pool across them on the dashboard. -const memberInfoCache = new Map(); // id -> { t, v } (60s): line views ask for every member's on-chain row -async function cachedMember(id) { - const c = memberInfoCache.get(id); if (c && Date.now() - c.t < 60000) return c.v; - let v = null; try { v = await chain.member(id); } catch (e) {} - memberInfoCache.set(id, { t: Date.now(), v }); return v; -} -async function myMemberIds(s) { - const main = await auth.refreshMemberId(s); - const ids = main ? [main] : []; - if (s && s.email) for (const p of await accounts.positions(s.email)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); - return { main, ids }; -} -function parseWallOffers(a) { - try { const v = JSON.parse((a && a.wallOffers) || '[]'); return Array.isArray(v) ? v.slice(0, 2) : []; } catch (e) { return []; } -} -// admin fallback ads for wall positions 2 & 3 when a member has no upline. -// Configurable by dropping data/admin-wall-ads.json ([{name,targetUrl,bannerUrl}]). -function getAdminWallAds() { - try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); if (Array.isArray(j) && j.length) return j; } catch (e) {} - return [{ name: 'InstantAdPay', targetUrl: 'https://instantadpay.com/', bannerUrl: null }]; -} -const chatHits = new Map(); -function chatLimited(ip) { - const now = Date.now(), rec = chatHits.get(ip); - if (!rec || now > rec.reset) { chatHits.set(ip, { count: 1, reset: now + 60000 }); return false; } - rec.count += 1; - return rec.count > 10; -} -// magic-code sign-in: emailLower -> {code, exp, tries} -const emailCodes = new Map(); -// Sponsor bound to the sign-up, not only to a cookie (Marty, 2026-09-29: nancyr #180 and others "supposed to land under -// Mad Dog" were created with no sponsor and fell to the company). The iap.sponsor cookie is SameSite=Lax, so it is -// rejected when the join page is shown inside another site (traffic-exchange frames), and it never crosses browsers -// (in-app browser -> mail app -> default browser). So: the join page sends the token from its own URL with the code -// request, the server remembers "this email asked for a code under " for 30 days on disk (deploys restart the -// process), and account creation uses page token, then cookie, then that memory. A token-less request never -// overwrites a remembered token. -const pendingSponsor = { - FILE: () => path.join(DATA_DIR, 'pending-sponsors.json'), db: null, - load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = {}; } }, - save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }, - set(email, f) { if (!email || !f || !f.ref) return; if (!this.db) this.load(); this.db[email] = { ref: f.ref, via: f.via || '', joinedRef: f.joinedRef || null, at: Date.now() }; this.prune(); this.save(); }, - get(email) { if (!this.db) this.load(); const r = this.db[email]; return r && Date.now() - r.at < 30 * 86400e3 ? r : null; }, - del(email) { if (!this.db) this.load(); if (this.db[email]) { delete this.db[email]; this.save(); } }, - prune() { const cut = Date.now() - 30 * 86400e3; for (const k of Object.keys(this.db)) if (this.db[k].at < cut) delete this.db[k]; } -}; -const pageTok = v => { const t = String(v || '').trim().toLowerCase(); return /^[a-z0-9_]{1,40}$/.test(t) ? (JOIN_ALIASES[t] || t) : ''; }; // a token the join page read from its own URL -// ── sign-up code guard (Marty, 2026-09-11): the email box is one field and one -// tap, so nothing visible stands in a human's way. Bots hit four invisible walls: -// a honeypot field, a minimum form age, per-IP + global send limits, and, only -// once an IP trips a limit, the same icon check the ad viewer uses. -const CODE_LIMITS = { per10m: 5, perDay: 20, globalPerMin: 60, passMs: 5 * 60 * 1000, minFormMs: 2000 }; -const codeHits = new Map(); // ip -> { t: [send timestamps, 24h], passUntil, chal: { answer, exp } } -const codeGlobal = { minute: 0, n: 0 }; -const codeAlert = { last: 0, trips: 0, ips: new Set() }; -function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; } -// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign) -function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; } -function codeChallenge(rec) { - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - rec.chal = { answer: pick[answer][0], exp: Date.now() + 5 * 60 * 1000 }; - return { prompt: pick[answer][1], options: pick.map(x => x[0]) }; -} -// returns null to allow the send, or { status, body } to answer with instead -const guardLog = (req, why, b) => console.log('signup-guard', why, clientIp(req), String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); -function codeGuard(req, b) { - const now = Date.now(); - // honeypot: bots fill it, humans never see it. Some form-filler extensions fill every field, - // hidden or not (seen 2026-09-11), so a filled honeypot is a CHALLENGE, never a silent drop: - // a person passes the icon check and gets the code, a bot cannot. - const hpRaw = String(b.hp_field_x9 || '').trim(); - const hpIsEmail = !!hpRaw && hpRaw.toLowerCase() === String(b.email || '').trim().toLowerCase(); - const hp = !!hpRaw && !hpIsEmail; // 2026-09-13: phones were autofilling the hidden field; own email = autofill, not a bot - if (hpRaw) console.log('signup-guard honeypot-value', clientIp(req), hpIsEmail ? 'own-email' : (/^https?:/i.test(hpRaw) ? 'url' : /@/.test(hpRaw) ? 'other-email' : /^\+?[\d\s()-]{6,}$/.test(hpRaw) ? 'phone' : 'text'), 'len=' + hpRaw.length, hpIsEmail ? '' : hpRaw.slice(0, 2) + '***'); - // Form age is measured on the visitor's own clock (fage = their Date.now() minus the moment the form loaded), so a - // phone whose clock runs fast or slow is not refused forever. Comparing their fts with OUR clock did exactly that - // (2026-10-07: a member retried and was stopped every time). Old cached pages send only fts: fall back to it. - const fts = Number(b.fts) || 0; - const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1); - if (fage < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; } - if (fage > 12 * 3600 * 1000) { guardLog(req, 'form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then tap again.' } }; } - const minute = Math.floor(now / 60000); - if (codeGlobal.minute !== minute) { codeGlobal.minute = minute; codeGlobal.n = 0; } - if (codeGlobal.n >= CODE_LIMITS.globalPerMin) { guardLog(req, 'global-limit', b); codeTrip(req, 'global'); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } - const ip = clientIp(req); - const rec = codeHits.get(ip) || { t: [], passUntil: 0, chal: null }; - rec.t = rec.t.filter(ts => now - ts < 24 * 3600 * 1000); - const n10 = rec.t.filter(ts => now - ts < 10 * 60 * 1000).length; - const limited = hp || n10 >= CODE_LIMITS.per10m || rec.t.length >= CODE_LIMITS.perDay; - if (limited && now >= rec.passUntil) { - const pick = String(b.pick || ''); - if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } - else { - guardLog(req, pick ? 'wrong-pick' : hp ? 'honeypot-challenge' : 'ip-limit', b); if (!hp) codeTrip(req, ip); - const challenge = codeChallenge(rec); codeHits.set(ip, rec); - return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send another code.', challenge } }; - } - } - rec.t.push(now); codeHits.set(ip, rec); codeGlobal.n += 1; - if (codeHits.size > 5000) for (const [k, v] of codeHits) { if (!v.t.length || now - v.t[v.t.length - 1] > 24 * 3600 * 1000) codeHits.delete(k); } - return null; -} -// burst alert: at most one message per 10 minutes, to the admin Telegram chat if set, else the admin email -function codeTrip(req, ip) { - codeAlert.trips += 1; codeAlert.ips.add(ip); - if (Date.now() - codeAlert.last < 10 * 60 * 1000) return; - codeAlert.last = Date.now(); - const text = '\u26A0\uFE0F InstantAdPay sign-up guard: ' + codeAlert.trips + ' blocked code request' + (codeAlert.trips === 1 ? '' : 's') + ' from ' + codeAlert.ips.size + ' source' + (codeAlert.ips.size === 1 ? '' : 's') + ' (' + [...codeAlert.ips].slice(0, 5).join(', ') + ') in the last window.'; - codeAlert.trips = 0; codeAlert.ips = new Set(); - const sc = siteConfig(); - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: sign-up guard tripped', text).catch(() => {}); -} -// earn-view tokens: emailLower -> {token, ts} (one live token per member) -const earnTokens = persistedMap('earn'); -// human-check pairs for the view verifier: [emoji shown, word named in the prompt] -const CAPTCHA = [['🚀', 'rocket'], ['⚡', 'lightning bolt'], ['🔑', 'key'], ['🎯', 'target'], - ['🌊', 'wave'], ['🔥', 'flame'], ['💎', 'diamond'], ['🧲', 'magnet'], ['🔔', 'bell'], ['🌙', 'moon']]; -// Spooky Doors' door check uses Halloween icons (Marty, 2026-10-02) -const DOOR_CAPTCHA = [['🎃', 'pumpkin'], ['👻', 'ghost'], ['🦇', 'bat'], ['🍬', 'candy'], ['🕷️', 'spider'], ['💀', 'skull'], ['🍭', 'lollipop'], ['🧙', 'witch'], ['🕸️', 'spider web'], ['🌕', 'full moon'], ['🍫', 'chocolate']]; - -// ── frame-breaking check ───────────────────────────────── -// Surf views frame the advertiser's URL full screen, so a target that refuses -// framing (X-Frame-Options / CSP frame-ancestors) would burn members' views on -// a blank frame. Catch it the moment the campaign is submitted. The lookup -// also refuses private/internal addresses so member URLs can't probe our LAN. -const PRIVATE_IP = /^(127\.|10\.|192\.168\.|169\.254\.|0\.|172\.(1[6-9]|2\d|3[01])\.|::1$|::$|f[cd])/i; -function frameFetch(url, depth) { - return new Promise(resolve => { - let u; - try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); } - if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' }); - if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' }); - if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' }); - dns.lookup(u.hostname, (de, addr) => { - if (de) return resolve({ error: 'that domain does not resolve' }); - if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' }); - const mod = u.protocol === 'https:' ? https : http; - const rq = mod.get(u.href, { timeout: 8000, - headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-FrameCheck/1.0)', Accept: 'text/html' } }, r => { - const loc = r.headers.location; - r.resume(); // headers are all we need - if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) { - rq.destroy(); - let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); } - return resolve(frameFetch(next, depth + 1)); // every hop re-runs the private-IP guard - } - resolve({ status: r.statusCode, xfo: r.headers['x-frame-options'] || '', csp: r.headers['content-security-policy'] || '' }); - rq.destroy(); - }); - rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); }); - rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' })); - }); - }); -} -// shared upload path for member creatives (/api/my/upload) and admin house-ad -// creatives (/api/admin/upload): `who` keys the per-day upload counter -async function handleUpload(req, res, who) { - const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase(); - const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', - 'video/mp4': 'mp4', 'video/webm': 'webm' }; - if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' }); - const isVideo = ct.startsWith('video/'); - const key = who + ':' + new Date().toISOString().slice(0, 10); - if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' }); - let buf; - try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); } - catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); } - const magicOk = buf.length > 16 && ( - (ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || - (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || - (ct === 'image/webp' && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') || - (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8') || - (ct === 'video/mp4' && buf.slice(4, 8).toString() === 'ftyp') || - (ct === 'video/webm' && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3)); - if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' }); - const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct]; - uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1); - // video goes to DO Spaces when configured (keeps big files off the volume); - // images stay local. Falls back to the volume if Spaces isn't set or errors. - if (isVideo && spaces.enabled()) { - try { - const url = await spaces.put('iap-uploads/' + name, buf, ct); - return json(res, 200, { url, type: 'video' }); - } catch (e) { console.error('spaces put', e.message); /* fall through to volume */ } - } - fs.writeFileSync(path.join(UPLOADS_DIR, name), buf); - return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' }); -} -// lead-capture page hooks (og tags + copy live in public/assets/join.js too) -const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position -const JOIN_ANGLES = { - // legacy bridge pages (/from/): former members of Marty's closed EvolutionScript sites - 'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/faucetwave?seg=advertiser' }, - 'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/faucetwave' }, - 't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/tieroneads?seg=advertiser' }, - 't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/tieroneads' }, - // SocialPix (socialpix.club) gate, 2026-09-20: the media-sharing site was being used as a free - // ad board; its signup/post flows now land here. Default copy = advertiser (that is why they came). - 'sp-adv': { t: 'Your ad, seen across a whole network.', d: 'SocialPix no longer takes ad posts. Advertising now runs through InstantAdPay: a free account, your ad in seven formats across every site in the network, and every package in your line paid out on Polygon in the same transaction. Real email required.', url: 'https://instantadpay.com/from/socialpix' }, - 'sp-earn': { t: 'Same feed. Real payouts on-chain.', d: 'SocialPix has moved its advertising to InstantAdPay. View ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Join free by email.', url: 'https://instantadpay.com/from/socialpix?seg=earn' }, - play: { t: 'If you have time to play a game, you have time to build a business.', d: 'Free games that pay real Polygon to your wallet, on chain, where anyone can check it. Play free, then join free by email.' }, - instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' }, - adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, packages from $5. Join free.' }, - free: { t: 'Watch first. Spend never.', d: 'Join free, view a few ads, earn credits, run your first campaign for zero dollars. Every payout public on Polygon.' }, - friday: { t: 'Five Dollar Friday: 20% bonus credits.', d: 'Every Friday, US Central time, any ad package from $5 up earns 20% bonus credits the moment it settles, and every pack pays its sponsor line in the same transaction. Join free by email.' }, - wednesday: { t: 'Wired Wednesday: 25% bonus credits, wired in the second it settles.', d: 'Every Wednesday, US Central time, any ad package from $20 up earns 25% bonus credits, wired into your balance the moment the purchase settles and good for any ad format. Join free by email.' }, - ledger: { t: 'No back office. No payday.', d: 'Every payout is a public transaction on Polygon you can read yourself. Nothing is ever held. Join free by email.' }, - two: { t: 'Two buyers open level two.', d: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written in a verified contract.' }, - // Build Wide hook (2026-10-15): the 'buildwide' promo video; files keep the uploaded promo/buildwide.* names - wide: { t: 'Width unlocks depth.', d: 'Watch the fifty percent land, then the deeper levels open. Every package in your line is split by a verified contract on Polygon in the same transaction. Join free by email.', img: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/buildwide.jpg', imgW: 1280, imgH: 720 } -}; -function serveJoinPage(res, tok, angle, ang, setCookies) { - let html; - try { html = fs.readFileSync(path.join(PUBLIC_DIR, 'join.html'), 'utf8'); } catch (e) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const base = 'https://instantadpay.com'; - const url = (ang && ang.url) || (base + '/join/' + tok + (angle ? '?v=' + angle : '')); - const title = ang ? ang.t : 'Advertise and earn. Paid on-chain, instantly.'; - const desc = ang ? ang.d : 'You are invited to InstantAdPay: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.'; - // each hook angle previews with its own video's opening frame (Marty 2026-10-13: shared angle links all showed the generic hero) - const ogImg = (ang && ang.img) || (base + (['play', 'instant', 'adspend', 'free', 'ledger', 'two'].includes(angle) ? '/banners/iap-angle-' + angle + '-1200x630.jpg?v=1' : '/banners/iap-hero-1200x630.png')); - const ogW = (ang && ang.imgW) || 1200, ogH = (ang && ang.imgH) || 630; - const escA = t => String(t).replace(/&/g, '&').replace(/"/g, '"').replace(/' - + '' // keeps ?v= so shares stay on the angle - + '' - + ''; - html = html.replace(/[^<]*<\/title>/, '<title>' + escA(title) + ' | InstantAdPay' + og); - if (ang) html = html.replace('', ''); // angle pages: squeeze layout from the first paint - // Network Ad Space zone on the two legacy squeeze pages only (Marty, 2026-09-19): below the - // fine print, above the footer links. The regular join pages stay ad-free. - if (/^(fw|t1)-(adv|earn)$/.test(String(angle || ''))) html = html.replace('
      ', - '
      ' + '
      '); - const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' }; - if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies; - res.writeHead(200, baseHeaders(headers)); - res.end(html); -} -// A banner creative must be an IMAGE (2026-09-16: campaign #134 had the member's join-page link in the -// image field and served a broken banner 141 times on the network). Accept /uploads/ files and -// image extensions outright; otherwise HEAD the URL and require an image/* content-type. -async function imageCheck(url) { - const u = String(url || '').trim(); - if (/^\/uploads\//.test(u) || /^https?:\/\/instantadpay\.com\/(uploads|banners)\//i.test(u)) return { ok: true }; - if (/\.(png|jpe?g|gif|webp|svg)([?#].*)?$/i.test(u)) return { ok: true }; - try { - const h = await headUrl(u); - if (h && /^image\//i.test(String(h.contentType || ''))) return { ok: true }; - return { ok: false, reason: 'That link is a web page, not an image. Paste the direct image link (it usually ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' }; - } catch (e) { return { ok: false, reason: 'Could not load that image link. Paste the direct image link (ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' }; } -} -// A video campaign's source has to actually exist. The create form only matched the URL -// shape, so a placeholder (yourdomain.com/....mp4) went live on 2026-09-11 and sat there for -// eleven days handing every Tier 1 viewer a black player they could never finish. -// PolHunter pays real POL out of its own faucet and none of it passes through this contract, so -// the P&L cannot derive it from chain events and has to read it across (Marty, 2026-09-23). Cached -// and fail-soft: the P&L page must never hang or break because the other site is down. -let huntCache = { at: 0, data: null }; -// real block timestamps for the tax summary, read once and kept (a block's time never changes) -let blockTimesCache = null; -function blockTimes() { if (!blockTimesCache) { try { blockTimesCache = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'blocktimes.json'), 'utf8')); } catch (e) { blockTimesCache = {}; } } return blockTimesCache; } -function saveBlockTimes(bt) { try { const f = path.join(DATA_DIR, 'blocktimes.json'); fs.writeFileSync(f + '.tmp', JSON.stringify(bt)); fs.renameSync(f + '.tmp', f); } catch (e) {} } -async function huntLedger() { - if (Date.now() - huntCache.at < 120000) return huntCache.data; - const base = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, ''); - try { - const r = await fetch(base + '/api/ledger', { signal: AbortSignal.timeout(6000) }); - if (!r.ok) throw new Error('HTTP ' + r.status); - const j = await r.json(); - huntCache = { at: Date.now(), data: { totals: j.totals || null, referrals: j.referrals || null, pools: j.pools || null, at: Date.now() } }; - } catch (e) { - huntCache = { at: Date.now(), data: huntCache.data || { error: e.message } }; - } - return huntCache.data; -} -async function videoCheck(url) { - const u = String(url || '').trim(); - if (/^\/uploads\//.test(u)) return { ok: true }; // uploaded here, already on our disk - let h; - try { h = await headUrl(u); } - catch (e) { // no DNS, refused, timed out - return { ok: false, reason: 'We could not reach that video link, so members would just see a black player. Check the address, or upload the file here instead.' }; - } - if (h && (h.status === 404 || h.status === 410)) - return { ok: false, reason: 'That video link answers with HTTP ' + h.status + ' — the file is not there. Point the campaign at a file that loads, or upload it here.' }; - const ct = String((h && h.contentType) || '').split(';')[0].trim().toLowerCase(); - if (ct && !/^video\//.test(ct) && ct !== 'application/octet-stream' && ct !== 'binary/octet-stream') - return { ok: false, reason: 'That link returns ' + ct + ', not a video file. Paste the direct .mp4 or .webm link, or upload the file here.' }; - return { ok: true }; -} -function headUrl(url) { - return new Promise((resolve, reject) => { - let u; try { u = new URL(url); } catch (e) { return reject(new Error('bad url')); } - const mod = u.protocol === 'http:' ? require('http') : require('https'); - const req = mod.request({ method: 'HEAD', hostname: u.hostname, port: u.port || undefined, path: u.pathname + u.search, timeout: 6000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-ImageCheck/1.0)' } }, r => { - if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location && !u.searchParams.has('_r')) { try { const nx = new URL(r.headers.location, url); nx.searchParams.set('_r', '1'); return resolve(headUrl(nx.toString())); } catch (e) {} } - resolve({ status: r.statusCode, contentType: r.headers['content-type'] || '' }); r.resume(); - }); - req.on('error', reject); req.on('timeout', () => req.destroy(new Error('timeout'))); req.end(); - }); -} -// login-ad gate: can this sponsor's page load inside our frame? Cached 6 h per campaign + url; an answer that -// takes longer than 4 s counts as "no" for this sign-in (new-tab fallback) while the check finishes for the cache. -const loginFrameCache = new Map(); -async function loginFrameable(id, url, inGame) { // inGame: the frame sits on a game's page, so an allowance for instantadpay.com alone is not enough - const key = (inGame ? 'g|' : '') + id + '|' + url, hit = loginFrameCache.get(key); - if (hit && Date.now() - hit.ts < 6 * 3600 * 1000) return hit.ok; - if (!url) return false; - const check = frameCheck(url, inGame).then(r => { loginFrameCache.set(key, { ok: !!r.ok, ts: Date.now() }); return !!r.ok; }).catch(() => false); - return Promise.race([check, new Promise(r => setTimeout(() => r(false), 4000))]); -} -async function frameCheck(url, inGame) { - const h = await frameFetch(url, 0); - if (h.error) return { ok: false, reason: 'We checked your URL and ' + h.error + '. Fix the URL and try again.' }; - if (h.status >= 400) return { ok: false, reason: 'Your URL answers with HTTP ' + h.status + '. Point the campaign at a working page.' }; - if (/deny|sameorigin/i.test(String(h.xfo))) - return { ok: false, reason: 'That site blocks framing (X-Frame-Options), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; - const fa = /frame-ancestors\s+([^;]+)/i.exec(String(h.csp)); - if (fa && !fa[1].split(/\s+/).some(x => { - const v = x.replace(/['"]/g, '').toLowerCase(); - return v === '*' || v === 'https:' || (!inGame && v.includes('instantadpay.com')); - })) - return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; - return { ok: true }; -} -async function boot() { - await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode) - marks.init({ db }); - marks.ensureTable().catch(e => console.error('marks table', e.message)); - setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref(); - chain.init({ onEvent: ev => { - // the in-memory feed is per instance and always runs - attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); - // everything outward (email, Telegram, the Friday bonus, sponsor sync) happens ONCE across - // every running copy of the app: during a deploy two copies watch the chain for ~30 s, - // and on 2026-09-25 both emailed Marty and both granted his Friday bonus - marks.claim('ev:' + ev.tx + ':' + ev.li).then(mine => { - if (!mine) return; - emailOnEvent(ev).catch(() => {}); - telegramOnEvent(ev).catch(() => {}); - starter.onEvent(ev).catch(e => console.error('starter bonus', e.message)); - pwMintOnEvent(ev).catch(e => console.error('polywarriors mint', e.message)); - // the Friday bonus and the pass order first, then the Friday pass perk, which needs both results (Marty 2026-10-23) - Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).catch(e => { console.error('gamepass order', e.message); return null; })]) - .then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message)); - wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message)); - sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message)); - }).catch(e => console.error('marks claim', e.message)); - } }); - auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: 'instantadpay.com' }); - accounts.init({ dataDir: DATA_DIR }); - ads.init({ dataDir: DATA_DIR, chain, tiers: () => geo.tierLists(siteConfig()) }); - mailer.init({ dataDir: DATA_DIR }); - messages.init({ dataDir: DATA_DIR }); - reports.init({ dataDir: DATA_DIR }); - drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' }); - chatbot.init({ dataDir: DATA_DIR, chain, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22) - setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000); - setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000); - setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends - // follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot) - coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); - pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); - translate.init({ dataDir: DATA_DIR }); - tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram, translate }); - inbound.init({ tickets }); - supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' }); - badge.init({ publicDir: PUBLIC_DIR }); - gamestats.init({ dataDir: DATA_DIR }); - snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT())).map(g => g.name), - send: async (c, t, th) => { await telegramSend(c, t, th); return true; }, - sendPhoto: (c, jpeg, cap, th) => telegramSendPhoto(c, jpeg, cap, th) }); - fridaybank.init({ db }); - starter.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts }); - friday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, - telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + text, sc.telegramEchoTopicId); }, - notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } }); - // Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped, - // with the bonus ladder in the same message, and every send is watched for what they did next. - refill.init({ - dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, - creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; }, - message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); }, - }); - // prepaid login-ad line (2026-10-23): when a reservation starts, its owner gets an on-site notice (kind 'notice', never the - // sign-in pop) and an email unless they unsubscribed. ads.js calls this once per start, from the one copy that won it. - ads.onLoginPromoted(async c => { - const owner = String(c.owner || '').toLowerCase(); if (!owner) return; - const name = c.name || ('campaign #' + c.id); - const until = new Date(Number(c.expires)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; - const days = Number(c.body) || ads.rates().loginSlotDays || 30; - const subject = 'Your login ad "' + name + '" is live'; - const text = 'Your place in line came up. Your reserved login-ad slot has started, so "' + name + '" now shows full screen to members as they sign in, for ' + days + ' days, until ' + until + '.\n\n' - + 'You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns: https://instantadpay.com/my#campaigns\n\nInstantAdPay'; - const esc = s => String(s).replace(/&/g, '&').replace(//g, '>'); - const html = '

      Your place in line came up. Your reserved login-ad slot has started, so ' + esc(name) + ' now shows full screen to members as they sign in, for ' + days + ' days, until ' + esc(until) + '.

      ' - + '

      You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns.

      '; - try { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [owner], subject, html, 'notice'); } catch (e) { console.error('login line inbox', e.message); } - const stopped = drip && drip.isUnsubscribed ? await drip.isUnsubscribed(owner).catch(() => false) : false; - if (!stopped && mailer.hasKey()) { try { await mailer.send(owner, subject, text); } catch (e) { console.error('login line mail', e.message); } } - console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2')); - }); - setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes - setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000); - setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000); - setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 60 * 1000); - wednesday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, rates: () => ads.rates(), - telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay · ' + text, sc.telegramEchoTopicId); }, - notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } }); - setInterval(() => wednesday.tick().catch(e => console.error('wednesday', e.message)), 5 * 60 * 1000); - override.init({ dataDir: DATA_DIR, chain, siteConfig, notify: supportTelegram }); - setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000); - setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); - // sponsor follow (sponsorfollow.js): a deliberate change (tank adoption, rescue, release, window expiry, admin edit) is - // recorded and follows to LinkSpin, and LinkSpin's deliberate changes are applied here, until the member is bound on - // InstantAdPay's contract (memberId, or the wallet already on chain). Ordinary bindings keep the first-platform rule. - followStore = SF.create({ dataDir: DATA_DIR, platform: 'instantadpay' }); - follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'linkspin', - isBound: async a => { - if (Number(a.memberId) > 0) return { bound: true, why: 'InstantAdPay member #' + a.memberId }; - if (!a.address) return { bound: false }; - try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; return id ? { bound: true, why: 'wallet is InstantAdPay member #' + id } : { bound: false }; } - catch (e) { return { retry: true, why: 'InstantAdPay chain read failed' }; } - }, - sponsorAccount: em => accounts.byEmail(em), - wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; }, - activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null }); - tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore }); - // LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest - lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email)); - lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore }); - setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); - setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); - setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account - walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com', - message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } }); - setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window - setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000); - // 1,000-member POL drop (Marty 2026-10-10): watches the account count every 2 minutes while milestoneMode is dry or armed - milestone.init({ dataDir: DATA_DIR, accounts, chain, mailer, ledger, optedIn: updates.optedIn, site: 'https://instantadpay.com', siteConfig, noPayoutSet, - message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); }, - telegram: async html => { const sc = siteConfig(); if (sc.telegramChatId) await telegramSend(sc.telegramChatId, html, sc.telegramTopicId); if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, html, sc.telegramEchoTopicId); } }); - setTimeout(() => milestone.tick().catch(e => console.error('milestone', e.message)), 4 * 60 * 1000); - setInterval(() => milestone.tick().catch(e => console.error('milestone', e.message)), 2 * 60 * 1000); - await fraud.init({ dataDir: DATA_DIR }); - { // a suspended account is signed out everywhere: every member route sees no session - const realFrom = auth.fromRequest.bind(auth); - auth.fromRequest = async (req) => { const sess = await realFrom(req); if (sess && sess.email && fraud.isSuspended(sess.email)) return null; return sess; }; - } - legacy.init({ dataDir: DATA_DIR }); - traffic.init({ dataDir: DATA_DIR }); - loginShows.init({ dataDir: DATA_DIR }); - promos.init({ dataDir: DATA_DIR }); - blog.init({ dataDir: DATA_DIR }); - adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR }); - gamepass.init({ dataDir: DATA_DIR, siteConfig, accounts, marks, isProd: IS_PROD, persistedMap, polUsd: polUsdLive, - blockTime: async n => { const blk = await chain.rpc('eth_getBlockByNumber', ['0x' + Number(n).toString(16), false]); return blk && blk.timestamp ? parseInt(blk.timestamp, 16) : 0; }, // a pass order is fulfilled only by a purchase mined after it - telegram: async html => { const sc = siteConfig(); const chat = String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return false; await telegramSend(chat, html, sc.telegramGamesTopicId || null); return true; }, - notify: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice') }); // before loadOpenTokens: its maps must exist to be restored - loadOpenTokens(); - setTimeout(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 120 * 1000); - setInterval(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 60 * 60 * 1000); - setInterval(() => { try { gamepass.prune(); } catch (e) { console.error('gamepass prune', e.message); } }, 6 * 3600 * 1000).unref(); - syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR }); - releases.init({ dataDir: DATA_DIR }); - ledger.init({ dataDir: DATA_DIR }); - // re-check live video sources on a schedule: videoCheck only ever runs at save time, so a - // campaign created before it existed, or a link that rots later, is otherwise invisible - const videosweepAlert = async text => { - const sc = siteConfig(); - // Marty's own Hermes chat, where his other operational pings land (@CoolifyHermes_Bot). - // Admin channels ONLY, never a member-visible one: this names a member's campaign and - // their email address, so the shared payments topic would put it in front of the team. - const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); - if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, text); - if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, text); - if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: broken video sources', text.replace(/<[^>]+>/g, '')); - console.log('videosweep: no admin channel configured, alert not sent'); - }; - videosweep.init({ dataDir: DATA_DIR, fs, path, db, videoCheck, alert: videosweepAlert }); - videosweep.start(); - // Screen every advertiser destination against Google Safe Browsing: refuse a flagged one at - // save time, and re-screen the live ones daily. Added 2026-09-24 after Google marked the - // site "deceptive pages" with campaign #225 opening llclickpro.com (flagged) from our pages. - // Shares videosweep's alert path on purpose: it names members and their emails, admin only. - sbcheck.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert }); - sbcheck.start(); - // Destination reachability (2026-10-07): a link that resolved when saved can die later (campaign #163's - // lmgnow.co vanished and 65 members hit a dead end while Safe Browsing read 'cannot resolve' as unknown). - // Refuses a host with no DNS record at save time; pauses live ads whose host is dead two days running. - reach.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert, site: 'https://instantadpay.com', - message: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'), - mailer, optedIn: email => updates.optedIn(email) }); - reach.start(); - toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain }); - updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL }); - audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: counter audit', text).catch(() => {}); } }); - setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000); - videomaker.init({ dataDir: DATA_DIR, spaces, accounts }); - leaderboard.init({ chain, accounts, ads, fraud, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL, - notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } }); - setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000); - setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000); - console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)'); - setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram - geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message)); - setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily - setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window - burner.init({ chain, ads, accounts }); - setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000); - setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000); - 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); - 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); - // NAS reconcile: pull syndicated delivery into the unified credit pool - // (inert unless NAS_DB_* is set). Every 5 min after a short warm-up. - if (ads.nasEnabled()) { - console.log('NAS syndication enabled'); - setTimeout(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 90 * 1000); - pdsync.init({ dataDir: DATA_DIR, ads }); - if (pdsync.enabled()) { const every = Math.max(2, Number(process.env.PD_SYNC_MIN || 5)) * 60 * 1000; setTimeout(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), 90 * 1000); setInterval(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), every); console.log('PassiveDrip PTC bridge: on, every', every / 60000, 'min'); } else console.log('PassiveDrip PTC bridge: off (no PD_BRIDGE_URL/SECRET)'); - setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000); - } -} - -// Game Pass partner helpers (2026-10-16): which secret signs for which game, signature compare, member resolution, dev clock -const GP_SECRETS = () => ({ polhunter: String(process.env.HUNT_SSO_SECRET || '').trim(), gemkingdom: GK_SECRET(), spellwheel: SW_SECRET(), spookydoors: SD_SECRET(), polywarriors: PW_SECRET(), - clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET(), shardsofvalor: SOV_SECRET() }); -function gpPartnerCheck(game) { if (!gamepass.GAMES.includes(game)) return { error: 'unknown game', code: 400 }; const secret = GP_SECRETS()[game] || ''; if (secret.length < 32) return { error: game + ' is not connected', code: 503 }; return { secret }; } -const gpSigOk = (want, got) => typeof got === 'string' && want.length === got.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got)); -async function gpResolve(memberId, email) { // the account behind a game's player: main member id, a linked position's id, or (no wallet yet) the email - const id = Number(memberId) || 0; let a = null; - if (id) { a = await accounts.byMemberId(id); if (!a) { const pos = await accounts.positionByMember(id); if (pos && pos.email) a = await accounts.byEmail(pos.email); } } - if (!a && email && /^[^\s@]+@[^\s@]+$/.test(String(email))) a = await accounts.byEmail(String(email).trim().toLowerCase()); - return a && a.email ? { email: String(a.email).toLowerCase(), memberId: a.memberId || id || 0, acct: a } : null; -} -const gpDevNow = devDay => (!IS_PROD && /^\d{4}-\d{2}-\d{2}$/.test(String(devDay || ''))) ? Date.parse(devDay + 'T17:00:00Z') : Date.now(); // local tests fake the Central day -// live USD per POL from the catalog quotes (the rate the games use for the tournament pool); cached 10 minutes -const polUsdCache = { at: 0, v: 0 }; -async function polUsdLive() { - if (!IS_PROD && Number(process.env.DEV_POL_USD) > 0) return Number(process.env.DEV_POL_USD); // local tests: no RPC - if (polUsdCache.at && Date.now() - polUsdCache.at < 300000 && polUsdCache.v > 0) return polUsdCache.v; // 5 min: what members see as today's dollar value - const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (!pk) return polUsdCache.v || 0; - const v = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); if (v > 0) { polUsdCache.v = v; polUsdCache.at = Date.now(); } return v; -} -// the Game Pass flag rides in every sign-in hand-off token (3a: games get it at sign-in and on every polgrant answer) -// gamePass: { active, until, tier } (tier = the highest active pass: weekly | explorer | champion | sovereign | legend | null; a game treats a missing tier as weekly) -const gpClaim = c => { if (!(c && c.email && (!c.kind || c.kind === 'sso'))) return {}; const f = gamepass.flag(c.email); return { gamePass: { active: f.active, until: f.until, tier: f.tier } }; }; -function siteConfig() { - let saved = {}; - try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {} - return Object.assign({ - siteName: 'InstantAdPay', - tagline: 'Advertise and earn. Locked in code, not promises.', - rehearsal: true, // shows the testnet banner; flipped off at mainnet launch - // payment-proof Telegram feed (blank = off) and the P&L pane's fixed monthly cost - telegramBotToken: '', telegramChatId: '', telegramTopicId: '', telegramEvents: 'payouts', telegramCtaUrl: 'https://instantadpay.com/', - fraudMaxSignupsPerIpDay: 2, fraudBlockSharedDevice: 'on', // anti-fraud: accounts per IP per day; block a second account from the same browser - telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic - telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL - fridayPromo: '1', // Five Dollar Friday on/off (Marty, 2026-09-20) - fridayBonusPct: '20', // bonus credits on any $5+ package bought on a Friday, Central - fridayStart: '2026-09-25', // the first Five Dollar Friday - wednesdayPromo: '1', wednesdayBonusPct: '25', wednesdayMinCents: '2000', wednesdayStart: '2026-09-30', // Wired Wednesday (Marty, 2026-09-29) - wednesdayNotice: '0', wednesdayKick: '0', // the Tuesday email/notice and the Wednesday Telegram kickoff stay off until Marty approves the copy - launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark - aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation - snapshotEnabled: '1', snapshotHourUtc: '14', snapshotTargets: 'feed,echo', // daily growth snapshot: 14 UTC = 9 AM Central; feed = proof channel, echo = shared payments topic - pipelineMode: 'off', // Pipeline board: off = 'coming soon' card, preview = only the admin account sees the live board, on = everyone (Marty, 2026-09-15) - pipelineEta: 'Sep 28', // what the coming-soon card and the roadmap promise - memberWeeklyEmail: '0', // 1 = the weekly 'Your week on InstantAdPay' email goes to every active member, not only sponsors with a line - noPayoutIds: '25', // positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14) - leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover) - legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ - geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) - geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else - // Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records - gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5, - // Explorer ($20) and Champion ($40) monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks - // in Shards of Valor, never power, never more POL (same caps as the weekly pass). sovTiers = the sale switch for both (off: only ADMIN_EMAIL - // sees and can buy them, for testing; holders keep their pass). gamePassEnabled '0' stops one tier alone. passTournamentTierSales '1' - // would add their sales to the Pass Tournament pool (off = the pool exactly as before). - // 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 / Champion $39.99 for 30 days, plus Sovereign $99.99 for 30 days and - // Legend $249.99 for 365 days (the yearly pass), all behind sovTiers. Names, perks and the rank live in gamepass.js TIER_DEFS. - sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 1999, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 3999, gamePassChampionDays: 30, - gamePassSovereignEnabled: '1', gamePassSovereignPriceCredits: 9999, gamePassSovereignDays: 30, gamePassLegendEnabled: '1', gamePassLegendPriceCredits: 24999, gamePassLegendDays: 365, passTournamentTierSales: '0', - supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback - supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set - telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat) - // share-link domain (2026-10-20, Marty): member invite links go out as https:///, which 302s to - // /join/ here, so shared links do not carry instantadpay.com (Spamhaus DBL). '' = old instantadpay.com/join links. - // Switch to the spare (mylinehq.com) if one gets flagged. Old links keep working either way. - shareDomain: 'ctbgo.com', - pnlFixedMonthlyUsd: 0 - }, saved); -} - -// ---- helpers ---- -const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', - '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', - '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', - '.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; -const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; -function baseHeaders(extra) { - return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', - 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); -} -function json(res, code, obj, extra) { - const body = JSON.stringify(obj); - res.writeHead(code, baseHeaders(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); - res.end(body); -} -function sendFile(res, file) { - fs.readFile(file, (err, data) => { - if (err) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const ext = path.extname(file).toLowerCase(); - res.writeHead(200, baseHeaders({ 'Content-Type': MIME[ext] || 'application/octet-stream', - // HTML is never stored (so a fresh load always gets the current asset - // versions — aggressive in-app wallet browsers were serving stale pages - // that pointed at old, since-fixed JS); versioned assets cache for an hour. - // the games load the sign-in kit from here with no version tag, so it revalidates every load (2026-10-18) - 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : path.basename(file) === 'game-signin.js' ? 'no-cache' : 'public, max-age=3600' })); - res.end(data); - }); -} -function readRaw(req, maxBytes) { - return new Promise((resolve, reject) => { - const chunks = []; - let n = 0; - req.on('data', c => { - n += c.length; - if (n > maxBytes) { req.destroy(); reject(new Error('too big')); return; } - chunks.push(c); - }); - req.on('end', () => resolve(Buffer.concat(chunks))); - req.on('error', reject); - }); -} -function readBody(req) { - return new Promise((resolve, reject) => { - let d = ''; let n = 0; - req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); reject(new Error('too big')); } d += c; }); - req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } }); - req.on('error', reject); - }); -} -function parseCookies(req) { - const out = {}; - for (const p of (req.headers.cookie || '').split(';')) { - const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); - } - return out; -} -// First sign-in to a waiting account made from a LinkSpin row (lsinbound.js): it becomes the person's own ordinary account. -// Its LinkSpin sponsor stands; one that arrived with no sponsor at all takes the link they signed in through, exactly as a -// brand-new account would (first InstantAdPay touch). Marked seen at once, so the sweeps count it from here on. -async function claimShell(email, shell, ref) { - try { - if (!shell.sponsorRef && ref) { const tok = String(ref).toLowerCase(); let sp = await accounts.byCode(tok); if (!sp) sp = await accounts.byUsername(tok); if (sp && sp.email !== email) await accounts.setSponsorRef(email, ref); } - await accounts.touchSeen(email); - console.log('linkspin waiting account claimed', email.replace(/^(.).*(@.*)$/, '$1***$2'), shell.sponsorRef ? 'sponsor ' + shell.sponsorRef : (ref ? 'sponsor from link ' + ref : 'no sponsor')); - } catch (e) { console.error('claimShell', e.message); } -} -function isAdmin(req) { - const h = req.headers.authorization || ''; - if (h === 'Bearer ' + ADMIN_PASSWORD) return true; - return !!adminFromRequest(req); // /admin portal session -} -// attach a memberId->username map to events so activity shows real people -// Payment trace (Marty, 2026-09-16): every purchase a member is involved in, tier by tier — who was -// paid, who was skipped and why (with how many qualifying buyers the skipped person had at that block) -// — so "why didn't X get paid on Y's buy" becomes a self-serve lookup instead of a support thread. -async function nameForMember(id) { - try { const a = await accounts.byMemberId(id); if (a && a.username) return a.username; } catch (e) {} - if (db.enabled()) { // a linked extra wallet: name it after its owner - try { const r = await db.q('SELECT email FROM positions WHERE member_id=? LIMIT 1', [Number(id)]); if (r.length) { const a = await accounts.byEmail(r[0].email); if (a && a.username) return a.username + ' (linked wallet)'; } } catch (e) {} - } - return null; -} -function sponsorMapFromIndex(evs) { const m = new Map(); for (const e of evs) if (e.type === 'MemberActivated' && e.id) m.set(e.id, Number(e.sponsorId) || 0); return m; } -function uplineIds(map, id, hops) { const out = []; let cur = map.get(Number(id)) || 0; for (let i = 0; i < hops && cur; i++) { out.push(cur); cur = map.get(cur) || 0; } return out; } -async function tracePurchases(targetId, limit) { - const id = Number(targetId) || 0; if (!id) return { error: 'Which member?' }; - const evs = chain.recentEvents(1e9); // whole history, newest first - const byTx = new Map(); - for (const e of evs) { if (!e.tx) continue; let g = byTx.get(e.tx); if (!g) { g = []; byTx.set(e.tx, g); } g.push(e); } - const counted = evs.filter(e => e.type === 'BuyerCounted'); - const buyersBefore = (sid, block) => counted.filter(e => e.sponsorId === sid && e.block < block).length; - const out = []; - for (const e of evs) { - if (e.type !== 'Purchase') continue; - const g = byTx.get(e.tx) || []; - const paid = g.filter(x => x.type === 'TierPaid' && x.buyerId === e.buyerId); - const skipped = g.filter(x => x.type === 'PassedUp' && x.buyerId === e.buyerId); - const act = g.find(x => x.type === 'MemberActivated' && x.id === e.buyerId); - const admin = g.find(x => x.type === 'AdminPaid' && x.buyerId === e.buyerId); - const involved = e.buyerId === id || paid.some(x => x.recipientId === id) || skipped.some(x => x.skippedId === id) || (act && act.sponsorId === id); - if (!involved) continue; - const tiers = [1, 2, 3].map(t => { - const p = paid.find(x => x.tier === t); const sk = skipped.filter(x => x.tier === t); - return { tier: t, pct: [50, 20, 10][t - 1], paidTo: p ? p.recipientId : 0, amountWei: p ? p.amountWei : '0', hops: p ? p.hops : 0, - skipped: sk.map(x => ({ id: x.skippedId, reason: x.reason, buyersThen: x.reason === 'unqualified' ? buyersBefore(x.skippedId, e.block) : null })) }; - }); - out.push({ ts: e.ts, block: e.block, tx: e.tx, buyerId: e.buyerId, sponsorId: act ? act.sponsorId : null, priceCents: e.priceCents, paidWei: e.paidWei, tiers, adminWei: admin ? admin.amountWei : '0' }); - if (out.length >= (limit || 30)) break; - } - const ids = new Set([id]); - for (const p of out) { ids.add(p.buyerId); if (p.sponsorId) ids.add(p.sponsorId); for (const t of p.tiers) { if (t.paidTo) ids.add(t.paidTo); for (const x of t.skipped) ids.add(x.id); } } - const names = {}; for (const i of ids) { const n = await nameForMember(i); if (n) names[i] = n; } - const smap = sponsorMapFromIndex(evs); - return { memberId: id, name: names[id] || null, activated: smap.has(id), sponsorId: smap.get(id) || 0, buyersNow: counted.filter(e => e.sponsorId === id).length, purchases: out, names }; -} -async function attachNames(evts) { - try { - const ids = []; - for (const ev of evts) - for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId']) - if (ev[k]) ids.push(ev[k]); - const names = await accounts.namesForMembers(ids); - if (!Object.keys(names).length) return evts; - return evts.map(ev => Object.assign({}, ev, { names })); - } catch (e) { return evts; } -} -// A sponsor token is a numeric chain id or a site share code. Codes resolve -// to the referrer's CURRENT chain id, so activation any time before the -// referral's first purchase still locks the line to them. -// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again. -// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three -// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys -// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0. -function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); } -async function payoutChainBlocked(id, hops) { - const bad = noPayoutSet(); if (!bad.size || !id) return 0; - let cur = Number(id); - for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; } - return 0; -} -// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a -// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account) -// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now). -async function resolveSponsorDetailed(tok) { - const t = String(tok || '').trim().toLowerCase(); - if (!t) return { id: 0, reason: 'none' }; - if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' }; - let acct = await accounts.byCode(t); - if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/ - if (!acct) return { id: 0, reason: 'unknown', name: t }; - if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t }; - try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; } - catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; } -} -async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; } -// 2026-09-16 (Marty): a buyer is never held up because their sponsor has not activated. Walk the -// site's sponsor line upward to the first upline who can be paid on-chain (activated, payouts on, -// not on the no-payout list); none -> the catch position (#1, Marty's top). The referral then follows -// the money: sponsorSyncOnEvent re-points the buyer's account to whoever was paid once the position exists. -async function walkUpActivatedSponsor(tok) { - const skipped = []; const seen = new Set(); - const t = String(tok || '').trim().toLowerCase(); - let acct = await accounts.byCode(t); if (!acct) acct = await accounts.byUsername(t); - for (let hop = 0; acct && hop < 25 && !seen.has(acct.email); hop++) { - seen.add(acct.email); - const name = acct.username ? '@' + acct.username : acct.email.replace(/@.*/, '') + '@'; - let id = 0; - if (acct.address) { try { id = await chain.memberIdByAccount(acct.address); } catch (e) { return { id: 0, name: null, skipped, reason: 'rpc' }; } } - if (id && !(await payoutChainBlocked(id, 2))) return { id, name, skipped, reason: 'ok' }; - skipped.push({ email: acct.email, name }); - acct = await accounts.sponsorOf(acct.email); - } - return { id: 0, name: null, skipped, reason: 'none' }; -} -// The feed line for a walk-up: who had not switched on payouts, whose referral (and purchase, when the -// activation and the buy share a tx) routed past them, and who it belongs to now. -async function postWalkUp(buyerId, oldRef, toId, pur) { - const sc = siteConfig(); if (!sc.telegramBotToken || (!sc.telegramChatId && !sc.telegramEchoChatId)) return; - const lostAcct = await refAccount(oldRef); if (!lostAcct) return; - const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@'; - const nm = await accounts.namesForMembers([buyerId, toId]).catch(() => ({})); - const who = id => '#' + id + (nm[id] ? ' @' + nm[id] : ''); - const site = 'https://instantadpay.com/my'; - const what = pur ? who(buyerId) + "'s $" + Math.round(pur.priceCents / 100) + ' purchase routed past them' : who(buyerId) + ' switched on payouts and their position routed past them'; - const missed = '\u{1F62C} Missed sale: ' + lostName + ' had not switched on payouts, so ' + what + '. That member, and every payout from them, now belongs to ' + who(toId) + '.' - + '\nTwo minutes on the Wallet tab prevents this: ' + site.replace(/^https:\/\//, '') + ''; - if (sc.telegramChatId && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {}); - if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {}); -} -// The referral follows the money (Marty, 2026-09-16): when a position is created on-chain under a -// different sponsor than the account's stored referrer (walk-up past an unactivated sponsor, or the -// catch-position fallback), move the account to the sponsor that actually got paid, #1 included. -async function sponsorSyncOnEvent(ev) { - if (!ev || ev.type !== 'MemberActivated' || !ev.account) return; - const acct = await accounts.byAddress(ev.account); if (!acct) return; - if (acct.address && acct.address.toLowerCase() !== String(ev.account).toLowerCase()) return; // a linked extra position, not the main wallet - const onchain = Number(ev.sponsorId) || 0; if (!onchain) return; - const spAcct = await accounts.byMemberId(onchain); - if (spAcct && spAcct.email === acct.email) return; // never self-sponsor an account - const cur = acct.sponsorRef ? (await resolveSponsorDetailed(acct.sponsorRef)).id : 0; - if (cur === onchain) return; - const ref = spAcct && spAcct.code ? spAcct.code : String(onchain); - const old = acct.sponsorRef || ''; - await accounts.setSponsorRef(acct.email, ref); - movedByTx.set(ev.tx, { buyerId: Number(ev.id) || 0, toId: onchain, oldRef: old, at: Date.now(), posted: true }); // posted below, at activation; the Purchase branch stays quiet - // Post it now (Marty, 2026-09-21): the post used to wait for a Purchase in the same tx, so an activation that - // came first (switch on payouts, buy later) was never posted. The activation is the fact; it goes out here. - try { const pur = chain.recentEvents(1e9).find(x => x.tx === ev.tx && x.type === 'Purchase') || null; await postWalkUp(Number(ev.id) || 0, old, onchain, pur); } catch (e) { console.error('walk-up post', e.message); } - if (movedByTx.size > 200) { const k = movedByTx.keys().next().value; movedByTx.delete(k); } - console.log('referral moved to where the pay landed:', acct.email, JSON.stringify(old), '->', ref, '(#' + onchain + ')'); - // Notices, now that it is a fact on the chain (Marty, 2026-09-16): everyone between the stored - // referrer and the paid sponsor who was simply not activated is told they lost this referral for - // good; the sponsor who was paid is told they gained it and should coach the one who missed it. - try { - const nameOf = a => a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@'; - const toName = spAcct ? nameOf(spAcct) : 'the company (#' + onchain + ')'; - const lost = []; const seen = new Set(); - let x = await refAccount(old); - while (x && !seen.has(x.email) && (!spAcct || x.email !== spAcct.email) && lost.length < 25) { - seen.add(x.email); - let activated = false; if (x.address) { try { activated = !!(await chain.memberIdByAccount(x.address)); } catch (e) { activated = true; } } - if (!activated) lost.push(x); // an activated-but-excluded (no-payout) sponsor is an admin matter, not a "switch on payouts" lesson - x = await accounts.sponsorOf(x.email); - } - for (const l of lost) sponsorHoldNudge(l.email, acct.email, toName).catch(() => {}); - if (spAcct && lost.length) sponsorGainNudge(spAcct, nameOf(acct), lost.map(nameOf)).catch(() => {}); - } catch (e) { console.error('sponsor move notices', e.message); } -} -const movedByTx = new Map(); // tx -> { buyerId, toId, oldRef } for purchases routed past an unactivated sponsor -async function refAccount(ref) { - const t = String(ref || '').trim().toLowerCase(); if (!t) return null; - let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); - if (!a && /^\d+$/.test(t)) a = await accounts.byMemberId(Number(t)); - return a || null; -} -const sponsorGainLast = new Map(); // sponsor email|buyer -> ts -async function sponsorGainNudge(sp, buyerName, lostNames) { - if (!sp || !sp.email) return; - const key = sp.email + '|' + buyerName; if (sponsorGainLast.has(key)) return; sponsorGainLast.set(key, Date.now()); - const who = lostNames.length === 1 ? lostNames[0] : lostNames.slice(0, -1).join(', ') + ' and ' + lostNames[lostNames.length - 1]; - const subject = buyerName + ' is now in your line for good (' + who + ' had not switched on payouts)'; - const lines = [ - buyerName + ' just bought an ad package on InstantAdPay. They came in through ' + who + ', but ' + (lostNames.length === 1 ? who + ' had' : 'they had') + ' not linked a wallet and switched on payouts, so the contract could not pay ' + (lostNames.length === 1 ? 'them' : 'any of them') + '. It walked up your line and paid you at level 1 instead.', - 'That is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + buyerName + ' is in your line on the chain from now on: this purchase and every one after it pays you as their level 1. They now show under you in My line.', - 'The lesson to pass down: ' + who + ' just lost a referral they worked for because payouts were off. Take two minutes with them, help them link a wallet and switch on payouts (Wallet tab, one free signature and one small transaction), and show them how to check it. Every leader in this line who teaches that step keeps their people from losing the next one.', - 'My line: https://instantadpay.com/my#line' - ]; - const text = lines.join('\n\n'); - if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {}); - try { - const html = lines.map(l => '

      ' + l.replace(/&/g, '&').replace(/$1') + '

      ').join(''); - await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'notice'); - } catch (e) {} -} -// Partner-code credits arrive as a drip (Marty, 2026-09-19): a fifth on the day the code is -// redeemed, then a fifth on each day the member finishes their daily ad set, five days in all, -// nothing after 30 days. Same headline number for the partner to promote; paid only to people -// who show up. Member-funded codes charge the funder one installment at a time. -async function payPromo(email, day) { - return promos.payDue(email, day, async (r, amount, n) => { - if (r.funder && r.funder !== email) { - const ok = await ads.spendEarned(r.funder, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ' funded for ' + email + ' (day ' + n + ' of ' + promos.STEPS + ')' } }); - if (!ok) { console.log('promo funder short', r.code, r.funder); return false; } - } - await ads.addEarned(email, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ': ' + amount + ' of ' + r.credits + ' (day ' + n + ' of ' + promos.STEPS + ')' } }); - return true; - }); -} -// anti-fraud admin alert (Telegram admin chat, else email): who, which flags, and whether the sign-up was blocked -// Send as a specific bot, for operational alerts that should arrive from Marty's own Hermes bot -// rather than from the member-facing InstantAdPay one. -function tgSendAs(token, chatId, text, threadId) { - return new Promise(resolve => { - const body = JSON.stringify(Object.assign({ chat_id: String(chatId), text, parse_mode: 'HTML', disable_web_page_preview: true }, - threadId ? { message_thread_id: Number(threadId) } : {})); - const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + token + '/sendMessage', method: 'POST', timeout: 12000, - headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, - r => { r.resume(); resolve(r.statusCode === 200); }); - rq.on('error', () => resolve(false)); - rq.on('timeout', () => { rq.destroy(); resolve(false); }); - rq.end(body); - }); -} -// Help desk pings (2026-10-16): Marty's PRIVATE Telegram chat only, never a group, topic or feed. tgSendAs skips the -// Discord relay entirely. Site bot (telegramBotToken) first, Marty's Hermes bot if that one cannot reach him. -async function supportTelegram(text, ref) { - // the dedicated support bot (two-way: buttons + replies) goes first; the old one-way path stays as the fallback - if (supportbot.enabled() && await supportbot.ping(text, ref)) return true; - const sc = siteConfig(); - const chat = String(sc.supportTelegramChat || '1289244227').trim(); - if (!/^\d{4,15}$/.test(chat)) { console.error('support ping refused: supportTelegramChat must be a private chat id (positive number), not', chat); return false; } - let ok = false; - const site = String(sc.telegramBotToken || '').trim(), hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); - if (site) ok = await tgSendAs(site, chat, text); - if (!ok && hermes) ok = await tgSendAs(hermes, chat, text); - if (!ok) console.error('support ping not delivered (chat ' + chat + ', site bot ' + (site ? 'set' : 'missing') + ', hermes ' + (hermes ? 'set' : 'missing') + ')'); - return ok; -} -// Public support form + signed-out chatbot hand-off: the sign-up guard's walls (honeypot, form age, per-IP limits with the -// icon check once tripped, a global cap) plus a hard per-email cap. Returns null to allow, or { status, body }. -const SUPPORT_LIMITS = { ipHour: 5, ipDay: 15, emailHour: 3, emailDay: 8, globalPerMin: 20, minFormMs: 2000 }; -const supportHits = new Map(); // 'ip:' | 'em:' | 'tk:' -> [timestamps, 24h] -const supportChal = new Map(); // ip -> { chal, passUntil } -const supportGlobal = { minute: 0, n: 0 }; -const supportRecent = (k, ms) => { const now = Date.now(); const t = (supportHits.get(k) || []).filter(ts => now - ts < 86400000); supportHits.set(k, t); return t.filter(ts => now - ts < ms).length; }; -const supportMark = k => { const t = supportHits.get(k) || []; t.push(Date.now()); supportHits.set(k, t); if (supportHits.size > 5000) for (const [kk, v] of supportHits) if (!v.length || Date.now() - v[v.length - 1] > 86400000) supportHits.delete(kk); }; -const supportFlood = (k, n, ms) => { if (supportRecent(k, ms) >= n) return true; supportMark(k); return false; }; // signed-in and private-link replies: a plain cap -function supportGuard(req, b, email) { - const now = Date.now(); - const hpRaw = String(b.hp_field_x9 || '').trim(); - const hp = !!hpRaw && hpRaw.toLowerCase() !== email; // own email = phone autofill, not a bot - const fts = Number(b.fts) || 0; - const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1); - if (fage < SUPPORT_LIMITS.minFormMs) { guardLog(req, 'support form-age', b); return { status: 400, body: { error: 'Give the page a few seconds, then send again.' } }; } - if (fage > 12 * 3600 * 1000) { guardLog(req, 'support form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then send again.' } }; } - const minute = Math.floor(now / 60000); - if (supportGlobal.minute !== minute) { supportGlobal.minute = minute; supportGlobal.n = 0; } - if (supportGlobal.n >= SUPPORT_LIMITS.globalPerMin) { guardLog(req, 'support global-limit', b); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } - if (supportRecent('em:' + email, 3600000) >= SUPPORT_LIMITS.emailHour || supportRecent('em:' + email, 86400000) >= SUPPORT_LIMITS.emailDay) { - guardLog(req, 'support email-limit', b); - return { status: 429, body: { error: 'You have sent several tickets already. Reply on the one you have open (the link is in your confirmation email) and Marty will see it there.' } }; - } - const ip = clientIp(req); - const limited = hp || supportRecent('ip:' + ip, 3600000) >= SUPPORT_LIMITS.ipHour || supportRecent('ip:' + ip, 86400000) >= SUPPORT_LIMITS.ipDay; - const rec = supportChal.get(ip) || { chal: null, passUntil: 0 }; - if (limited && now >= rec.passUntil) { - const pick = String(b.pick || ''); - if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } - else { guardLog(req, pick ? 'support wrong-pick' : hp ? 'support honeypot-challenge' : 'support ip-limit', b); const challenge = codeChallenge(rec); supportChal.set(ip, rec); if (supportChal.size > 5000) supportChal.clear(); return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send it.', challenge } }; } - supportChal.set(ip, rec); - } - supportGlobal.n += 1; supportMark('ip:' + ip); supportMark('em:' + email); - return null; -} -// LinkSpin partner calls (registry rows, help desk): one secret both ways, LS_SYNC_SECRET, as X-LS-Ts (ms) + X-LS-Sig = -// hex HMAC-SHA256(ts + newline + raw body), 10-minute window. Resolves { body } or { status, error }. -async function readLsSigned(req, maxBytes) { - const secret = String(process.env.LS_SYNC_SECRET || '').trim(); if (secret.length < 32) return { status: 503, error: 'sync not configured' }; - const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > maxBytes) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); - const ts = String(req.headers['x-ls-ts'] || ''), sig = String(req.headers['x-ls-sig'] || ''); - if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' }; - const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); - if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' }; - try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; } -} -function fraudAlert(email, fc, spAcct, blocked) { - try { - const sc = siteConfig(); - const text = (blocked ? '\u26D4 InstantAdPay sign-up BLOCKED: ' : '\u{1F6A9} InstantAdPay sign-up flagged: ') + String(email).replace(/^(.{2}).*(@.*)$/, '$1***$2') - + ' [' + (fc.flags || []).join(', ') + ']' + (fc.ip ? ' ip ' + fc.ip : '') + (spAcct ? ' sponsor ' + (spAcct.username ? '@' + spAcct.username : spAcct.email) : '') + '. Admin > Members > Duplicate signals.'; - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: sign-up ' + (blocked ? 'blocked' : 'flagged'), text).catch(() => {}); - } catch (e) {} -} -const sponsorRoutedLast = new Map(); // buyer email -> ts (one alert per buyer per hour) -function sponsorRoutedAlert(who, spd, routed, skipped) { - const k = String(who || '?'); if (Date.now() - (sponsorRoutedLast.get(k) || 0) < 3600000) return; sponsorRoutedLast.set(k, Date.now()); - const text = '\u2934\uFE0F InstantAdPay heads-up: ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + ' is at checkout. Their sponsor ' + (spd.name || '?') - + ' has not switched on payouts, so if this purchase goes through it pays ' + routed.to + ' instead.' + (skipped.length > 1 ? ' Also skipped: ' + skipped.map(x => x.name).join(', ') + '.' : '') - + ' Nothing has been paid yet; the on-chain result posts to Telegram when the sale settles.'; - const sc = siteConfig(); - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay heads-up: a checkout will route past an unactivated sponsor', text).catch(() => {}); - // the skipped sponsor and the one who gains are told by sponsorSyncOnEvent, once the position exists on the chain -} -const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour) -function sponsorBlockedAlert(who, r) { - const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now()); - const text = '\u26A0\uFE0F InstantAdPay: purchase held for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be resolved (' + r.reason + '), so the buy was blocked instead of crediting the company. ' + (r.reason === 'notActivated' ? 'The sponsor needs to switch on payouts.' : r.reason === 'rpc' ? 'Chain lookup failed; they can retry.' : 'Check the sponsor field in Admin > Members.'); - const sc = siteConfig(); - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: purchase held, sponsor unresolved', text).catch(() => {}); - // and the sponsor themselves (Marty, 2026-09-15): a buy is waiting on them, once an hour at most - if (r.reason === 'notActivated') sponsorHoldNudge(String(r.tok || ''), k).catch(() => {}); -} -const sponsorNudgeLast = new Map(); // sponsor email -> ts -async function sponsorHoldNudge(tok, buyerEmail, routedTo) { - const t = String(tok || '').trim().toLowerCase(); if (!t) return; - let sp = t.includes('@') ? await accounts.byEmail(t) : null; - if (!sp) sp = await accounts.byCode(t); if (!sp) sp = await accounts.byUsername(t); - if (!sp || !sp.email) return; - if (Date.now() - (sponsorNudgeLast.get(sp.email) || 0) < 3600000) return; sponsorNudgeLast.set(sp.email, Date.now()); - const buyer = await accounts.byEmail(buyerEmail); const bn = buyer && buyer.username ? '@' + buyer.username : 'One of your referrals'; - const step = !sp.address ? 'link a wallet and switch on payouts' : 'switch on payouts'; - const subject = routedTo - ? 'You lost ' + bn + ' to ' + routedTo + ' (payouts were not switched on)' - : bn + ' is trying to buy. ' + (sp.address ? 'Switch on payouts' : 'Link your wallet') + ' so it pays you'; - const lines = routedTo ? [ - 'You just lost a sale. ' + bn + ' is buying an ad package on InstantAdPay right now, and because payouts are not switched on for your account, the contract cannot pay you. The purchase is paying ' + routedTo + ' instead.', - 'This is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + bn + ' now belongs to ' + routedTo + ', has moved out of your line, and will never pay you from that wallet. Nothing can bring that referral back.', - 'The next one does not have to go the same way. Open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Two minutes, and every purchase in your line from then on pays you the moment it happens.', - 'Wallet tab: https://instantadpay.com/my#wallet' - ] : [ - bn + ' just tried to buy an ad package on InstantAdPay, and the purchase is on hold because payouts are not switched on for your account yet. The contract pays your share in the same transaction, but only to a wallet that is switched on, so the site paused the buy instead of sending your 50 percent to someone else.', - 'To fix it: open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Takes two minutes, and every purchase in your line from then on pays you the moment it happens.', - 'Until then their purchase waits, and they have been told why.', - 'Wallet tab: https://instantadpay.com/my#wallet' - ]; - const text = lines.join('\n\n'); - if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {}); - try { - const html = lines.map(l => '

      ' + l.replace(/&/g, '&').replace(/$1') + '

      ').join(''); - await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'alert'); - } catch (e) {} -} -// The moment someone joins through a code, nudge its owner to activate. -// Email a member's sponsor the moment they get a new referral (free OR paid). -// Resolves the sponsor from the join token by member id, share code, or username, -// and notifies EVERY sponsor — activated or not (an active sponsor still wants to -// know their team grew). A referral is on the line from signup; it only counts -// toward qualification once it makes a $20+ purchase. -async function notifyNewReferral(ref, newAcct) { - try { - if (!mailer.hasKey()) return; - const t = String(ref || '').trim().toLowerCase(); - if (!t) return; - let owner = null; - if (/^\d+$/.test(t)) { try { owner = await accounts.byMemberId(Number(t)); } catch (e) {} } - if (!owner) { try { owner = await accounts.byCode(t); } catch (e) {} } - if (!owner) { try { owner = await accounts.byUsername(t); } catch (e) {} } - if (!owner || !owner.email) return; - const who = newAcct && newAcct.username ? '@' + newAcct.username : 'A new member'; - let body = who + ' just joined InstantAdPay through your link — they are on your team from today.\n\n' - + 'They count toward your qualification once they make a $20+ purchase.\n\n'; - if (!owner.address) body += 'Make sure payouts are switched on (one free wallet step) so you never miss a commission — ' - + 'the contract locks each buyer to their sponsor at their first purchase.\n\n'; - body += 'See your team: https://instantadpay.com/my\n\nInstantAdPay'; - mailer.send(owner.email, 'You have a new referral on InstantAdPay', body) - .catch(e => console.error('referral notify failed', e.message)); - } catch (e) {} -} -// welcome email on a new account: onboarding steps + who their sponsor is -// how a member is named in emails/alerts: @username, a linked position named after its owner, else member #id -async function memberLabel(id) { - try { - let a = await accounts.byMemberId(id); - if (!a) { // brand-new buyer: the account learns its member id on its next page load, so read the - // wallet from the chain and match it now (Jim's purchase mailed as "member #25", 2026-09-13) - try { const m = await chain.member(id); if (m && m.account) { a = await accounts.byAddress(String(m.account).toLowerCase()); if (a && !a.memberId) accounts.setMemberId(a.email, id).catch(() => {}); } } catch (e) {} - } - if (a && a.username) return '@' + a.username; - const pos = await accounts.positionByMember(id); - if (pos && pos.email) { const o = await accounts.byEmail(pos.email); if (o && o.username) return '@' + o.username + ' (extra position #' + id + ')'; } - } catch (e) {} - return 'member #' + id; -} -async function sendWelcome(email, ref) { - try { - if (!mailer.hasKey()) return; - const spon = await accounts.sponsorOf(email); - const who = spon ? (spon.username ? '@' + spon.username : 'member #' + (spon.memberId || 0)) : ''; - const sponsorLine = who ? ('You joined through ' + who + ', your sponsor. They are there to help you get started, and you can message them anytime from your dashboard.\n\n') : ''; - mailer.send(email, 'Welcome to InstantAdPay', - 'Your free InstantAdPay account is ready.\n\n' + sponsorLine - + 'Getting started:\n' - + '1. Pick your username and fill out your profile.\n' - + '2. Grab your invite link and start sharing to build your line.\n' - + '3. Explore the ad packages when you are ready. Every payout settles on-chain, straight to your wallet.\n\n' - + 'Sign in anytime: https://instantadpay.com/my\n\nInstantAdPay').catch(() => {}); - } catch (e) {} -} -// on-chain event emails: a payout received, or a payout that passed you by -const weiToPol = w => { try { return (Number(BigInt(w) / (10n ** 14n)) / 10000).toString(); } catch (e) { return '?'; } }; -async function emailOnEvent(ev) { - if (!ev) return; - const notify = async (memberId, subject, body) => { - if (!memberId || !mailer.hasKey()) return; - const a = await accounts.byMemberId(memberId); - if (a && a.email) mailer.send(a.email, subject, body + '\n\nSee it on the live ledger: https://instantadpay.com/ledger\n\nInstantAdPay', null, { transactional: true }).catch(() => {}); // receipts + payouts: sent even after an unsubscribe - }; - // Marty (2026-09-15): payment and missed-payment notices also land in the on-site inbox, so - // they are waiting (login modal + Messages card) whether or not the email was read. Sent as - // the company account (#1), the same sender the credit-return notes used. Plain text in, HTML out. - const inboxNote = async (memberId, subject, text, kind) => { - if (!memberId) return; - try { - const a = await accounts.byMemberId(memberId); - if (!a || !a.email) return; - const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>') - .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; - await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); - } catch (e) {} - }; - const tell = async (memberId, subject, text, kind) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text, kind); }; - const PCT = { 1: 50, 2: 20, 3: 10 }; - // the Purchase event of the same tx is already indexed (it precedes every payout log), so the - // dollar side of any share is that purchase's price times the tier percentage - const purchaseOf = tx => { try { return chain.recentEvents(1e9).find(e => e.tx === tx && e.type === 'Purchase'); } catch (e) { return null; } }; - const usdShare = (pur, pct) => pur ? (' (about ' + ('$' + (pur.priceCents * pct / 10000).toFixed(2)).replace(/\.00$/, '') + ')') : ''; - const txUrlOf = tx => { const cc = chain.getConfig(); return (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + tx; }; - if (ev.type === 'Purchase') { - const cc = chain.getConfig(); - const txUrl = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; - let bal = ev.creditAmount; - try { bal = await chain.creditBalance(ev.buyerId, ev.creditType); } catch (e) {} - await notify(ev.buyerId, 'Your InstantAdPay purchase is confirmed', - 'Your purchase is complete and settled on-chain.\n\n' + - 'Ad credits added: ' + ev.creditAmount + '\n' + - 'Your ad-credit balance is now: ' + bal + '\n' + - 'Amount paid: ' + weiToPol(ev.paidWei) + ' POL\n\n' + - 'View your transaction on the blockchain:\n' + txUrl); - // tell the buyer's DIRECT sponsor their referral just bought (upline earners - // are separately notified by the TierPaid payout email when they earn) - try { - const buyer = await chain.member(ev.buyerId); - if (buyer && buyer.sponsorId) { - const sp = await accounts.byMemberId(buyer.sponsorId); - if (sp && sp.email) { - const bn = await memberLabel(ev.buyerId); // @username at a glance (Marty, 2026-09-12) - const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, ''); - const qual = ev.priceCents >= 2000 - ? ' This is a $20+ purchase, so it counts toward your qualification.' - : ' (Purchases under $20 do not count toward qualification.)'; - mailer.send(sp.email, bn + ' just bought a ' + usd + ' ad package', - 'Your referral ' + bn + ' (member #' + ev.buyerId + ') just purchased a package (' + usd + ' — ' + ev.creditAmount + ' credits).' + qual + '\n\n' + - 'See your team and the live ledger: https://instantadpay.com/my\n\nInstantAdPay').catch(() => {}); - } - } - } catch (e) {} - } - else if (ev.type === 'TierPaid') { - const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); - let buyer = 'a member on your level ' + ev.tier; try { buyer = await memberLabel(ev.buyerId); } catch (e) {} - const pol = weiToPol(ev.amountWei); - await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on InstantAdPay', - 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 dashboard: https://instantadpay.com/my'); - } - else if (ev.type === 'AwardPaid') await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on InstantAdPay', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my'); - 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 - await tell(ev.skippedId, 'Your wallet rejected a payout on InstantAdPay', 'A level-' + ev.tier + ' payout tried to reach your linked wallet and the wallet refused the transfer, so it passed to the next qualified member. This happens with some smart-contract wallets. Link a regular wallet address (MetaMask, SafePal, Phantom) on the Wallet tab so the next payout lands.\n\nTransaction: ' + txUrlOf(ev.tx)); - if (ADMIN_EMAIL) mailer.send(ADMIN_EMAIL, 'InstantAdPay: payout send-failed for member #' + ev.skippedId, 'A level-' + ev.tier + ' payout to member #' + ev.skippedId + ' failed at the wallet (send-failed) and passed up. Tx: ' + ev.tx + '\n\nThe member has been emailed to link a regular wallet.').catch(() => {}); - } - else if (ev.type === 'PassedUp') { - // Marty (2026-09-15): a member who missed a payout because they were not qualified must be told - // exactly what they missed: who bought, the share in POL and dollars, and how to close the gap. - const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); - let pol = '', buyer = 'a member on your level ' + ev.tier; - try { if (pur) pol = weiToPol((BigInt(pur.paidWei) * BigInt(pct) / 100n).toString()); buyer = await memberLabel(ev.buyerId); } catch (e) {} - let bc = 0; try { bc = (await chain.member(ev.skippedId)).buyerCount || 0; } catch (e) {} - const need = ev.tier === 3 ? 5 : 2, short = Math.max(0, need - bc); - const what = pol ? pol + ' POL' + usdShare(pur, pct) : 'a level-' + ev.tier + ' payout'; - await tell(ev.skippedId, 'You missed ' + (pol ? pol + ' POL' : 'a payout') + ' on InstantAdPay', - buyer + ' just bought an ad package on your level ' + ev.tier + '. Your share was ' + what + ', and it passed you by because level ' + ev.tier + ' is not open on your account yet. The contract paid it to the next qualified person above you.\n\n' + - 'Level ' + ev.tier + ' opens at ' + need + ' qualifying buyers (people you referred who bought a $20 or larger package). You have ' + bc + (short ? ', so you are ' + short + ' buyer' + (short === 1 ? '' : 's') + ' away.' : '.') + '\n\n' + - 'Two ways to close the gap: bring ' + (short || 1) + ' more buyer' + (short === 1 ? '' : 's') + ' from your My line page, or use Qualified Start under Buy packages to be your own buyer today. Every package on level ' + ev.tier + ' pays you ' + pct + ' percent once it is open, and the next one is coming whether you are ready or not.\n\n' + - 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my', 'alert'); - } -} -// payment-proof Telegram feed (same pattern as the RM Circle proof channel): one compact -// line per event, admin-configured under Settings > Site (telegramBotToken, telegramChatId, -// optional telegramTopicId, telegramEvents = payouts | payouts+purchases | all, telegramCtaUrl) -// A second target, telegramEchoChatId + telegramEchoTopicId (+ telegramEchoEvents), echoes -// the same lines into a shared cross-program payments topic that RM Circle also posts to, -// so every line there carries the program name. -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 who = id => '#' + id + (names[id] ? ' @' + names[id] : ''); - // a brand-new chain id is not mapped to its account yet when the activation lands, so the line read bare "#200" (Marty 2026-10-11): name them by wallet - if (ev.type === 'MemberActivated' && ev.id && !names[ev.id] && ev.account) { const a = await accounts.byAddress(ev.account).catch(() => null); if (a && a.username) names[ev.id] = a.username; } - const cc = chain.getConfig(); - const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; - const build = async (mode) => { - let line = null; - // Tier payouts and the purchase itself are no longer posted one by one: they are composed - // into ONE message on AdminPaid, the last event of every purchase tx, so the feed reads - // "who bought what, then who was paid" (Marty, 2026-09-25). In payouts mode a purchase that - // paid no member (root or unsponsored buyer) stays silent, as before. - if (ev.type === 'AdminPaid') { - const txEvents = chain.recentEvents(1e9).filter(x => x.tx === ev.tx); - const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'recipientId', 'skippedId']) if (x[k]) ids.add(x[k]); }); - const nm = await accounts.namesForMembers([...ids]).catch(() => ({})); - line = feedgroup.compose(txEvents, id => '#' + id + (nm[id] ? ' @' + nm[id] : ''), weiToPol, { requirePayout: mode === 'payouts' }); - } - 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 === 'AwardPaid') line = '\u{1F4B8} 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' : ''); - }; - // Missed-payout lines (Marty, 2026-09-16): when a share is passed over, say who missed it and who got it. - // (a) on-chain pass-up: the TierPaid with hops>0 follows the PassedUp events of the same tx, already indexed. - // (b) off-chain walk-up past an unactivated sponsor: recorded by sponsorSyncOnEvent, posted on the Purchase. - let missed = null; - try { - const site = 'https://instantadpay.com/my'; - // (a) on-chain pass-ups: AdminPaid is the last event of every purchase tx, so by then every - // PassedUp and TierPaid of the tx is indexed; one message shows the whole chain (missed.js). - if (ev.type === 'AdminPaid') { - const all = chain.recentEvents(1e9); - const txEvents = all.filter(x => x.tx === ev.tx); - if (txEvents.some(x => x.type === 'PassedUp')) { - const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'skippedId', 'recipientId']) if (x[k]) ids.add(x[k]); }); - const nm2 = await accounts.namesForMembers([...ids]).catch(() => ({})); - const who2 = id => '#' + id + (nm2[id] ? ' @' + nm2[id] : ''); - const had = (id, tier) => all.filter(y => y.type === 'BuyerCounted' && y.sponsorId === id && y.block < ev.block).length; - missed = missedNotice.composeMissed(txEvents, who2, had, site); - } - } - if (ev.type === 'Purchase' && movedByTx.has(ev.tx) && !movedByTx.get(ev.tx).posted) { // legacy path; walk-ups now post at activation - const mv = movedByTx.get(ev.tx); movedByTx.delete(ev.tx); - const lostAcct = await refAccount(mv.oldRef); - if (lostAcct) { - const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@'; - const nm3 = await accounts.namesForMembers([mv.toId]).catch(() => ({})); - missed = '\u{1F62C} Missed sale: ' + lostName + ' had not switched on payouts, so ' + who(ev.buyerId) + "'s $" + Math.round(ev.priceCents / 100) + ' purchase routed past them. That buyer, and every payout from them, now belongs to #' + mv.toId + (nm3[mv.toId] ? ' @' + nm3[mv.toId] : '') + ' for good.' - + '\nTwo minutes on the Wallet tab prevents this: ' + site.replace(/^https:\/\//, '') + ''; - } - } - } catch (e) { console.error('missed-payout post', e.message); } - // the main group used to get bare payout lines with no product name: nobody knew what they were from - const brand = t => '\u{1F7E0} InstantAdPay\n' + t; - if (sc.telegramChatId) { const t = await build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, brand(t), sc.telegramTopicId); if (missed && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {}); } - if (sc.telegramEchoChatId) { const t = await build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, brand(t), sc.telegramEchoTopicId); } - if (missed && sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {}); -} -// holding-tank arrivals -> one digest line in the shared payments topic (Marty, 2026-09-12): who is -// waiting for a sponsor, by username, so builders go adopt them. Runs every 15 min, posts only -// when someone new landed since the last check. -async function tankNotifyTick() { - const sc = siteConfig(); - if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; - const f = path.join(DATA_DIR, 'tank-notify.json'); - let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} - const since = st.last || (Date.now() - 24 * 3600 * 1000); - const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since); - st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st)); - if (!fresh.length) return; - const named = fresh.filter(w => w.username).map(w => '@' + w.username); - const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : ''; - const text = '\u{1FAA3} InstantAdPay \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who - + '\nAdopt from My line \u203a Holding tank: instantadpay.com/my'; - await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); -} -// one sendMessage call; never throws, never logs the token -async function telegramSend(chatId, text, threadId) { - const sc = siteConfig(); - if (!sc.telegramBotToken || !chatId) return; - discordRelay.mirror({ chatId, threadId, text }); - const body = JSON.stringify(Object.assign({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }, threadId ? { message_thread_id: Number(threadId) } : {})); - await new Promise((resolve) => { - const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, r => { - // say what happened: a feed that fails silently is indistinguishable from a quiet day (2026-09-25) - let raw = ''; r.setEncoding('utf8'); r.on('data', d => { raw += d; }); - r.on('end', () => { let j = null; try { j = JSON.parse(raw); } catch (e) {} - if (j && j.ok) console.log('tg-ok chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' message_id=' + (j.result && j.result.message_id)); - else console.error('tg-fail chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' http=' + r.statusCode + ' ' + ((j && j.description) || raw.slice(0, 160))); - resolve(); }); - }); - rq.on('error', e => { console.error('tg-fail chat=' + chatId + ' network: ' + e.message); resolve(); }); - rq.on('timeout', () => { console.error('tg-fail chat=' + chatId + ' timeout'); rq.destroy(); resolve(); }); rq.end(body); - }); -} - -// photo post (multipart) for the achievement badges (Marty, 2026-09-13); same bot, sendPhoto only -async function telegramSendPhoto(chatId, jpeg, caption, threadId) { - const sc = siteConfig(); - if (!sc.telegramBotToken || !chatId || !jpeg) return false; - discordRelay.mirror({ chatId, threadId, text: caption, photo: jpeg }); - const B = '----iapbadge' + crypto.randomBytes(8).toString('hex'); - const field = (n, v) => Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="' + n + '"\r\n\r\n' + v + '\r\n'); - const parts = [field('chat_id', String(chatId)), field('caption', caption), field('parse_mode', 'HTML')]; - if (threadId) parts.push(field('message_thread_id', String(Number(threadId)))); - parts.push(Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="photo"; filename="badge.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'), jpeg, Buffer.from('\r\n--' + B + '--\r\n')); - const body = Buffer.concat(parts); - return new Promise((resolve) => { - const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendPhoto', method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=' + B, 'Content-Length': body.length }, timeout: 20000 }, res => { - let out = ''; res.on('data', c => out += c); res.on('end', () => resolve(res.statusCode === 200)); - }); - rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body); - }); -} -const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'] }; -const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json'); -function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } } -// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the -// automatic Friday Game Pass perk; returns how many chats it reached (0 when already posted or not configured). -async function postBadgeOnce(email, key, note) { - const e = String(email || '').toLowerCase(); const log = badgeLog(); const mine = log[e] || {}; if (mine[key] || !BADGE_META[key]) return 0; - const a = await accounts.byEmail(e); if (!a) return 0; - const who = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member'); - const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; - const [label, sub] = BADGE_META[key]; - const caption = '\u{1F3C6} InstantAdPay · ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + (note ? ' · ' + note : '') + '\n' + link; - const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return 0; - mine[key] = { ts: Date.now(), sent: 0, auto: note || true }; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} // claim first: no double post - const sc = siteConfig(); let sent = 0; - if (sc.telegramBotToken && sc.telegramEchoChatId) { - if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; - if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; - } - mine[key].sent = sent; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} - pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); - console.log('badge posted (auto)', e, key, 'sent', sent); - return sent; -} -// Five Dollar Friday Game Pass perk (Marty 2026-10-23: "this should happen automatically every Friday"): a $5+ package on a -// Friday (the Friday bonus landed, so it qualified) also gives the buyer a free 7-day Game Pass, once per member per Friday. -// A purchase that itself started a paid pass gets no second week on top. The Game Pass badge posts only the first time a -// member ever holds a pass. Counts as no sale (comp). Switch: site setting fridayPassPerk '0' turns it off. -async function fridayPassPerk(ev, bonus, gp) { - if (!(Number(bonus) > 0) || gp) return null; - if (String(siteConfig().fridayPassPerk || '1') === '0' || !gamepass.cfg().enabled) return null; - const a = await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; - const ms = Number(ev.ts) > 1e12 ? Number(ev.ts) : (Number(ev.ts) > 0 ? Number(ev.ts) * 1000 : Date.now()); - const day = new Date(ms).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); - if (!(await marks.claim('fdfpass:' + day + ':' + a.email))) return null; // once per member per Friday, across app copies - const r = gamepass.comp(a.email, 'Five Dollar Friday perk ' + day, 'weekly'); - console.log('friday pass perk', a.email, day, 'until', new Date(r.until).toISOString()); - try { - const until = new Date(r.until).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Five Dollar Friday: a free Game Pass week', '

      Your Friday package came with a free 7-day Game Pass, on top of the Friday bonus credits. It runs until ' + until + ' Central, across all nine games.

      ', 'notice'); - } catch (e) { console.error('friday pass notice', e.message); } - try { await postBadgeOnce(a.email, 'gamepass', 'Five Dollar Friday'); } catch (e) { console.error('friday pass badge', e.message); } - return r; -} - -// ---- live feed (SSE) ---- -const feedClients = new Set(); -function pushFeed(ev) { - const line = 'data: ' + JSON.stringify(ev) + '\n\n'; - for (const res of feedClients) { try { res.write(line); } catch (e) { feedClients.delete(res); } } -} - -// ---- server ---- -// -- Drip Runner (2026-09-30): the hand-off, refuel visits and the signed callback to the game. -// Tokens share PolHunter's shape (base64url payload . base64url HMAC) under a separate secret. -const DR_SECRET = () => String(process.env.DR_SSO_SECRET || '').trim(); -const DR_URL = () => String(process.env.DR_URL || 'https://driprunner.saasy.top').replace(/\/+$/, ''); -const drB64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); -const drSign = payload => drB64u(crypto.createHmac('sha256', DR_SECRET()).update(payload).digest()); -function drMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + drSign(payload); } -function drOpen(token) { - if (DR_SECRET().length < 32) return { error: 'Drip Runner is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = drSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That refuel link has expired. Go back to the game and tap Refuel again.' }; - return { ok: true, claims: c }; -} -const refuelTokens = new Map(); // nonce -> { email, memberId, id, title, target, ts, ret, challenge, done } -async function drCallback(body) { - const raw = JSON.stringify(body); const ts = String(Date.now()); - const sig = crypto.createHmac('sha256', DR_SECRET()).update(ts + '\n' + raw).digest('hex'); - try { const r = await fetch(DR_URL() + '/api/refuel/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-DR-Ts': ts, 'X-DR-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } - catch (e) { console.warn('driprunner callback', e.message); return false; } -} - - -// -- Gem Kingdom (2026-10-01): sign-in hand-off + the Crown shop checkout. Same token shape as Drip Runner, its own -// secret GK_SSO_SECRET (also set on the game). The game mints a 'gk-buy' order; this site shows the member what it -// costs, spends the ad credits through ads.gamePurchase (credit log + on-chain burn like any flat buy), then signs a -// 'gk-receipt' back: as a redirect to the game AND as a server-to-server callback, so Crowns land even if they never return. -const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim(); -const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, ''); -const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest()); -function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gkSign(payload); } -function gkOpen(token) { - if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = gkSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That order has expired. Go back to Gem Kingdom and open the shop again.' }; - return { ok: true, claims: c }; -} -const gkOrders = persistedMap('gkorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts } -const gkEsc = s => String(s == null ? '' : s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch])); -function gkPage(res, code, title, inner, head) { - res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - res.end('' + gkEsc(title) + ' | InstantAdPay' + (head || '') - + '' - + '
      ' + inner + '
      '); -} -function gkFormBody(req) { return new Promise((ok, no) => { let d = ''; req.on('data', ch => { d += ch; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(new URLSearchParams(d))); req.on('error', no); }); } -const gkCookie = (k, v, maxAge) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + maxAge + (IS_PROD ? '; Secure' : ''); -// -- ClutterHunt (2026-10-03): seasonal hidden-object rooms at clutterhunt.com; its own secret SEEK_SSO_SECRET (also on the game) -const SEEK_SECRET = () => String(process.env.SEEK_SSO_SECRET || '').trim(); -const SEEK_URL = () => String(process.env.SEEK_URL || 'https://clutterhunt.com').replace(/\/+$/, ''); -const SEEK_ALT = () => String(process.env.SEEK_ALT_URLS || 'https://www.clutterhunt.com,https://clutterhunt.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); -const seekSign = p => drB64u(crypto.createHmac('sha256', SEEK_SECRET()).update(p).digest()); -function seekMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + seekSign(payload); } -// -- Shards of Valor (2026-10-18): multiplayer RPG at shardsofvalor.com; its own secret SOV_SSO_SECRET (also on the game). -// Same token shape as ClutterHunt; the Game Pass flag rides along (gpClaim). Not in the public games list until launch. -const SOV_SECRET = () => String(process.env.SOV_SSO_SECRET || '').trim(); -const SOV_URL = () => String(process.env.SOV_URL || 'https://shardsofvalor.com').replace(/\/+$/, ''); -const SOV_ALT = () => String(process.env.SOV_ALT_URLS || 'https://www.shardsofvalor.com,https://sov.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); -const sovSign = p => drB64u(crypto.createHmac('sha256', SOV_SECRET()).update(p).digest()); -function sovMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sovSign(payload); } -function seekOpen(token) { - if (SEEK_SECRET().length < 32) return { error: 'ClutterHunt is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = seekSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to ClutterHunt and tap Hint again.' }; - return { ok: true, claims: c }; -} -const seekIsGameUrl = u => [SEEK_URL()].concat(SEEK_ALT()).some(o => String(u || '').startsWith(o + '/')); -async function seekCallback(cbUrl, receipt) { - if (!seekIsGameUrl(cbUrl)) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('clutterhunt callback', e.message); return false; } -} -// -- SpellWheel (2026-10-04): the letter-wheel word game at spellwheel.com; its own secret SW_SSO_SECRET (also on the game) -const SW_SECRET = () => String(process.env.SW_SSO_SECRET || '').trim(); -const SW_URL = () => String(process.env.SW_URL || 'https://spellwheel.com').replace(/\/+$/, ''); -const SW_ALT = () => String(process.env.SW_ALT_URLS || 'https://www.spellwheel.com,https://spellwheel.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); -const swSign = p => drB64u(crypto.createHmac('sha256', SW_SECRET()).update(p).digest()); -function swMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + swSign(payload); } -function swOpen(token) { - if (SW_SECRET().length < 32) return { error: 'SpellWheel is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = swSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to SpellWheel and tap Hint again.' }; - return { ok: true, claims: c }; -} -const swIsGameUrl = u => [SW_URL()].concat(SW_ALT()).some(o => String(u || '').startsWith(o + '/')); -// -- PolyBreak (2026-10-13): the brick breaker; its own secret PB_SSO_SECRET (also on the game), same shape as SpellWheel -const PB_SECRET = () => String(process.env.PB_SSO_SECRET || '').trim(); -const PB_URL = () => String(process.env.PB_URL || 'https://polybreak.app').replace(/\/+$/, ''); -const PB_ALT = () => String(process.env.PB_ALT_URLS || 'https://www.polybreak.app,https://polybreak.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); -const pbSign = p => drB64u(crypto.createHmac('sha256', PB_SECRET()).update(p).digest()); -function pbMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pbSign(payload); } -function pbOpen(token) { - if (PB_SECRET().length < 32) return { error: 'PolyBreak is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = pbSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to PolyBreak and tap One more paddle again.' }; - return { ok: true, claims: c }; -} -const pbIsGameUrl = u => [PB_URL()].concat(PB_ALT()).some(o => String(u || '').startsWith(o + '/')); -async function pbCallback(cbUrl, receipt) { - if (!pbIsGameUrl(cbUrl)) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polybreak callback', e.message); return false; } -} -// -- PolyWarriors (2026-10-05): the cyberpunk fighting game at polywarriors.com; its own secret PW_SSO_SECRET (also on the game) -const PW_SECRET = () => String(process.env.PW_SSO_SECRET || '').trim(); -const PW_URL = () => String(process.env.PW_URL || 'https://polywarriors.com').replace(/\/+$/, ''); -const PW_ALT = () => String(process.env.PW_ALT_URLS || 'https://www.polywarriors.com,https://polywarriors.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); -const pwSign = p => drB64u(crypto.createHmac('sha256', PW_SECRET()).update(p).digest()); -function pwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pwSign(payload); } -async function swCallback(cbUrl, receipt) { - if (!swIsGameUrl(cbUrl)) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spellwheel callback', e.message); return false; } -} -const PW_MINT_COOKIE_S = 4 * 3600; // the dashboard "back to the mint" bar lives this long (was 7 days: people who looked at the price and left saw it for a week, Marty 2026-10-11) -// -- PolyWarriors paid mints (2026-10-05): the first mint is free in the game; later mints cost PW_MINT_CREDITS (100) from -// PURCHASED credits only (package credits on a position; earned credits never count, Marty's rule). The game signs an order -// with PW_SSO_SECRET (kind 'pw-mint'), the member confirms here, ads.gamePurchase(purchasedOnly) charges, and a signed -// receipt goes back to the game twice (server callback + redirect), whichever lands first. The game mints on the receipt. -function pwOpen(token) { - if (PW_SECRET().length < 32) return { error: 'PolyWarriors is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = pwSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: 'That mint order has expired. Tap Mint in PolyWarriors again.' }; - return { ok: true, claims: c }; -} -const pwPasses = persistedMap('pwpasses'); // email -> { n, earned, used, log: [{ at, d, why }] } -const pwPassN = e => ((pwPasses.get(e) || {}).n || 0); -function pwPassAdd(e, d, why) { const c = pwPasses.get(e) || { n: 0, earned: 0, used: 0, log: [] }; const v = { n: Math.max(0, c.n + d), earned: c.earned + Math.max(0, d), used: c.used + Math.max(0, -d), ts: Date.now(), log: [{ at: Date.now(), d, why }].concat(c.log || []).slice(0, 50) }; pwPasses.set(e, v); return v.n; } -const pwPrizes = persistedMap('pwprizes'); // 'YYYY-MM-DD:place' -> { email, credits, at } -const pwOrders = persistedMap('pworders'); // order -> { status: 'waiting'|'paid', email, serial, ret, cb, ts, tx, cents, delivered } -const pwIsGameUrl = x => [PW_URL()].concat(PW_ALT()).some(o => String(x || '').startsWith(o + '/')); -async function pwCallback(cbUrl, receipt) { - if (!pwIsGameUrl(cbUrl)) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polywarriors callback', e.message); return false; } -} -const pwReceipt = (order, o) => pwMint({ kind: 'pw-mint-receipt', order, email: o.email, serial: o.serial, paid: 5, usd: (o.cents || 500) / 100, ref: o.tx || null }, 3 * 86400000); -async function pwDeliver(order) { // the game mints on the receipt; retried each minute until the game says ok (up to a day) - const o = pwOrders.get(order); if (!o || o.status !== 'paid' || o.delivered) return; - const ok = await pwCallback(o.cb, pwReceipt(order, o)); - const cur = pwOrders.get(order); if (!cur) return; - pwOrders.set(order, Object.assign({}, cur, ok ? { delivered: Date.now() } : { tries: (cur.tries || 0) + 1 })); -} -setInterval(() => { for (const [k, o] of pwOrders) { if (o.status === 'paid' && !o.delivered && (o.tries || 0) < 1440) pwDeliver(k).catch(() => {}); if (o.status === 'waiting' && Date.now() - o.ts > 7 * 86400000) pwOrders.delete(k); } }, 60000).unref(); -async function pwMintOnEvent(ev) { // a package bought while a mint waits earns one mint pass per $5; waiting mints use them first - if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null; - const a = (!IS_PROD && ev.devEmail) ? { email: ev.devEmail } : await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; // devEmail: local tests only - const e = String(a.email).toLowerCase(), when = ev.ts || Date.now(), seen = pwPasses.get(e) || {}; - if ((seen.log || []).some(x => x.why === 'buy:' + ev.tx)) return null; // each purchase counts once - const waiting = [...pwOrders.entries()].filter(([k, o]) => o.status === 'waiting' && o.email === e && o.ts <= when + 60000).sort((x, y) => y[1].ts - x[1].ts); // newest first: the warrior the member just tapped Mint on gets the first pass (an old forgotten order took Marty's on 10-06) - if (!waiting.length) return null; // passes come from packages bought for minting - const earned = Math.floor(ev.priceCents / 500); pwPassAdd(e, earned, 'buy:' + ev.tx); - const used = []; - for (const [k, o] of waiting) { if (pwPassN(e) < 1) break; pwPassAdd(e, -1, 'mint:' + k); pwOrders.set(k, Object.assign({}, o, { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() })); used.push(k); } - console.log('polywarriors mint passes', e, '+' + earned, 'from tx', String(ev.tx).slice(0, 12), 'used', used.length, 'left', pwPassN(e)); - for (const k of used) await pwDeliver(k); - return { earned, used, left: pwPassN(e) }; -} -async function gkCallback(cbUrl, receipt) { - if (!String(cbUrl || '').startsWith(GK_URL() + '/')) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; } -} - -// -- Spooky Doors (2026-10-02, the Halloween season game): sign-in hand-off, door visits and the costume shop. Same token -// shape as Drip Runner and Gem Kingdom under its own secret SD_SSO_SECRET (also set on the game, at least 32 characters). -// A door is a verified visit of its own kind ('door', own daily cap doorCapPerDay, never touching refuel or Earn counts). -// The game hears about it twice: a signed server-to-server callback AND a signed receipt on the redirect back, whichever -// lands first. Costumes are bought with ad credits through ads.gamePurchase, exactly like Gem Kingdom Crowns. -const SD_SECRET = () => String(process.env.SD_SSO_SECRET || '').trim(); -const SD_URL = () => String(process.env.SD_URL || 'https://spookydoors.com').replace(/\/+$/, ''); -const SD_SEASON = { start: '2026-10-04', end: '2026-11-01' }; // Central days, end exclusive (through Halloween night); start moved up from 10-17 (Marty, 2026-10-02) -const sdGoldenBonus = () => { const n = Number(ads.rates().goldenBonusCandy); return Number.isFinite(n) && n >= 0 ? Math.round(n) : 2; }; // extra candy on a Golden Door -const sdSign = p => drB64u(crypto.createHmac('sha256', SD_SECRET()).update(p).digest()); -function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sdSign(payload); } -function sdOpen(token, expiredMsg) { - if (SD_SECRET().length < 32) return { error: 'Spooky Doors is not connected yet.' }; - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - const want = sdSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || 'That link has expired. Go back to Spooky Doors and try again.' }; - return { ok: true, claims: c }; -} -// -- Road Agent (2026-10-07): the same door round trip under its own secret; a fuel stop is a door with game: 'roadagent' -const RA_SECRET = () => String(process.env.RA_SSO_SECRET || '').trim(); -const RA_URL = () => String(process.env.RA_URL || 'https://roadagent.app').replace(/\/+$/, ''); -const DOOR_GAMES = () => ({ spookydoors: { name: 'Spooky Doors', secret: SD_SECRET(), url: SD_URL(), hdr: 'SD', back: 'Go back to Spooky Doors and knock again.' }, - roadagent: { name: 'Road Agent', secret: RA_SECRET(), url: RA_URL(), hdr: 'RA', back: 'Go back to Road Agent and fuel up again.' } }); -const gSign = (g, p) => drB64u(crypto.createHmac('sha256', g.secret).update(p).digest()); -function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gSign(g, payload); } -// open a door token from whichever game signed it: { ok, claims, game } or { error } -function doorOpen(token, expiredMsg) { - const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; - let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } - let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } - const G = DOOR_GAMES(); const key = G[c.game] ? c.game : 'spookydoors'; const g = G[key]; - if (!g.secret || g.secret.length < 32) return { error: g.name + ' is not connected yet.' }; - const want = gSign(g, payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; - if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || ('That link has expired. ' + g.back) }; - return { ok: true, claims: c, game: key }; -} -const gameUrlOk = (key, x) => String(x || '').startsWith(DOOR_GAMES()[key].url + '/'); -async function gameCallback(key, body) { // door done -> the game's server, signed over ts + newline + raw body - const g = DOOR_GAMES()[key]; const raw = JSON.stringify(body); const ts = String(Date.now()); - const sig = crypto.createHmac('sha256', g.secret).update(ts + '\n' + raw).digest('hex'); - const h = { 'Content-Type': 'application/json' }; h['X-' + g.hdr + '-Ts'] = ts; h['X-' + g.hdr + '-Sig'] = sig; - try { const r = await fetch(g.url + '/api/door/callback', { method: 'POST', headers: h, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } - catch (e) { console.warn(key + ' callback', e.message); return false; } -} -const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id, title, target|videoUrl, host, ts, ret, challenge, done, doneRet } -const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts } -const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/'); -const sdJoin = (ret, q) => ret + (String(ret).includes('?') ? '&' : '?') + q; // ret is SD_URL/play?door=, so this appends &... -async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host} (+ house, program on a house ad), X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody) - const raw = JSON.stringify(body); const ts = String(Date.now()); - const sig = crypto.createHmac('sha256', SD_SECRET()).update(ts + '\n' + raw).digest('hex'); - try { const r = await fetch(SD_URL() + '/api/door/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SD-Ts': ts, 'X-SD-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } - catch (e) { console.warn('spookydoors callback', e.message); return false; } -} -async function sdShopCallback(cbUrl, receipt) { - if (!sdIsGameUrl(cbUrl)) return false; - try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spookydoors shop callback', e.message); return false; } -} -// the visited campaign owner's public username ("+12 candy from @host"); null for house ads or members without one -async function sdHost(campaignId) { - try { const c = await ads.campaignById(campaignId); if (!c || !c.owner) return null; const a = await accounts.byEmail(String(c.owner).toLowerCase()); return (a && a.username) || null; } catch (e) { return null; } -} -// house ads (2026-10-02): when a door finds no visit pack and no video, one of Marty's own programs (rates.doorHouseAds) -// instead of "Nobody's home". Never the same one twice in a row for a member; otherwise the one least recently shown to -// them today. The player's own IAP username rides along where the program takes a share link (ref with {u}). -const doorHouse = persistedMap('doorhouse'); // email -> { ts, day, last, shown: { program: ts } } -function doorHouseList() { - const l = ads.rates().doorHouseAds; - return (Array.isArray(l) ? l : []).filter(x => x && String(x.name || '').trim() && /^https:\/\/[^\s"'<>]+$/i.test(String(x.url || ''))).slice(0, 20); -} -async function doorHousePick(email, claimedUsername) { - const list = doorHouseList(); if (!list.length) return null; - const day = todayCT(); const prev = doorHouse.get(email) || {}; const shown = prev.day === day ? Object.assign({}, prev.shown) : {}; - const pool = list.length > 1 ? list.filter(x => x.name !== prev.last) : list; - const h = pool.slice().sort((a, b) => (shown[a.name] || 0) - (shown[b.name] || 0))[0]; // never shown today sorts first, list order breaks ties - shown[h.name] = Date.now(); doorHouse.set(email, { ts: Date.now(), day, last: h.name, shown }); - let username = null; try { const a = await accounts.byEmail(email); username = (a && a.username) || null; } catch (e) {} - if (!username && claimedUsername) username = String(claimedUsername); - const withRef = username && /^[A-Za-z0-9_.-]{1,40}$/.test(username) && /^https:\/\/[^\s"'<>]*\{u\}/i.test(String(h.ref || '')); - return { name: String(h.name).trim().slice(0, 60), title: String(h.title || h.name).trim().slice(0, 120), target: withRef ? String(h.ref).replace('{u}', encodeURIComponent(username)) : String(h.url) }; -} -function sdPage(res, code, title, inner) { - res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - res.end('' + gkEsc(title) + ' | InstantAdPay' - + '' - + '' - + '
      ' + inner + '
      '); -} - - -// the generic season window (2026-10-02), shared by the Games card and the Promo tools card: 'live' while today (Central) is in -// [start, end), 'preview' before start for the admin only, 'hidden' otherwise (and for everyone from end on) -function seasonState(season, day, admin) { - if (!season) return 'live'; - if (day >= season.end) return 'hidden'; - if (day < season.start) return admin ? 'preview' : 'hidden'; - return 'live'; -} -// game testers: GAMES_TESTERS env = comma list of usernames or emails who may play coming-soon / not-yet-live games from the Games tab -const GAME_TESTERS = () => new Set(String(process.env.GAMES_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); -const isGameTester = (acct, email) => { const T = GAME_TESTERS(); if (!T.size) return false; return T.has(String((acct && acct.username) || '').toLowerCase()) || T.has(String(email || '').toLowerCase()); }; -// -- the games registry (2026-10-01). Add a game here; launch it by adding its slug to site config gamesLive. -function GAMES() { - return withPerks([ - { slug: 'spookydoors', name: 'Spooky Doors', tag: 'Halloween \u00b7 Oct 4 to 31', blurb: 'Trick or treat! Walk the street, knock on doors and fill your candy bucket. Every door is a short visit to a member\u2019s page or ad, and candy climbs a ladder with POL at set levels. Gone after Halloween night.', - art: SD_URL() + '/og-spookydoors.jpg', play: '/api/my/spookydoors', pays: 'POL at set candy levels', season: { start: SD_SEASON.start, end: SD_SEASON.end }, progress: sdProgress }, - { slug: 'roadagent', name: 'Road Agent', tag: 'Night highway shooter', blurb: 'Drive the night highway, shoot the hostiles that hunt you, spare the civilians. Fuel from a sponsor visit brings the weapons truck. Every sector you clear for the first time pays POL.', - art: RA_URL() + '/og-roadagent.jpg', play: '/api/my/roadagent', pays: 'POL for first sector clears and the daily patrol', progress: raProgress, - soon: { opens: '2026-10-15', label: 'Opens Thursday, Oct 15' } }, // Marty 2026-10-07: release Thu Oct 15; testers reach it by direct link meanwhile - { slug: 'driprunner', name: 'Drip Runner', tag: 'Arcade runner', blurb: 'Hop the network, dodge the bots, clear chapters. Each first clear drips POL into your game balance, and a refuel on a member\u2019s page keeps your run alive.', - art: DR_URL() + '/og-driprunner.jpg?v=20261002', artPos: 'left', play: '/api/my/driprunner', pays: 'POL to your wallet at 0.10', progress: drProgress }, - { slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.', - art: GK_URL() + '/fantasy/og-gemkingdom.jpg?v=20261002', play: '/api/my/gemkingdom', cta: 'Play', pays: 'POL for first clears; Crowns from ad credits' }, - { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt', blurb: 'Hunt hidden codes on sites across the network. Every find drips POL straight to your wallet.', - art: 'https://polhunter.com/img/hero-800.webp', play: '/api/my/polhunter', pays: 'POL per find' }, - { slug: 'clutterhunt', name: 'ClutterHunt', tag: 'Hidden objects', blurb: 'Search cozy, cluttered rooms for hidden objects. New rooms every season, starting with the Haunted Manor.', - art: SEEK_URL() + '/og-clutterhunt.jpg?v=c2', play: '/api/my/clutterhunt', pays: 'POL for first clears and 3-star clears' }, - // coming soon (2026-10-04, Marty: "build some anticipation... show that it's coming soon and put the date"): every member sees - // the card with its date and no Play button until `soon.opens` (Central); from then it is an ordinary card, live via gamesLive - { slug: 'spellwheel', name: 'SpellWheel', tag: 'Word game', blurb: 'Swipe the letter wheel to fill the crossword, travel through six cozy places, and solve a new daily puzzle with everyone. Clear levels and chapters to earn POL.', - art: SW_URL() + '/og-spellwheel.jpg?v=1', play: '/api/my/spellwheel', pays: 'POL for levels, chapters and daily puzzles', soon: { opens: '2026-10-10', label: 'Opens Saturday, Oct 10' } }, - // PolyWarriors (Marty 2026-10-05: "put Poly Warriors there as well, saying that it's coming next Monday") - { slug: 'polywarriors', name: 'PolyWarriors', tag: 'Cyberpunk fighting', blurb: 'Turn-based fights with collectible low-poly warriors. Recruit fighters born with rare traits, climb the arena, challenge other members, and mint your warriors as NFTs.', - art: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.jpg', video: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.mp4', play: '/api/my/polywarriors', pays: 'POL for first wins over arena rivals', soon: { opens: '2026-10-12', label: 'Opens Monday, Oct 12' } }, // live 10-12: trailer poster + 16:9 trailer on the public games page - // PolyBreak (2026-10-13): the brick breaker; first round clears and the purple Polygon gem pay POL - { slug: 'polybreak', name: 'PolyBreak', tag: 'Brick breaker', blurb: 'Break walls of glass jewel bricks with the classic arcade capsules, and catch the purple Polygon gem when it falls. First clears of each round pay POL.', - art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak-clean.jpg', play: '/api/my/polybreak', pays: 'POL for first round clears and gem catches' }, - ]); -} -// each game's member perk (the $5 welcome offer, 2026-10-05) shown on its card -const withPerks = list => { const st = starter.cfg(); return list.map(g => starter.GAMES[g.slug] && st.on ? Object.assign({}, g, { perk: starter.GAMES[g.slug].perk }) : g); }; -// -- cross-promo strip (2026-10-03): one short line per game and where a signed-out player lands (the game's own page) -const STRIP = () => ({ - spookydoors: { line: 'Halloween only. Run the graveyard, knock on doors, climb the candy ladder to POL.', open: SD_URL() + '/play', host: SD_URL().replace(/^https?:\/\//, '') }, - roadagent: { line: 'Night highway. Shoot the hostiles, clear sectors, get paid in POL.', open: RA_URL() + '/', host: RA_URL().replace(/^https?:\/\//, '') }, - driprunner: { line: 'Hop, dodge the bots, clear chapters. Every first clear drips POL.', open: DR_URL() + '/play', host: DR_URL().replace(/^https?:\/\//, '') }, - gemkingdom: { line: 'Match gems, beat the bosses, rebuild your kingdom. First clears pay POL.', open: GK_URL() + '/play', host: GK_URL().replace(/^https?:\/\//, '') }, - polhunter: { line: 'Find hidden codes on sites across the network. Every find drips POL.', open: 'https://polhunter.com/', host: 'polhunter.com' }, - clutterhunt: { line: 'Search cozy, cluttered rooms for hidden objects. New rooms every season.', open: SEEK_URL() + '/', host: SEEK_URL().replace(/^https?:\/\//, '') }, - polybreak: { line: 'Break the glass jewel wall, catch the capsules and the purple Polygon gem. First clears pay POL.', open: PB_URL() + '/', host: PB_URL().replace(/^https?:\/\//, '') }, - spellwheel: { line: 'Swipe the letter wheel, fill the grid, solve the daily puzzle. Levels and dailies pay POL.', open: SW_URL() + '/', host: SW_URL().replace(/^https?:\/\//, '') }, - polywarriors: { line: 'Recruit one-of-a-kind warriors, fight the arena, challenge members. First wins pay POL.', open: PW_URL() + '/', host: PW_URL().replace(/^https?:\/\//, '') }, -}); -// live for the strip: in gamesLive, and a seasonal game until its season ends (Marty 2026-10-03: Spooky Doors may show before -// its formal announcement; "if someone manages to see it and play it, that's fine") -function stripGames() { - const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); - const day = todayCT(), S = STRIP(); const lbl = d => { const t = new Date(d + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; - return GAMES().filter(g => live.has(g.slug) && S[g.slug] && !(g.season && day >= g.season.end)) - .map(g => ({ slug: g.slug, name: g.name, tag: g.season ? 'Limited time \u00b7 ends ' + lbl(g.season.end) : g.tag, line: S[g.slug].line, art: g.art, artPos: g.artPos || 'center', seasonal: !!g.season })); -} - -// -- PassiveDrip hand-off (2026-10-01): same token shape as Drip Runner, its own secret (PD_SSO_SECRET, also stored in -// PassiveDrip's site_config iap_sso_secret). PassiveDrip signs the member in or creates the account, carries the sponsor -// over by email, and OFFERS the wallet with one confirm tap; it never writes or overwrites a payout address silently. -const PD_SECRET = () => String(process.env.PD_SSO_SECRET || '').trim(); -const PD_URL = () => String(process.env.PD_URL || 'https://passivedrip.com').replace(/\/+$/, ''); -function pdMint(claims) { const payload = JSON.stringify(Object.assign({ aud: 'passivedrip', iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(16).toString('hex') }, claims)); return drB64u(payload) + '.' + drB64u(crypto.createHmac('sha256', PD_SECRET()).update(payload).digest()); } -async function pdProgress(memberId, email) { - const j = await pdsync.member(memberId, email); if (!j) return null; - if (!j.exists) return { line: 'No PassiveDrip account yet. Open it and one is made for you.' }; - const coins = Math.floor(Number(j.coins) || 0); - return { line: '@' + j.username + ' · ' + coins.toLocaleString('en-US') + ' of ' + Number(j.threshold || 2000).toLocaleString('en-US') + ' coins' + (j.hasWallet ? '' : ' · no payout wallet yet') + (j.paidPol ? ' · ' + Number(j.paidPol).toFixed(2) + ' POL paid out' : '') }; -} -// the player's own line on the Drip Runner card, read from the game with a signed request -async function drProgress(memberId) { - if (DR_SECRET().length < 32) return null; - const ts = String(Date.now()); const sig = crypto.createHmac('sha256', DR_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); - const r = await fetch(DR_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); - if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; - return { line: 'Chapter ' + j.chapter + ' \u00b7 ' + Number(j.unpaid).toFixed(3) + ' POL in your game balance' + (j.paidTotal ? ' \u00b7 ' + Number(j.paidTotal).toFixed(3) + ' POL paid out' : '') }; -} - -// the player's own line on the Road Agent card (signed, like the others) -async function raProgress(memberId) { - if (RA_SECRET().length < 32) return null; - const ts = String(Date.now()); const sig = crypto.createHmac('sha256', RA_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); - const r = await fetch(RA_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); - if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; - return { line: (Number(j.bestDist || 0) / 1000).toFixed(2) + ' km best \u00b7 ' + Number(j.sectors || 0) + ' sector' + (Number(j.sectors) === 1 ? '' : 's') + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') }; -} -// the player's own line on the Spooky Doors card, read from the game with a signed request (same scheme as Drip Runner) -async function sdProgress(memberId) { - if (SD_SECRET().length < 32) return null; - const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SD_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); - const r = await fetch(SD_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); - if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; - const cap = ads.rates().doorCapPerDay || 15; - return { line: Number(j.candy || 0).toLocaleString('en-US') + ' candy \u00b7 ' + Number(j.doorsToday || 0) + ' of ' + cap + ' doors today' + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') }; -} - -// -- in-game sign-in (Marty, 2026-10-03: "an integrated sign-on that never leaves the game"). The game's own /signin -// page calls these endpoints straight from the player's browser (CORS, no cookies), so the sign-up guard and the -// one-account-per-person checks see the player's real connection. Same email code, same guard and the same account -// as the dashboard; the answer is the game's hand-off token instead of a session cookie, plus a GAME PASS (signed -// here, kept by the game in localStorage, 30 days) that lets the game's "open InstantAdPay" nudges arrive signed in -// (POST /api/game/enter). The IAP device cookie cannot ride a cross-site request, so the game sends its own -// browser id (req.gameDev) for the device checks. -// frames: false = that game's page CSP (default-src 'self', no frame-src) refuses iframes, so its login ad opens in a new tab -const GAME_AUTH = { - driprunner: { name: 'Drip Runner', frames: false, origins: () => [DR_URL()], host: () => DR_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => drMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), wallet: a.address || null, username: a.username || null, - sponsorRef: a.sponsorRef || null, joinedRef: a.joinedRef || null, joinedAt: a.created || null }) }, - seek: { name: 'ClutterHunt', origins: () => [SEEK_URL()].concat(SEEK_ALT()), host: () => SEEK_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => seekMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, - polybreak: { name: 'PolyBreak', frames: false, origins: () => [PB_URL()].concat(PB_ALT()), host: () => PB_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => pbMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) }, - spellwheel: { name: 'SpellWheel', origins: () => [SW_URL()].concat(SW_ALT()), host: () => SW_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => swMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, - polywarriors: { name: 'PolyWarriors', origins: () => [PW_URL()].concat(PW_ALT()), host: () => PW_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => pwMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, - shardsofvalor: { name: 'Shards of Valor', frames: false, origins: () => [SOV_URL()].concat(SOV_ALT()), host: () => SOV_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => sovMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, - gemkingdom: { name: 'Gem Kingdom', origins: () => [GK_URL(), 'https://gemkingdom.saasy.top'], host: () => GK_URL().replace(/^https?:\/\//, ''), - mint: (a, memberId) => gkMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, -}; -// a game's one-tap link carries the inviter's ?ref to /my, where the viral-link rule sets the sponsor (2026-10-05: only Gem Kingdom and -// Spooky Doors passed it before; signed-out visitors from the other games lost their sponsor) -const refQ = u => { const r = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); return r ? '?ref=' + encodeURIComponent(r) : ''; }; -const devOrigin = o => !IS_PROD && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(o); -// the sign-in login ad, shared by the dashboard (GET /api/ads/slot?type=login) and the games' sign-in kit -// (GET /api/game/ads/login). ads.serve counts the impression and marks lastShownDay, exactly as before; the -// member clicks "Open Ad" (a real, counted click through /api/ads/click) while the countdown runs. Every call -// is tallied per Central day and surface (loginshows.js) so the admin can compare dashboard and game sign-ins. -async function loginAdFor(req, surface) { - const ad = await ads.serve('login', viewerGeo(req)); - let house = false; - if (ad) { - ad.dwell = ads.rates().loginDwellSeconds || 10; - // 2026-10-09: the gate frames the sponsor's page under our bar (timer + way out visible on the ad itself). - // Login campaigns were never frame-checked, so check here, once per campaign, and fall back to a new tab. - const site = await ads.targetOf(ad.id); - ad.siteUrl = site; - ad.frameable = await loginFrameable(ad.id, site, surface !== 'dashboard'); - try { const c = await ads.campaignById(ad.id); house = !!(c && (c.house || c.owner === ads.HOUSE_OWNER)); } catch (e) {} - } - loginShows.record(surface, ad ? { house } : null).catch(() => {}); - return ad; -} -function gameOf(req, slug) { - const g = Object.prototype.hasOwnProperty.call(GAME_AUTH, String(slug || '')) ? GAME_AUTH[slug] : null; if (!g) return null; - const o = String(req.headers.origin || ''); - return g.origins().includes(o) || devOrigin(o) ? g : null; -} -function gameCors(req) { - const o = String(req.headers.origin || ''); - const ok = Object.values(GAME_AUTH).some(g => g.origins().includes(o)) || devOrigin(o); - return ok ? { 'Access-Control-Allow-Origin': o, Vary: 'Origin', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'content-type', 'Access-Control-Max-Age': '600' } : { Vary: 'Origin' }; -} -let gamePassKey = ''; -function gamePassSecret() { - if (gamePassKey) return gamePassKey; - const f = path.join(DATA_DIR, 'game-pass.secret'); - try { gamePassKey = fs.readFileSync(f, 'utf8').trim(); } catch (e) {} - if (gamePassKey.length < 32) { gamePassKey = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, gamePassKey, { mode: 0o600 }); } catch (e) { console.error('game pass secret', e.message); } } - return gamePassKey; -} -const gamePassSign = p => drB64u(crypto.createHmac('sha256', gamePassSecret()).update(p).digest()); -function gamePassMint(email, game) { const p = JSON.stringify({ e: String(email).toLowerCase(), g: game, iat: Date.now(), exp: Date.now() + 30 * 86400000 }); return drB64u(p) + '.' + gamePassSign(p); } -function gamePassOpen(tok) { - const [p, sig] = String(tok || '').split('.'); if (!p || !sig) return null; - let payload; try { payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return null; } - const want = gamePassSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null; - let c; try { c = JSON.parse(payload); } catch (e) { return null; } - return c && c.e && c.exp > Date.now() ? c : null; -} -const gameDevOf = b => { const d = String((b && b.dev) || ''); return /^[a-f0-9]{32}$/.test(d) ? d : ''; }; -async function gameAnswer(g, slug, acct) { // the game token (only once a username exists) + a fresh pass - let memberId = acct.memberId || 0; - if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } - const needUsername = !acct.username; - return { ok: true, needUsername, username: acct.username || null, token: needUsername ? null : g.mint(acct, memberId), pass: gamePassMint(acct.email, slug) }; -} - -const SHARE_HOSTS = String(process.env.SHARE_HOSTS || 'ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); -const server = http.createServer(async (req, res) => { - { const t0 = Date.now(); res.on('finish', () => { const ms = Date.now() - t0; if (ms > 3000) console.warn('slow request', req.method, String(req.url || '').split('?')[0].slice(0, 80), ms + 'ms', res.statusCode); }); } // visibility for member-felt delays (2026-10-12) - try { - const u = new URL(req.url, 'http://x'); - const p = u.pathname; - // share-link domains (ctbgo.com, mylinehq.com): / goes to that member's join page, anything else to the same path - // here. 302 (not 301) so links never get pinned in caches; the query (?v= angle, ?promo=) rides along. - { const sh = String(req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, ''); - if (SHARE_HOSTS.includes(sh)) { - const ref = /^\/([A-Za-z0-9_]{1,40})\/?$/.exec(p); - const to = 'https://instantadpay.com' + (p === '/' ? '/' : ref ? '/join/' + ref[1] : p) + (u.search || ''); - res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end(); - } } - - // -- traffic log: public page views by referring domain (admin > Traffic) - if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']); - // -- viral links (Marty, 2026-09-21): ANY public page + ?ref= is that member's - // referral link. Same 30-day last-touch sponsor cookie as /join, the view counts under the - // "page" hook in link stats. Served IN PLACE, not redirected (2026-09-21): Facebook's crawler follows - // redirects and canonicalizes a share to og:url, so the redirect (and a clean og:url) dropped the member's - // name from every share. og:url now carries the ref; rel=canonical stays clean for search engines. - // /join, /from and the APIs keep their own meaning of ?ref. - if ((req.method === 'GET' || req.method === 'HEAD') && u.searchParams.has('ref') && !p.startsWith('/api/') && !p.startsWith('/admin') && !/^\/(join|from)\//.test(p) && !/\.[a-z0-9]{2,5}$/i.test(p)) { - const raw = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); - const tok = JOIN_ALIASES[raw] || raw; - u.searchParams.delete('ref'); - const clean = p + (u.searchParams.toString() ? '?' + u.searchParams.toString() : ''); - let known = false; - if (/^[a-z0-9_]{1,20}$/.test(tok)) { try { known = !!((await accounts.byCode(tok)) || (await accounts.byUsername(tok)) || (/^\d+$/.test(tok) && (await accounts.byMemberId(Number(tok))))); } catch (e) {} } - const set = []; - if (known) { - req.viralTok = tok; // later routes (bare /join) can use the sponsor even before the cookie round-trips - const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; - set.push('iap.sponsor=' + tok + cookieTail); // last touch wins, exactly like /join - set.push('iap.angle=page' + cookieTail); // the join shows under the "any page" hook - if (!parseCookies(req)['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source - if (req.method === 'GET') coach.recordView(tok, 'page', req.headers.referer); - } - if (known) { - const wh = res.writeHead.bind(res); let html = false; - res.writeHead = function (code, headers) { - headers = Object.assign({}, headers || {}); - if (set.length) headers['Set-Cookie'] = [].concat(headers['Set-Cookie'] || [], set); - html = /text\/html/i.test(String(headers['Content-Type'] || '')); if (html) delete headers['Content-Length']; - return wh(code, headers); - }; - const end = res.end.bind(res); - res.end = function (chunk, enc, cb) { - if (html && chunk) { - let s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk); - s = s.replace(/( a + url + (url.includes('?') ? '&' : '?') + 'ref=' + encodeURIComponent(tok) + c); - return end(s, 'utf8', cb); - } - return end(chunk, enc, cb); - }; - } - req.url = clean; // the routes below see the clean path; u already has the ref removed - } - // -- join links: /join/ — LAST-touch cookie (Marty, - // 2026-09-10): the link a visitor opened most recently is the sponsor shown - // and used, and it locks the moment the account is created (accounts.ensure - // never changes an existing account's sponsor; the contract binds the buyer at - // their first purchase). Codes resolve LATE (at buy time) to whatever chain id - // the referrer has by then, so free members refer from day one. - // Bare /join (Diann 2026-10-11: the games page's "Join free" and the Friday/Wednesday pages linked to /join and got - // "Not found"): send the visitor to the sponsored join page. ?ref= has already been folded into the iap.sponsor cookie by - // the viral-link handler above, so the cookie decides; nobody known -> the company position, like the partner kit. - if ((p === '/join' || p === '/join/') && (req.method === 'GET' || req.method === 'HEAD')) { - const clean = s => String(s || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); - const refQ = clean(u.searchParams.get('ref') || req.viralTok); const spon = (refQ && (JOIN_ALIASES[refQ] || refQ)) || clean(parseCookies(req)['iap.sponsor']); // ?ref= wins, then the cookie - u.searchParams.delete('ref'); const qs = u.searchParams.toString(); - res.writeHead(302, baseHeaders({ Location: '/join/' + (spon || 'company') + (qs ? '?' + qs : ''), 'Cache-Control': 'no-store' })); return res.end(); - } - let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'HEAD')) { - // lead-capture page: email first, wallet later. ?v= picks the hook - // copy and is remembered so the account records which angle converted. - // partner placement: instantadpay.com/join/company (or /top) places the visitor directly under - // member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit) - const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase(); - const cookies = parseCookies(req); - const angle = String(u.searchParams.get('v') || '').toLowerCase(); - const ang = JOIN_ANGLES[angle] || null; - if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source - const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit - const set = []; - set.push('iap.sponsor=' + tok + cookieTail); // last touch wins - if (u.searchParams.get('from') === 'polhunter') set.push('iap.return=polhunter' + cookieTail); // came through a PolHunter share link: send them back after the wallet step - if (u.searchParams.get('from') === 'driprunner') set.push('iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=7200' + (IS_PROD ? '; Secure' : '')); // a Drip Runner share link: back into the game once they have a username - const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup - if (promo) { const pref = String(req.headers.referer || '').replace(/^https?:\/\//, '').split('/')[0].toLowerCase().slice(0, 80); if (pref) set.push('iap.promoref=' + encodeURIComponent(pref) + cookieTail); } // which partner page it came from - if (ang) set.push('iap.angle=' + angle + cookieTail); - // First-touch source. A PolHunter share link carries ?from=polhunter in the URL itself, which - // survives the referrer being stripped (in-app browsers, a link pasted into chat). PolHunter - // pays a referral bounty only for people it actually sent, so that proof has to be reliable - // rather than dependent on a header (Marty, 2026-09-24: "not just members that come on board - // IAP and work their way over to POL Hunter"). - if (!cookies['iap.ref']) { - const host = u.searchParams.get('from') === 'polhunter' ? 'polhunter.com' : u.searchParams.get('from') === 'driprunner' ? 'driprunner.saasy.top' : coach.refHost(req.headers.referer); - set.push('iap.ref=' + encodeURIComponent(host) + cookieTail); - } - return serveJoinPage(res, tok, ang ? angle : '', ang, set); - } - // -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page - // with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding - // tank for adoption), the angle remembered so the welcome-back grant fires at signup, and - // a forced first-touch source so link stats / admin can see the legacy arrivals. - m = /^\/from\/(faucetwave|tieroneads|socialpix)$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'HEAD')) { - const brand = m[1]; - // SocialPix arrivals came to POST ads, so their default copy is the advertiser one (?seg=earn flips it); - // the closed EvolutionScript brands default to the earner copy (?seg=advertiser flips it). - const seg = String(u.searchParams.get('seg') || '').toLowerCase(); - const prefix = { faucetwave: 'fw', tieroneads: 't1', socialpix: 'sp' }[brand]; - const key = prefix + (brand === 'socialpix' ? (seg.startsWith('earn') ? '-earn' : '-adv') : (seg.startsWith('adv') ? '-adv' : '-earn')); - const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; - const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page - const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail]; - return serveJoinPage(res, '', key, JOIN_ANGLES[key], set); - } - if (p === '/unsubscribe' && (req.method === 'GET' || req.method === 'POST')) { // POST = RFC 8058 one-click from the mail client - const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t')); - const msg = r.error ? r.error : 'Done. You will not get any more emails from InstantAdPay, apart from sign-in codes you ask for and receipts for payments to or from your account. Your account is unchanged.'; - res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - return res.end('InstantAdPay
      InstantAdPay

      ' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

      ' + msg + '

      Member area

      '); - } - - // -- public API - if (p === '/api/friday' && req.method === 'GET') return json(res, 200, friday.view(), { 'Cache-Control': 'public, max-age=60' }); - // member welcome offer from the games: public numbers for the game cards, the member's own view, and the 'came from' mark - if (p === '/api/starter/public' && req.method === 'GET') return json(res, 200, starter.publicView(), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); - if (p === '/api/starter' && (req.method === 'GET' || req.method === 'POST')) { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (req.method === 'POST') { const b = await readBody(req); starter.setFrom(s.email, String(b.game || '')); } - const acct = await accounts.byEmail(s.email); - return json(res, 200, await starter.view(s.email, Number((acct && acct.memberId) || s.memberId || 0))); - } - if (p === '/api/wednesday' && req.method === 'GET') return json(res, 200, wednesday.view(), { 'Cache-Control': 'public, max-age=60' }); - if (p === '/api/admin/pdsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, pdsync.status()); } - if (p === '/api/admin/pdsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await pdsync.sync()); } - if (p === '/api/admin/wednesday-previews' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, wednesday.previews()); } - if (p === '/api/admin/wednesday/kick' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = await wednesday.kickNow(); return json(res, r.error ? 400 : 200, r); } - // -- the pages a member can turn into a viral link (promo tools > Viral links) - if (p === '/api/pages' && req.method === 'GET') { - const pages = [{ path: '/', title: 'Home page' }, { path: '/blog', title: 'Blog' }, { path: '/earning', title: 'How earning works' }, { path: '/games', title: 'Games that pay POL' }, { path: '/ledger', title: 'Live ledger' }, { path: '/leaderboard', title: 'Leaderboard' }, { path: '/contract', title: 'The contract' }, { path: '/plays', title: 'Team-building plays' }, { path: '/wallets', title: 'Wallet guide' }, { path: '/friday', title: 'Five Dollar Friday' }, { path: '/whats-new', title: "What's new" }, { path: '/shorts', title: 'Shorts' }, { path: '/presentation', title: 'The presentation (narrated video)' }]; - try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {} - return json(res, 200, { pages }); - } - if (p === '/api/config' && req.method === 'GET') { - const c = chain.getConfig(); - // public copy of the site settings: never anything that looks like a credential - const pubSite = {}; - for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies) - return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId, - chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0], - emailAuth: mailer.hasKey() || !IS_PROD }, pubSite)); - } - if (p === '/api/moonpay-url' && req.method === 'GET') { - // Card on-ramp deep link. With MoonPay keys set — PUBLIC key via - // MOONPAY_PUBLIC_KEY env or site config, SECRET key via MOONPAY_SECRET_KEY - // env ONLY (never site config, since /api/config exposes siteConfig) — - // returns a SIGNED checkout URL prefilled with the buyer's own wallet and - // a POL amount; otherwise a generic MoonPay buy page. Zero custody either - // way: MoonPay is merchant of record and the crypto goes straight to the - // buyer's wallet — this site never touches or holds anyone's money. - const addr = (u.searchParams.get('address') || '').trim(); - let pol = Math.round(Number(u.searchParams.get('pol')) || 0); - if (!pol || pol < 30) pol = 30; - if (pol > 100000) pol = 100000; - const pk = (process.env.MOONPAY_PUBLIC_KEY || siteConfig().moonpayPublicKey || '').trim(); - const sk = (process.env.MOONPAY_SECRET_KEY || '').trim(); - if (pk && sk && /^0x[0-9a-fA-F]{40}$/.test(addr)) { - const qs = '?apiKey=' + encodeURIComponent(pk) + '¤cyCode=pol_polygon&walletAddress=' + encodeURIComponent(addr) + '"eCurrencyAmount=' + pol; - const sig = crypto.createHmac('sha256', sk).update(qs).digest('base64'); - return json(res, 200, { url: 'https://buy.moonpay.com/' + qs + '&signature=' + encodeURIComponent(sig), signed: true, pol }); - } - return json(res, 200, { url: 'https://www.moonpay.com/buy/matic', signed: false, pol }); // MoonPay's Polygon page still lives at the old slug; /buy/pol renders their 404 (same fix as RM Circle) - } - if (p === '/api/catalog' && req.method === 'GET') { - // five live quotes per call: serve a 20-second cache so pages that load the - // ladder (join, home, buy) are not waiting on the RPC every time - // stale-while-revalidate (2026-10-19): serve the cached ladder at once and refresh it in the background after - // 20 s, one refresh at a time; only wait for a fresh read when there is none or it is over 2 minutes old - const age = catalogCache.at ? Date.now() - catalogCache.at : Infinity; - if (age > 20000 && !catalogCache.busy) { - catalogCache.busy = chain.catalog().then(pr => { catalogCache.products = pr; catalogCache.at = Date.now(); }) - .catch(e => console.error('catalog refresh', e.message)).finally(() => { catalogCache.busy = null; }); - } - if (!catalogCache.products || age > 120000) { - try { await catalogCache.busy; } catch (e) {} - if (!catalogCache.products) throw new Error('catalog unavailable'); - } - return json(res, 200, { products: catalogCache.products }); - } - if (p === '/api/feed' && req.method === 'GET') { - return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) }); - } - if (p === '/api/feed/live' && req.method === 'GET') { - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' })); - res.write(': connected\n\n'); - feedClients.add(res); - req.on('close', () => feedClients.delete(res)); - return; - } - m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p); - if (m && req.method === 'GET') { - // tx relay so the browser never talks to the RPC directly (CSP stays 'self'). - // Serves both the wallet's waitTx poll (found/status) and the built-in - // /tx/ viewer (full details + decoded events). - try { - const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]); - if (!r) return json(res, 200, { found: false }); - const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed }; - try { - const t = await chain.rpc('eth_getTransactionByHash', [m[1]]); - if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); } - } catch (e) {} - try { - const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]); - if (blk) out.ts = blk.timestamp; - } catch (e) {} - try { - out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean) - .map(ev => Object.assign(ev, { tx: m[1] }))); - } catch (e) { out.events = []; } - return json(res, 200, out); - } catch (e) { return json(res, 200, { found: false, rpcError: true }); } - } - if (p === '/api/sponsor' && req.method === 'GET') { - // The account's stored sponsor is authoritative — it persists across - // devices, cleared cookies, and return visits. Fall back to the first-touch - // cookie only for anonymous visitors with no account sponsor yet. (Reading - // the cookie alone was orphaning buyers to root when the cookie was absent.) - const s = await auth.fromRequest(req); - const acct = s && s.email ? await accounts.byEmail(s.email) : null; - const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || ''; - const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id; - let sponsorBlocked = null; // set only for transient/unknown failures now: the client refuses the transaction - let sponsorRouted = null; // set when an unactivated sponsor was walked past: the client tells the buyer, then proceeds - if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'notActivated') { - const w = await walkUpActivatedSponsor(tok); - if (w.reason === 'rpc') sponsorBlocked = 'rpc'; - else { - const catchId = Number(siteConfig().defaultSponsorId) || 1; - sponsorId = w.id; - sponsorRouted = { from: spd.name || null, to: w.id ? w.name : 'the company (#' + catchId + ')', toId: w.id || catchId, skipped: w.skipped.map(x => x.name) }; - if (u.searchParams.get('intent') === 'buy') sponsorRoutedAlert(acct.email, spd, sponsorRouted, w.skipped); // the dashboard's display-only pre-check never alerts (Marty, 2026-09-21) - } - } else if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; if (u.searchParams.get('intent') === 'buy') sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); } - if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; } - // orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands - // the new member under the configured catch position (#1) instead of root - if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1; - let name = null, avatarUrl = null, own = false; - // the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own - // sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13) - let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase(); - if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok]; - const nameTok = showTok || tok; - if (nameTok) { - const t = nameTok.toLowerCase(); - let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); - if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok)); - if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} } - } - // "You're joining the line of X" must only greet someone who is actually about to - // join. The last-touch sponsor cookie lives 30 days, so an EXISTING member who once - // clicked a teammate's link was being told on the sign-in page that logging in would - // place them under that person (Marty, 2026-09-17). Alarming, and untrue: their - // sponsor locked at their first purchase and nothing here can move it. - // Show it when they just arrived through a link (?ref= in the URL), or when the cookie - // is there AND this browser has never had an account. Attribution itself is untouched. - let invited = !!showTok; - if (!invited && tok) { try { invited = !(await fraud.hasAccountOnDevice(req)); } catch (e) { invited = true; } } - if (acct) invited = false; // already a member: they are not joining anybody's line - return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited, name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand }); - } - if (p === '/api/stats' && req.method === 'GET') { - let members = 0; try { members = await chain.memberCount(); } catch (e) {} - return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count() }, chain.totals())); - } - - // -- 24/7 assistant - if (p === '/api/chat' && req.method === 'POST') { - const ip = req.socket.remoteAddress || 'x'; - if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' }); - const b = await readBody(req); - const r = await chatbot.answer(b.message, b.history); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // qa/chatbot-sync.mjs: the newest knowledge-base change (Central day) and the entry count - return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' }); - } - - // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off - if (p === '/api/inbound/email' && req.method === 'POST') { // SendGrid Inbound Parse: secret key in the URL, always 200 once it matches - const k = inbound.key(); - if (!k || u.searchParams.get('k') !== k) { req.resume(); return json(res, 403, { error: 'forbidden' }); } - const chunks = []; let n = 0, tooBig = false; - await new Promise(done => { req.on('data', c => { n += c.length; if (n > 12e6) tooBig = true; else chunks.push(c); }); req.on('end', done); req.on('error', done); }); - if (tooBig) { console.log('inbound email: too big, dropped'); return json(res, 200, { ok: true }); } - try { console.log('inbound email:', await inbound.handle(Buffer.concat(chunks), req.headers['content-type'])); } catch (e) { console.error('inbound email', e.message); } - return json(res, 200, { ok: true }); - } - if (p === '/api/telegram/support' && req.method === 'POST') { // the support bot's webhook: secret header checked inside, always 200 - let b = {}; try { b = await readBody(req); } catch (e) {} - try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); } - return json(res, 200, { ok: true }); - } - if (p === '/api/support' && req.method === 'POST') { - const b = await readBody(req); - const s = await auth.fromRequest(req); - const acct = s && s.email ? await accounts.byEmail(s.email) : null; // signed in: the ticket is theirs, whatever was typed - const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' }); - if (!acct) { const iss = await newEmailIssue(email); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } // replies must reach them - const guard = supportGuard(req, b, email); - if (guard) return json(res, guard.status, guard.body); - const r = await tickets.create({ source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body }); - if (r.error) return json(res, 400, r); - return json(res, 200, { ok: true, ref: r.ticket.ref, token: r.token, member: !!acct }); - } - m = /^\/api\/support\/t\/([A-Za-z0-9_.-]{20,80})(\/reply)?$/.exec(p); - if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { - const t = await tickets.byToken(m[1]); - if (!t) return json(res, 404, { error: 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' }); - if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); - const b = await readBody(req); - if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); - const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: 'link' }); - return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); - } - if (p === '/api/support/chatbot' && req.method === 'POST') { - const b = await readBody(req); - const s = await auth.fromRequest(req); - const acct = s && s.email ? await accounts.byEmail(s.email) : null; - const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true }); - if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your dashboard to add to one.' }); } - else { const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); } - const tr = Array.isArray(b.transcript) ? b.transcript : []; - const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6); - const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim()); - const note = String(b.note || '').trim().slice(0, 2000); - const body = (note ? note + '\n\n' : '') + (turns.length ? 'From the chat assistant:\n' + turns.join('\n') : '(sent from the chat assistant)'); - const r = await tickets.create({ source: 'chatbot', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, category: 'Other', - subject: 'Chat: ' + (firstQ ? String(firstQ.text).replace(/\s+/g, ' ').trim().slice(0, 100) : 'question for support'), body }); - if (r.error) return json(res, 400, r); - return json(res, 200, { ok: true, ref: r.ticket.ref, member: !!acct, link: acct ? '/my#help?t=' + r.ticket.ref : '/support/t/' + r.token }); - } - - // -- accounts: email + password is the normal join path (wallet comes - // out only at purchase / payout-activation time and gets linked then) - if (p === '/api/signup' && req.method === 'POST') { - const b = await readBody(req); - if (fraud.isBlocked(b.email)) return json(res, 403, { error: 'This address cannot open an account.' }); - { const iss = await newEmailIssue(String(b.email || '').trim().toLowerCase()); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } - const pendS = pendingSponsor.get(String(b.email || '').trim().toLowerCase()); - const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pendS && pendS.ref) || ''; // last-touch attribution, locked at account creation - const r = await accounts.signup(b.email, b.password, ref); - if (r.error) return json(res, 400, r); - pendingSponsor.del(String(b.email || '').trim().toLowerCase()); - // sponsor is notified once the new member picks a username (onboarding), - // so the email can name them — see /api/my/profile - if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent - const token = await auth.mintSession({ email: r.account.email }); - return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); - } - if (p === '/api/login' && req.method === 'POST') { - const b = await readBody(req); - const r = await accounts.login(b.email, b.password); - if (r.error) return json(res, 400, r); - let memberId = 0; - if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} } - const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); - return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); - } - - // -- passwordless: email code sign-in (signup and login are the same act) - if (p === '/api/auth/email/start' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - const devHdr = fraud.deviceOf(req) ? undefined : { 'Set-Cookie': fraud.deviceCookie(fraud.newDeviceId(), IS_PROD) }; // browser id for one-account-per-person checks - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }); - if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }); - { const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } - const prev = emailCodes.get(e); - if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, devHdr); } - const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited - if (guard) return json(res, guard.status, guard.body, devHdr); - const code = String(Math.floor(100000 + Math.random() * 900000)); - emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); - { const ck = parseCookies(req); const bound = pageTok(b.ref) || ck['iap.sponsor'] || ''; - if (bound && !(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: bound, via: pageTok(b.ref) ? (String(b.angle || '').toLowerCase().slice(0, 20) || ck['iap.angle'] || 'page') : (ck['iap.angle'] || ''), joinedRef: decodeURIComponent(ck['iap.ref'] || '') || null }); } - if (mailer.hasKey()) { - try { await mailer.sendCode(e, code); } catch (err) { - console.error('sendCode failed', err.message); - return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, devHdr); - } - return json(res, 200, { ok: true, sent: true }, devHdr); - } - if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, devHdr); - return json(res, 503, { error: 'Email sign-in is not configured yet.' }); - } - if (p === '/api/auth/email/verify' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - const rec = emailCodes.get(e); - if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); - rec.tries += 1; - if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } - if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); - emailCodes.delete(e); - const pend = pendingSponsor.get(e); - const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pend && pend.ref) || ''; - const via = parseCookies(req)['iap.angle'] || (pend && pend.via) || ''; - const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || (pend && pend.joinedRef) || null; - if (ref && !parseCookies(req)['iap.sponsor']) console.log('sponsor recovered without cookie', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'ref', ref, pageTok(b.ref) ? '(page token)' : '(remembered from the code request)'); - if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }); - let fraudFlags = []; - const existing = await accounts.byEmail(e); - const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up - if (!existing || claim) { // anti-fraud checks apply to NEW accounts only (Marty, 2026-09-16: one account per person) - let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(String(ref).toLowerCase()); if (!spAcct) spAcct = await accounts.byUsername(String(ref).toLowerCase()); } catch (err) {} } - const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); - fraudFlags = fc.flags; - // an approved exception is worth a log line: it is the difference between "the guard - // is broken" and "Marty said yes to this person" - if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy); - if (fc.block) { console.log('signup blocked', fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }); } - } - const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged - if (r.error) return json(res, 400, r); - if (r.created) pendingSponsor.del(e); - if (claim) await claimShell(e, existing, ref); - if (r.created || claim) { fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } - else fraud.recordSeen(e, req).catch(() => {}); - // the lead is in the door: queue the getting-started sequence (opt-in box is pre-checked on both forms) - if (r.created && (b.followups || b.newsletter)) drip.enqueue(e, ref, via).catch(() => {}); - // a wallet-only session (signed with a wallet, no account) finishing setup: - // adopt that wallet into the email account so member #, purchases and - // payouts stay attached, then retire the wallet-only session - const prior = await auth.fromRequest(req); - if (prior && prior.address && !prior.email) { - const lr = await accounts.linkWallet(e, prior.address); - if (lr.error) return json(res, 400, lr); - r.account = lr.account || await accounts.byEmail(e); - await auth.logout(req); - } - if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile) - // partner promo code carried on the join link: redeem once per account (ignored if invalid/used) - try { - const pc = parseCookies(req)['iap.promo']; - if (pc) { - const pref = parseCookies(req)['iap.promoref'] ? decodeURIComponent(parseCookies(req)['iap.promoref']) : ''; - const g = await promos.redeem(pc, e, 'link', pref); - if (g.ok) { const paid = await payPromo(e, todayCT()); console.log('promo redeemed', g.code, 'day 1:', paid.map(x => x.amount).join('+') || 0, 'of', g.credits, e, pref ? 'from ' + pref : ''); } - } - } catch (err) { console.error('promo redeem', err.message); } - // legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once - if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) { - try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits, { log: { kind: 'grant', note: 'Welcome-back credits (' + g.brand + ')' } }); console.log('legacy grant', g.brand, g.seg, g.credits, e); } } - catch (err) { console.error('legacy grant', err.message); } - } - if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only - let memberId = 0; - if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} } - const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); - return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30) - } - - // -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies. - if (p.startsWith('/api/game/auth/') && req.method === 'OPTIONS') { res.writeHead(204, gameCors(req)); return res.end(); } - // the login ad inside a game's sign-in kit, after a fresh sign-in (2026-10-18). CORS only for the GAME_AUTH - // origins of the named game (dev mode: localhost); the dashboard route stays same-origin. - if (p === '/api/game/ads/login' && (req.method === 'GET' || req.method === 'OPTIONS')) { - const g = gameOf(req, u.searchParams.get('game')); - const cors = g ? Object.assign(gameCors(req), { 'Access-Control-Allow-Methods': 'GET, OPTIONS' }) : { Vary: 'Origin' }; - if (req.method === 'OPTIONS') { res.writeHead(204, cors); return res.end(); } - if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); - const ad = await loginAdFor(req, String(u.searchParams.get('game'))); - if (ad && g.frames === false) ad.frameable = false; - return json(res, 200, { ad }, cors); - } - if (p === '/api/game/auth/start' && req.method === 'POST') { - const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); - if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); - req.gameDev = gameDevOf(b); - const e = String(b.email || '').trim().toLowerCase(); - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }, cors); - if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }, cors); - { const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }, cors); } - const prev = emailCodes.get(e); - if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, cors); - const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited - if (guard) return json(res, guard.status, guard.body, cors); - const code = String(Math.floor(100000 + Math.random() * 900000)); - emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); - const ref = pageTok(b.ref); - const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); // paid-traffic source the game saw (2026-10-03) - if (!(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: ref || '', via: String(b.game), joinedRef: g.host() + (srcTag ? '/' + srcTag : '') }); - console.log('game-signin code', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'ref ' + ref : ''); - if (mailer.hasKey()) { - try { await mailer.sendCode(e, code); } catch (err) { console.error('sendCode failed', err.message); return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, cors); } - return json(res, 200, { ok: true, sent: true }, cors); - } - if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, cors); - return json(res, 503, { error: 'Email sign-in is not configured yet.' }, cors); - } - if (p === '/api/game/auth/verify' && req.method === 'POST') { - const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); - if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); - req.gameDev = gameDevOf(b); - const e = String(b.email || '').trim().toLowerCase(); - const rec = emailCodes.get(e); - if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }, cors); - rec.tries += 1; - if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); } - if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors); - emailCodes.delete(e); - if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors); - const pend = pendingSponsor.get(e); - const ref = pageTok(b.ref) || (pend && pend.ref) || ''; - const via = String(b.game); const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); - const joinedRef = (pend && pend.joinedRef) || (g.host() + (srcTag ? '/' + srcTag : '')); // e.g. driprunner.app/adsterra - let fraudFlags = []; - const existing = await accounts.byEmail(e); - const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up - if (!existing || claim) { // one account per person, exactly as on the dashboard - let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} } - const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); - fraudFlags = fc.flags; - if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy); - if (fc.block) { console.log('signup blocked (game)', b.game, fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }, cors); } - } - const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged - if (r.error) return json(res, 400, r, cors); - if (claim) { await claimShell(e, existing, ref); fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } - if (r.created) { - pendingSponsor.del(e); - fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); - if (b.newsletter) { drip.enqueue(e, ref, via).catch(() => {}); sendy.subscribe(e, '').catch(() => {}); } - sendWelcome(e, ref).catch(() => {}); - console.log('game-signin new account', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'sponsor ' + ref : 'no sponsor'); - } else fraud.recordSeen(e, req).catch(() => {}); - const acct = r.account || await accounts.byEmail(e); - return json(res, 200, Object.assign(await gameAnswer(g, b.game, acct), { created: !!r.created }), cors); - } - if (p === '/api/game/auth/username' && req.method === 'POST') { - const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); - if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); - const pass = gamePassOpen(b.pass); if (!pass) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors); - const before = await accounts.byEmail(pass.e); if (!before) return json(res, 404, { error: 'Account not found.' }, cors); - if (!before.username) { - const r = await accounts.setUsername(pass.e, b.username); - if (r.error) return json(res, 400, r, cors); - const acct = await accounts.byEmail(pass.e); // first username: the sponsor hears now, as from the dashboard - notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); - if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); - } - return json(res, 200, await gameAnswer(g, b.game, await accounts.byEmail(pass.e)), cors); - } - // remembered sign-in (2026-10-19): the kit's 29-day pass for this game becomes a fresh hand-off token, no code - if (p === '/api/game/auth/resume' && req.method === 'POST') { - const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); - if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); - const pass = gamePassOpen(b.pass); - if (!pass || (pass.g && pass.g !== b.game)) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors); - if (fraud.isSuspended(pass.e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors); - const acct = await accounts.byEmail(pass.e); if (!acct) return json(res, 404, { error: 'Account not found. Start again with your email.' }, cors); - return json(res, 200, await gameAnswer(g, b.game, acct), cors); - } - // the game's nudges ("Add your wallet", "Level up") post the pass here in a new tab: signed in on arrival - if (p === '/api/game/enter' && req.method === 'POST') { - let f; try { f = new URLSearchParams((await readRaw(req, 4096)).toString('utf8')); } catch (e) { f = new URLSearchParams(); } - const pass = gamePassOpen(f.get('p')); - const to = ['overview', 'wallet', 'buy', 'earn', 'promo', 'games', 'profile', 'campaigns'].includes(f.get('to')) ? f.get('to') : 'overview'; - if (!pass || fraud.isSuspended(pass.e)) { res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store' }); return res.end(); } - const acct = await accounts.byEmail(pass.e); if (!acct) { res.writeHead(303, { Location: '/my', 'Cache-Control': 'no-store' }); return res.end(); } - let memberId = acct.memberId || 0; - if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } - const token = await auth.mintSession({ email: acct.email, address: acct.address, memberId }); - res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store', 'Set-Cookie': auth.sessionCookie(token) }); return res.end(); - } - - // -- wallet auth: link-to-account when an email session exists, or - // wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session - // is walked to the email card, which adopts the wallet on verify) - if (p === '/api/auth/challenge' && req.method === 'POST') { - const b = await readBody(req); - const r = auth.makeChallenge(b.address); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/auth/verify' && req.method === 'POST') { - const b = await readBody(req); - const r = await auth.verifyChallenge(b.address, b.signature); - if (r.error) return json(res, 400, r); - let memberId = 0; - try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {} - const s = await auth.fromRequest(req); - if (s && s.email && b.asPosition) { - // Qualified Start: a second (third…) wallet on the same account. It becomes - // its own on-chain member under this member's id when it buys; the session - // stays on the main wallet. - // policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a - // wallet that is already registered on-chain under anything other than this account's main - // member is refused (a position-under-position chain would recapture 70% of a self-buy) - const MAX_POS = 5; - const have = await accounts.positions(s.email); - if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS) - return json(res, 400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' }); - if (memberId) { - const mainId = await auth.refreshMemberId(s); - let mm = null; try { mm = await chain.member(memberId); } catch (e) {} - if (mm && mainId && mm.sponsorId !== mainId) - return json(res, 400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' }); - } - const pr = await accounts.addPosition(s.email, r.address); - if (pr.error) return json(res, 400, pr); - if (memberId) await accounts.setPositionMember(r.address, memberId); - return json(res, 200, { ok: true, position: true, address: r.address, memberId }); - } - if (s && s.email) { - const lr = await accounts.linkWallet(s.email, r.address); - if (lr.error) return json(res, 400, lr); - await auth.updateSession(s.token, { address: r.address, memberId }); - return json(res, 200, { ok: true, linked: true, address: r.address, memberId, next: parseCookies(req)['iap.return'] === 'polhunter' ? '/api/my/polhunter' : null }); - } - const acct = await accounts.byAddress(r.address); - if (!acct && await accounts.positionOwner(r.address)) - return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' }); - const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId }); - return json(res, 200, { ok: true, address: r.address, memberId }, - { 'Set-Cookie': auth.sessionCookie(token) }); - } - if (p === '/api/auth/logout' && req.method === 'POST') { - await auth.logout(req); - return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() }); - } - if (p === '/api/gas' && req.method === 'GET') { - try { return json(res, 200, await chain.suggestedFees()); } - catch (e) { return json(res, 200, {}); } - } - - if (p === '/api/me' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 200, { signedIn: false }); - const memberId = await auth.refreshMemberId(s); - const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; - const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id; - let sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null; - let sponsorRouted = null; - if (sponsorBlocked === 'notActivated') { // never hold a buyer for an unactivated sponsor: walk up the line - const w = await walkUpActivatedSponsor(acct.sponsorRef); - if (w.reason === 'rpc') sponsorBlocked = 'rpc'; - else { sponsorBlocked = null; sponsorId = w.id; sponsorRouted = { from: spdMe.name || null, to: w.id ? w.name : 'the company', toId: w.id || (Number(siteConfig().defaultSponsorId) || 1) }; } - } - if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0; - const _defSpon = Number(siteConfig().defaultSponsorId) || 1; - if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) - if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); - const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null, - address: s.address || (acct && acct.address) || null, memberId, - username: (acct && acct.username) || null, - refCode: (acct && acct.code) || null, sponsorId, - // profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned) - avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null, - socials: (acct && acct.socials) || null, - wallOffers: parseWallOffers(acct), - lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null }; - if (memberId) { - try { - const mm = await chain.member(memberId); - out.buyerCount = mm.buyerCount; - out.onchainSponsorId = mm.sponsorId; - const bal = await ads.balances((await myMemberIds(s)).ids, s.email); - out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; - } catch (e) { out.chainReadError = true; } - } - return json(res, 200, out); - } - - if (p === '/api/my/dashboard' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; - if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); - let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12) - try { - if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() }; - const tw = tankWaitCache.list; - tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok }; - } catch (e) {} - const sc0 = siteConfig(); - const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null, - pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' }, - address: s.address || (acct && acct.address) || null, - username: (acct && acct.username) || null, - refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0, - earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 }; - if (out.email) { - // welcome credits unlock via the welcome tour when an upline with a - // line banner exists; members with no tour to walk get them instantly - const welcomed = await ads.welcomeGranted(out.email); - const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl); - if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add - else { out.welcomeCredits = 0; out.gauntletPending = true; } - } - if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too - if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor - accounts.touchSeen(out.email).catch(() => {}); - out.chatUnread = await messages.chatUnread(out.email); - out.chatAvailable = (acct && acct.chatAvailable !== false); - const spon = await accounts.sponsorOf(out.email); - if (spon && spon.email) out.sponsor = { - email: spon.email, - name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'), - online: (Date.now() - (spon.lastSeen || 0)) < 60000, - available: spon.chatAvailable !== false }; - } - if (out.email) { // the one modal that interrupts: a human broadcast, or a money-at-stake alert - const un = await messages.newestUnread(out.email); - if (un) { - const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {}; - out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body, kind: un.kind || 'broadcast', - fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') }; - } - } - if (memberId) { - try { - const mm = await chain.member(memberId); - out.buyerCount = mm.buyerCount; - const mine = await myMemberIds(s); - // linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14) - out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0; - for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} } - out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone - const bal = await ads.balances(mine.ids, s.email); - out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; - } catch (e) { out.chainReadError = true; } - let earned = 0n, n = 0; - for (const ev of chain.recentEvents(1e9)) { // whole history, not the last 600 - if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) { - earned += BigInt(ev.amountWei); n += 1; - } - } - out.earnedWei = earned.toString(); - out.earnCount = n; - } - // achievement milestones (same ladder as the Overview stepper) + one-time credit - // bonuses — computed AFTER buyerCount is read from chain above (else always 0) - { - const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0); - const reached = []; - if (out.memberId) reached.push('payouts'); - if (bc >= 1) reached.push('firstBuyer'); - if (bc >= 2) reached.push('level2'); - if (bc >= 5) reached.push('level3'); - try { if (out.memberId && friday.earnedBadge(out.memberId)) reached.push('fridays'); } catch (e) {} // five Five Dollar Fridays in a row - try { if (out.email && gamepass.flag(out.email).until) reached.push('gamepass'); } catch (e) {} // ever held a Game Pass (2026-10-22) - try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned - out.milestonesReached = reached; - if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached); - } - // who joined through this member: their invite link uses username when set, - // else code, and the numeric id once on-chain — match all three - const refs = []; - if (acct && acct.code) refs.push(acct.code); - if (acct && acct.username) refs.push(acct.username); - if (memberId) refs.push(String(memberId)); - const joined = await accounts.listByReferrer(refs); - const rTot = await ads.earnedTotals(joined.map(r => r.email)); // surf earnings per referral (Marty, 2026-09-29) - out.referrals = joined.map(r => ({ - name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask - joined: r.created, - lastSeen: r.lastSeen || 0, - wallet: !!r.address, activated: !!r.memberId, - earned: (rTot[r.email] || {}).earned || 0, balance: (rTot[r.email] || {}).balance || 0, - status: r.memberId ? 'payouts on' : r.address ? 'wallet linked' : 'joined free' - })); - out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link - out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own - return json(res, 200, out); - } - // -- linked positions (Qualified Start): list, refresh from chain, unlink - if (p === '/api/my/positions' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const acct = await accounts.byEmail(s.email); - const mainId = await auth.refreshMemberId(s); - const list = await accounts.positions(s.email); - const out = []; - const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean); - let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {} - // every position's chain reads run side by side (2026-10-19: one after another took 3-8 s for members with several) - out.push(...await Promise.all(list.map(async pos => { - let id = pos.memberId; - if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} } - const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created }; - if (id) { - const [mm, blocked] = await Promise.all([chain.member(id).catch(() => null), payoutChainBlocked(id, 3).catch(() => false)]); - if (mm) { row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; } - row.credits = balPer[id] != null ? balPer[id] : 0; - row.noPayout = blocked; // linkage only: a buy from here would pay a listed wallet - } - return row; - }))); - const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 }; - if (mainId) { - main.credits = balPer[mainId] != null ? balPer[mainId] : 0; - try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {} - main.noPayout = await payoutChainBlocked(mainId, 3); - } - // live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog - const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } }; - if (main.address) main.balanceWei = await bal(main.address); - for (const row of out) row.balanceWei = await bal(row.address); - let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} - return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited }); - } - if (p === '/api/my/positions/remove' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await accounts.removePosition(s.email, b.address); - return json(res, r.error ? 400 : 200, r); - } - // -- coaching: every direct's ladder rung, stalled flag, and what to say - // -- holding tank: waiting members, my adoptions, adopt, release (pay it forward) - // -- promo code typed on the dashboard - if (p === '/api/my/promo/redeem' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const g = await promos.redeem(b.code, s.email, 'dashboard', ''); - if (g.error) return json(res, 400, g); - const paid = await payPromo(s.email, todayCT()); - return json(res, 200, { ok: true, credits: g.credits, now: paid.reduce((n, x) => n + x.amount, 0), step: g.step, steps: g.steps, code: g.code, partner: g.partner }); - } - // -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet; - // PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13) - if (p === '/api/admin/member' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const q = u.searchParams.get('q') || u.searchParams.get('email') || ''; - const a = await adminMember.resolve(q); - if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' }); - return json(res, 200, Object.assign(await adminMember.view(a.email), { pwPasses: pwPasses.get(String(a.email).toLowerCase()) || null })); // mint passes on the card (2026-10-10) - } - if (p === '/api/admin/member' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); - if (!acct) return json(res, 404, { error: 'No such member.' }); - if (b.username !== undefined) { - const un = String(b.username || '').trim().toLowerCase(); - if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' }); - const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r); - console.log('admin username', e, un); - } - if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to LinkSpin until bound - if (b.address !== undefined) { - const a = String(b.address || '').trim().toLowerCase(); - if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' }); - const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r); - let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} } - await accounts.setMemberId(e, mid); - if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {}); - console.log('admin wallet swap', e, a || '(none)', 'member', mid); - } - if (b.grantCredits !== undefined) { - const n = Math.round(Number(b.grantCredits)); - if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' }); - // The member sees this note in their Credit activity, so let the reason travel with - // the grant. A correction that reads "granted by admin" explains nothing; one that - // names itself is the difference between a refund and a mystery (Marty, 2026-09-17). - const why = String(b.note || '').trim().slice(0, 120) || 'Credits granted by admin'; - // purchased: true returns PURCHASED credits (a refund of money the member paid) at purchase grade, so they keep their - // money value; without it the grant is ordinary earned credits (2026-10-04, the Shift AI refunds) - if (b.purchased === true) await ads.addEarned(e, n, { purchased: true, log: { kind: 'credit', note: why } }); - else await ads.addEarned(e, n, { log: { kind: 'grant', note: why } }); - console.log('admin credits', e, n, String(b.note || '').slice(0, 100)); - } - return json(res, 200, await adminMember.view(e)); - } - if (p === '/api/admin/member' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); - if (!acct) return json(res, 404, { error: 'No such member.' }); - if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' }); - const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' }); - const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r); - if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {}); - console.log('admin removed account', e); - return json(res, 200, { ok: true }); - } - // -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14) - if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView()); - // -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance - if (p === '/api/my/toolkit' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.status(s.email)); - } - if (p === '/api/my/toolkit/generate' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const memberId = await auth.refreshMemberId(s); - const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.split(s.email)); - } - if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.videos(s.email)); - } - if (p === '/api/my/toolkit/video' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.makeVideo(s.email, String(b.slug || '')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.team(s.email)); - } - if (p === '/api/my/toolkit/nudge' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const memberId = await auth.refreshMemberId(s); - const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || '')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/grant' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0); - if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() }); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/promo' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/toolkit' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await toolkit.adminUsage()); - } - if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row - const s = await auth.fromRequest(req); - const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; - return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null)); - } - if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const since = updates.lastSentAt(); - return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: updates.countsSnapshot(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status())); - } - if (p === '/api/admin/updates/draft' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) }); - } - if (p === '/api/admin/updates/preview' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' })); - } - if (p === '/api/admin/updates/send' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, image: b.image, imageLink: b.imageLink, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test }); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/releases' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES }); - } - if (p === '/api/admin/releases' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/releases' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || ''))); - } - // -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12) - if (p === '/api/admin/blog' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const slug = u.searchParams.get('slug'); - if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); } - return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) }); - } - if (p === '/api/admin/blog' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const before = b.existingSlug ? await blog.get(b.existingSlug) : null; - const r = await blog.save(b, b.existingSlug || null); - if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) { - // first time this article goes live: push it to X + Instagram (never repeated for the same slug) - syndicate.publish(r.post).catch(e => console.error('syndication', e.message)); - r.syndicating = syndicate.enabled(); - } - r.syndicated = syndicate.statusOf(r.post.slug); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const post = await blog.get(String(b.slug || '')); - if (!post) return json(res, 404, { error: 'No such post.' }); - if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' }); - if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' }); - const st = await syndicate.publish(post, { force: !!b.force }); - return json(res, 200, { ok: true, syndicated: st }); - } - if (p === '/api/admin/blog' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' }); - return json(res, 200, await blog.remove(slug)); - } - // -- admin: promo codes (create/update, switch on/off, redemptions) - if (p === '/api/admin/promos' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await promos.adminView()); - } - if (p === '/api/admin/promos' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await promos.create(b); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/promos' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await promos.setActive(b.code, !!b.active); - return json(res, r.error ? 400 : 200, r); - } - // -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique - if (p === '/api/my/username-suggest' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18); - if (!/[a-z]/.test(base)) base = 'member' + base; - if (base.length < 3) base = (base + 'xyz').slice(0, 3); - let pick = base; - for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i; - return json(res, 200, { suggest: pick }); - } - if (p === '/api/my/tank' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await tank.view(s.email)); - } - // -- achievement badge -> Telegram (payments topic + the main group), once per badge per member. - // The browser composes the personalised image (canvas, same as Share) and posts it here. - if (p === '/api/my/badge-post' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const key = String(u.searchParams.get('key') || ''); - if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); - if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' }); - let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } - if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); - const held = await ads.milestonesOf(s.email); - if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); - const log = badgeLog(); const mine = log[s.email] || {}; - if (mine[key]) return json(res, 200, { ok: true, already: true }); - // manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock - if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' }); - const a = await accounts.byEmail(s.email); - const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member'); - const link = a && a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; - const [label, sub] = BADGE_META[key]; - const caption = '\u{1F3C6} InstantAdPay \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; - // the server draws the card (a phone's canvas can come out blank: cryptomonk, 2026-09-16); the upload is the fallback - try { const srv = await badge.render(key, a && a.username ? a.username : (a && a.memberId ? 'member #' + a.memberId : '')); if (srv) jpeg = srv; } catch (e) {} - const sc = siteConfig(); let sent = 0; - if (sc.telegramBotToken && sc.telegramEchoChatId) { - if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic - if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General) - } - mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} - pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); - console.log('badge posted', s.email, key, 'sent', sent); - return json(res, 200, { ok: true, sent }); - } - // -- member's own share: store the composed badge so a public page can carry it as the preview image - if (p === '/api/my/badge-image' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const key = String(u.searchParams.get('key') || ''); - if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); - let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } - if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); - if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); - const a = await accounts.byEmail(s.email); - if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' }); - try { const srv = await badge.render(key, a.username); if (srv) jpeg = srv; } catch (e) {} - fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg); - return json(res, 200, { ok: true, page: 'https://instantadpay.com/b/' + a.username + '/' + key, image: 'https://instantadpay.com/badge-img/' + a.username + '/' + key + '.jpg' }); - } - if (p === '/api/admin/badge-repost' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); const key = String(b.key || ''); const a = await accounts.byEmail(String(b.email || '').toLowerCase()); - if (!a || !BADGE_META[key]) return json(res, 400, { error: 'Unknown member or badge.' }); - if (!(await ads.milestonesOf(a.email)).includes(key) && !(key === 'gamepass' && gamepass.flag(a.email).until)) return json(res, 400, { error: 'That member has not unlocked that badge.' }); // the Game Pass badge is earned by holding a pass, recorded or not yet - const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return json(res, 500, { error: 'Render failed.' }); - const who = a.username ? '@' + a.username : 'member #' + a.memberId; const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; - const [label, sub] = BADGE_META[key]; - const caption = '\u{1F3C6} InstantAdPay \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; - const sc = siteConfig(); let sent = 0; - if (sc.telegramBotToken && sc.telegramEchoChatId) { - if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; - if (String(sc.telegramBadgeGeneral || '1') !== '0' && b.general !== false && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; - } - const log = badgeLog(); const mine = log[a.email] || {}; mine[key] = { ts: Date.now(), sent, repost: true }; log[a.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} - return json(res, 200, { ok: true, sent, bytes: jpeg.length }); - } - if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL }); - } - if (p === '/api/my/tank/adopt' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' }); - const r = await tank.adopt(s.email, b.who, b.note); - if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12) - pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() }); - try { - const sc = siteConfig(); - const clean = t => String(t || '').replace(/[<>&]/g, ''); - if (sc.telegramBotToken && sc.telegramEchoChatId) - telegramSend(sc.telegramEchoChatId, '\u{1F91D} InstantAdPay \u00b7 ' + clean(r.adopterName) + ' picked up ' + clean(r.adopteeName) + ' from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {}); - } catch (e) {} - } - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/tank/release' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.release(s.email, b.email); - if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13) - pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() }); - try { - const sc = siteConfig(); - const clean = t => String(t || '').replace(/[<>&]/g, ''); - if (sc.telegramBotToken && sc.telegramEchoChatId) - telegramSend(sc.telegramEchoChatId, '\u{1FAA3} InstantAdPay \u00b7 ' + clean(r.ownerName) + ' returned ' + clean(r.memberName) + ' to the holding tank', sc.telegramEchoTopicId); - } catch (e) {} - } - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.markContacted(s.email, b.email); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.recordGift(s.email, b.email, b.tx, b.pol); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); } - if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); } - if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); } - if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView() })); } - if (p === '/api/admin/lsinbound' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lsinbound.adminView()); } - // -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET - // over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing - // accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js). - if (p === '/api/partner/registry' && req.method === 'POST') { - const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); - const b = sg.body; - const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : []; - return json(res, 200, Object.assign({ ok: true }, await lsinbound.receive(rows))); - } - // -- sponsor check between InstantAdPay and LinkSpin (2026-10-22, sponsorfollow.js). Partner side: LinkSpin reads our - // facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here). - if (p === '/api/partner/sponsor-facts' && req.method === 'POST') { - const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); - const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null; - return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'instantadpay', rows: await follow.facts(emails), view: followStore.view() }); - } - if (p === '/api/partner/sponsor-apply' && req.method === 'POST') { - const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); - const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on LinkSpin').slice(0, 120) }); - console.log('sponsor check (from LinkSpin)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok'); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/sponsor-check' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const mine = await follow.facts(); let peer = null, peerError = null; - try { peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; } - const mm = peer ? SF.mismatches(mine, peer.rows || []) : { shared: 0, same: 0, rows: [] }; - return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'instantadpay', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' }); - } - if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase(); - if (!email) return json(res, 400, { error: 'Which member?' }); - let r; - if (b.use === 'linkspin') { // LinkSpin's sponsor, applied HERE (refused when bound here) - const peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message })); - if (peer.error) return json(res, 502, { error: 'Could not read LinkSpin: ' + peer.error }); - const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' }); - r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used LinkSpin's sponsor" }); - } else if (b.use === 'instantadpay') { // our sponsor, applied ON LINKSPIN (LinkSpin refuses when bound there) - const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' }); - r = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on InstantAdPay: used InstantAdPay's sponsor" }, 30000).catch(e => ({ error: e.message })); - } else return json(res, 400, { error: 'use must be instantadpay or linkspin' }); - console.log('sponsor check resolve', email, b.use, r.error || 'ok'); - return json(res, r.error ? 400 : 200, r); - } - // -- help desk for LinkSpin (2026-10-16): LinkSpin has no desk of its own; its Help screen, /support page, private ticket - // link and chat hand-off all proxy here, signed like the registry rows. LinkSpin runs the person-facing guards (sign-in, - // honeypot, form age, icon check) and vouches for the email; this side only ever touches platform 'linkspin' tickets - // (LS- refs). Replies to the requester point at LinkSpin (tickets.js BRAND), never an InstantAdPay notice. - m = /^\/api\/partner\/support\/(create|list|view|reply|token|token-reply)$/.exec(p); - if (m && req.method === 'POST') { - const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); - const b = sg.body, op = m[1]; - const email = String(b.email || '').trim().toLowerCase(); - const mine = async () => { const t = await tickets.byRef(b.ref); return t && t.platform === 'linkspin' && t.email === email ? t : null; }; - const byTok = async () => { const t = await tickets.byToken(b.token); return t && t.platform === 'linkspin' ? t : null; }; - if (op === 'create') { - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' }); - if (supportFlood('ls:' + email, 8, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Add to one of those instead.' }); // backstop behind LinkSpin's own limits - const r = await tickets.create({ platform: 'linkspin', source: ['form', 'public', 'chatbot'].includes(b.source) ? b.source : 'public', email, name: b.name, username: b.username, subject: b.subject, category: b.category, body: b.body }); - return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref, token: r.token }); - } - if (op === 'list') return json(res, 200, { tickets: await tickets.memberList(email, 'linkspin'), unread: await tickets.memberUnread(email, 'linkspin'), categories: tickets.CATEGORIES }); - const t = op === 'view' || op === 'reply' ? await mine() : await byTok(); - if (!t) return json(res, 404, { error: op.startsWith('token') ? 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' : 'Ticket not found.' }); - if (op === 'view' || op === 'token') return json(res, 200, await tickets.memberView(t)); - if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); - const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: op === 'token-reply' ? 'link' : 'web' }); - return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); - } - if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); } - if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); } - if (p === '/api/admin/tank' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await tank.adminView()); - } - // -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring - // domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12) - // login-ad showings per Central day, dashboard vs games (2026-10-18: a week of combined sign-ins before the cap decision) - if (p === '/api/admin/login-shows' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { days: await loginShows.report(Number(u.searchParams.get('days')) || 14), slots: await ads.loginSlots() }); - } - if (p === '/api/admin/traffic' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30)); - const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10); - const hosts = {}, paths = {}, daily = {}, angles = {}; - const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 }); - const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 }); - for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; } - for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; } - const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId); - for (const a of await accounts.listAll(5000)) { - if (!a.created || a.created < since) continue; - const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1; - Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1; - const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1; - } - const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10)); - return json(res, 200, { starter: starter.adminView(), days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits), - angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1), - totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } }); - } - if (p === '/api/my/coach' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const cv = await coach.coachView(s.email); - for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock - return json(res, 200, cv); - } - // -- link stats: views, joins and buyers per angle link - if (p === '/api/my/linkstats' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await coach.linkStats(s.email)); - } - // -- prospects: the member's own follow-up list - // -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor) - if (p === '/api/my/pipeline' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const sc = siteConfig(); - if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' }); - const b = await pipeline.board(s.email); - return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/pipeline/note' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' }); - const r = await pipeline.save(s.email, await readBody(req)); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/prospects' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES }); - } - if (p === '/api/my/prospects' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await coach.saveProspect(s.email, await readBody(req)); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/prospects/remove' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await coach.removeProspect(s.email, b.id); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/profile' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const before = await accounts.byEmail(s.email); - // a username is permanent once set: the invite link, the public wall and every - // banner already printed carry it (Marty, 2026-09-10) - if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) - return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support (instantadpay.com/support) if it truly has to change.' }); - const r = await accounts.setUsername(s.email, b.username); - // First time a username is set (onboarding): now there's a real name to - // show, so notify the sponsor here rather than at signup (where it'd just - // say "a new member"). Fires once — only on the empty→set transition. - if (!r.error && before && !before.username && b.username) { - const acct = await accounts.byEmail(s.email); - notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); - // everyone's dashboard: "@name just joined" (and whether they are waiting in the tank) - if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); - } - return json(res, r.error ? 400 : 200, r); - } - // -- earn credits by viewing ads (attention-gated daily claim) - if (p === '/api/my/earn' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await ads.viewStatus(s.email)); - } - // fraud-guarded view flow: the server issues a single-use token when it - // serves the ad, and only counts the view if the dwell elapsed on the - // SERVER clock. Client-side focus tracking pauses the countdown; this is - // the floor a script cannot cheat past. - if (p === '/api/my/earnview' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.viewStatus(s.email); - if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status }); - const type = String(u.searchParams.get('type') || 'banner'); - // members never see (or earn from) their own campaigns in the viewer - const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req))); - if (!ad) return json(res, 200, { ad: null, status }); - const token = crypto.randomBytes(16).toString('hex'); - // the viewer tab frames the advertiser's REAL url (no click counted for a paid view) - earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id, - targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null }); - return json(res, 200, { ad, token, viewUrl: '/view/' + token, status }); - } - // the viewer tab asks where to point the frame (does not consume the token) - if (p === '/api/my/viewinfo' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = earnTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) - return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' }); - return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null, - dwell: ads.rates().viewDwellSeconds || 10 }); - } - // human check: handed out only once the dwell has elapsed on the SERVER clock - if (p === '/api/my/viewchallenge' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = earnTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) - return json(res, 400, { error: 'That view is no longer open.' }); - const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/my/adview' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = earnTokens.get(s.email); - const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' }); - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' }); - if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } - // the human check must be solved on the same token - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { - t.attempts = (t.attempts || 0) + 1; - t.challenge = null; // force a fresh challenge for the next try - if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); } - return json(res, 400, { error: 'Wrong pick.', retry: true }); - } - earnTokens.delete(s.email); // single use - return json(res, 200, await ads.recordView(s.email)); - } - // -- Friday Bonus Hunts (2026-09-26). The member's own progress, for the Earn tab card. - if (p === '/api/my/friday-bank' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await fridaybank.bankFor(s.email)); - } - // PolHunter asks, server to server, signed with the same shared secret as the hand-off: - // sig = HMAC-SHA256(HUNT_SSO_SECRET, 'fridaybank:' + email + ':' + ts), ts within 5 minutes. - if (p === '/api/hunt/friday-bank' && req.method === 'GET') { - const secret = String(process.env.HUNT_SSO_SECRET || '').trim(); - if (secret.length < 32) return json(res, 503, { error: 'not connected' }); - const q = new URL(req.url, 'http://x').searchParams; - const email = String(q.get('email') || '').trim().toLowerCase(), ts = Number(q.get('ts') || 0), sig = String(q.get('sig') || ''); - if (!email || !ts || Math.abs(Date.now() - ts) > 300000) return json(res, 400, { error: 'stale or missing' }); - const want = crypto.createHmac('sha256', secret).update('fridaybank:' + email + ':' + ts).digest('hex'); - if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'bad signature' }); - return json(res, 200, await fridaybank.bankFor(email)); - } - // -- PolHunter hand-off (2026-09-19): sign the member across; polhunter.com verifies with the shared secret - if (p === '/api/my/polhunter' && req.method === 'GET') { gamestats.handoff('polhunter'); - const s = await auth.fromRequest(req); - // not signed in: to sign-in, keeping a PolHunter share link's ?ref so the newcomer's sponsor holds (the viral-link rule on /my sets it) - if (!s || !s.email) { const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); res.writeHead(302, { Location: '/my' + (ref ? '?ref=' + ref : '') }); return res.end(); } - const secret = String(process.env.HUNT_SSO_SECRET || '').trim(); const huntUrl = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, ''); - if (secret.length < 32) return json(res, 503, { error: 'PolHunter is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const memberId = (acct && acct.memberId) || s.memberId || 0; - if (!memberId) { res.writeHead(302, { Location: '/my#wallet' }); return res.end(); } - const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); - // the sponsor rides across too (Marty, 2026-09-23): PolHunter pays a referral bounty, and the - // person who gets it has to be the one this member actually joined under here, not a cookie - // PolHunter guessed at. sponsorRef is the upline's username or code, matching /join/. - let sponsorRef = (acct && acct.sponsorRef) || ''; - const payload = JSON.stringify({ iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(12).toString('hex'), memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, sponsorRef: sponsorRef || null, joinedAt: (acct && acct.created) || null, - // where they first arrived from, so PolHunter can pay a bounty only for people it sent - joinedRef: (acct && acct.joinedRef) || null, gamePass: gamepass.flag(s.email) }); - const tok = b64u(payload) + '.' + b64u(crypto.createHmac('sha256', secret).update(payload).digest()); - res.writeHead(302, { Location: huntUrl + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); // the loop is closed - } - // -- Drip Runner hand-off (2026-09-30): sign the member across, the game verifies with the shared secret - if (p === '/api/my/driprunner' && req.method === 'GET') { gamestats.handoff('driprunner'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight back into the game - if (DR_SECRET().length < 32) return json(res, 503, { error: 'Drip Runner is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const memberId = (acct && acct.memberId) || s.memberId || 0; - const tok = drMint({ memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, - sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }); // the game credits referrals to the IAP sponsor - res.writeHead(302, { Location: DR_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); - } - // -- PolyWarriors hand-off (2026-10-05): sign the member across; the game verifies with PW_SSO_SECRET - // PolyWarriors weekly member-fight season prizes (Marty 2026-10-05): the game signs one claim per week and place; InstantAdPay - // decides the amount (setting pwWeeklyPrize, default '1000,500,250' earned credits) and pays each week+place once. - // admin: credit or remove PolyWarriors mint passes on an account (support fixes), logged in the pass history - if (p === '/api/admin/pw/pass' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(), n = Math.round(Number(b.n) || 0); - if (!e || !n || Math.abs(n) > 20) return json(res, 400, { error: 'email and n (1-20, or negative to remove) required' }); - const left = pwPassAdd(e, n, 'admin:' + String(b.why || 'support').slice(0, 80)); - console.log('polywarriors admin pass', e, n > 0 ? '+' + n : n, 'left', left, b.why || ''); - return json(res, 200, { ok: true, email: e, passes: left }); - } - if (p === '/api/game/pw/prize' && req.method === 'POST') { - const b = await readBody(req); const r = pwOpen(b.t); - if (r.error) return json(res, 400, { error: r.error }); - const c = r.claims, place = Number(c.place), week = String(c.week || ''); - if (c.kind !== 'pw-prize' || !(place >= 1 && place <= 3) || !/^\d{4}-\d{2}-\d{2}$/.test(week) || !c.email) return json(res, 400, { error: 'bad claim' }); - if (Math.abs(Date.now() - new Date(week + 'T12:00:00Z').getTime()) > 14 * 86400000) return json(res, 400, { error: 'stale week' }); - const k = week + ':' + place; if (pwPrizes.get(k)) return json(res, 200, { ok: true, already: true }); - const acct = await accounts.byEmail(String(c.email).toLowerCase()); if (!acct) return json(res, 404, { error: 'no account' }); - const amts = String(siteConfig().pwWeeklyPrize || '1000,500,250').split(',').map(x => Math.max(0, Math.round(Number(x) || 0))); - const credits = Math.min(amts[place - 1] || 0, 5000); if (!credits) return json(res, 200, { ok: true, credits: 0 }); - pwPrizes.set(k, { email: acct.email, credits, at: Date.now() }); - await ads.addEarned(acct.email, credits, { log: { kind: 'bonus', note: 'PolyWarriors weekly season: #' + place + ' (week of ' + week + ')', ref: 'pwprize:' + k } }); - console.log('polywarriors weekly prize', k, acct.email, credits); - return json(res, 200, { ok: true, credits }); - } - if (p === '/api/my/polywarriors' && req.method === 'GET') { gamestats.handoff('polywarriors'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polywarriors', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (PW_SECRET().length < 32) return json(res, 503, { error: 'PolyWarriors is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = pwMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); - res.writeHead(302, { Location: PW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- SpellWheel hand-off (2026-10-04): sign the member across; the game verifies with SW_SSO_SECRET - if (p === '/api/my/polybreak' && req.method === 'GET') { gamestats.handoff('polybreak'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polybreak', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (PB_SECRET().length < 32) return json(res, 503, { error: 'PolyBreak is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = pbMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null }); - res.writeHead(302, { Location: PB_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - if (p === '/api/my/spellwheel' && req.method === 'GET') { gamestats.handoff('spellwheel'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'spellwheel', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (SW_SECRET().length < 32) return json(res, 503, { error: 'SpellWheel is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = swMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); - res.writeHead(302, { Location: SW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- ClutterHunt hand-off (2026-10-03): sign the member across; the game verifies with SEEK_SSO_SECRET - if (p === '/api/my/clutterhunt' && req.method === 'GET') { gamestats.handoff('clutterhunt'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'clutterhunt', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (SEEK_SECRET().length < 32) return json(res, 503, { error: 'ClutterHunt is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = seekMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); - res.writeHead(302, { Location: SEEK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- Shards of Valor hand-off (2026-10-18): sign the member across; the game verifies with SOV_SSO_SECRET - if (p === '/api/my/shardsofvalor' && req.method === 'GET') { gamestats.handoff('shardsofvalor'); - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'shardsofvalor', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (SOV_SECRET().length < 32) return json(res, 503, { error: 'Shards of Valor is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = sovMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); - res.writeHead(302, { Location: SOV_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- Gem Kingdom hand-off (2026-10-01): sign the member across; the game verifies with GK_SSO_SECRET - if (p === '/api/my/gemkingdom' && req.method === 'GET') { gamestats.handoff('gemkingdom'); - const s = await auth.fromRequest(req); - // a newcomer from a Gem Kingdom feed post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor - const gkRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (gkRef ? '?ref=' + encodeURIComponent(gkRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'gemkingdom', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (GK_SECRET().length < 32) return json(res, 503, { error: 'Gem Kingdom is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = gkMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); - res.writeHead(302, { Location: GK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- the Crown shop checkout: confirm, spend the credits, sign a receipt back to the game - if (p === '/gk/shop' && req.method === 'GET') { - const t = u.searchParams.get('t') || ''; const r = gkOpen(t); - if (r.error) return gkPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      Back to Gem Kingdom'); - const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '

      That is not a Crown order

      '); - const done = gkOrders.get(c.order); - if (done && done.status === 'paid') { const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: c.email, crowns: c.crowns, credits: c.credits, paid: done.paid != null ? done.paid : c.credits, ref: done.campaignId }, 24 * 3600000); res.writeHead(302, { Location: c.ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); } - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.gkshop', t, 7200), gkCookie('iap.return', 'gkshop', 1800)] }); return res.end(); } - if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '

      Different account

      This order was started by the Gem Kingdom player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.

      Back to Gem Kingdom'); - const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email); - const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 }; - const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail); - const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0); - const head = '

      Gem Kingdom · Crown Shop

      ' + gkEsc(c.label || 'Crowns') + '

      ' + Number(c.crowns) + ' Crowns
      ' - + '
      Price' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')
      ' - + '
      Your available credits' + Number(bal.available || 0).toLocaleString('en-US') + '
      '; - if (can) { - const csrf = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); - return gkPage(res, 200, 'Confirm your Crowns', head + '
      ' - + 'Cancel and go back

      Crowns are game items. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.

      '); - } - const need = c.credits - usable; - return gkPage(res, 200, 'More credits needed', head + '

      You need ' + need.toLocaleString('en-US') + ' more credits for this pack' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.

      ' - + 'Buy a credit packagePick a smaller pack' - + '

      A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.

      '); - } - // ---- PolyWarriors paid mints: every mint after the free first one comes with a new $5+ package purchase - if (p === '/pw/mint' && req.method === 'GET') { - const t = u.searchParams.get('t') || ''; const r = pwOpen(t); - if (r.error) return gkPage(res, 400, 'Mint problem', '

      That mint did not work

      ' + gkEsc(r.error) + '

      Back to PolyWarriors'); - const c = r.claims; if (c.kind !== 'pw-mint' || !c.order || !(c.serial > 0)) return gkPage(res, 400, 'Mint problem', '

      That is not a mint order

      '); - const done = pwOrders.get(c.order); - if (done && done.status === 'paid') { - // a visible hand-back instead of a silent redirect chain (Zachary's iPad sat on the mint form after a pass mint, - // 2026-10-12): the page says the mint is done, returns to the game by itself, and keeps a button in case it does not. - const rc = pwReceipt(c.order, done); const back = (pwIsGameUrl(done.ret) ? done.ret : PW_URL() + '/api/iap/mint-receipt') + '?t=' + rc; - res.setHeader('Set-Cookie', gkCookie('iap.pwmint', '', 0)); - return gkPage(res, 200, 'Minted', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(done.label || ('Warrior #' + done.serial)) + '

      Minting now
      ' - + '

      Your warrior is on its way to the wallet on your InstantAdPay account. Taking you back to the game.

      ' - + 'Back to PolyWarriors' - + '

      If this page stays, tap the button. The game shows the warrior as On Polygon once the transaction confirms, usually within a minute.

      ', ''); - } - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S), gkCookie('iap.return', 'pwmint', 1800)] }); return res.end(); } - if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '

      Different account

      This mint was started by the PolyWarriors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account and tap Mint again.

      '); - // the order waits here until a new package purchase from this account lands on chain (oldest waiting order first) - if (!done) pwOrders.set(c.order, { status: 'waiting', email: String(s.email).toLowerCase(), serial: Number(c.serial), label: String(c.label || '').slice(0, 60), ret: c.ret, cb: c.cb, ts: Date.now() }); - res.setHeader('Set-Cookie', gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S)); - const have = pwPassN(String(s.email).toLowerCase()); - if (have > 0) { - const csrf = pwSign('pass:' + c.order + ':' + String(s.email).toLowerCase()); - return gkPage(res, 200, 'Mint your warrior', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(c.label || ('Warrior #' + c.serial)) + '

      ' + have + ' mint pass' + (have === 1 ? '' : 'es') + '
      ' - + '
      ' - + 'Cancel and go back

      You earned these passes with your package purchases: one mint for every $5. The game pays the network fee.

      '); - } - return gkPage(res, 200, 'Mint your warrior', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(c.label || ('Warrior #' + c.serial)) + '

      Comes with a $5 package
      ' - + '

      Your first mint was free. After that, every $5 of new ad packages earns one mint: $5 mints this warrior, $10 earns 2 mints, $20 earns 4, and any extra mints stay on your account for next time. You keep every package\'s ad credits.

      ' - + 'Buy a $5 packageBack to PolyWarriors' - + '

      Buy while this mint is waiting and it mints to your wallet automatically. Credits you already have cannot be used for mints. The game pays the network fee.

      '); - } - if (!IS_PROD && p === '/api/dev/pw-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await pwMintOnEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email }) }); } // local tests only - if (p === '/pw/mint/pass' && req.method === 'POST') { - const f = await gkFormBody(req); const t = f.get('t') || ''; const r = pwOpen(t); - if (r.error) return gkPage(res, 400, 'Mint problem', '

      That mint did not work

      ' + gkEsc(r.error) + '

      '); - const c = r.claims; const s = await auth.fromRequest(req); const e = s && s.email ? String(s.email).toLowerCase() : ''; - if (!e || e !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); - const want = pwSign('pass:' + c.order + ':' + e), got = String(f.get('csrf') || ''); - if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Mint problem', '

      That form expired

      Try again'); - const o = pwOrders.get(c.order); - // the redirect goes out at once; the game is told in the background (and the GET below hands the member's own browser the - // receipt too, so the mint never waits on this callback). Marty's phone sat on this form on 2026-10-09 while the mint had - // already gone through. - if (o && o.status === 'waiting' && pwPassN(e) > 0) { pwPassAdd(e, -1, 'mint:' + c.order); pwOrders.set(c.order, Object.assign({}, o, { status: 'paid', tx: 'pass', cents: 500, paidAt: Date.now() })); pwDeliver(c.order).catch(() => {}); } - res.writeHead(303, Object.assign({ Location: '/pw/mint?t=' + encodeURIComponent(t), 'Cache-Control': 'no-store' }, pwOrders.get(c.order) && pwOrders.get(c.order).status === 'paid' ? { 'Set-Cookie': gkCookie('iap.pwmint', '', 0) } : {})); return res.end(); - } - if (p === '/pw/mint/leave' && req.method === 'GET') { res.writeHead(302, { Location: PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the waiting order stays; a later package still completes the mint - if (p === '/pw/mint/dismiss' && req.method === 'POST') { res.writeHead(204, { 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the dashboard bar's x - if (p === '/pw/mint/resume' && req.method === 'GET') { const t = parseCookies(req)['iap.pwmint']; res.writeHead(302, { Location: t ? '/pw/mint?t=' + encodeURIComponent(t) : PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); } - if (p === '/gk/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back - const t = u.searchParams.get('t') || ''; if (gkOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); } - res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', t, 7200) }); return res.end(); - } - if (p === '/gk/shop/resume' && req.method === 'GET') { - const t = parseCookies(req)['iap.gkshop']; res.writeHead(302, { Location: t ? '/gk/shop?t=' + encodeURIComponent(t) : GK_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - if (p === '/gk/shop/confirm' && req.method === 'POST') { - const f = await gkFormBody(req); const t = f.get('t') || ''; const r = gkOpen(t); - if (r.error) return gkPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      '); - const c = r.claims; const s = await auth.fromRequest(req); - if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); - const want = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || ''); - if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Order problem', '

      That form expired

      Try again'); - const prev = gkOrders.get(c.order); - if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } - gkOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() }); - const { ids } = await myMemberIds(s); - const out = await ads.gamePurchase(s.email, ids, c.credits, 'Gem Kingdom: ' + c.crowns + ' Crowns', GK_URL()); - if (out.error) { gkOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } return gkPage(res, 500, 'Order problem', '

      Something went wrong

      ' + gkEsc(out.error) + '

      '); } - gkOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() }); - console.log('gemkingdom crowns', s.email, c.crowns, 'for', c.credits, 'credits (' + out.paid + ' purchased), campaign', out.campaignId); - const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: String(c.email).toLowerCase(), crowns: Number(c.crowns), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000); - gkCallback(c.cb, rc); // the server copy; the redirect below is the fast path - const ret = String(c.ret || '').startsWith(GK_URL() + '/') ? c.ret : GK_URL() + '/api/iap/receipt'; - // a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site (the page just sat there) - const back = gkEsc(ret + '?t=' + rc); - res.setHeader('Set-Cookie', gkCookie('iap.gkshop', '', 0)); - return gkPage(res, 200, 'Crowns added', '

      Gem Kingdom · Crown Shop

      Paid!

      +' + Number(c.crowns).toLocaleString('en-US') + ' Crowns

      Taking you back to your kingdom...

      Back to Gem Kingdom'); - } - // -- Spooky Doors hand-off (2026-10-02): sign the member across; the game verifies with SD_SSO_SECRET - // -- Spooky Doors promo card in Promo tools (2026-10-02): shown on the same season window as the Games card (admin preview - // before the start). The member's link is SD_URL/?ref=, built in the page from their own username. - if (p === '/api/my/spookydoors/promo' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); - const ss = seasonState(SD_SEASON, todayCT(), admin); - if (ss === 'hidden') return json(res, 200, { show: false }); - return json(res, 200, { show: true, preview: ss === 'preview', base: SD_URL(), image: SD_URL() + '/og-spookydoors.jpg', season: { start: SD_SEASON.start, end: SD_SEASON.end } }); - } - if (p === '/api/my/spookydoors' && req.method === 'GET') { gamestats.handoff('spookydoors'); - const s = await auth.fromRequest(req); - // a newcomer from a Spooky Doors post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor - const sdRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (sdRef ? '?ref=' + encodeURIComponent(sdRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'spookydoors', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (SD_SECRET().length < 32) return json(res, 503, { error: 'Spooky Doors is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = sdMint({ kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null, - sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000); - res.writeHead(302, { Location: SD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- Road Agent hand-off (2026-10-07): sign the member across; the game verifies with RA_SSO_SECRET - if (p === '/api/my/roadagent' && req.method === 'GET') { gamestats.handoff('roadagent'); - const s = await auth.fromRequest(req); - const raRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (raRef ? '?ref=' + encodeURIComponent(raRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'roadagent', 1800), 'Cache-Control': 'no-store' }); return res.end(); } - if (RA_SECRET().length < 32) return json(res, 503, { error: 'Road Agent is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const tok = gMint(DOOR_GAMES().roadagent, { kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null, - sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000); - res.writeHead(302, { Location: RA_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - // -- the Spooky Doors costume shop checkout: the Crown shop flow with a Halloween coat (confirm, spend, signed receipt back) - if (p === '/sd/shop' && req.method === 'GET') { - const t = u.searchParams.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.'); - if (r.error) return sdPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      Back to Spooky Doors'); - const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0) || !c.email) return sdPage(res, 400, 'Order problem', '

      That is not a costume order

      Back to Spooky Doors'); - const label = String(c.label || c.item).slice(0, 60); - const done = sdOrders.get(c.order); - if (done && done.status === 'paid') { const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: done.paid != null ? done.paid : Number(c.credits), ref: done.campaignId }, 24 * 3600000); const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); } - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.sdshop', t, 7200), gkCookie('iap.return', 'sdshop', 1800)] }); return res.end(); } - if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Different account', '

      Different account

      This order was started by the Spooky Doors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.

      Back to Spooky Doors'); - const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email); - const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 }; - const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail); - const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0); - const head = '

      Spooky Doors · Costume shop

      ' + gkEsc(label) + '

      ' - + '
      Price' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')
      ' - + '
      Your available credits' + Number(bal.available || 0).toLocaleString('en-US') + '
      '; - if (can) { - const csrf = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); - return sdPage(res, 200, 'Confirm your costume', head + '
      ' - + 'Cancel and go back

      Costumes are game items for this Halloween season. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.

      '); - } - const need = c.credits - usable; - return sdPage(res, 200, 'More credits needed', head + '

      You need ' + need.toLocaleString('en-US') + ' more credits for this costume' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.

      ' - + 'Buy a credit packageBack to the costume shop' - + '

      A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.

      '); - } - if (p === '/sd/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back - const t = u.searchParams.get('t') || ''; if (sdOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); } - res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.sdshop', t, 7200) }); return res.end(); - } - if (p === '/sd/shop/resume' && req.method === 'GET') { - const t = parseCookies(req)['iap.sdshop']; res.writeHead(302, { Location: t ? '/sd/shop?t=' + encodeURIComponent(t) : SD_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); - } - if (p === '/sd/shop/confirm' && req.method === 'POST') { - const f = await gkFormBody(req); const t = f.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.'); - if (r.error) return sdPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      '); - const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0)) return sdPage(res, 400, 'Order problem', '

      That is not a costume order

      '); - const s = await auth.fromRequest(req); - if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); - const want = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || ''); - if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return sdPage(res, 403, 'Order problem', '

      That form expired

      Try again'); - const prev = sdOrders.get(c.order); - if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } - sdOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() }); - const label = String(c.label || c.item).slice(0, 60); - const { ids } = await myMemberIds(s); - const out = await ads.gamePurchase(s.email, ids, Number(c.credits), 'Spooky Doors: ' + label, SD_URL()); - if (out.error) { sdOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } return sdPage(res, 500, 'Order problem', '

      Something went wrong

      ' + gkEsc(out.error) + '

      '); } - sdOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() }); - console.log('spookydoors costume', s.email, c.item, 'for', c.credits, 'credits, campaign', out.campaignId); - const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000); - sdShopCallback(c.cb, rc); // the server copy; the redirect below is the fast path - const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; - // a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site - const back = gkEsc(ret + '?t=' + rc); - res.setHeader('Set-Cookie', gkCookie('iap.sdshop', '', 0)); - return sdPage(res, 200, 'Costume ready', '

      Spooky Doors · Costume shop

      Paid!

      ' + gkEsc(label) + '

      Taking you back to the street...

      Back to Spooky Doors'); - } - // -- PassiveDrip card on the Earn tab (Marty, 2026-10-01: "It's an earning site", not a game). Members see it when - // site config passivedripLive is 'on'; until then only the admin sees it, marked preview. - if (p === '/api/my/passivedrip/card' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const live = String(siteConfig().passivedripLive || 'off') === 'on'; - const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); - if ((!live && !admin) || PD_SECRET().length < 32) return json(res, 200, { show: false }); - const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0; - let progress = null; try { progress = await pdProgress(memberId, s.email); } catch (e) {} - return json(res, 200, { show: true, preview: !live, line: progress && progress.line || null }); - } - // -- PassiveDrip hand-off (2026-10-01): sign the member across; PassiveDrip verifies with the shared secret. - // wallet = the signature-verified main wallet (accounts.linkWallet runs only after /api/auth/verify), offered there, never imposed. - if (p === '/api/my/passivedrip' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=passivedrip; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight across - if (PD_SECRET().length < 32) return json(res, 503, { error: 'PassiveDrip is not connected yet.' }); - const acct = await accounts.byEmail(s.email); - const memberId = (acct && acct.memberId) || s.memberId || 0; - let sponsorEmail = null; try { const up = await uplineSlides(s.email, 1); sponsorEmail = (up[0] && up[0].email) || null; } catch (e) {} - const tok = pdMint({ memberId: Number(memberId), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorEmail }); - res.writeHead(302, { Location: PD_URL() + '/iap-signin.php?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); - } - // -- Drip Runner refuel: a real verified visit (advertiser charged as usual); the player gets fuel, not credits - if (p === '/api/refuel/open' && req.method === 'GET') { - // Drip Runner refuels and Gem Kingdom continues (2026-10-03) share this flow; the token's secret says which game - let r = drOpen(u.searchParams.get('t')), game = 'driprunner'; - if (r.error) { const g = gkOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'gemkingdom') { r = g; game = 'gemkingdom'; } } - if (r.error) { const g = seekOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'seek') { r = g; game = 'seek'; } } - if (r.error) { const g = swOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'spellwheel') { r = g; game = 'spellwheel'; } } - if (r.error) { const g = pbOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polybreak') { r = g; game = 'polybreak'; } } - if (r.error) return json(res, 400, { error: r.error }); - const c = r.claims; if (c.kind !== 'refuel' || !c.nonce || !c.email || !c.ret) return json(res, 400, { error: 'That is not a refuel link.' }); - if (game === 'gemkingdom' && !String(c.ret).startsWith(GK_URL() + '/')) return json(res, 400, { error: 'That is not a Gem Kingdom link.' }); - if (game === 'seek' && !seekIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a ClutterHunt link.' }); - if (game === 'spellwheel' && !swIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a SpellWheel link.' }); - if (game === 'polybreak' && !pbIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a PolyBreak link.' }); - const G = game === 'polybreak' ? { game: 'PolyBreak', label: 'one more paddle' } : game === 'gemkingdom' ? { game: 'Gem Kingdom', label: 'continue' } : game === 'seek' ? { game: 'ClutterHunt', label: 'hint' } : game === 'spellwheel' ? { game: 'SpellWheel', label: 'hint' } : { game: 'Drip Runner', label: 'refuel' }; - for (const [n, v] of refuelTokens) if (v.ts + 30 * 60000 < Date.now()) refuelTokens.delete(n); - let t = refuelTokens.get(c.nonce); - if (t && t.done) return json(res, 200, Object.assign({ done: true, ret: t.doneRet || t.ret }, G)); - if (!t) { - const email = String(c.email).toLowerCase(); - const status = await ads.visitStatus(email, 'refuel'); // refuels have their own daily allowance - if (status.count >= status.cap) return json(res, 200, Object.assign({ none: true, why: 'cap', ret: c.ret }, G)); - const ad = await ads.serveVisit(email, viewerGeo(req)); - if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId), id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; - else { // every visit pack already visited: a member video ad instead (2026-09-30) - const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req))); - if (!v) return json(res, 200, Object.assign({ none: true, why: 'empty', ret: c.ret }, G)); - t = { kind: 'video', email, memberId: Number(c.memberId), id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; - } - t.game = game; t.cb = c.cb || null; - refuelTokens.set(c.nonce, t); - } - if (t.kind === 'video') return json(res, 200, Object.assign({ mode: 'video', title: t.title, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G)); - return json(res, 200, Object.assign({ mode: 'visit', title: t.title, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G)); - } - if (p === '/api/refuel/challenge' && req.method === 'GET') { - const t = refuelTokens.get(String(u.searchParams.get('n') || '')); - if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' }); - const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/refuel/done' && req.method === 'POST') { - const b = await readBody(req); const nonce = String(b.n || ''); const t = refuelTokens.get(nonce); - if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' }); - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } - let credits; - if (t.kind === 'video') { - const st = await ads.visitStatus(t.email, 'refuel'); if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s refuels. More at midnight Central.' }); - if (!(await ads.markRefuelVideo(t.email, t.id))) return json(res, 400, { error: 'You already refuelled on this video. Go back and try again for another.' }); - const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab - if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try again.' }); - await ads.markVideoSeen(t.email, t.id); credits = tier.cost; - } else { - const r = await ads.completeVisit(t.email, t.id, { reward: false, note: t.game === 'polybreak' ? 'PolyBreak paddle' : t.game === 'gemkingdom' ? 'Gem Kingdom continue' : t.game === 'seek' ? 'ClutterHunt hint' : t.game === 'spellwheel' ? 'SpellWheel hint' : 'Drip Runner refuel' }); - if (r.error) return json(res, 400, r); - credits = ads.rates().visitCostPerVisit || 3; - { const camp = await ads.campaignById(t.id).catch(() => null); if (camp && camp.house) credits = 0; } // a house ad costs nobody anything: no POL pool income (2026-10-03) - } - t.done = true; - if (t.game === 'polybreak') { // PolyBreak one more paddle: signed receipt to the game's callback and on the ret page - const receipt = pbMint({ kind: 'pb-paddle', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); - const posted = await pbCallback(t.cb, receipt); - t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); - return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'PolyBreak', label: 'one more paddle' }); - } - if (t.game === 'spellwheel') { // SpellWheel hint: signed receipt to the game's callback and on the ret page - const receipt = swMint({ kind: 'sw-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); - const posted = await swCallback(t.cb, receipt); - t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); - return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'SpellWheel', label: 'hint' }); - } - if (t.game === 'seek') { // ClutterHunt hint: signed receipt to the game's callback and on the ret page - const receipt = seekMint({ kind: 'seek-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); - const posted = await seekCallback(t.cb, receipt); - t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); - return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'ClutterHunt', label: 'hint' }); - } - if (t.game === 'gemkingdom') { // signed receipt to the game's callback (server copy) and on the ret page (fast path) - const receipt = gkMint({ kind: 'gk-continue', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); - const posted = await gkCallback(t.cb || (GK_URL() + '/api/continue/callback'), receipt); - t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); - return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'Gem Kingdom', label: 'continue' }); - } - const posted = await drCallback({ nonce, memberId: t.memberId, campaignId: t.id, credits }); - const receipt = drMint({ kind: 'refuel-receipt', nonce, campaignId: t.id, credits }, 15 * 60000); - t.doneRet = t.ret + '&ok=1&r=' + encodeURIComponent(receipt); - return json(res, 200, { ok: true, posted, ret: t.doneRet }); - } - // -- Spooky Doors door: a real verified visit of kind 'door' (own daily cap, advertiser charged as usual); the player gets candy, not credits - if (p === '/api/door/open' && req.method === 'GET') { - const r = doorOpen(u.searchParams.get('t')); if (r.error) return json(res, 400, { error: r.error }); - const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !gameUrlOk(r.game, c.ret)) return json(res, 400, { error: 'That is not a door link.' }); - for (const [n, v] of doorTokens) if (v.ts + 30 * 60000 < Date.now()) doorTokens.delete(n); - let t = doorTokens.get(c.nonce); - if (t && t.done) return json(res, 200, { done: true, ret: t.doneRet || t.ret }); - const email = String(c.email).toLowerCase(); - const status = await ads.visitStatus(email, 'door'); // doors have their own daily allowance - if (!t) { - if (status.count >= status.cap) return json(res, 200, { none: true, why: 'cap', ret: sdJoin(c.ret, 'cap=1') }); - // door packs + Golden Doors first (golden, then doors; once per player per Central day), then the existing chain - const pack = await ads.serveDoorPack(email, viewerGeo(req)); - const ad = pack || await ads.serveVisit(email, viewerGeo(req), { kind: 'door' }); // doors may repeat a campaign after doorRepeatDays - if (ad) t = { kind: 'visit', game: r.game, email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false, - credits: pack ? pack.credits : (ads.rates().visitCostPerVisit || 3), golden: !!(pack && pack.golden), bonus: (pack && pack.golden) ? sdGoldenBonus() : 0 }; - else { // every visit pack already visited: a member video ad instead, one door per video per person - const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req))); - if (v) t = { kind: 'video', game: r.game, email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; - else { // nothing left on the street: a house ad (one of Marty's programs, a smaller treat); none=1 only when the list is empty - const h = await doorHousePick(email, c.username); - if (!h) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') }); - t = { kind: 'house', game: r.game, email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; - } - } - t.host = t.kind === 'house' ? null : await sdHost(t.id); - doorTokens.set(c.nonce, t); - } - const doors = { used: status.count, cap: status.cap, game: t.game || 'spookydoors', gameName: DOOR_GAMES()[t.game || 'spookydoors'].name }; - if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); - if (t.kind === 'house') return json(res, 200, { mode: 'visit', house: true, program: t.program, title: t.title, host: null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); - return json(res, 200, Object.assign({ mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000), credits: t.credits || (ads.rates().visitCostPerVisit || 3) }, t.golden ? { golden: true, bonus: t.bonus } : {})); - } - if (p === '/api/door/challenge' && req.method === 'GET') { - const n = String(u.searchParams.get('n') || ''); const t = doorTokens.get(n); - if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' }); - const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - const pick = DOOR_CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; doorTokens.set(n, t); - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/door/done' && req.method === 'POST') { - const b = await readBody(req); const nonce = String(b.n || ''); const t = doorTokens.get(nonce); - if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' }); - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; doorTokens.set(nonce, t); return json(res, 400, { error: 'Wrong pick.', retry: true }); } - const st = await ads.visitStatus(t.email, 'door'); - if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s doors. More at midnight Central.', cap: true, ret: sdJoin(t.ret, 'cap=1') }); - let credits; - if (t.kind === 'video') { - if (!(await ads.markRefuelVideo(t.email, t.id, 'door'))) return json(res, 400, { error: 'You already knocked on this video. Go back and try another door.' }); - const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab - if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try another door.' }); - await ads.markVideoSeen(t.email, t.id); credits = tier.cost; - } else if (t.kind === 'house') { // no advertiser and no campaign imps, but it uses one of today's doors - const r = await ads.markHouseDoor(t.email); - if (r.error) return json(res, 400, { error: r.error, cap: true, ret: sdJoin(t.ret, 'cap=1') }); - credits = 0; - } else { - const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: 'door', note: 'Spooky Doors door' }); - if (r.error) return json(res, 400, r); - credits = r.unit || ads.rates().visitCostPerVisit || 3; // the per-door price actually charged (door pack 4, Golden Door 6, a visit pack 3) - if (t.golden && r.golden === false) t.golden = false; // the season closed between open and done: an ordinary door - } - t.done = true; - const host = t.host || null; - const house = t.kind === 'house' ? { house: true, program: t.program } : {}; // a house ad: credits 0, host null, campaignId 0 - const gold = (t.kind === 'visit' && t.golden) ? { golden: true, bonus: t.bonus } : {}; // a Golden Door: the game adds `bonus` candy - const gk = t.game || 'spookydoors'; - const posted = await gameCallback(gk, Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold)); - const receipt = gMint(DOOR_GAMES()[gk], Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold), 24 * 3600000); - t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt)); - doorTokens.set(nonce, t); - return json(res, 200, Object.assign({ ok: true, posted, host, credits, ret: t.doneRet }, house, gold)); - } - // -- cross-promo strip (2026-10-03): the list every game reads, and the counted hop between games - // -- the public games page (2026-10-10, Marty: a page to send people): every game, open ones first, dated ones after - // featured PolyWarriors listings for the games page, fetched server-side (the page CSP allows no cross-origin calls), cached 60 s - if (p === '/api/public/pw-featured' && req.method === 'GET') { - const now = Date.now(); if (!global.__pwFeat || now - global.__pwFeat.at > 60000) { try { const r = await fetch(String(process.env.PW_URL || 'https://www.polywarriors.com').replace(/\/+$/, '') + '/api/public/featured', { signal: AbortSignal.timeout(6000) }); global.__pwFeat = { at: now, body: r.ok ? await r.json() : { featured: [] } }; } catch (e) { global.__pwFeat = { at: now, body: { featured: [] } }; } } - return json(res, 200, global.__pwFeat.body, { 'Cache-Control': 'public, max-age=60' }); - } - if (p === '/api/public/games/all' && req.method === 'GET') { - const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); - const day = todayCT(), S = STRIP(); const lbl = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; - const out = []; - for (const g of GAMES()) { - if (g.season && day >= g.season.end) continue; // a finished season is gone - const soon = !!(g.soon && day < g.soon.opens), preSeason = !!(g.season && day < g.season.start); - const isLive = !soon && !preSeason && live.has(g.slug); - if (!isLive && !soon && !preSeason) continue; // not live and no date: not announced yet - out.push({ slug: g.slug, name: g.name, tag: g.tag, blurb: g.blurb, pays: g.pays, art: /^https?:/.test(g.art) ? g.art : 'https://instantadpay.com' + g.art, artPos: g.artPos || 'center', live: isLive, video: isLive && g.video ? g.video : null, - opens: soon ? g.soon.label : preSeason ? 'Opens ' + lbl(g.season.start) : null, season: g.season && isLive ? { ends: lbl(g.season.end, true) } : null, open: S[g.slug] ? S[g.slug].open : null, host: S[g.slug] ? S[g.slug].host : null }); - } - return json(res, 200, { games: out }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' }); - } - // Today's POL price in US dollars for the member pages (Marty, 2026-10-22, Brian's ask): the same rate the contract prices - // packages with (its Chainlink POL/USD feed), cached 5 minutes on the server, so browsers never call a price service. - if (p === '/api/public/polusd' && req.method === 'GET') { let usd = 0; try { usd = await polUsdLive(); } catch (e) {} return json(res, 200, { usd, at: polUsdCache.at || Date.now() }, { 'Cache-Control': 'public, max-age=60' }); } - if (p === '/api/public/games' && req.method === 'GET') return json(res, 200, { games: stripGames() }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' }); - { const mg = /^\/g\/([a-z]{3,20})$/.exec(p); if (mg && req.method === 'GET') { - const g = GAMES().find(x => x.slug === mg[1]); const S = STRIP()[mg[1]]; - if (!g || !S) { res.writeHead(302, { Location: '/my#games', 'Cache-Control': 'no-store' }); return res.end(); } - const from = String(u.searchParams.get('from') || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 20); const src = STRIP()[from]; - traffic.hit('/g/' + g.slug, req.headers.referer || (src ? 'https://' + src.host + '/' : ''), req.headers['user-agent']); // Traffic tab: host = sending game, path g/ - const s = await auth.fromRequest(req); - res.writeHead(302, { Location: (s && s.email) ? g.play : S.open, 'Cache-Control': 'no-store' }); return res.end(); // signed in here: straight into the game, signed in - } } - // -- Game Pass + account-wide POL caps (2026-10-16, docs/GAME-PASS.md section 3a) -------------------------------------------- - // Partner auth: each game signs with the shared secret it already holds (its *_SSO_SECRET), 10-minute window. - // GET ...?game=&m=&e=&ts=&sig=hex sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts), who = memberId when > 0, else the lowercased email - // POST JSON body with `game`, headers X-Game-Ts (ms) + X-Game-Sig sig = HMAC-SHA256(secret, ts + '\n' + rawBody) - // The pass is per ACCOUNT (email): a linked position's member id resolves to the owner's account. Games fail closed. - if (p === '/api/partner/player' && req.method === 'GET') { - const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); - if (chk.error) return json(res, chk.code, { error: chk.error }); - const m = Number(u.searchParams.get('m')) || 0, e = String(u.searchParams.get('e') || '').trim().toLowerCase(), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); - if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); - if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:' + (m > 0 ? String(m) : e) + ':' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); - const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null, tier: null, tiers: { weekly: null, explorer: null, champion: null } } }); - const now = gpDevNow(u.searchParams.get('devDay')); - return json(res, 200, { ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email), - pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled }); - } - if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') { - let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); } - let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } - const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error }); - const ts = String(req.headers['x-game-ts'] || ''), sig = String(req.headers['x-game-sig'] || ''); - if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); - if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update(ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); - if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); } - const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' }); - const now = gpDevNow(b.devDay); - if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref })); - if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later - const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now }); - if (!out.error && out.capHit && !out.repeat) console.log('gamepass cap hit', out.capHit, game, r.email.replace(/^(.).*(@.*)$/, '$1***$2'), out.pass ? 'pass' : 'free', out.enforced ? 'enforced' : 'recorded'); - return json(res, out.error ? 400 : 200, out); - } - if (p === '/api/partner/tournament/pending' && req.method === 'GET') { // prize rows the games still have to pay out in POL (admin session may read too) - if (!isAdmin(req)) { - const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error }); - const ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); - if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); - if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); - } - const rows = gamepass.pending(); - return json(res, 200, { ok: true, rows, pending: rows }); // `rows` is what the games' polgrant.js tournamentPending() reads; `pending` is the admin pane's name - } - if (p === '/api/my/gamepass' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay')), { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL })); - } - if (p === '/api/my/gamepass/buy' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (fraud.isSuspended(s.email)) return json(res, 403, { error: 'This account is suspended.' }); - const b = await readBody(req); - // 2026-10-22 (Marty): no pass is ever bought with credits. Buy only opens a waiting order; a FRESH package purchase of at least the - // tier price, by one of this member's own positions, fulfils it (gamepass.onEvent), so the sponsor and team are paid as usual. - // tier: weekly (missing) | explorer | champion | sovereign | legend; every tier above weekly is refused unless sovTiers is on, except for the ADMIN_EMAIL account (testing) - const r = gamepass.buy(s.email, gpDevNow(b.devDay), b.tier, { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL }); - return json(res, r.error ? 400 : 200, r); - } - if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: /^0x[0-9a-f]{64}$/.test(String(b.tx || '')) ? b.tx : '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email, devMinedAt: Number(b.minedAt) || 0, devNow: Number(b.now) || 0 }) }); } // local tests only (minedAt fakes the block time, now the fulfilment time, tx replays a hash) - if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); } - if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); - const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' }); - const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80), tier); console.log('gamepass comp', tier, e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r)); - } - if (p === '/api/admin/gamepass/revoke' && req.method === 'POST') { // support refund only: ends one tier now (never automatic); the record keeps what it was - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); - const r = gamepass.revoke(e, String(b.tier || '').toLowerCase(), String(b.why || 'support').slice(0, 80)); if (!r.error) console.log('gamepass revoke', r.tier, e, b.why || ''); - return json(res, r.error ? 400 : 200, Object.assign({ email: e }, r)); - } - if (p === '/api/admin/gamepass/tournament/run' && req.method === 'POST') { // settle a week by hand (the Monday job normally does this) - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); - const at = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? Date.parse(b.week + 'T17:00:00Z') : Date.now() - 7 * 86400000; - const r = await gamepass.runTournament(at, { force: !!b.force }); return json(res, r.error ? 400 : 200, r); - } - // -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive) - if (p === '/api/my/games' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); - const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); - const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0; - const out = []; const day = todayCT(); - const dayLabel = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; - for (const g of GAMES()) { - // a seasonal game (2026-10-02) shows only while today (Central) is in [start, end); before start the admin sees a preview, after end nobody - // testers (env GAMES_TESTERS, usernames or emails; Marty 2026-10-07) get the Play button on a coming-soon game before it opens - const tester = isGameTester(acct, s.email); - if (g.soon && day < g.soon.opens && !tester) { out.push(Object.assign({}, g, { live: false, preview: false, soon: g.soon.label, play: null })); continue; } // coming soon: shown to all, not playable - if (g.soon && day < g.soon.opens && tester) { out.push(Object.assign({}, g, { live: false, preview: true, previewNote: 'testing · ' + g.soon.label.toLowerCase(), soon: null })); continue; } // soon cleared: the client prints a soon card's label where the Play button goes - const ss = seasonState(g.season, day, admin); if (ss === 'hidden') continue; - const seasonPreview = ss === 'preview'; - const isLive = live.has(g.slug); if (!isLive && !admin && !tester) continue; - // soon: null once the opening day arrives: the registry's {opens,label} object must not reach the client, which prints x.soon - // as the button label (SpellWheel showed "[object Object]" on the morning of 2026-10-10) - const card = Object.assign({}, g, { live: isLive, preview: !isLive || seasonPreview, soon: null }); - if (g.season) { card.season = Object.assign({}, g.season, { opens: dayLabel(g.season.start), ends: dayLabel(g.season.end, true) }); if (seasonPreview) card.previewNote = 'preview, opens ' + card.season.opens; } - if (g.progress && (memberId || g.slug === 'passivedrip')) { try { card.progress = await g.progress(memberId, s.email); } catch (e) {} } - out.push(card); - } - return json(res, 200, { games: out.map(g => { const c = Object.assign({}, g); if (typeof c.progress === 'function') delete c.progress; return c; }) }); - } - if (p === '/api/my/claim' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.claimDaily(s.email); - if (!r.error) { try { const paid = await payPromo(s.email, todayCT()); if (paid.length) r.promo = paid; } catch (e) { console.error('promo drip', e.message); } } - return json(res, r.error ? 400 : 200, r); - } - // -- downline lineage: 3 levels, usernames+IDs; email only for directs - if (p === '/api/my/line' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const levels = await accounts.downline(s.email, 3); - // what each person has paid THIS member so far: sum of TierPaid events where - // this member is the recipient and that person is the buyer (all indexed events) - // ...counting payouts to every position this account owns (main id + linked positions) - const myId = await auth.refreshMemberId(s); - const own = (await accounts.positions(s.email)).filter(p => p.memberId); - const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean)); - const earnedBy = {}; - const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($20+) - if (myIds.size) { - for (const ev of chain.recentEvents(1e9)) { - if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId) - earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString(); - if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId); - } - } - // who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself - const meAcct = await accounts.byEmail(s.email); const byTok = {}; - const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'); - for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; } - const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); }; - // a member's linked positions are theirs too: a qualifying buy from one of them lights their chip - const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } } - const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean); - // Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $20+ buy (counted for their own - // sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short - const lTot = await ads.earnedTotals(levels.flatMap(L => L.members.map(m => m.email))); // surf earnings per person (Marty, 2026-09-29) - const onchain = {}; - for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; } - const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({ - bought: onchain[m.email].bought, buyers: onchain[m.email].buyers, - memberId: m.memberId || 0, - sponsor: sponsorOf(m), - name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member', - ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels - email: L.level === 1 ? m.email : null, // directs only - joined: m.created, - lastSeen: m.lastSeen || 0, - wallet: !!m.address, activated: !!m.memberId, - earned: (lTot[m.email] || {}).earned || 0, balance: (lTot[m.email] || {}).balance || 0, - qualified: idsOf(m).some(id => qualified.has(id)), - earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) })); - // the member's own linked positions sit on level 1 too, labelled as theirs - if (own.length) { - if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] }); - const L1 = out.find(L => L.level === 1); - own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true, - email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' })); - } - return json(res, 200, { levels: out, counts: out.map(L => L.members.length) }); - } - // -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14) - if (p === '/api/my/line/activity' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); - const a = ref ? await accounts.byCode(ref) : null; - if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' }); - const now = Date.now(); - const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 }; - try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {} - try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {} - try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {} - try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {} - try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; } - try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; } - try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; } - return json(res, 200, out); - } - // -- broadcast a message to your downline (1/day), on-site inbox + email - if (p === '/api/my/broadcast' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const subject = String(b.subject || '').trim().slice(0, 160); - const body = ads.sanitizeRich(b.body); - const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); - if (!subject) return json(res, 400, { error: 'Give your message a subject.' }); - if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' }); - const last = await messages.lastBroadcastAt(s.email); - if (Date.now() - last < 24 * 3600 * 1000) - return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' }); - const depth = b.scope === 'direct' ? 1 : 3; - const levels = await accounts.downline(s.email, depth); - const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))]; - if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' }); - const memberId = s.memberId || await auth.refreshMemberId(s); - await messages.deliver(memberId, s.email, recipients, subject, body); - // email each recipient too (best-effort; never blocks the on-site delivery) - if (mailer.hasKey()) { - const who = (await accounts.byEmail(s.email)); - const from = who && who.username ? '@' + who.username : 'your sponsor'; - for (const to of recipients) { - mailer.send(to, 'Message from ' + from + ': ' + subject, - plain + '\n\n— sent via your InstantAdPay upline. Read it in your dashboard: https://instantadpay.com/my#line') - .catch(() => {}); - } - } - return json(res, 200, { ok: true, sent: recipients.length }); - } - // -- help desk, member side (2026-10-16): the Help pane lists, opens and answers this member's tickets - if (p === '/api/my/support' && (req.method === 'GET' || req.method === 'POST')) { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (req.method === 'GET') return json(res, 200, { tickets: await tickets.memberList(s.email, 'iap'), unread: await tickets.memberUnread(s.email, 'iap'), categories: tickets.CATEGORIES }); // LinkSpin tickets live in LinkSpin's Help - const b = await readBody(req); - if (supportFlood('em:' + String(s.email).toLowerCase(), 5, 3600000)) return json(res, 429, { error: 'You have opened several tickets in the last hour. Add to one of those instead.' }); - const a = await accounts.byEmail(s.email); - const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments }); - return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref }); - } - m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); - if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = await tickets.byRef(m[1]); - if (!t || t.email !== String(s.email).toLowerCase() || t.platform !== 'iap') return json(res, 404, { error: 'Ticket not found.' }); - if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); - const b = await readBody(req); - if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); - const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, attachments: b.attachments }); - return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); - } - // -- sponsor messages: this member's inbox from their upline - if (p === '/api/my/messages' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const items = await messages.inbox(s.email); - const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]); - for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember] - : i.fromMember ? 'member #' + i.fromMember : 'your upline'; - return json(res, 200, { items, unread: items.filter(i => !i.read).length }); - } - m = /^\/api\/my\/messages\/(\d+)\/read$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await messages.markRead(s.email, m[1])); - } - - // ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ── - const chatOnline = ts => (Date.now() - (ts || 0)) < 60000; - const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member')); - // lightweight presence heartbeat (called on a timer while the dashboard is open) - if (p === '/api/my/ping' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 }); - accounts.touchSeen(s.email).catch(() => {}); - return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) }); - } - // training center content (admin-curated via data/training.json) - if (p === '/api/training' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - let items = []; - try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {} - // a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15) - const scT = siteConfig(); const launched = scT.launchAt && Date.now() >= new Date(scT.launchAt).getTime(); // feature:'polhunter' waits for the launch moment (Marty, 2026-09-20) - items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL)) || (it.feature === 'polhunter' && launched)); - if (!items.length) items = [{ title: 'Getting started with InstantAdPay', - desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.', - docUrl: 'https://instantadpay.com/' }]; - return json(res, 200, { items }); - } - // daily login bonus (once/day, gentle streak) — granted after the login flow - if (p === '/api/my/login-bonus' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const cfg = siteConfig(); // comebackBonus (250) after comebackDays (7) away; 0 switches it off - return json(res, 200, await ads.grantLoginBonus(s.email, { comeback: cfg.comebackBonus == null ? 250 : Number(cfg.comebackBonus), comebackDays: cfg.comebackDays == null ? 7 : Number(cfg.comebackDays) })); - } - // -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL - // (anvil_setBalance, no key needed). Rehearsal-only, rate-limited. - if (p === '/api/my/faucet' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' }); - const b = await readBody(req); - const addr = String(b.address || '').trim().toLowerCase(); - if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' }); - // Amoy is a public testnet: testers fund their own connected wallet from - // the public Amoy faucet (no server-minted balance). We just echo the - // address + faucet link; the client copies the address and opens it. - let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {} - return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() }); - } - // -- report an ad (auto-approved ads need a safety valve): store + notify admin - if (p === '/api/report-ad' && req.method === 'POST') { - const b = await readBody(req); - if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' }); - const s = await auth.fromRequest(req); - const who = (s && s.email) || ''; - const rec = await reports.add(b.campaignId, who, b.reason, b.note); - try { - const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config - if (adminEmail && mailer.hasKey()) { - mailer.send(adminEmail, 'Ad reported on InstantAdPay (campaign #' + rec.campaignId + ')', - 'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason - + '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)') - + '\n\nPause or review it from the admin.').catch(() => {}); - } - } catch (e) {} - return json(res, 200, { ok: true }); - } - if (p === '/api/my/chat/send' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const me = s.email.toLowerCase(); - const b = await readBody(req); - const to = String(b.to || '').trim().toLowerCase(); - const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim(); - if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' }); - if (!text) return json(res, 400, { error: 'Write a message first.' }); - const target = await accounts.byEmail(to); - if (!target) return json(res, 404, { error: 'No such member.' }); - // authorize: existing thread, my direct sponsor, or someone in my downline - let ok = (await messages.thread(me, to, 0, 1)).length > 0; - if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); } - if (!ok) ok = await accounts.isDownlineOf(me, to); - if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' }); - if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me)) - return json(res, 403, { error: 'They are not accepting messages from you right now.' }); - const memberId = s.memberId || await auth.refreshMemberId(s); - const msg = await messages.sendChat(memberId, me, to, text); - // email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam) - try { - if (mailer.hasKey() && !chatOnline(target.lastSeen)) { - const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me); - const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0; - if (Date.now() - lastMineTs > 10 * 60 * 1000) { - const who = await accounts.byEmail(me); - const from = who && who.username ? '@' + who.username : 'someone in your InstantAdPay line'; - mailer.send(to, 'New message from ' + from, - text.slice(0, 400) + '\n\n— reply in your dashboard: https://instantadpay.com/my').catch(() => {}); - } - } - } catch (e) {} - return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } }); - } - if (p === '/api/my/chat/thread' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const me = s.email.toLowerCase(); - const other = String(u.searchParams.get('with') || '').trim().toLowerCase(); - const after = Number(u.searchParams.get('after')) || 0; - if (!other) return json(res, 400, { error: 'Who with?' }); - // may view a thread I'm party to (existing), or one I'm allowed to start - let ok = (await messages.thread(me, other, 0, 1)).length > 0; - if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); } - if (!ok) ok = await accounts.isDownlineOf(me, other); - if (!ok) return json(res, 403, { error: 'Not your conversation.' }); - const msgs = await messages.thread(me, other, after, 300); - await messages.markChatRead(me, other); - accounts.touchSeen(me).catch(() => {}); - const oa = await accounts.byEmail(other); - const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other); - const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me); - return json(res, 200, { - messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })), - otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false, - available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe, - canMute: await accounts.isDownlineOf(me, other) }); - } - if (p === '/api/my/chat/threads' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const list = await messages.threadList(s.email.toLowerCase()); - for (const t of list) { - const a = await accounts.byEmail(t.email); - t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false; - } - list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0)); - const meAcct = await accounts.byEmail(s.email); - return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true }); - } - if (p === '/api/my/chat/available' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available)); - } - if (p === '/api/my/chat/mute' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const target = String(b.email || '').trim().toLowerCase(); - if (!target) return json(res, 400, { error: 'Who?' }); - const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0; - if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' }); - return json(res, 200, await accounts.setMute(s.email, target, !!b.muted)); - } - // -- featured rotation: the live featured links + dilution stats - if (p === '/api/featured' && req.method === 'GET') { - const items = await ads.serveFeatured(viewerGeo(req)); - try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour) - const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]); - for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null); - return json(res, 200, { items }); - } - if (p === '/api/featured/stats' && req.method === 'GET') { - return json(res, 200, await ads.featuredStats()); - } - // -- QR code (SVG) for any InstantAdPay URL — used on bio/wall pages - if (p === '/api/qr' && req.method === 'GET') { - const data = String(u.searchParams.get('d') || '').slice(0, 300); - if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); } - try { - const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240, - color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning - res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' })); - return res.end(svg); - } catch (e) { res.writeHead(500, baseHeaders()); return res.end(); } - } - // -- profile: avatar + bio - if (p === '/api/my/profile-details' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim(); - if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar)) - return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' }); - const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600); - // socials: {platform: url}; keep only known platforms with valid https urls - let socials; - if (b.socials !== undefined) { - const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; - const clean = {}; - for (const p of PLAT) { - const v = String((b.socials && b.socials[p]) || '').trim(); - if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v; - } - // intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only - if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video)) - return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' }); - socials = Object.keys(clean).length ? JSON.stringify(clean) : null; - } - const r = await accounts.setProfile(s.email, avatar, bio, socials); - return json(res, r.error ? 400 : 200, r); - } - // -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers - if (p === '/api/my/wall-offers' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : []; - const out = []; - for (let i = 0; i < 2; i++) { - const o = src[i] || {}; - const targetUrl = String(o.targetUrl || '').trim(); - const bannerUrl = String(o.bannerUrl || '').trim(); - const title = String(o.title || '').trim().slice(0, 60); - if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' }); - if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' }); - out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null); - } - const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null); - return json(res, r.error ? 400 : 200, r); - } - // -- line banner: the member's viral slot on welcome tours + their wall - if (p === '/api/my/linebanner' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const target = String(b.targetUrl || '').trim(); - if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' }); - const fc = await frameCheck(target); // welcome tours frame it full screen - if (!fc.ok) return json(res, 400, { error: fc.reason }); - const banner = String(b.bannerUrl || '').trim(); - if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner)) - return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' }); - const r = await accounts.setLineBanner(s.email, banner || null, target); - return json(res, r.error ? 400 : 200, r); - } - // -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits - if (p === '/api/my/gauntlet' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false }); - const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl) - .map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member', - bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl })); - if (!slides.length) return json(res, 200, { pending: false }); - const token = crypto.randomBytes(16).toString('hex'); - gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length }); - return json(res, 200, { pending: true, slides, dwell: 10, token }); - } - if (p === '/api/my/gauntlet/complete' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = gauntletTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' }); - if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' }); - gauntletTokens.delete(s.email); - await ads.grantWelcome(s.email); - return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 }); - } - // -- public banner wall - m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m && req.method === 'GET') { - const tok = m[1].toLowerCase(); - let a = await accounts.byUsername(tok); - if (!a) a = await accounts.byCode(tok); - if (!a) return json(res, 404, { error: 'No wall under that name.' }); - const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member'; - let bc = 0; - if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} } - const unlocked = wallUnlockedFor(bc); - const offers = parseWallOffers(a); - // uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty) - const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl) - .map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member', - bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true })); - const adAds = getAdminWallAds(); let ai = 0; - const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'InstantAdPay', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || 'https://instantadpay.com/', admin: true }; }; - const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }]; - for (let i = 1; i < 3; i++) { - const o = offers[i - 1]; - if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; } - const u = ups.shift(); if (u) { ladder.push(u); continue; } - const h = houseAd(); if (h) ladder.push(h); - } - const finalLadder = ladder.slice(0, 3); - // the wall owner's achievement badge (their highest reached tier) - let badge = null; - if (a.memberId) { - const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark']; - badge = { img: '/badges/badge-' + t[0] + '.jpg?v=2', label: t[1] }; - } - const joinPath = '/join/' + (a.username || a.code); - let socials = null; try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} - return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), - avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials, badge, - joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent('https://instantadpay.com' + joinPath), ladder: finalLadder, unlocked, buyerCount: bc }); - } - // -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch - if (p === '/api/my/videos' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.videoStatus(s.email); - if (status.left <= 0) return json(res, 200, { ad: null, status }); - const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab - const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video - if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13) - let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {} - // this surface is empty but the other one may not be: the Watch tab holds the landscape - // videos and Shorts holds the portrait ones, and they share one daily cap, so a member - // who runs the tab dry still has clips waiting (Marty, 2026-09-22) - let otherFormat = null; - if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) { - const alt = orientation === 'landscape' ? 'portrait' : 'landscape'; - try { if (await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation: alt }, viewerGeo(req)))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {} - } - return json(res, 200, { ad: null, status, allWatched, otherFormat }); - } - const token = crypto.randomBytes(16).toString('hex'); - videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs }); - return json(res, 200, { ad, token, status }); - } - if (p === '/api/my/videowatch' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = videoTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' }); - const age = Date.now() - t.ts; - if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' }); - if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); } - videoTokens.delete(s.email); // single use - if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning - return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true }); - const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry - if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true }); - await ads.addEarned(s.email, tier.reward, { log: { kind: 'earn', note: 'Watched a video (' + tier.secs + 's)' } }); - await ads.markVideoSeen(s.email, t.id); - const status = await ads.recordVideoWatch(s.email); - return json(res, 200, { ok: true, credited: tier.reward, status }); - } - // -- verified visits: view a member's site (new tab) for the dwell, pass a - // human check, and it counts as one guaranteed unique visit for the pack - if (p === '/api/my/visits' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.visitStatus(s.email); - if (status.count >= status.cap) return json(res, 200, { ad: null, status }); - const ad = await ads.serveVisit(s.email, viewerGeo(req)); - if (!ad) return json(res, 200, { ad: null, status }); - const token = crypto.randomBytes(16).toString('hex'); - visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id }); - return json(res, 200, { ad, token, status }); - } - if (p === '/api/my/visitchallenge' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = visitTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' }); - const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); } - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/my/visitdone' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = visitTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' }); - const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; - if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' }); - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } - visitTokens.delete(s.email); - const r = await ads.completeVisit(s.email, t.id); - if (r.error) return json(res, 400, r); - return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) })); - } - // -- onsite solo ads: member inbox with read rewards - if (p === '/api/my/inbox' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.inboxList(s.email, viewerGeo(req)); - const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]); - for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId] - : i.fromMemberId ? 'member #' + i.fromMemberId : 'a member'; - return json(res, 200, r); - } - m = /^\/api\/my\/inbox\/(\d+)$/.exec(p); - if (m && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.inboxOpen(s.email, m[1]); - if (!r.error) { - const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {}; - r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId] - : r.fromMemberId ? 'member #' + r.fromMemberId : 'a member'; - } - return json(res, r.error ? 404 : 200, r); - } - // media upload for solo ads: raw body, size-capped, magic-byte verified - if (p === '/api/my/upload' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return handleUpload(req, res, s.email); - } - m = /^\/api\/my\/inbox\/(\d+)\/visit$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.markSoloVisit(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/inbox\/(\d+)\/claim$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.claimSoloRead(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/activity' && req.method === 'GET') { - const s = await auth.fromRequest(req); - 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(1e9); // whole history (was the last 600 events: older members saw three empty boxes) - return json(res, 200, { - memberId: id, - earnings: await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id)).slice(0, 300)), - purchases: await attachNames(evs.filter(e => e.type === 'Purchase' && e.buyerId === id).slice(0, 300)), - referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id)).slice(0, 300)) - }); - } - - // -- ad engine (spec §8b v1: banners, text, login ads) - if (p === '/api/ads/slot' && req.method === 'GET') { - const t = String(u.searchParams.get('type') || 'banner'); - if (t === 'login') return json(res, 200, { ad: await loginAdFor(req, 'dashboard') }); - const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req))); - return json(res, 200, { ad }); - } - m = /^\/api\/ads\/click\/(\d+)$/.exec(p); - if (m && req.method === 'GET') { - // an advertiser opening their own ad's link (from Campaigns, a preview, a test) is not a click: relay it uncounted (Marty, 2026-09-30) - let own = false; - try { const s = await auth.fromRequest(req); if (s && s.email) { const cm = await ads.campaignById(m[1]); own = !!(cm && cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } } catch (e) {} - const target = own ? await ads.targetOf(m[1]) : await ads.click(m[1]); - if (!target) { res.writeHead(404, baseHeaders()); return res.end(); } - if (!own) coach.recordClick(m[1], req.headers.referer); // where the click happened - res.writeHead(302, baseHeaders({ Location: target })); - return res.end(); - } - if (p === '/api/my/trace' && req.method === 'GET') { // payment trace for yourself or anyone within 3 levels of you, either direction - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const mine = (await myMemberIds(s)).ids.filter(Boolean); - const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase(); - let target = /^\d+$/.test(who) ? Number(who) : 0; - if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (a && a.memberId) target = a.memberId; } - if (!target && !who && mine.length) target = mine[0]; - if (!target) return json(res, 400, { error: who ? 'No activated member called "' + who.slice(0, 40) + '". Use a member number or a username of someone who has bought a package.' : 'Enter a member number or username.' }); - if (!mine.length) return json(res, 403, { error: 'Link a wallet and buy a package first; the trace works on chain positions.' }); - const smap = sponsorMapFromIndex(chain.recentEvents(1e9)); - const ok = mine.includes(target) || uplineIds(smap, target, 3).some(x => mine.includes(x)) || mine.some(m => uplineIds(smap, m, 3).includes(target)); - if (!ok) return json(res, 403, { error: 'You can trace yourself, anyone up to 3 levels below you, and your own 3 uplines.' }); - return json(res, 200, await tracePurchases(target, 30)); - } - if (p === '/api/my/credits/activity' && req.method === 'GET') { // credit ledger: every earn and spend with a reason, newest first - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { items: await ads.creditActivity(s.email, 40) }); - } - if (p === '/api/my/campaigns' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const all = await ads.listCampaigns(s.email); - // archived ones keep their full stats but leave the working list (Marty, 2026-09-23) - const out = { campaigns: all.filter(c => c.status !== 'archived'), archived: all.filter(c => c.status === 'archived'), - rates: ads.rates(), bannerSizes: ads.bannerSizes() }; - const ids = all.map(c => c.id); // archived included: their numbers are the whole point of keeping them - out.clickSources = await coach.clickSources(ids); - out.hours = await ads.hoursFor(ids); // on-site views per UTC hour, last 7 days - out.geo = await ads.geoFor(ids); // on-site serves per viewer country - out.doorStats = await ads.doorStats(all.filter(c => c.type === 'visits').map(c => c.id)); // Spooky Doors: doors opened + unique players per pack - { const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; } - const pool = await ads.balances((await myMemberIds(s)).ids, s.email); - out.purchasedCredits = pool.total; - out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position - out.positionCount = pool.per.length; - out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits) - out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold - out.earnedReserved = pool.earnedReserved; - out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns - out.availableCredits = pool.available; - out.loginLine = await ads.loginQueueView(s.email); // login-ad slots: open now, the paid line, this member's places + estimated starts - return json(res, 200, out); - } - if (p === '/api/my/campaigns' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text - const b = await readBody(req); - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player - if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } - if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } - { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } - { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } - // charge the best-funded of the member's positions (main + Qualified Start - // wallets). A campaign burns from one member id, so the budget must fit inside it. - const ids = (await myMemberIds(s)).ids; - const pool = await ads.balances(ids, s.email); - const fundId = pool.best.memberId || memberId; - const earnedNow = String(b.type) !== 'login' ? pool.earned : 0; - const budget = Math.floor(Number(b.budget) || 0); - if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow) - return json(res, 400, { error: 'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' }); - const r = await ads.createCampaign(s.email, fundId, b, ids); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const b = await readBody(req); - const positions = [memberId, ...(await accounts.positions(s.email).catch(() => [])).map(x => x.memberId)].filter(Boolean); - const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits, { positions, switchTo: Number(b.switchTo) || 0 }); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/extend$/.exec(p); // featured links: book more days (flat, charged now) - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const b = await readBody(req); - const r = await ads.extendFeatured(s.email, memberId, m[1], b.days); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/(archive|unarchive)$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = m[2] === 'archive' ? await ads.archive(s.email, m[1]) : await ads.unarchive(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active'); - return json(res, r.error ? 400 : 200, r); - } - // prepaid login-ad line (2026-10-23): cancel a reservation before it starts (full refund), or edit it for free - m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.cancelLoginReservation(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/edit-reservation$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - if (b.targetUrl !== undefined) { - const t = String(b.targetUrl || '').trim(); - { const sb = await sbcheck.check(t); if (!sb.ok) return json(res, 400, { error: sb.reason }); } - { const rc = await reach.check(t); if (!rc.ok) return json(res, 400, { error: rc.reason }); } - } - if (b.imageUrl) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } - const r = await ads.editLoginReservation(s.email, m[1], b); - return json(res, r.error ? 400 : 200, r); - } - - // -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL - if (p === '/api/admin/auth/start' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' }); - if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); - const k = 'admin:' + e; - const prev = emailCodes.get(k); - if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); - const code = String(Math.floor(100000 + Math.random() * 900000)); - emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); - if (mailer.hasKey()) { - try { await mailer.sendCode(e, code); } catch (err) { - console.error('admin sendCode failed', err.message); - return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); - } - return json(res, 200, { ok: true, sent: true }); - } - if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); - return json(res, 503, { error: 'Email sign-in is not configured yet.' }); - } - if (p === '/api/admin/auth/verify' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - const k = 'admin:' + e; - const rec = emailCodes.get(k); - if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); - rec.tries += 1; - if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } - if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); - emailCodes.delete(k); - if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); - const token = mintAdminSession(e); - return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) }); - } - if (p === '/api/admin/auth/logout' && req.method === 'POST') { - dropAdminSession(req); - return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() }); - } - if (p === '/api/admin/me' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 200, { admin: false }); - return json(res, 200, { admin: true, email: ADMIN_EMAIL }); - } - // -- level-4 override dry run (2026-10-17): ?week=YYYY-MM-DD (any day in the week) or ?from=&to= (ms); rows=1 adds every purchase - 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; - return json(res, 200, r, { 'Cache-Control': 'no-store' }); - } - // -- help desk, admin side (2026-10-16): the Support pane - if (p === '/api/admin/support/telegram/register' && req.method === 'POST') { // point @CTBTickets_bot's webhook at this server - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await supportbot.register('https://instantadpay.com/api/telegram/support')); - } - if (p === '/api/admin/support' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, Object.assign(await tickets.adminList({ status: u.searchParams.get('status'), platform: u.searchParams.get('platform'), category: u.searchParams.get('category'), q: u.searchParams.get('q') }), - { categories: tickets.CATEGORIES, platforms: tickets.PLATFORMS })); - } - if (p === '/api/admin/support/counts' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await tickets.counts()); - } - if (p === '/api/admin/support/templates' && (req.method === 'GET' || req.method === 'PUT')) { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const read = () => { const v = siteConfig().supportTemplates; let a = v; if (typeof v === 'string') { try { a = JSON.parse(v); } catch (e) { a = null; } } return Array.isArray(a) && a.length ? a : tickets.DEFAULT_TEMPLATES; }; - if (req.method === 'GET') return json(res, 200, { templates: read() }); - const b = await readBody(req); - const list = (Array.isArray(b.templates) ? b.templates : []).map(t => ({ name: String((t && t.name) || '').trim().slice(0, 60), body: String((t && t.body) || '').trim().slice(0, 3000) })).filter(t => t.name && t.body).slice(0, 30); - const cur = siteConfig(); cur.supportTemplates = list; fs.writeFileSync(SITE_FILE, JSON.stringify(cur, null, 2)); - return json(res, 200, { ok: true, templates: read() }); - } - // -- the assistant's knowledge base (2026-10-20, kb.js): Admin > Knowledge base, and "Save as KB entry" on a ticket reply - if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' }); - const r = await kb.create(await readBody(req)); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/kb/test' && req.method === 'POST') { // which entry would answer this question, and what would ride along to the AI - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, await kb.test(b.question)); - } - m = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p); - if (m) { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - if (req.method === 'GET') { const e = await kb.get(m[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); } - if (req.method === 'PUT') { const r = await kb.update(m[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); } - if (req.method === 'DELETE') { const r = await kb.remove(m[1]); return json(res, r.error ? 404 : 200, r); } - return json(res, 405, { error: 'method' }); - } - m = /^\/api\/admin\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); - if (m) { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const t = await tickets.byRef(m[1]); - if (!t) return json(res, 404, { error: 'Ticket not found.' }); - if (m[2] && req.method === 'POST') { const b = await readBody(req); const r = await tickets.addMessage(t.id, { author: 'admin', body: b.body, internal: !!b.internal, status: b.status, attachments: b.attachments }); if (r.error) return json(res, 400, r); } - else if (!m[2] && req.method === 'PATCH') { const r = await tickets.setFields(t.id, await readBody(req)); if (r.error) return json(res, 400, r); } - else if (m[2] || req.method !== 'GET') return json(res, 405, { error: 'method' }); - const v = await tickets.adminView(t.id); - const a = await accounts.byEmail(v.ticket.email); - v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email }; - return json(res, 200, v); - } - if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, refill.stats()); - } - if (p === '/api/admin/refill/reset' && req.method === 'POST') { // re-decide conversions under a corrected rule - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, refill.resetConversions(Array.isArray(b.kinds) ? b.kinds : null)); - } - if (p === '/api/admin/refill/run' && req.method === 'POST') { // send the next batch now instead of waiting for the tick - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await refill.tick()); - } - if (p === '/api/admin/overview' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const camps = await ads.adminList(); - const byStatus = {}, byType = {}; - for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; } - let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {} - const cc = chain.getConfig(); - return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length, - house: camps.filter(c => c.house).length, byStatus, byType, - openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length, - followups: await drip.stats(), - chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer }, - site: siteConfig(), rates: ads.rates() }); - } - if (p === '/api/admin/members' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const members = await accounts.listAll(5000, { shells: true }); // waiting LinkSpin accounts included (2026-10-15); was 500: older members (igor147, joined 09-12) vanished from the table and its search once the site passed 500 accounts (Marty, 2026-09-29) - // resolve each sponsor token (username, share code or member #) to the sponsor's name - // the lookup covers EVERY account, not the page's slice: built from `members` it called every - // sponsor who joined before the newest 500 a dead link (144 of them, Marty 2026-09-23) - const byTok = {}; - for (const m of await accounts.identities()) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m; - for (const m of members) { - const t = String(m.sponsorRef || '').toLowerCase(); - const sp = t ? byTok[t] : null; - m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null; - m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : ''); - } - for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } } - for (const m of members) { try { const sg = await fraud.get(m.email); m.flags = sg ? sg.flags : []; m.suspended = !!(sg && sg.suspended); m.lastIp = sg ? sg.lastIp : ''; } catch (e) { m.flags = []; m.suspended = false; } } - return json(res, 200, { members }); - } - if (p === '/api/admin/members' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - if (!b.email) return json(res, 400, { error: 'Which member?' }); - if (b.suspend !== undefined) { // anti-fraud switch: suspended accounts cannot sign in; flags keep them off the leaderboard and out of adoptions - if (b.suspend) await fraud.suspend(b.email, b.reason || 'duplicate account'); else await fraud.unsuspend(b.email); - if (b.flags) await fraud.addFlags(b.email, [].concat(b.flags)); - return json(res, 200, { ok: true, signals: await fraud.get(b.email) }); - } - if (b.flags !== undefined) { const f = b.flags === null ? (await fraud.clearFlags(b.email), []) : await fraud.addFlags(b.email, [].concat(b.flags)); return json(res, 200, { ok: true, flags: f }); } - const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to LinkSpin until bound - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/fraud' && req.method === 'GET') { // duplicate signals: shared browsers / IPs, flagged and suspended accounts - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, Object.assign(await fraud.report(), { allow: fraud.allowList(), block: fraud.blockList() })); - } - // Approved exceptions: people Marty has okayed to hold more than one account. Adding an - // address here stops the duplicate checks blocking or hard-flagging them, and stops them - // being dropped from the leaderboard or barred from adopting. - if (p === '/api/admin/fraud/block' && req.method === 'POST') { - const b = await readBody(req); - const r = b.remove ? fraud.blockRemove(b.email) : fraud.blockAdd(b.email, b.note, ADMIN_EMAIL || 'admin'); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/fraud/allow' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = b.remove ? fraud.allowRemove(b.email) : fraud.allowAdd(b.email, b.note, ADMIN_EMAIL || 'admin'); - if (r.error) return json(res, 400, r); - console.log('fraud exception ' + (b.remove ? 'removed' : 'added') + ': ' + String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); - return json(res, 200, r); - } - // stop a member's campaign for good (2026-10-04, Marty: Shift AI closed, stop its ads): pause it on every rail, then archive it. - // Reserved budget is computed from active/paused campaigns, so archiving releases the unspent remainder to the member at - // once; flat up-front buys (visit packs) are refunded separately through /api/admin/member grantCredits. - if (p === '/api/admin/campaign/stop' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); const c = await ads.campaignById(Number(b.id)); if (!c) return json(res, 404, { error: 'No such campaign.' }); - const owner = c.owner || c.ownerEmail || c.owner_email; - if (c.status === 'active') { const r = await ads.setStatus(owner, c.id, 'paused'); if (r && r.error) return json(res, 400, r); } - const a = (c.status === 'archived') ? { ok: true, already: true, freed: 0 } : await ads.archive(owner, c.id); - console.log('admin stop campaign', c.id, owner, String(b.reason || '').slice(0, 80), JSON.stringify({ freed: a.freed })); - return json(res, a.error ? 400 : 200, Object.assign({ id: c.id, owner }, a)); - } - if (p === '/api/admin/login-queue' && req.method === 'GET') { // the prepaid login-ad line, oldest paid first (2026-10-23) - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await ads.adminLoginQueue()); - } - m = /^\/api\/admin\/login-queue\/(\d+)\/cancel$/.exec(p); - if (m && req.method === 'POST') { // admin cancel = the same full refund the owner would get - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const r = await ads.cancelLoginReservation(null, m[1], { admin: true }); - if (!r.error) console.log('admin cancelled login reservation', r.id, String(r.owner || '').replace(/^(.).*(@.*)$/, '$1***$2'), 'refunded', r.refunded); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/campaigns' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER }); - } - if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - // A house video was never checked: videoCheck guarded the member path only, so a bad - // source pasted here would hand every viewer a black player exactly as #146 did. - if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } - { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } - { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { - if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } - const r = await ads.createHouseCampaign(b); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); - if (m && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active'); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await audit.run()); - } - if (p === '/api/admin/sponsor-resolve' && req.method === 'GET') { // support: where would a buy under ?ref= land right now? - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const ref = String(u.searchParams.get('ref') || '').trim(); - const detailed = await resolveSponsorDetailed(ref); - const walk = detailed.reason === 'notActivated' ? await walkUpActivatedSponsor(ref) : null; - return json(res, 200, { ref, detailed, walk, catchId: Number(siteConfig().defaultSponsorId) || 1 }); - } - if (p === '/api/admin/trace' && req.method === 'GET') { // payment trace for any member - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase(); - let target = /^\d+$/.test(who) ? Number(who) : 0; - if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (!a && who.includes('@')) a = await accounts.byEmail(who); if (a && a.memberId) target = a.memberId; } - if (!target) return json(res, 400, { error: 'No activated member matches "' + who.slice(0, 40) + '".' }); - return json(res, 200, await tracePurchases(target, 60)); - } - if (p === '/api/admin/chain/rescan' && req.method === 'POST') { // rebuild the full event history from the deploy block - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await chain.rescan()); - } - if (p === '/api/admin/chain/status' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { events: chain.eventCount(), historyComplete: chain.historyComplete(), totals: chain.totals() }); - } - if (p === '/api/admin/reports' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { reports: await reports.list(200) }); - } - m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p); - if (m && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await reports.resolve(m[1])); - } - if (p === '/api/admin/upload' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return handleUpload(req, res, 'admin'); - } - if (p === '/api/admin/rates' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { rates: ads.rates() }); - } - if (p === '/api/admin/drip' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() }); - } - if (p === '/api/admin/drip' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' }); - if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' }); - try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); } - catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); } - } - // wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists - if (p === '/api/admin/wall-ads' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {} - return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length }); - } - if (p === '/api/admin/wall-ads' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : []; - const out = []; - for (const o of src) { - const name = String((o && o.name) || '').trim().slice(0, 60); - const targetUrl = String((o && o.targetUrl) || '').trim(); - const bannerUrl = String((o && o.bannerUrl) || '').trim(); - if (!targetUrl) continue; - if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' }); - if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' }); - out.push({ name: name || 'InstantAdPay', targetUrl, bannerUrl: bannerUrl || null }); - } - const file = path.join(DATA_DIR, 'admin-wall-ads.json'); - if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} } - return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length }); - } - // -- growth snapshot: preview the post, or send it now - if (p === '/api/admin/snapshot' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { text: await snapshot.preview() }); - } - if (p === '/api/admin/snapshot/send' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r); - } - // -- 1,000-member drop: view, mode (off|dry|armed via site config), snapshot now, pay now, resend the missed-it notices, reset (only before any payment) - if (p === '/api/admin/milestone') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - if (req.method === 'GET') return json(res, 200, await milestone.view()); - const b = await readBody(req); const act = String(b.action || ''); - if (act === 'mode') { const m = ['off', 'dry', 'armed'].includes(b.mode) ? b.mode : 'off'; const cur = siteConfig(); fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, { milestoneMode: m }, b.target ? { milestoneTarget: Number(b.target) } : {}, b.pol ? { milestonePol: Number(b.pol) } : {}), null, 2)); return json(res, 200, await milestone.view()); } - if (act === 'snapshot') { await milestone.snapshot(!!b.force); return json(res, 200, await milestone.view()); } - if (act === 'recheck') { await milestone.recheck(); return json(res, 200, await milestone.view()); } - if (act === 'pay') { const r = await milestone.pay(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } - if (act === 'settle') { await milestone.settle(); return json(res, 200, await milestone.view()); } - if (act === 'notify-missed') { const r = await milestone.notifyMissed(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } - if (act === 'reset') { const v = await milestone.view(); if (v.paid || v.sent) return json(res, 400, { error: 'Payments exist; the record stays.' }); milestone.reset(); return json(res, 200, await milestone.view()); } - return json(res, 400, { error: 'Unknown action.' }); - } - if (p === '/api/admin/site' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { site: siteConfig() }); - } - // -- profit and loss from the chain index: volume, platform fees, member payouts, - // pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee - // wallets' live balances and an admin-entered fixed monthly cost - if (p === '/api/admin/pnl' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const hunt = await huntLedger(); // marketing spend that never touches this contract - let gamesAll = null; try { gamesAll = await gamestats.allTime(); } catch (e) { gamesAll = { error: e.message }; } // every game wallet's payouts, all time, from Polygon - const days = Math.max(0, Number(u.searchParams.get('days') || 30)); - let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {} - const fromBlock = days ? latest - Math.round(days * 43200) : 0; - const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock); - const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n); - const pol = wei => Number(BigInt(wei) / 10n ** 12n) / 1e6; // 6-decimal POL, no float drift - const purchases = evs.filter(e => e.type === 'Purchase'); - const tier = evs.filter(e => e.type === 'TierPaid'); - const admin = evs.filter(e => e.type === 'AdminPaid'); - const passed = evs.filter(e => e.type === 'PassedUp'); - const byTier = {}; - for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString(); - const byPkg = {}; - for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; } - let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} - const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null }; - const balances = {}; - for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } } - return json(res, 200, { days, fromBlock, latest, polUsd, - purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg }, - platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier, - passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length }, - wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status(), polhunter: hunt, gamesAll, - // hand-entered movements in and out of the receivers: draws the chain cannot explain, and - // outside income (a ClickBaitPays withdrawal, say) that is not an AdminPaid event - ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'), - reconcile: ledger.reconcile(pol(sum(admin, e => e.amountWei)), pol(BigInt(balances.feeA || '0')), 'feeA') } }); - } - // tax summary (2026-10-04, Marty: "show what I spent in advertising versus income" at tax time). Income = the platform's cut - // of every package sale (AdminPaid), valued in dollars at that sale's own price (Purchase.priceCents / paidWei in the same - // transaction), minus sales to Marty's own positions (site config ownMemberIds, default "1": his own money moving around is - // not income), plus outside revenue lines. Costs = ledger 'cost' lines by category. Draws and transfers are listed apart: - // they are owner money, not expenses. Dates are the blocks' REAL timestamps (2026-10-04: a 2-second-per-block - // estimate drifted weeks and put September sales in August), read once from the chain and kept in DATA_DIR/blocktimes.json. - if (p === '/api/admin/tax' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const year = String(Number(u.searchParams.get('year')) || new Date().getFullYear()); - const own = new Set(String(siteConfig().ownMemberIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean)); - const evs = chain.recentEvents(1e9); - const bt = blockTimes(); const need = Array.from(new Set(evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).map(e => e.block))); - for (let i = 0; i < need.length; i += 8) await Promise.all(need.slice(i, i + 8).map(async blk => { try { const b = await chain.rpc('eth_getBlockByNumber', ['0x' + blk.toString(16), false]); if (b && b.timestamp) bt[blk] = parseInt(b.timestamp, 16) * 1000; } catch (e) {} })); - if (need.length) saveBlockTimes(bt); - const missing = evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).length; - if (missing) return json(res, 503, { error: missing + ' sale dates could not be read from the chain right now. Try again in a minute.' }); - const dayOf = blk => new Date(bt[blk]).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); - const buys = new Map(); for (const e of evs) if (e.type === 'Purchase') buys.set(e.tx, e); - const months = {}; let incomeUsd = 0, incomePol = 0, ownUsd = 0, sales = 0; - for (const e of evs) { - if (e.type !== 'AdminPaid') continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; - const b = buys.get(e.tx); const pol = Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6; - const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0; - if (own.has(Number(e.buyerId))) { ownUsd += usd; continue; } - incomeUsd += usd; incomePol += pol; sales++; const m = day.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; months[m].incomeUsd += usd; - } - const lines = ledger.entriesFor(year); let outsideUsd = 0; const costs = {}; const draws = []; const transfers = []; - for (const l of lines) { - const m = l.date.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; - if (l.kind === 'revenue') { outsideUsd += l.usd; months[m].incomeUsd += l.usd; } - else if (l.kind === 'cost') { const c = l.category || 'other', v = l.dir === 'out' ? l.usd : -l.usd; costs[c] = (costs[c] || 0) + v; months[m].costUsd[c] = (months[m].costUsd[c] || 0) + v; } - else if (l.kind === 'draw') draws.push(l); else transfers.push(l); - } - const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.games || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0); - const csv = [['Section', 'Date', 'Category', 'Description', 'POL', 'USD', 'Transaction'].join(',')]; - const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"'; - for (const e of evs) { if (e.type !== 'AdminPaid' || own.has(Number(e.buyerId))) continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; const b = buys.get(e.tx); - const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0; - csv.push(['Income', day, 'Platform share of package sale', 'Member #' + e.buyerId + (b ? ' bought the $' + Math.round(b.priceCents / 100) + ' package' : ''), (Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6).toFixed(6), usd.toFixed(2), e.tx].map(q).join(',')); } - for (const l of lines) { const sec = l.kind === 'revenue' ? 'Income' : l.kind === 'cost' ? 'Expense' : l.kind === 'draw' ? 'Owner draw (not an expense)' : 'Transfer (not income or expense)'; - csv.push([sec, l.date, l.kind === 'cost' ? (ledger.CATS[l.category] || l.category) : l.kind, l.note, (l.dir === 'out' ? -1 : 1) * l.amount, (l.kind === 'cost' && l.dir === 'out' ? -1 : 1) * l.usd, l.tx].map(q).join(',')); } - csv.push(''); csv.push(q('Sale dates are the Polygon block timestamps, in US Central time. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out. USD values are each sale\'s own package price.')); - return json(res, 200, { year, ownMemberIds: Array.from(own), - income: { platformUsd: r2(incomeUsd), platformPol: Math.round(incomePol * 1e4) / 1e4, sales, outsideUsd: r2(outsideUsd), totalUsd: r2(incomeUsd + outsideUsd), ownSalesExcludedUsd: r2(ownUsd) }, - expenses: { byCategory: Object.fromEntries(Object.entries(costs).map(([k, v]) => [k, r2(v)])), labels: ledger.CATS, advertisingAndPromotionUsd: r2(adPromo), totalUsd: r2(allCosts) }, - netUsd: r2(incomeUsd + outsideUsd - allCosts), draws: draws.length, transfers: transfers.length, - months: Object.fromEntries(Object.keys(months).sort().map(k => [k, { incomeUsd: r2(months[k].incomeUsd), costUsd: r2(Object.values(months[k].costUsd).reduce((n, v) => n + v, 0)) }])), - csv: csv.join('\n') }); - } - if (p === '/api/admin/ledger' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = ledger.put(b); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/ledger/delete' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = ledger.remove(String(b.id || '')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/videosweep' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, await videosweep.run({ dry: !!b.dry })); - } - if (p === '/api/admin/sbcheck' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, await sbcheck.run({ dry: !!b.dry })); - } - if (p === '/api/admin/burner' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, burner.status()); - } - if (p === '/api/admin/burner/run' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await burner.tick()); - } - - // -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session) - if (p === '/api/admin/burns' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { pending: await ads.pendingBurns() }); - } - if (p === '/api/admin/burns/mark' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await ads.markBurned(b.id, b.tx); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/rates' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, { ok: true, rates: ads.setRates(b) }); - } - - if (p === '/api/admin/site' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const cur = siteConfig(); - fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2)); - return json(res, 200, { ok: true, site: siteConfig() }); - } - if (p === '/api/admin/chain' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const file = path.join(DATA_DIR, 'config.json'); - let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {} - fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2)); - chain.reloadConfig(); - return json(res, 200, { ok: true, config: chain.getConfig() }); - } - - // -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body) - if (req.method === 'GET' || req.method === 'HEAD') { - if (p === '/') { - // arrived from PolHunter: remember it for 30 days so the dashboard can send them back once a wallet is linked - if (u.searchParams.get('from') === 'polhunter') { res.writeHead(302, { Location: '/', 'Set-Cookie': 'iap.return=polhunter; Path=/; SameSite=Lax; Max-Age=' + (30 * 24 * 3600) + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } - return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); - } - if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html')); - if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html')); - if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html')); - if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html')); - if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html')); - if (p === '/facts') return sendFile(res, path.join(PUBLIC_DIR, 'facts.html')); // verified platform facts (2026-10-06), linked from every footer - if (p === '/llms.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(fs.readFileSync(path.join(PUBLIC_DIR, 'llms.txt'))); } - if (p === '/my') return sendFile(res, path.join(PUBLIC_DIR, 'my.html')); - if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); - if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html')); - if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html')); - if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12) - if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); - if (p === '/games') return sendFile(res, path.join(PUBLIC_DIR, 'games.html')); - if (p === '/presentation') return sendFile(res, path.join(PUBLIC_DIR, 'presentation.html')); // narrated Build Wide presentation, captions in 6 languages (2026-10-15) // public games list (2026-10-10) // member guide: how earning works (2026-09-12) - // -- badge share page + image: /b// (OG preview = the member's composed badge) (Marty, 2026-09-13) - m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p); - if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg')); - m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p); - if (m) { - const un = m[1].toLowerCase(), key = m[2]; - const a = await accounts.byUsername(un); - const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg'); - if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const [label, sub] = BADGE_META[key]; - const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const url = 'https://instantadpay.com/b/' + un + '/' + key, img = 'https://instantadpay.com/badge-img/' + un + '/' + key + '.jpg'; - const title = '@' + un + ' unlocked ' + label + ' on InstantAdPay'; - const desc = label + ': ' + sub + '. InstantAdPay pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.'; - const html = '' + esc(title) + '' - + '' - + '' - + '' - + '' - + '' - + '
      ' + esc(label) + ' badge for @' + esc(un) + '

      @' + esc(un) + ' unlocked ' + label + '

      ' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

      ' - + 'Join @' + esc(un) + '\u2019s line free

      Advertising with a performance referral program. Not an investment; no income is guaranteed.

      ' - + ''; - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); - return res.end(html); - } - // -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12) - if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) { - const posts = await blog.listPublished(); - const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1; - const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null; - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); - return res.end(blog.renderIndex(posts, pg, tag)); - } - m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p); - if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); } - if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); } - if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); } - if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); } - if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); } - if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); } - m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p); - if (m) { - const post = await blog.get(m[1]); - const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL - if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('', '<title>Not found | ')); } - if (!preview && req.method === 'GET') blog.bumpViews(post.slug); - const related = blog.relatedFor(post, await blog.listPublished()); - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' })); - return res.end(blog.renderPost(post, related)); - } - if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html')); - if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link - if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html')); - if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html')); - if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Drip Runner refuel visit (2026-09-30) - if (p === '/door') return sendFile(res, path.join(PUBLIC_DIR, 'door.html')); // Spooky Doors door visit (2026-10-02) - // per-partner kit pages (Marty, 2026-09-29): /partners/<slug> serves public/kits/<slug>.html, one file per reviewer or site owner - { const mk = p.match(/^\/partners\/([a-z0-9-]{2,40})$/); if (mk) { const f = path.join(PUBLIC_DIR, 'kits', mk[1] + '.html'); if (fs.existsSync(f)) return sendFile(res, f); } } - if (p === '/plan-lab') return sendFile(res, path.join(PUBLIC_DIR, 'plan-lab.html')); // Reach Ladder simulator for Marty's planning group: unlisted, shared by link (2026-09-27) - if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html')); - if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html')); - m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p); - if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1])); - if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html')); - m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS) - try { - const tok = m[1].toLowerCase(); - let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok); - let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8'); - if (a) { - const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0); - const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const title = nm + ' on InstantAdPay'; - const desc = a.bio ? esc(a.bio).slice(0, 200) : 'Join ' + nm + '’s line on InstantAdPay — instant on-chain ad payouts, free to join.'; - const img = a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : 'https://instantadpay.com/banners/iap-hero-1200x630.png'; - const url = 'https://instantadpay.com/wall/' + (a.username || a.code); - const og = [ - '<meta property="og:type" content="profile">', - '<meta property="og:site_name" content="InstantAdPay">', - '<meta property="og:url" content="' + url + '">', - '<meta property="og:title" content="' + esc(title) + '">', - '<meta property="og:description" content="' + desc + '">', - '<meta property="og:image" content="' + esc(img) + '">', - '<meta name="twitter:card" content="summary_large_image">', - '<meta name="twitter:title" content="' + esc(title) + '">', - '<meta name="twitter:description" content="' + desc + '">', - '<meta name="twitter:image" content="' + esc(img) + '">', - '<meta name="description" content="' + desc + '">', - '<link rel="canonical" href="' + url + '">' - ].join('\n'); - html = html.replace('<title>Banner wall | InstantAdPay', '' + esc(title) + '').replace('', og); - } - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); - return res.end(html); - } catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); } - } - const safe = path.normalize(p).replace(/^([.\\/])+/, ''); - const file = path.join(PUBLIC_DIR, safe); - if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file); - } - - res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); - res.end('Not found'); - } catch (e) { - console.error('request error', req.url, e.message); - try { json(res, 500, { error: 'server error' }); } catch (_) {} - } -}); -boot().then(() => { - server.listen(PORT, () => console.log(`InstantAdPay site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}`)); -}).catch(e => { console.error('boot failed:', e.message); process.exit(1); }); +// InstantAdPay — membership advertising with immutable on-chain settlement. +// Zero-dependency Node server (RM Circle pattern): static pages + JSON API, +// wallet sign-in (SIWE), live contract ledger, sponsor join links. +// +// Chain selection (Amoy rehearsal vs mainnet) lives in data/config.json — +// see chain.js. Wipe the volume's accounts/sessions + flip config = launch. +const http = require('http'); +const discordRelay = require('./discord-relay.cjs'); // mirror group posts into the CTB Discord (2026-10-09) +const https = require('https'); +const dns = require('dns'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const sendy = require('./sendy'); +const { URL } = require('url'); +const chain = require('./chain'); +const auth = require('./auth'); +const accounts = require('./accounts'); +const ads = require('./ads'); +const mailer = require('./mailer'); +const { emailIssue } = require('./emailcheck'); // typo / no-mail-domain check for NEW addresses (2026-10-22) +// only addresses we have never seen get the typo check; existing members always sign in with what they have. +// Skipped when this server cannot send mail (local QA copies sign in as @example.com via devCode). +const newEmailIssue = async e => (!mailer.hasKey() || (await accounts.byEmail(e)) ? null : emailIssue(e)); +const messages = require('./messages'); +const reports = require('./reports'); +const drip = require('./drip'); +const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) +let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } +const chatbot = require('./chatbot'); +const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20) +const fraud = require('./fraud'); +const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats +const tank = require('./tank'); +const walletnudge = require('./walletnudge'); +const milestone = require('./milestone'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward +const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails +const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) +const loginShows = require('./loginshows'); // login-ad showings per day, dashboard vs games (2026-10-18) +const promos = require('./promos'); +const missedNotice = require('./missed'); // the whole-chain missed-payout notice // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box) +const blog = require('./blog'); +const adminMember = require('./adminmember'); +const syndicate = require('./syndicate'); +const releases = require('./releases'); +const ledger = require('./ledger'); +const videosweep = require('./videosweep'); +const sbcheck = require('./sbcheck'); +const reach = require('./reach'); +const lssync = require('./lssync'); +const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) +const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22) +let follow = null, followStore = null; +const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''); +let activationCache = { at: 0, map: null }; +function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor) + if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map; + const m = new Map(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'MemberActivated' && ev.account) { const k = String(ev.account).toLowerCase(); if (!m.has(k)) m.set(k, { id: ev.id, sponsorId: ev.sponsorId, block: ev.block, tx: ev.tx }); } + activationCache = { at: Date.now(), map: m }; return m; +} +const gamestats = require('./gamestats'); +const marks = require('./marks'); +const gamepass = require('./gamepass'); // the $5 weekly Game Pass + the account-wide POL cap service the games call (2026-10-16) +const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations +const updates = require('./updates'); +const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14) +const leaderboard = require('./leaderboard'); +const toolkit = require('./toolkit'); +const badge = require('./badge'); // achievement badge image drawn on the server with ffmpeg (2026-09-16) +const friday = require('./friday'); +const starter = require('./starter'); // member welcome offer from the games (2026-10-05) +const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29) +const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26) +const refill = require('./refill'); +const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) +const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +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 translate = require('./translate'); // help desk: member messages in other languages, replies back in theirs (2026-10-16) +const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16) +const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16) +const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16) +const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) +const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) +const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/presentation', '/support']); +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 PORT = Number(process.env.PORT || 3000); +const ROOT = __dirname; +const PUBLIC_DIR = path.join(ROOT, 'public'); +const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data'); +const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; +const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); +// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept +// in the volume so a restart doesn't log the admin out. Separate cookie and +// store from member sessions; the Bearer ADMIN_PASSWORD API path still works. +const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json'); +const ADMIN_TTL = 12 * 60 * 60 * 1000; +let adminSessions = {}; +try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } +function saveAdminSessions() { + const now = Date.now(); + for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k]; + try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {} +} +function mintAdminSession(email) { + const t = crypto.randomBytes(32).toString('hex'); + adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL }; + saveAdminSessions(); + return t; +} +function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; } +function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; } +function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } } +function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); } +function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; } +const IS_PROD = process.env.NODE_ENV === 'production'; +const todayCT = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Marty's day, never UTC +const SITE_FILE = path.join(DATA_DIR, 'site.json'); + +const db = require('./db'); +fs.mkdirSync(DATA_DIR, { recursive: true }); +const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume +fs.mkdirSync(UPLOADS_DIR, { recursive: true }); +const uploadCounts = new Map(); // email:day -> uploads today +// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a +// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart) +const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json'); +const persistedMaps = {}; +let tokenSaveTimer = null; +function saveOpenTokens() { + tokenSaveTimer = null; + try { + const out = {}; + for (const [name, m] of Object.entries(persistedMaps)) out[name] = Object.fromEntries(m); + fs.writeFileSync(OPEN_TOKENS_FILE(), JSON.stringify(out)); + } catch (e) {} +} +function persistedMap(name) { + const m = new Map(); + const touch = () => { if (!tokenSaveTimer) tokenSaveTimer = setTimeout(saveOpenTokens, 500); }; + const set = m.set.bind(m), del = m.delete.bind(m); + m.set = (k, v) => { set(k, v); touch(); return m; }; + m.delete = k => { const r = del(k); if (r) touch(); return r; }; + persistedMaps[name] = m; + return m; +} +function loadOpenTokens() { + let saved = null; try { saved = JSON.parse(fs.readFileSync(OPEN_TOKENS_FILE(), 'utf8')); } catch (e) { return; } + const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0; + // durable maps are balances and orders, not short-lived tokens: restore every entry whatever its age. Before 2026-10-10 the + // age filter silently dropped every PolyWarriors mint pass (no ts on the record) on each deploy; Orlando lost his. + const DURABLE = new Set(['pwpasses', 'pwprizes', 'pworders', 'gkorders', 'sdorders', 'gamepass', 'gporders', 'gpprizes']); + for (const [name, m] of Object.entries(persistedMaps)) { + for (const [k, v] of Object.entries(saved[name] || {})) if (v && (DURABLE.has(name) || Number(v.ts || 0) > cutoff)) { Map.prototype.set.call(m, k, v); n++; } + } + if (n) console.log('open earn tokens restored:', n); +} +const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor) +const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor) +const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit) +const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor) +// walk the referral chain upward via sponsorRef (code/username/member id) +async function uplineSlides(email, depth = 3) { + const out = []; + let cur = await accounts.byEmail(email); + for (let i = 0; i < depth && cur; i++) { + const ref = String(cur.sponsorRef || '').trim().toLowerCase(); + if (!ref) break; + let s = null; + if (/^\d+$/.test(ref)) s = await accounts.byMemberId(Number(ref)); + if (!s) s = await accounts.byCode(ref); + if (!s) s = await accounts.byUsername(ref); + if (!s || s.email === cur.email) break; + out.push(s); + cur = s; + } + return out; +} +// Wall ownership ladder: position 1 is always the member's own line banner; +// positions 2 and 3 become theirs at 2 and 5 qualifying buyers (the same +// thresholds that open payout levels 2 and 3). Until then, or while an unlocked +// slot is empty, the slot shows an upline's banner, then a house ad. +const catalogCache = { at: 0, products: null }; +const wallUnlockedFor = bc => (bc >= 5 ? 3 : bc >= 2 ? 2 : 1); +// every on-chain member id this session controls: the main wallet plus linked +// positions (Qualified Start). Credits pool across them on the dashboard. +const memberInfoCache = new Map(); // id -> { t, v } (60s): line views ask for every member's on-chain row +async function cachedMember(id) { + const c = memberInfoCache.get(id); if (c && Date.now() - c.t < 60000) return c.v; + let v = null; try { v = await chain.member(id); } catch (e) {} + memberInfoCache.set(id, { t: Date.now(), v }); return v; +} +async function myMemberIds(s) { + const main = await auth.refreshMemberId(s); + const ids = main ? [main] : []; + if (s && s.email) for (const p of await accounts.positions(s.email)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); + return { main, ids }; +} +function parseWallOffers(a) { + try { const v = JSON.parse((a && a.wallOffers) || '[]'); return Array.isArray(v) ? v.slice(0, 2) : []; } catch (e) { return []; } +} +// admin fallback ads for wall positions 2 & 3 when a member has no upline. +// Configurable by dropping data/admin-wall-ads.json ([{name,targetUrl,bannerUrl}]). +function getAdminWallAds() { + try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); if (Array.isArray(j) && j.length) return j; } catch (e) {} + return [{ name: 'InstantAdPay', targetUrl: 'https://instantadpay.com/', bannerUrl: null }]; +} +const chatHits = new Map(); +function chatLimited(ip) { + const now = Date.now(), rec = chatHits.get(ip); + if (!rec || now > rec.reset) { chatHits.set(ip, { count: 1, reset: now + 60000 }); return false; } + rec.count += 1; + return rec.count > 10; +} +// magic-code sign-in: emailLower -> {code, exp, tries} +const emailCodes = new Map(); +// Sponsor bound to the sign-up, not only to a cookie (Marty, 2026-09-29: nancyr #180 and others "supposed to land under +// Mad Dog" were created with no sponsor and fell to the company). The iap.sponsor cookie is SameSite=Lax, so it is +// rejected when the join page is shown inside another site (traffic-exchange frames), and it never crosses browsers +// (in-app browser -> mail app -> default browser). So: the join page sends the token from its own URL with the code +// request, the server remembers "this email asked for a code under " for 30 days on disk (deploys restart the +// process), and account creation uses page token, then cookie, then that memory. A token-less request never +// overwrites a remembered token. +const pendingSponsor = { + FILE: () => path.join(DATA_DIR, 'pending-sponsors.json'), db: null, + load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = {}; } }, + save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }, + set(email, f) { if (!email || !f || !f.ref) return; if (!this.db) this.load(); this.db[email] = { ref: f.ref, via: f.via || '', joinedRef: f.joinedRef || null, at: Date.now() }; this.prune(); this.save(); }, + get(email) { if (!this.db) this.load(); const r = this.db[email]; return r && Date.now() - r.at < 30 * 86400e3 ? r : null; }, + del(email) { if (!this.db) this.load(); if (this.db[email]) { delete this.db[email]; this.save(); } }, + prune() { const cut = Date.now() - 30 * 86400e3; for (const k of Object.keys(this.db)) if (this.db[k].at < cut) delete this.db[k]; } +}; +const pageTok = v => { const t = String(v || '').trim().toLowerCase(); return /^[a-z0-9_]{1,40}$/.test(t) ? (JOIN_ALIASES[t] || t) : ''; }; // a token the join page read from its own URL +// ── sign-up code guard (Marty, 2026-09-11): the email box is one field and one +// tap, so nothing visible stands in a human's way. Bots hit four invisible walls: +// a honeypot field, a minimum form age, per-IP + global send limits, and, only +// once an IP trips a limit, the same icon check the ad viewer uses. +const CODE_LIMITS = { per10m: 5, perDay: 20, globalPerMin: 60, passMs: 5 * 60 * 1000, minFormMs: 2000 }; +const codeHits = new Map(); // ip -> { t: [send timestamps, 24h], passUntil, chal: { answer, exp } } +const codeGlobal = { minute: 0, n: 0 }; +const codeAlert = { last: 0, trips: 0, ips: new Set() }; +function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; } +// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign) +function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; } +function codeChallenge(rec) { + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + rec.chal = { answer: pick[answer][0], exp: Date.now() + 5 * 60 * 1000 }; + return { prompt: pick[answer][1], options: pick.map(x => x[0]) }; +} +// returns null to allow the send, or { status, body } to answer with instead +const guardLog = (req, why, b) => console.log('signup-guard', why, clientIp(req), String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); +function codeGuard(req, b) { + const now = Date.now(); + // honeypot: bots fill it, humans never see it. Some form-filler extensions fill every field, + // hidden or not (seen 2026-09-11), so a filled honeypot is a CHALLENGE, never a silent drop: + // a person passes the icon check and gets the code, a bot cannot. + const hpRaw = String(b.hp_field_x9 || '').trim(); + const hpIsEmail = !!hpRaw && hpRaw.toLowerCase() === String(b.email || '').trim().toLowerCase(); + const hp = !!hpRaw && !hpIsEmail; // 2026-09-13: phones were autofilling the hidden field; own email = autofill, not a bot + if (hpRaw) console.log('signup-guard honeypot-value', clientIp(req), hpIsEmail ? 'own-email' : (/^https?:/i.test(hpRaw) ? 'url' : /@/.test(hpRaw) ? 'other-email' : /^\+?[\d\s()-]{6,}$/.test(hpRaw) ? 'phone' : 'text'), 'len=' + hpRaw.length, hpIsEmail ? '' : hpRaw.slice(0, 2) + '***'); + // Form age is measured on the visitor's own clock (fage = their Date.now() minus the moment the form loaded), so a + // phone whose clock runs fast or slow is not refused forever. Comparing their fts with OUR clock did exactly that + // (2026-10-07: a member retried and was stopped every time). Old cached pages send only fts: fall back to it. + const fts = Number(b.fts) || 0; + const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1); + if (fage < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; } + if (fage > 12 * 3600 * 1000) { guardLog(req, 'form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then tap again.' } }; } + const minute = Math.floor(now / 60000); + if (codeGlobal.minute !== minute) { codeGlobal.minute = minute; codeGlobal.n = 0; } + if (codeGlobal.n >= CODE_LIMITS.globalPerMin) { guardLog(req, 'global-limit', b); codeTrip(req, 'global'); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } + const ip = clientIp(req); + const rec = codeHits.get(ip) || { t: [], passUntil: 0, chal: null }; + rec.t = rec.t.filter(ts => now - ts < 24 * 3600 * 1000); + const n10 = rec.t.filter(ts => now - ts < 10 * 60 * 1000).length; + const limited = hp || n10 >= CODE_LIMITS.per10m || rec.t.length >= CODE_LIMITS.perDay; + if (limited && now >= rec.passUntil) { + const pick = String(b.pick || ''); + if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } + else { + guardLog(req, pick ? 'wrong-pick' : hp ? 'honeypot-challenge' : 'ip-limit', b); if (!hp) codeTrip(req, ip); + const challenge = codeChallenge(rec); codeHits.set(ip, rec); + return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send another code.', challenge } }; + } + } + rec.t.push(now); codeHits.set(ip, rec); codeGlobal.n += 1; + if (codeHits.size > 5000) for (const [k, v] of codeHits) { if (!v.t.length || now - v.t[v.t.length - 1] > 24 * 3600 * 1000) codeHits.delete(k); } + return null; +} +// burst alert: at most one message per 10 minutes, to the admin Telegram chat if set, else the admin email +function codeTrip(req, ip) { + codeAlert.trips += 1; codeAlert.ips.add(ip); + if (Date.now() - codeAlert.last < 10 * 60 * 1000) return; + codeAlert.last = Date.now(); + const text = '\u26A0\uFE0F InstantAdPay sign-up guard: ' + codeAlert.trips + ' blocked code request' + (codeAlert.trips === 1 ? '' : 's') + ' from ' + codeAlert.ips.size + ' source' + (codeAlert.ips.size === 1 ? '' : 's') + ' (' + [...codeAlert.ips].slice(0, 5).join(', ') + ') in the last window.'; + codeAlert.trips = 0; codeAlert.ips = new Set(); + const sc = siteConfig(); + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: sign-up guard tripped', text).catch(() => {}); +} +// earn-view tokens: emailLower -> {token, ts} (one live token per member) +const earnTokens = persistedMap('earn'); +// human-check pairs for the view verifier: [emoji shown, word named in the prompt] +const CAPTCHA = [['🚀', 'rocket'], ['⚡', 'lightning bolt'], ['🔑', 'key'], ['🎯', 'target'], + ['🌊', 'wave'], ['🔥', 'flame'], ['💎', 'diamond'], ['🧲', 'magnet'], ['🔔', 'bell'], ['🌙', 'moon']]; +// Spooky Doors' door check uses Halloween icons (Marty, 2026-10-02) +const DOOR_CAPTCHA = [['🎃', 'pumpkin'], ['👻', 'ghost'], ['🦇', 'bat'], ['🍬', 'candy'], ['🕷️', 'spider'], ['💀', 'skull'], ['🍭', 'lollipop'], ['🧙', 'witch'], ['🕸️', 'spider web'], ['🌕', 'full moon'], ['🍫', 'chocolate']]; + +// ── frame-breaking check ───────────────────────────────── +// Surf views frame the advertiser's URL full screen, so a target that refuses +// framing (X-Frame-Options / CSP frame-ancestors) would burn members' views on +// a blank frame. Catch it the moment the campaign is submitted. The lookup +// also refuses private/internal addresses so member URLs can't probe our LAN. +const PRIVATE_IP = /^(127\.|10\.|192\.168\.|169\.254\.|0\.|172\.(1[6-9]|2\d|3[01])\.|::1$|::$|f[cd])/i; +function frameFetch(url, depth) { + return new Promise(resolve => { + let u; + try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); } + if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' }); + if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' }); + if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' }); + dns.lookup(u.hostname, (de, addr) => { + if (de) return resolve({ error: 'that domain does not resolve' }); + if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' }); + const mod = u.protocol === 'https:' ? https : http; + const rq = mod.get(u.href, { timeout: 8000, + headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-FrameCheck/1.0)', Accept: 'text/html' } }, r => { + const loc = r.headers.location; + r.resume(); // headers are all we need + if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) { + rq.destroy(); + let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); } + return resolve(frameFetch(next, depth + 1)); // every hop re-runs the private-IP guard + } + resolve({ status: r.statusCode, xfo: r.headers['x-frame-options'] || '', csp: r.headers['content-security-policy'] || '' }); + rq.destroy(); + }); + rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); }); + rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' })); + }); + }); +} +// shared upload path for member creatives (/api/my/upload) and admin house-ad +// creatives (/api/admin/upload): `who` keys the per-day upload counter +async function handleUpload(req, res, who) { + const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase(); + const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', + 'video/mp4': 'mp4', 'video/webm': 'webm' }; + if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' }); + const isVideo = ct.startsWith('video/'); + const key = who + ':' + new Date().toISOString().slice(0, 10); + if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' }); + let buf; + try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); } + catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); } + const magicOk = buf.length > 16 && ( + (ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || + (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || + (ct === 'image/webp' && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') || + (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8') || + (ct === 'video/mp4' && buf.slice(4, 8).toString() === 'ftyp') || + (ct === 'video/webm' && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3)); + if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' }); + const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct]; + uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1); + // video goes to DO Spaces when configured (keeps big files off the volume); + // images stay local. Falls back to the volume if Spaces isn't set or errors. + if (isVideo && spaces.enabled()) { + try { + const url = await spaces.put('iap-uploads/' + name, buf, ct); + return json(res, 200, { url, type: 'video' }); + } catch (e) { console.error('spaces put', e.message); /* fall through to volume */ } + } + fs.writeFileSync(path.join(UPLOADS_DIR, name), buf); + return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' }); +} +// lead-capture page hooks (og tags + copy live in public/assets/join.js too) +const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position +const JOIN_ANGLES = { + // legacy bridge pages (/from/): former members of Marty's closed EvolutionScript sites + 'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/faucetwave?seg=advertiser' }, + 'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/faucetwave' }, + 't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. InstantAdPay was built for the people who bought ads there: packages from $5, seven formats, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/tieroneads?seg=advertiser' }, + 't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: 'https://instantadpay.com/from/tieroneads' }, + // SocialPix (socialpix.club) gate, 2026-09-20: the media-sharing site was being used as a free + // ad board; its signup/post flows now land here. Default copy = advertiser (that is why they came). + 'sp-adv': { t: 'Your ad, seen across a whole network.', d: 'SocialPix no longer takes ad posts. Advertising now runs through InstantAdPay: a free account, your ad in seven formats across every site in the network, and every package in your line paid out on Polygon in the same transaction. Real email required.', url: 'https://instantadpay.com/from/socialpix' }, + 'sp-earn': { t: 'Same feed. Real payouts on-chain.', d: 'SocialPix has moved its advertising to InstantAdPay. View ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Join free by email.', url: 'https://instantadpay.com/from/socialpix?seg=earn' }, + play: { t: 'If you have time to play a game, you have time to build a business.', d: 'Free games that pay real Polygon to your wallet, on chain, where anyone can check it. Play free, then join free by email.' }, + instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' }, + adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, packages from $5. Join free.' }, + free: { t: 'Watch first. Spend never.', d: 'Join free, view a few ads, earn credits, run your first campaign for zero dollars. Every payout public on Polygon.' }, + friday: { t: 'Five Dollar Friday: 20% bonus credits.', d: 'Every Friday, US Central time, any ad package from $5 up earns 20% bonus credits the moment it settles, and every pack pays its sponsor line in the same transaction. Join free by email.' }, + wednesday: { t: 'Wired Wednesday: 25% bonus credits, wired in the second it settles.', d: 'Every Wednesday, US Central time, any ad package from $20 up earns 25% bonus credits, wired into your balance the moment the purchase settles and good for any ad format. Join free by email.' }, + ledger: { t: 'No back office. No payday.', d: 'Every payout is a public transaction on Polygon you can read yourself. Nothing is ever held. Join free by email.' }, + two: { t: 'Two buyers open level two.', d: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written in a verified contract.' }, + // Build Wide hook (2026-10-15): the 'buildwide' promo video; files keep the uploaded promo/buildwide.* names + wide: { t: 'Width unlocks depth.', d: 'Watch the fifty percent land, then the deeper levels open. Every package in your line is split by a verified contract on Polygon in the same transaction. Join free by email.', img: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/buildwide.jpg', imgW: 1280, imgH: 720 } +}; +function serveJoinPage(res, tok, angle, ang, setCookies) { + let html; + try { html = fs.readFileSync(path.join(PUBLIC_DIR, 'join.html'), 'utf8'); } catch (e) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const base = 'https://instantadpay.com'; + const url = (ang && ang.url) || (base + '/join/' + tok + (angle ? '?v=' + angle : '')); + const title = ang ? ang.t : 'Advertise and earn. Paid on-chain, instantly.'; + const desc = ang ? ang.d : 'You are invited to InstantAdPay: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.'; + // each hook angle previews with its own video's opening frame (Marty 2026-10-13: shared angle links all showed the generic hero) + const ogImg = (ang && ang.img) || (base + (['play', 'instant', 'adspend', 'free', 'ledger', 'two'].includes(angle) ? '/banners/iap-angle-' + angle + '-1200x630.jpg?v=1' : '/banners/iap-hero-1200x630.png')); + const ogW = (ang && ang.imgW) || 1200, ogH = (ang && ang.imgH) || 630; + const escA = t => String(t).replace(/&/g, '&').replace(/"/g, '"').replace(/' + + '' // keeps ?v= so shares stay on the angle + + '' + + ''; + html = html.replace(/[^<]*<\/title>/, '<title>' + escA(title) + ' | InstantAdPay' + og); + if (ang) html = html.replace('', ''); // angle pages: squeeze layout from the first paint + // Network Ad Space zone on the two legacy squeeze pages only (Marty, 2026-09-19): below the + // fine print, above the footer links. The regular join pages stay ad-free. + if (/^(fw|t1)-(adv|earn)$/.test(String(angle || ''))) html = html.replace('
      ', + '
      ' + '
      '); + const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' }; + if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies; + res.writeHead(200, baseHeaders(headers)); + res.end(html); +} +// A banner creative must be an IMAGE (2026-09-16: campaign #134 had the member's join-page link in the +// image field and served a broken banner 141 times on the network). Accept /uploads/ files and +// image extensions outright; otherwise HEAD the URL and require an image/* content-type. +async function imageCheck(url) { + const u = String(url || '').trim(); + if (/^\/uploads\//.test(u) || /^https?:\/\/instantadpay\.com\/(uploads|banners)\//i.test(u)) return { ok: true }; + if (/\.(png|jpe?g|gif|webp|svg)([?#].*)?$/i.test(u)) return { ok: true }; + try { + const h = await headUrl(u); + if (h && /^image\//i.test(String(h.contentType || ''))) return { ok: true }; + return { ok: false, reason: 'That link is a web page, not an image. Paste the direct image link (it usually ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' }; + } catch (e) { return { ok: false, reason: 'Could not load that image link. Paste the direct image link (ends in .png or .jpg), or use Promo tools > Banners > Copy image URL.' }; } +} +// A video campaign's source has to actually exist. The create form only matched the URL +// shape, so a placeholder (yourdomain.com/....mp4) went live on 2026-09-11 and sat there for +// eleven days handing every Tier 1 viewer a black player they could never finish. +// PolHunter pays real POL out of its own faucet and none of it passes through this contract, so +// the P&L cannot derive it from chain events and has to read it across (Marty, 2026-09-23). Cached +// and fail-soft: the P&L page must never hang or break because the other site is down. +let huntCache = { at: 0, data: null }; +// real block timestamps for the tax summary, read once and kept (a block's time never changes) +let blockTimesCache = null; +function blockTimes() { if (!blockTimesCache) { try { blockTimesCache = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'blocktimes.json'), 'utf8')); } catch (e) { blockTimesCache = {}; } } return blockTimesCache; } +function saveBlockTimes(bt) { try { const f = path.join(DATA_DIR, 'blocktimes.json'); fs.writeFileSync(f + '.tmp', JSON.stringify(bt)); fs.renameSync(f + '.tmp', f); } catch (e) {} } +async function huntLedger() { + if (Date.now() - huntCache.at < 120000) return huntCache.data; + const base = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, ''); + try { + const r = await fetch(base + '/api/ledger', { signal: AbortSignal.timeout(6000) }); + if (!r.ok) throw new Error('HTTP ' + r.status); + const j = await r.json(); + huntCache = { at: Date.now(), data: { totals: j.totals || null, referrals: j.referrals || null, pools: j.pools || null, at: Date.now() } }; + } catch (e) { + huntCache = { at: Date.now(), data: huntCache.data || { error: e.message } }; + } + return huntCache.data; +} +async function videoCheck(url) { + const u = String(url || '').trim(); + if (/^\/uploads\//.test(u)) return { ok: true }; // uploaded here, already on our disk + let h; + try { h = await headUrl(u); } + catch (e) { // no DNS, refused, timed out + return { ok: false, reason: 'We could not reach that video link, so members would just see a black player. Check the address, or upload the file here instead.' }; + } + if (h && (h.status === 404 || h.status === 410)) + return { ok: false, reason: 'That video link answers with HTTP ' + h.status + ' — the file is not there. Point the campaign at a file that loads, or upload it here.' }; + const ct = String((h && h.contentType) || '').split(';')[0].trim().toLowerCase(); + if (ct && !/^video\//.test(ct) && ct !== 'application/octet-stream' && ct !== 'binary/octet-stream') + return { ok: false, reason: 'That link returns ' + ct + ', not a video file. Paste the direct .mp4 or .webm link, or upload the file here.' }; + return { ok: true }; +} +function headUrl(url) { + return new Promise((resolve, reject) => { + let u; try { u = new URL(url); } catch (e) { return reject(new Error('bad url')); } + const mod = u.protocol === 'http:' ? require('http') : require('https'); + const req = mod.request({ method: 'HEAD', hostname: u.hostname, port: u.port || undefined, path: u.pathname + u.search, timeout: 6000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; InstantAdPay-ImageCheck/1.0)' } }, r => { + if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location && !u.searchParams.has('_r')) { try { const nx = new URL(r.headers.location, url); nx.searchParams.set('_r', '1'); return resolve(headUrl(nx.toString())); } catch (e) {} } + resolve({ status: r.statusCode, contentType: r.headers['content-type'] || '' }); r.resume(); + }); + req.on('error', reject); req.on('timeout', () => req.destroy(new Error('timeout'))); req.end(); + }); +} +// login-ad gate: can this sponsor's page load inside our frame? Cached 6 h per campaign + url; an answer that +// takes longer than 4 s counts as "no" for this sign-in (new-tab fallback) while the check finishes for the cache. +const loginFrameCache = new Map(); +async function loginFrameable(id, url, inGame) { // inGame: the frame sits on a game's page, so an allowance for instantadpay.com alone is not enough + const key = (inGame ? 'g|' : '') + id + '|' + url, hit = loginFrameCache.get(key); + if (hit && Date.now() - hit.ts < 6 * 3600 * 1000) return hit.ok; + if (!url) return false; + const check = frameCheck(url, inGame).then(r => { loginFrameCache.set(key, { ok: !!r.ok, ts: Date.now() }); return !!r.ok; }).catch(() => false); + return Promise.race([check, new Promise(r => setTimeout(() => r(false), 4000))]); +} +async function frameCheck(url, inGame) { + const h = await frameFetch(url, 0); + if (h.error) return { ok: false, reason: 'We checked your URL and ' + h.error + '. Fix the URL and try again.' }; + if (h.status >= 400) return { ok: false, reason: 'Your URL answers with HTTP ' + h.status + '. Point the campaign at a working page.' }; + if (/deny|sameorigin/i.test(String(h.xfo))) + return { ok: false, reason: 'That site blocks framing (X-Frame-Options), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; + const fa = /frame-ancestors\s+([^;]+)/i.exec(String(h.csp)); + if (fa && !fa[1].split(/\s+/).some(x => { + const v = x.replace(/['"]/g, '').toLowerCase(); + return v === '*' || v === 'https:' || (!inGame && v.includes('instantadpay.com')); + })) + return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; + return { ok: true }; +} +async function boot() { + await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode) + marks.init({ db }); + marks.ensureTable().catch(e => console.error('marks table', e.message)); + setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref(); + chain.init({ onEvent: ev => { + // the in-memory feed is per instance and always runs + attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); + // everything outward (email, Telegram, the Friday bonus, sponsor sync) happens ONCE across + // every running copy of the app: during a deploy two copies watch the chain for ~30 s, + // and on 2026-09-25 both emailed Marty and both granted his Friday bonus + marks.claim('ev:' + ev.tx + ':' + ev.li).then(mine => { + if (!mine) return; + emailOnEvent(ev).catch(() => {}); + telegramOnEvent(ev).catch(() => {}); + starter.onEvent(ev).catch(e => console.error('starter bonus', e.message)); + pwMintOnEvent(ev).catch(e => console.error('polywarriors mint', e.message)); + // the Friday bonus and the pass order first, then the Friday pass perk, which needs both results (Marty 2026-10-23) + Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).catch(e => { console.error('gamepass order', e.message); return null; })]) + .then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message)); + wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message)); + sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message)); + }).catch(e => console.error('marks claim', e.message)); + } }); + auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: 'instantadpay.com' }); + accounts.init({ dataDir: DATA_DIR }); + ads.init({ dataDir: DATA_DIR, chain, tiers: () => geo.tierLists(siteConfig()) }); + mailer.init({ dataDir: DATA_DIR }); + messages.init({ dataDir: DATA_DIR }); + reports.init({ dataDir: DATA_DIR }); + drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' }); + chatbot.init({ dataDir: DATA_DIR, chain, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22) + setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000); + setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000); + setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends + // follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot) + coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); + pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); + translate.init({ dataDir: DATA_DIR }); + tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram, translate }); + inbound.init({ tickets }); + supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' }); + badge.init({ publicDir: PUBLIC_DIR }); + gamestats.init({ dataDir: DATA_DIR }); + snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT())).map(g => g.name), + send: async (c, t, th) => { await telegramSend(c, t, th); return true; }, + sendPhoto: (c, jpeg, cap, th) => telegramSendPhoto(c, jpeg, cap, th) }); + fridaybank.init({ db }); + starter.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts }); + friday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, + telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + text, sc.telegramEchoTopicId); }, + notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } }); + // Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped, + // with the bonus ladder in the same message, and every send is watched for what they did next. + refill.init({ + dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, + creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; }, + message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); }, + }); + // prepaid login-ad line (2026-10-23): when a reservation starts, its owner gets an on-site notice (kind 'notice', never the + // sign-in pop) and an email unless they unsubscribed. ads.js calls this once per start, from the one copy that won it. + ads.onLoginPromoted(async c => { + const owner = String(c.owner || '').toLowerCase(); if (!owner) return; + const name = c.name || ('campaign #' + c.id); + const until = new Date(Number(c.expires)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; + const days = Number(c.body) || ads.rates().loginSlotDays || 30; + const subject = 'Your login ad "' + name + '" is live'; + const text = 'Your place in line came up. Your reserved login-ad slot has started, so "' + name + '" now shows full screen to members as they sign in, for ' + days + ' days, until ' + until + '.\n\n' + + 'You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns: https://instantadpay.com/my#campaigns\n\nInstantAdPay'; + const esc = s => String(s).replace(/&/g, '&').replace(//g, '>'); + const html = '

      Your place in line came up. Your reserved login-ad slot has started, so ' + esc(name) + ' now shows full screen to members as they sign in, for ' + days + ' days, until ' + esc(until) + '.

      ' + + '

      You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns.

      '; + try { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [owner], subject, html, 'notice'); } catch (e) { console.error('login line inbox', e.message); } + const stopped = drip && drip.isUnsubscribed ? await drip.isUnsubscribed(owner).catch(() => false) : false; + if (!stopped && mailer.hasKey()) { try { await mailer.send(owner, subject, text); } catch (e) { console.error('login line mail', e.message); } } + console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2')); + }); + setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes + setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000); + setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000); + setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 60 * 1000); + wednesday.init({ dataDir: DATA_DIR, siteConfig, chain, ads, accounts, mailer, drip, marks, rates: () => ads.rates(), + telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay · ' + text, sc.telegramEchoTopicId); }, + notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); } }); + setInterval(() => wednesday.tick().catch(e => console.error('wednesday', e.message)), 5 * 60 * 1000); + override.init({ dataDir: DATA_DIR, chain, siteConfig, notify: supportTelegram, db, brand: 'InstantAdPay', siteUrl: 'https://instantadpay.com' }); + setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000); + setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); + // sponsor follow (sponsorfollow.js): a deliberate change (tank adoption, rescue, release, window expiry, admin edit) is + // recorded and follows to LinkSpin, and LinkSpin's deliberate changes are applied here, until the member is bound on + // InstantAdPay's contract (memberId, or the wallet already on chain). Ordinary bindings keep the first-platform rule. + followStore = SF.create({ dataDir: DATA_DIR, platform: 'instantadpay' }); + follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'linkspin', + isBound: async a => { + if (Number(a.memberId) > 0) return { bound: true, why: 'InstantAdPay member #' + a.memberId }; + if (!a.address) return { bound: false }; + try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; return id ? { bound: true, why: 'wallet is InstantAdPay member #' + id } : { bound: false }; } + catch (e) { return { retry: true, why: 'InstantAdPay chain read failed' }; } + }, + sponsorAccount: em => accounts.byEmail(em), + wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; }, + activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null }); + tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore }); + // LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest + lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email)); + lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore }); + setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); + setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); + setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account + walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com', + message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } }); + setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window + setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000); + // 1,000-member POL drop (Marty 2026-10-10): watches the account count every 2 minutes while milestoneMode is dry or armed + milestone.init({ dataDir: DATA_DIR, accounts, chain, mailer, ledger, optedIn: updates.optedIn, site: 'https://instantadpay.com', siteConfig, noPayoutSet, + message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); }, + telegram: async html => { const sc = siteConfig(); if (sc.telegramChatId) await telegramSend(sc.telegramChatId, html, sc.telegramTopicId); if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, html, sc.telegramEchoTopicId); } }); + setTimeout(() => milestone.tick().catch(e => console.error('milestone', e.message)), 4 * 60 * 1000); + setInterval(() => milestone.tick().catch(e => console.error('milestone', e.message)), 2 * 60 * 1000); + await fraud.init({ dataDir: DATA_DIR }); + { // a suspended account is signed out everywhere: every member route sees no session + const realFrom = auth.fromRequest.bind(auth); + auth.fromRequest = async (req) => { const sess = await realFrom(req); if (sess && sess.email && fraud.isSuspended(sess.email)) return null; return sess; }; + } + legacy.init({ dataDir: DATA_DIR }); + traffic.init({ dataDir: DATA_DIR }); + loginShows.init({ dataDir: DATA_DIR }); + promos.init({ dataDir: DATA_DIR }); + blog.init({ dataDir: DATA_DIR }); + adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR }); + gamepass.init({ dataDir: DATA_DIR, siteConfig, accounts, marks, isProd: IS_PROD, persistedMap, polUsd: polUsdLive, + blockTime: async n => { const blk = await chain.rpc('eth_getBlockByNumber', ['0x' + Number(n).toString(16), false]); return blk && blk.timestamp ? parseInt(blk.timestamp, 16) : 0; }, // a pass order is fulfilled only by a purchase mined after it + telegram: async html => { const sc = siteConfig(); const chat = String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return false; await telegramSend(chat, html, sc.telegramGamesTopicId || null); return true; }, + notify: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice') }); // before loadOpenTokens: its maps must exist to be restored + loadOpenTokens(); + setTimeout(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 120 * 1000); + setInterval(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 60 * 60 * 1000); + setInterval(() => { try { gamepass.prune(); } catch (e) { console.error('gamepass prune', e.message); } }, 6 * 3600 * 1000).unref(); + syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR }); + releases.init({ dataDir: DATA_DIR }); + ledger.init({ dataDir: DATA_DIR }); + // re-check live video sources on a schedule: videoCheck only ever runs at save time, so a + // campaign created before it existed, or a link that rots later, is otherwise invisible + const videosweepAlert = async text => { + const sc = siteConfig(); + // Marty's own Hermes chat, where his other operational pings land (@CoolifyHermes_Bot). + // Admin channels ONLY, never a member-visible one: this names a member's campaign and + // their email address, so the shared payments topic would put it in front of the team. + const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); + if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, text); + if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, text); + if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: broken video sources', text.replace(/<[^>]+>/g, '')); + console.log('videosweep: no admin channel configured, alert not sent'); + }; + videosweep.init({ dataDir: DATA_DIR, fs, path, db, videoCheck, alert: videosweepAlert }); + videosweep.start(); + // Screen every advertiser destination against Google Safe Browsing: refuse a flagged one at + // save time, and re-screen the live ones daily. Added 2026-09-24 after Google marked the + // site "deceptive pages" with campaign #225 opening llclickpro.com (flagged) from our pages. + // Shares videosweep's alert path on purpose: it names members and their emails, admin only. + sbcheck.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert }); + sbcheck.start(); + // Destination reachability (2026-10-07): a link that resolved when saved can die later (campaign #163's + // lmgnow.co vanished and 65 members hit a dead end while Safe Browsing read 'cannot resolve' as unknown). + // Refuses a host with no DNS record at save time; pauses live ads whose host is dead two days running. + reach.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert, site: 'https://instantadpay.com', + message: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'), + mailer, optedIn: email => updates.optedIn(email) }); + reach.start(); + toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain }); + updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL }); + audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: counter audit', text).catch(() => {}); } }); + setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000); + videomaker.init({ dataDir: DATA_DIR, spaces, accounts }); + leaderboard.init({ chain, accounts, ads, fraud, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL, + notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } }); + setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000); + setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000); + console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)'); + setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram + geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message)); + setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily + setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window + burner.init({ chain, ads, accounts }); + setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000); + setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000); + 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); + 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); + // NAS reconcile: pull syndicated delivery into the unified credit pool + // (inert unless NAS_DB_* is set). Every 5 min after a short warm-up. + if (ads.nasEnabled()) { + console.log('NAS syndication enabled'); + setTimeout(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 90 * 1000); + pdsync.init({ dataDir: DATA_DIR, ads }); + if (pdsync.enabled()) { const every = Math.max(2, Number(process.env.PD_SYNC_MIN || 5)) * 60 * 1000; setTimeout(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), 90 * 1000); setInterval(() => pdsync.sync().catch(e => console.error('pdsync', e.message)), every); console.log('PassiveDrip PTC bridge: on, every', every / 60000, 'min'); } else console.log('PassiveDrip PTC bridge: off (no PD_BRIDGE_URL/SECRET)'); + setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000); + } +} + +// Game Pass partner helpers (2026-10-16): which secret signs for which game, signature compare, member resolution, dev clock +const GP_SECRETS = () => ({ polhunter: String(process.env.HUNT_SSO_SECRET || '').trim(), gemkingdom: GK_SECRET(), spellwheel: SW_SECRET(), spookydoors: SD_SECRET(), polywarriors: PW_SECRET(), + clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET(), shardsofvalor: SOV_SECRET() }); +function gpPartnerCheck(game) { if (!gamepass.GAMES.includes(game)) return { error: 'unknown game', code: 400 }; const secret = GP_SECRETS()[game] || ''; if (secret.length < 32) return { error: game + ' is not connected', code: 503 }; return { secret }; } +const gpSigOk = (want, got) => typeof got === 'string' && want.length === got.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got)); +async function gpResolve(memberId, email) { // the account behind a game's player: main member id, a linked position's id, or (no wallet yet) the email + const id = Number(memberId) || 0; let a = null; + if (id) { a = await accounts.byMemberId(id); if (!a) { const pos = await accounts.positionByMember(id); if (pos && pos.email) a = await accounts.byEmail(pos.email); } } + if (!a && email && /^[^\s@]+@[^\s@]+$/.test(String(email))) a = await accounts.byEmail(String(email).trim().toLowerCase()); + return a && a.email ? { email: String(a.email).toLowerCase(), memberId: a.memberId || id || 0, acct: a } : null; +} +const gpDevNow = devDay => (!IS_PROD && /^\d{4}-\d{2}-\d{2}$/.test(String(devDay || ''))) ? Date.parse(devDay + 'T17:00:00Z') : Date.now(); // local tests fake the Central day +// live USD per POL from the catalog quotes (the rate the games use for the tournament pool); cached 10 minutes +const polUsdCache = { at: 0, v: 0 }; +async function polUsdLive() { + if (!IS_PROD && Number(process.env.DEV_POL_USD) > 0) return Number(process.env.DEV_POL_USD); // local tests: no RPC + if (polUsdCache.at && Date.now() - polUsdCache.at < 300000 && polUsdCache.v > 0) return polUsdCache.v; // 5 min: what members see as today's dollar value + const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (!pk) return polUsdCache.v || 0; + const v = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); if (v > 0) { polUsdCache.v = v; polUsdCache.at = Date.now(); } return v; +} +// the Game Pass flag rides in every sign-in hand-off token (3a: games get it at sign-in and on every polgrant answer) +// gamePass: { active, until, tier } (tier = the highest active pass: weekly | explorer | champion | sovereign | legend | null; a game treats a missing tier as weekly) +const gpClaim = c => { if (!(c && c.email && (!c.kind || c.kind === 'sso'))) return {}; const f = gamepass.flag(c.email); return { gamePass: { active: f.active, until: f.until, tier: f.tier } }; }; +function siteConfig() { + let saved = {}; + try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {} + return Object.assign({ + siteName: 'InstantAdPay', + tagline: 'Advertise and earn. Locked in code, not promises.', + rehearsal: true, // shows the testnet banner; flipped off at mainnet launch + // payment-proof Telegram feed (blank = off) and the P&L pane's fixed monthly cost + telegramBotToken: '', telegramChatId: '', telegramTopicId: '', telegramEvents: 'payouts', telegramCtaUrl: 'https://instantadpay.com/', + fraudMaxSignupsPerIpDay: 2, fraudBlockSharedDevice: 'on', // anti-fraud: accounts per IP per day; block a second account from the same browser + telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic + telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL + fridayPromo: '1', // Five Dollar Friday on/off (Marty, 2026-09-20) + fridayBonusPct: '20', // bonus credits on any $5+ package bought on a Friday, Central + fridayStart: '2026-09-25', // the first Five Dollar Friday + wednesdayPromo: '1', wednesdayBonusPct: '25', wednesdayMinCents: '2000', wednesdayStart: '2026-09-30', // Wired Wednesday (Marty, 2026-09-29) + wednesdayNotice: '0', wednesdayKick: '0', // the Tuesday email/notice and the Wednesday Telegram kickoff stay off until Marty approves the copy + launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark + aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation + snapshotEnabled: '1', snapshotHourUtc: '14', snapshotTargets: 'feed,echo', // daily growth snapshot: 14 UTC = 9 AM Central; feed = proof channel, echo = shared payments topic + pipelineMode: 'off', // Pipeline board: off = 'coming soon' card, preview = only the admin account sees the live board, on = everyone (Marty, 2026-09-15) + pipelineEta: 'Sep 28', // what the coming-soon card and the roadmap promise + memberWeeklyEmail: '0', // 1 = the weekly 'Your week on InstantAdPay' email goes to every active member, not only sponsors with a line + noPayoutIds: '25', // positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14) + leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover) + legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ + geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) + geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else + // Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records + gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5, + // Explorer ($20) and Champion ($40) monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks + // in Shards of Valor, never power, never more POL (same caps as the weekly pass). sovTiers = the sale switch for both (off: only ADMIN_EMAIL + // sees and can buy them, for testing; holders keep their pass). gamePassEnabled '0' stops one tier alone. passTournamentTierSales '1' + // would add their sales to the Pass Tournament pool (off = the pool exactly as before). + // 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 / Champion $39.99 for 30 days, plus Sovereign $99.99 for 30 days and + // Legend $249.99 for 365 days (the yearly pass), all behind sovTiers. Names, perks and the rank live in gamepass.js TIER_DEFS. + sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 1999, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 3999, gamePassChampionDays: 30, + gamePassSovereignEnabled: '1', gamePassSovereignPriceCredits: 9999, gamePassSovereignDays: 30, gamePassLegendEnabled: '1', gamePassLegendPriceCredits: 24999, gamePassLegendDays: 365, passTournamentTierSales: '0', + supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback + supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set + telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat) + // share-link domain (2026-10-20, Marty): member invite links go out as https:///, which 302s to + // /join/ here, so shared links do not carry instantadpay.com (Spamhaus DBL). '' = old instantadpay.com/join links. + // Switch to the spare (mylinehq.com) if one gets flagged. Old links keep working either way. + shareDomain: 'ctbgo.com', + pnlFixedMonthlyUsd: 0 + }, saved); +} + +// ---- helpers ---- +const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', + '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', + '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', + '.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; +function baseHeaders(extra) { + return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); +} +function json(res, code, obj, extra) { + const body = JSON.stringify(obj); + res.writeHead(code, baseHeaders(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); + res.end(body); +} +function sendFile(res, file) { + fs.readFile(file, (err, data) => { + if (err) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const ext = path.extname(file).toLowerCase(); + res.writeHead(200, baseHeaders({ 'Content-Type': MIME[ext] || 'application/octet-stream', + // HTML is never stored (so a fresh load always gets the current asset + // versions — aggressive in-app wallet browsers were serving stale pages + // that pointed at old, since-fixed JS); versioned assets cache for an hour. + // the games load the sign-in kit from here with no version tag, so it revalidates every load (2026-10-18) + 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : path.basename(file) === 'game-signin.js' ? 'no-cache' : 'public, max-age=3600' })); + res.end(data); + }); +} +function readRaw(req, maxBytes) { + return new Promise((resolve, reject) => { + const chunks = []; + let n = 0; + req.on('data', c => { + n += c.length; + if (n > maxBytes) { req.destroy(); reject(new Error('too big')); return; } + chunks.push(c); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} +function readBody(req) { + return new Promise((resolve, reject) => { + let d = ''; let n = 0; + req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); reject(new Error('too big')); } d += c; }); + req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } }); + req.on('error', reject); + }); +} +function parseCookies(req) { + const out = {}; + for (const p of (req.headers.cookie || '').split(';')) { + const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); + } + return out; +} +// First sign-in to a waiting account made from a LinkSpin row (lsinbound.js): it becomes the person's own ordinary account. +// Its LinkSpin sponsor stands; one that arrived with no sponsor at all takes the link they signed in through, exactly as a +// brand-new account would (first InstantAdPay touch). Marked seen at once, so the sweeps count it from here on. +async function claimShell(email, shell, ref) { + try { + if (!shell.sponsorRef && ref) { const tok = String(ref).toLowerCase(); let sp = await accounts.byCode(tok); if (!sp) sp = await accounts.byUsername(tok); if (sp && sp.email !== email) await accounts.setSponsorRef(email, ref); } + await accounts.touchSeen(email); + console.log('linkspin waiting account claimed', email.replace(/^(.).*(@.*)$/, '$1***$2'), shell.sponsorRef ? 'sponsor ' + shell.sponsorRef : (ref ? 'sponsor from link ' + ref : 'no sponsor')); + } catch (e) { console.error('claimShell', e.message); } +} +function isAdmin(req) { + const h = req.headers.authorization || ''; + if (h === 'Bearer ' + ADMIN_PASSWORD) return true; + return !!adminFromRequest(req); // /admin portal session +} +// attach a memberId->username map to events so activity shows real people +// Payment trace (Marty, 2026-09-16): every purchase a member is involved in, tier by tier — who was +// paid, who was skipped and why (with how many qualifying buyers the skipped person had at that block) +// — so "why didn't X get paid on Y's buy" becomes a self-serve lookup instead of a support thread. +async function nameForMember(id) { + try { const a = await accounts.byMemberId(id); if (a && a.username) return a.username; } catch (e) {} + if (db.enabled()) { // a linked extra wallet: name it after its owner + try { const r = await db.q('SELECT email FROM positions WHERE member_id=? LIMIT 1', [Number(id)]); if (r.length) { const a = await accounts.byEmail(r[0].email); if (a && a.username) return a.username + ' (linked wallet)'; } } catch (e) {} + } + return null; +} +function sponsorMapFromIndex(evs) { const m = new Map(); for (const e of evs) if (e.type === 'MemberActivated' && e.id) m.set(e.id, Number(e.sponsorId) || 0); return m; } +function uplineIds(map, id, hops) { const out = []; let cur = map.get(Number(id)) || 0; for (let i = 0; i < hops && cur; i++) { out.push(cur); cur = map.get(cur) || 0; } return out; } +async function tracePurchases(targetId, limit) { + const id = Number(targetId) || 0; if (!id) return { error: 'Which member?' }; + const evs = chain.recentEvents(1e9); // whole history, newest first + const byTx = new Map(); + for (const e of evs) { if (!e.tx) continue; let g = byTx.get(e.tx); if (!g) { g = []; byTx.set(e.tx, g); } g.push(e); } + const counted = evs.filter(e => e.type === 'BuyerCounted'); + const buyersBefore = (sid, block) => counted.filter(e => e.sponsorId === sid && e.block < block).length; + const out = []; + for (const e of evs) { + if (e.type !== 'Purchase') continue; + const g = byTx.get(e.tx) || []; + const paid = g.filter(x => x.type === 'TierPaid' && x.buyerId === e.buyerId); + const skipped = g.filter(x => x.type === 'PassedUp' && x.buyerId === e.buyerId); + const act = g.find(x => x.type === 'MemberActivated' && x.id === e.buyerId); + const admin = g.find(x => x.type === 'AdminPaid' && x.buyerId === e.buyerId); + const involved = e.buyerId === id || paid.some(x => x.recipientId === id) || skipped.some(x => x.skippedId === id) || (act && act.sponsorId === id); + if (!involved) continue; + const tiers = [1, 2, 3].map(t => { + const p = paid.find(x => x.tier === t); const sk = skipped.filter(x => x.tier === t); + return { tier: t, pct: [50, 20, 10][t - 1], paidTo: p ? p.recipientId : 0, amountWei: p ? p.amountWei : '0', hops: p ? p.hops : 0, + skipped: sk.map(x => ({ id: x.skippedId, reason: x.reason, buyersThen: x.reason === 'unqualified' ? buyersBefore(x.skippedId, e.block) : null })) }; + }); + out.push({ ts: e.ts, block: e.block, tx: e.tx, buyerId: e.buyerId, sponsorId: act ? act.sponsorId : null, priceCents: e.priceCents, paidWei: e.paidWei, tiers, adminWei: admin ? admin.amountWei : '0' }); + if (out.length >= (limit || 30)) break; + } + const ids = new Set([id]); + for (const p of out) { ids.add(p.buyerId); if (p.sponsorId) ids.add(p.sponsorId); for (const t of p.tiers) { if (t.paidTo) ids.add(t.paidTo); for (const x of t.skipped) ids.add(x.id); } } + const names = {}; for (const i of ids) { const n = await nameForMember(i); if (n) names[i] = n; } + const smap = sponsorMapFromIndex(evs); + return { memberId: id, name: names[id] || null, activated: smap.has(id), sponsorId: smap.get(id) || 0, buyersNow: counted.filter(e => e.sponsorId === id).length, purchases: out, names }; +} +async function attachNames(evts) { + try { + const ids = []; + for (const ev of evts) + for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId']) + if (ev[k]) ids.push(ev[k]); + const names = await accounts.namesForMembers(ids); + if (!Object.keys(names).length) return evts; + return evts.map(ev => Object.assign({}, ev, { names })); + } catch (e) { return evts; } +} +// A sponsor token is a numeric chain id or a site share code. Codes resolve +// to the referrer's CURRENT chain id, so activation any time before the +// referral's first purchase still locks the line to them. +// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again. +// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three +// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys +// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0. +function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); } +async function payoutChainBlocked(id, hops) { + const bad = noPayoutSet(); if (!bad.size || !id) return 0; + let cur = Number(id); + for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; } + return 0; +} +// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a +// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account) +// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now). +async function resolveSponsorDetailed(tok) { + const t = String(tok || '').trim().toLowerCase(); + if (!t) return { id: 0, reason: 'none' }; + if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' }; + let acct = await accounts.byCode(t); + if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/ + if (!acct) return { id: 0, reason: 'unknown', name: t }; + if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t }; + try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; } + catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; } +} +async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; } +// 2026-09-16 (Marty): a buyer is never held up because their sponsor has not activated. Walk the +// site's sponsor line upward to the first upline who can be paid on-chain (activated, payouts on, +// not on the no-payout list); none -> the catch position (#1, Marty's top). The referral then follows +// the money: sponsorSyncOnEvent re-points the buyer's account to whoever was paid once the position exists. +async function walkUpActivatedSponsor(tok) { + const skipped = []; const seen = new Set(); + const t = String(tok || '').trim().toLowerCase(); + let acct = await accounts.byCode(t); if (!acct) acct = await accounts.byUsername(t); + for (let hop = 0; acct && hop < 25 && !seen.has(acct.email); hop++) { + seen.add(acct.email); + const name = acct.username ? '@' + acct.username : acct.email.replace(/@.*/, '') + '@'; + let id = 0; + if (acct.address) { try { id = await chain.memberIdByAccount(acct.address); } catch (e) { return { id: 0, name: null, skipped, reason: 'rpc' }; } } + if (id && !(await payoutChainBlocked(id, 2))) return { id, name, skipped, reason: 'ok' }; + skipped.push({ email: acct.email, name }); + acct = await accounts.sponsorOf(acct.email); + } + return { id: 0, name: null, skipped, reason: 'none' }; +} +// The feed line for a walk-up: who had not switched on payouts, whose referral (and purchase, when the +// activation and the buy share a tx) routed past them, and who it belongs to now. +async function postWalkUp(buyerId, oldRef, toId, pur) { + const sc = siteConfig(); if (!sc.telegramBotToken || (!sc.telegramChatId && !sc.telegramEchoChatId)) return; + const lostAcct = await refAccount(oldRef); if (!lostAcct) return; + const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@'; + const nm = await accounts.namesForMembers([buyerId, toId]).catch(() => ({})); + const who = id => '#' + id + (nm[id] ? ' @' + nm[id] : ''); + const site = 'https://instantadpay.com/my'; + const what = pur ? who(buyerId) + "'s $" + Math.round(pur.priceCents / 100) + ' purchase routed past them' : who(buyerId) + ' switched on payouts and their position routed past them'; + const missed = '\u{1F62C} Missed sale: ' + lostName + ' had not switched on payouts, so ' + what + '. That member, and every payout from them, now belongs to ' + who(toId) + '.' + + '\nTwo minutes on the Wallet tab prevents this: ' + site.replace(/^https:\/\//, '') + ''; + if (sc.telegramChatId && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {}); + if (sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {}); +} +// The referral follows the money (Marty, 2026-09-16): when a position is created on-chain under a +// different sponsor than the account's stored referrer (walk-up past an unactivated sponsor, or the +// catch-position fallback), move the account to the sponsor that actually got paid, #1 included. +async function sponsorSyncOnEvent(ev) { + if (!ev || ev.type !== 'MemberActivated' || !ev.account) return; + const acct = await accounts.byAddress(ev.account); if (!acct) return; + if (acct.address && acct.address.toLowerCase() !== String(ev.account).toLowerCase()) return; // a linked extra position, not the main wallet + const onchain = Number(ev.sponsorId) || 0; if (!onchain) return; + const spAcct = await accounts.byMemberId(onchain); + if (spAcct && spAcct.email === acct.email) return; // never self-sponsor an account + const cur = acct.sponsorRef ? (await resolveSponsorDetailed(acct.sponsorRef)).id : 0; + if (cur === onchain) return; + const ref = spAcct && spAcct.code ? spAcct.code : String(onchain); + const old = acct.sponsorRef || ''; + await accounts.setSponsorRef(acct.email, ref); + movedByTx.set(ev.tx, { buyerId: Number(ev.id) || 0, toId: onchain, oldRef: old, at: Date.now(), posted: true }); // posted below, at activation; the Purchase branch stays quiet + // Post it now (Marty, 2026-09-21): the post used to wait for a Purchase in the same tx, so an activation that + // came first (switch on payouts, buy later) was never posted. The activation is the fact; it goes out here. + try { const pur = chain.recentEvents(1e9).find(x => x.tx === ev.tx && x.type === 'Purchase') || null; await postWalkUp(Number(ev.id) || 0, old, onchain, pur); } catch (e) { console.error('walk-up post', e.message); } + if (movedByTx.size > 200) { const k = movedByTx.keys().next().value; movedByTx.delete(k); } + console.log('referral moved to where the pay landed:', acct.email, JSON.stringify(old), '->', ref, '(#' + onchain + ')'); + // Notices, now that it is a fact on the chain (Marty, 2026-09-16): everyone between the stored + // referrer and the paid sponsor who was simply not activated is told they lost this referral for + // good; the sponsor who was paid is told they gained it and should coach the one who missed it. + try { + const nameOf = a => a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@'; + const toName = spAcct ? nameOf(spAcct) : 'the company (#' + onchain + ')'; + const lost = []; const seen = new Set(); + let x = await refAccount(old); + while (x && !seen.has(x.email) && (!spAcct || x.email !== spAcct.email) && lost.length < 25) { + seen.add(x.email); + let activated = false; if (x.address) { try { activated = !!(await chain.memberIdByAccount(x.address)); } catch (e) { activated = true; } } + if (!activated) lost.push(x); // an activated-but-excluded (no-payout) sponsor is an admin matter, not a "switch on payouts" lesson + x = await accounts.sponsorOf(x.email); + } + for (const l of lost) sponsorHoldNudge(l.email, acct.email, toName).catch(() => {}); + if (spAcct && lost.length) sponsorGainNudge(spAcct, nameOf(acct), lost.map(nameOf)).catch(() => {}); + } catch (e) { console.error('sponsor move notices', e.message); } +} +const movedByTx = new Map(); // tx -> { buyerId, toId, oldRef } for purchases routed past an unactivated sponsor +async function refAccount(ref) { + const t = String(ref || '').trim().toLowerCase(); if (!t) return null; + let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); + if (!a && /^\d+$/.test(t)) a = await accounts.byMemberId(Number(t)); + return a || null; +} +const sponsorGainLast = new Map(); // sponsor email|buyer -> ts +async function sponsorGainNudge(sp, buyerName, lostNames) { + if (!sp || !sp.email) return; + const key = sp.email + '|' + buyerName; if (sponsorGainLast.has(key)) return; sponsorGainLast.set(key, Date.now()); + const who = lostNames.length === 1 ? lostNames[0] : lostNames.slice(0, -1).join(', ') + ' and ' + lostNames[lostNames.length - 1]; + const subject = buyerName + ' is now in your line for good (' + who + ' had not switched on payouts)'; + const lines = [ + buyerName + ' just bought an ad package on InstantAdPay. They came in through ' + who + ', but ' + (lostNames.length === 1 ? who + ' had' : 'they had') + ' not linked a wallet and switched on payouts, so the contract could not pay ' + (lostNames.length === 1 ? 'them' : 'any of them') + '. It walked up your line and paid you at level 1 instead.', + 'That is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + buyerName + ' is in your line on the chain from now on: this purchase and every one after it pays you as their level 1. They now show under you in My line.', + 'The lesson to pass down: ' + who + ' just lost a referral they worked for because payouts were off. Take two minutes with them, help them link a wallet and switch on payouts (Wallet tab, one free signature and one small transaction), and show them how to check it. Every leader in this line who teaches that step keeps their people from losing the next one.', + 'My line: https://instantadpay.com/my#line' + ]; + const text = lines.join('\n\n'); + if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {}); + try { + const html = lines.map(l => '

      ' + l.replace(/&/g, '&').replace(/$1') + '

      ').join(''); + await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'notice'); + } catch (e) {} +} +// Partner-code credits arrive as a drip (Marty, 2026-09-19): a fifth on the day the code is +// redeemed, then a fifth on each day the member finishes their daily ad set, five days in all, +// nothing after 30 days. Same headline number for the partner to promote; paid only to people +// who show up. Member-funded codes charge the funder one installment at a time. +async function payPromo(email, day) { + return promos.payDue(email, day, async (r, amount, n) => { + if (r.funder && r.funder !== email) { + const ok = await ads.spendEarned(r.funder, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ' funded for ' + email + ' (day ' + n + ' of ' + promos.STEPS + ')' } }); + if (!ok) { console.log('promo funder short', r.code, r.funder); return false; } + } + await ads.addEarned(email, amount, { log: { kind: 'promo', note: 'Partner code ' + r.code + ': ' + amount + ' of ' + r.credits + ' (day ' + n + ' of ' + promos.STEPS + ')' } }); + return true; + }); +} +// anti-fraud admin alert (Telegram admin chat, else email): who, which flags, and whether the sign-up was blocked +// Send as a specific bot, for operational alerts that should arrive from Marty's own Hermes bot +// rather than from the member-facing InstantAdPay one. +function tgSendAs(token, chatId, text, threadId) { + return new Promise(resolve => { + const body = JSON.stringify(Object.assign({ chat_id: String(chatId), text, parse_mode: 'HTML', disable_web_page_preview: true }, + threadId ? { message_thread_id: Number(threadId) } : {})); + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + token + '/sendMessage', method: 'POST', timeout: 12000, + headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, + r => { r.resume(); resolve(r.statusCode === 200); }); + rq.on('error', () => resolve(false)); + rq.on('timeout', () => { rq.destroy(); resolve(false); }); + rq.end(body); + }); +} +// Help desk pings (2026-10-16): Marty's PRIVATE Telegram chat only, never a group, topic or feed. tgSendAs skips the +// Discord relay entirely. Site bot (telegramBotToken) first, Marty's Hermes bot if that one cannot reach him. +async function supportTelegram(text, ref) { + // the dedicated support bot (two-way: buttons + replies) goes first; the old one-way path stays as the fallback + if (supportbot.enabled() && await supportbot.ping(text, ref)) return true; + const sc = siteConfig(); + const chat = String(sc.supportTelegramChat || '1289244227').trim(); + if (!/^\d{4,15}$/.test(chat)) { console.error('support ping refused: supportTelegramChat must be a private chat id (positive number), not', chat); return false; } + let ok = false; + const site = String(sc.telegramBotToken || '').trim(), hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); + if (site) ok = await tgSendAs(site, chat, text); + if (!ok && hermes) ok = await tgSendAs(hermes, chat, text); + if (!ok) console.error('support ping not delivered (chat ' + chat + ', site bot ' + (site ? 'set' : 'missing') + ', hermes ' + (hermes ? 'set' : 'missing') + ')'); + return ok; +} +// Public support form + signed-out chatbot hand-off: the sign-up guard's walls (honeypot, form age, per-IP limits with the +// icon check once tripped, a global cap) plus a hard per-email cap. Returns null to allow, or { status, body }. +const SUPPORT_LIMITS = { ipHour: 5, ipDay: 15, emailHour: 3, emailDay: 8, globalPerMin: 20, minFormMs: 2000 }; +const supportHits = new Map(); // 'ip:' | 'em:' | 'tk:' -> [timestamps, 24h] +const supportChal = new Map(); // ip -> { chal, passUntil } +const supportGlobal = { minute: 0, n: 0 }; +const supportRecent = (k, ms) => { const now = Date.now(); const t = (supportHits.get(k) || []).filter(ts => now - ts < 86400000); supportHits.set(k, t); return t.filter(ts => now - ts < ms).length; }; +const supportMark = k => { const t = supportHits.get(k) || []; t.push(Date.now()); supportHits.set(k, t); if (supportHits.size > 5000) for (const [kk, v] of supportHits) if (!v.length || Date.now() - v[v.length - 1] > 86400000) supportHits.delete(kk); }; +const supportFlood = (k, n, ms) => { if (supportRecent(k, ms) >= n) return true; supportMark(k); return false; }; // signed-in and private-link replies: a plain cap +function supportGuard(req, b, email) { + const now = Date.now(); + const hpRaw = String(b.hp_field_x9 || '').trim(); + const hp = !!hpRaw && hpRaw.toLowerCase() !== email; // own email = phone autofill, not a bot + const fts = Number(b.fts) || 0; + const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1); + if (fage < SUPPORT_LIMITS.minFormMs) { guardLog(req, 'support form-age', b); return { status: 400, body: { error: 'Give the page a few seconds, then send again.' } }; } + if (fage > 12 * 3600 * 1000) { guardLog(req, 'support form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then send again.' } }; } + const minute = Math.floor(now / 60000); + if (supportGlobal.minute !== minute) { supportGlobal.minute = minute; supportGlobal.n = 0; } + if (supportGlobal.n >= SUPPORT_LIMITS.globalPerMin) { guardLog(req, 'support global-limit', b); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } + if (supportRecent('em:' + email, 3600000) >= SUPPORT_LIMITS.emailHour || supportRecent('em:' + email, 86400000) >= SUPPORT_LIMITS.emailDay) { + guardLog(req, 'support email-limit', b); + return { status: 429, body: { error: 'You have sent several tickets already. Reply on the one you have open (the link is in your confirmation email) and Marty will see it there.' } }; + } + const ip = clientIp(req); + const limited = hp || supportRecent('ip:' + ip, 3600000) >= SUPPORT_LIMITS.ipHour || supportRecent('ip:' + ip, 86400000) >= SUPPORT_LIMITS.ipDay; + const rec = supportChal.get(ip) || { chal: null, passUntil: 0 }; + if (limited && now >= rec.passUntil) { + const pick = String(b.pick || ''); + if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } + else { guardLog(req, pick ? 'support wrong-pick' : hp ? 'support honeypot-challenge' : 'support ip-limit', b); const challenge = codeChallenge(rec); supportChal.set(ip, rec); if (supportChal.size > 5000) supportChal.clear(); return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send it.', challenge } }; } + supportChal.set(ip, rec); + } + supportGlobal.n += 1; supportMark('ip:' + ip); supportMark('em:' + email); + return null; +} +// LinkSpin partner calls (registry rows, help desk): one secret both ways, LS_SYNC_SECRET, as X-LS-Ts (ms) + X-LS-Sig = +// hex HMAC-SHA256(ts + newline + raw body), 10-minute window. Resolves { body } or { status, error }. +async function readLsSigned(req, maxBytes) { + const secret = String(process.env.LS_SYNC_SECRET || '').trim(); if (secret.length < 32) return { status: 503, error: 'sync not configured' }; + const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > maxBytes) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); + const ts = String(req.headers['x-ls-ts'] || ''), sig = String(req.headers['x-ls-sig'] || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' }; + const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); + if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' }; + try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; } +} +function fraudAlert(email, fc, spAcct, blocked) { + try { + const sc = siteConfig(); + const text = (blocked ? '\u26D4 InstantAdPay sign-up BLOCKED: ' : '\u{1F6A9} InstantAdPay sign-up flagged: ') + String(email).replace(/^(.{2}).*(@.*)$/, '$1***$2') + + ' [' + (fc.flags || []).join(', ') + ']' + (fc.ip ? ' ip ' + fc.ip : '') + (spAcct ? ' sponsor ' + (spAcct.username ? '@' + spAcct.username : spAcct.email) : '') + '. Admin > Members > Duplicate signals.'; + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: sign-up ' + (blocked ? 'blocked' : 'flagged'), text).catch(() => {}); + } catch (e) {} +} +const sponsorRoutedLast = new Map(); // buyer email -> ts (one alert per buyer per hour) +function sponsorRoutedAlert(who, spd, routed, skipped) { + const k = String(who || '?'); if (Date.now() - (sponsorRoutedLast.get(k) || 0) < 3600000) return; sponsorRoutedLast.set(k, Date.now()); + const text = '\u2934\uFE0F InstantAdPay heads-up: ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + ' is at checkout. Their sponsor ' + (spd.name || '?') + + ' has not switched on payouts, so if this purchase goes through it pays ' + routed.to + ' instead.' + (skipped.length > 1 ? ' Also skipped: ' + skipped.map(x => x.name).join(', ') + '.' : '') + + ' Nothing has been paid yet; the on-chain result posts to Telegram when the sale settles.'; + const sc = siteConfig(); + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay heads-up: a checkout will route past an unactivated sponsor', text).catch(() => {}); + // the skipped sponsor and the one who gains are told by sponsorSyncOnEvent, once the position exists on the chain +} +const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour) +function sponsorBlockedAlert(who, r) { + const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now()); + const text = '\u26A0\uFE0F InstantAdPay: purchase held for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be resolved (' + r.reason + '), so the buy was blocked instead of crediting the company. ' + (r.reason === 'notActivated' ? 'The sponsor needs to switch on payouts.' : r.reason === 'rpc' ? 'Chain lookup failed; they can retry.' : 'Check the sponsor field in Admin > Members.'); + const sc = siteConfig(); + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: purchase held, sponsor unresolved', text).catch(() => {}); + // and the sponsor themselves (Marty, 2026-09-15): a buy is waiting on them, once an hour at most + if (r.reason === 'notActivated') sponsorHoldNudge(String(r.tok || ''), k).catch(() => {}); +} +const sponsorNudgeLast = new Map(); // sponsor email -> ts +async function sponsorHoldNudge(tok, buyerEmail, routedTo) { + const t = String(tok || '').trim().toLowerCase(); if (!t) return; + let sp = t.includes('@') ? await accounts.byEmail(t) : null; + if (!sp) sp = await accounts.byCode(t); if (!sp) sp = await accounts.byUsername(t); + if (!sp || !sp.email) return; + if (Date.now() - (sponsorNudgeLast.get(sp.email) || 0) < 3600000) return; sponsorNudgeLast.set(sp.email, Date.now()); + const buyer = await accounts.byEmail(buyerEmail); const bn = buyer && buyer.username ? '@' + buyer.username : 'One of your referrals'; + const step = !sp.address ? 'link a wallet and switch on payouts' : 'switch on payouts'; + const subject = routedTo + ? 'You lost ' + bn + ' to ' + routedTo + ' (payouts were not switched on)' + : bn + ' is trying to buy. ' + (sp.address ? 'Switch on payouts' : 'Link your wallet') + ' so it pays you'; + const lines = routedTo ? [ + 'You just lost a sale. ' + bn + ' is buying an ad package on InstantAdPay right now, and because payouts are not switched on for your account, the contract cannot pay you. The purchase is paying ' + routedTo + ' instead.', + 'This is permanent. The contract locks a buyer to the sponsor who was paid at their first purchase, so ' + bn + ' now belongs to ' + routedTo + ', has moved out of your line, and will never pay you from that wallet. Nothing can bring that referral back.', + 'The next one does not have to go the same way. Open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Two minutes, and every purchase in your line from then on pays you the moment it happens.', + 'Wallet tab: https://instantadpay.com/my#wallet' + ] : [ + bn + ' just tried to buy an ad package on InstantAdPay, and the purchase is on hold because payouts are not switched on for your account yet. The contract pays your share in the same transaction, but only to a wallet that is switched on, so the site paused the buy instead of sending your 50 percent to someone else.', + 'To fix it: open the Wallet tab and ' + step + '. One free signature to link, one small transaction to switch on. Takes two minutes, and every purchase in your line from then on pays you the moment it happens.', + 'Until then their purchase waits, and they have been told why.', + 'Wallet tab: https://instantadpay.com/my#wallet' + ]; + const text = lines.join('\n\n'); + if (mailer.hasKey()) mailer.send(sp.email, subject, text + '\n\nInstantAdPay').catch(() => {}); + try { + const html = lines.map(l => '

      ' + l.replace(/&/g, '&').replace(/$1') + '

      ').join(''); + await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [sp.email], subject, html, 'alert'); + } catch (e) {} +} +// The moment someone joins through a code, nudge its owner to activate. +// Email a member's sponsor the moment they get a new referral (free OR paid). +// Resolves the sponsor from the join token by member id, share code, or username, +// and notifies EVERY sponsor — activated or not (an active sponsor still wants to +// know their team grew). A referral is on the line from signup; it only counts +// toward qualification once it makes a $20+ purchase. +async function notifyNewReferral(ref, newAcct) { + try { + if (!mailer.hasKey()) return; + const t = String(ref || '').trim().toLowerCase(); + if (!t) return; + let owner = null; + if (/^\d+$/.test(t)) { try { owner = await accounts.byMemberId(Number(t)); } catch (e) {} } + if (!owner) { try { owner = await accounts.byCode(t); } catch (e) {} } + if (!owner) { try { owner = await accounts.byUsername(t); } catch (e) {} } + if (!owner || !owner.email) return; + const who = newAcct && newAcct.username ? '@' + newAcct.username : 'A new member'; + let body = who + ' just joined InstantAdPay through your link — they are on your team from today.\n\n' + + 'They count toward your qualification once they make a $20+ purchase.\n\n'; + if (!owner.address) body += 'Make sure payouts are switched on (one free wallet step) so you never miss a commission — ' + + 'the contract locks each buyer to their sponsor at their first purchase.\n\n'; + body += 'See your team: https://instantadpay.com/my\n\nInstantAdPay'; + mailer.send(owner.email, 'You have a new referral on InstantAdPay', body) + .catch(e => console.error('referral notify failed', e.message)); + } catch (e) {} +} +// welcome email on a new account: onboarding steps + who their sponsor is +// how a member is named in emails/alerts: @username, a linked position named after its owner, else member #id +async function memberLabel(id) { + try { + let a = await accounts.byMemberId(id); + if (!a) { // brand-new buyer: the account learns its member id on its next page load, so read the + // wallet from the chain and match it now (Jim's purchase mailed as "member #25", 2026-09-13) + try { const m = await chain.member(id); if (m && m.account) { a = await accounts.byAddress(String(m.account).toLowerCase()); if (a && !a.memberId) accounts.setMemberId(a.email, id).catch(() => {}); } } catch (e) {} + } + if (a && a.username) return '@' + a.username; + const pos = await accounts.positionByMember(id); + if (pos && pos.email) { const o = await accounts.byEmail(pos.email); if (o && o.username) return '@' + o.username + ' (extra position #' + id + ')'; } + } catch (e) {} + return 'member #' + id; +} +async function sendWelcome(email, ref) { + try { + if (!mailer.hasKey()) return; + const spon = await accounts.sponsorOf(email); + const who = spon ? (spon.username ? '@' + spon.username : 'member #' + (spon.memberId || 0)) : ''; + const sponsorLine = who ? ('You joined through ' + who + ', your sponsor. They are there to help you get started, and you can message them anytime from your dashboard.\n\n') : ''; + mailer.send(email, 'Welcome to InstantAdPay', + 'Your free InstantAdPay account is ready.\n\n' + sponsorLine + + 'Getting started:\n' + + '1. Pick your username and fill out your profile.\n' + + '2. Grab your invite link and start sharing to build your line.\n' + + '3. Explore the ad packages when you are ready. Every payout settles on-chain, straight to your wallet.\n\n' + + 'Sign in anytime: https://instantadpay.com/my\n\nInstantAdPay').catch(() => {}); + } catch (e) {} +} +// on-chain event emails: a payout received, or a payout that passed you by +const weiToPol = w => { try { return (Number(BigInt(w) / (10n ** 14n)) / 10000).toString(); } catch (e) { return '?'; } }; +async function emailOnEvent(ev) { + if (!ev) return; + const notify = async (memberId, subject, body) => { + if (!memberId || !mailer.hasKey()) return; + const a = await accounts.byMemberId(memberId); + if (a && a.email) mailer.send(a.email, subject, body + '\n\nSee it on the live ledger: https://instantadpay.com/ledger\n\nInstantAdPay', null, { transactional: true }).catch(() => {}); // receipts + payouts: sent even after an unsubscribe + }; + // Marty (2026-09-15): payment and missed-payment notices also land in the on-site inbox, so + // they are waiting (login modal + Messages card) whether or not the email was read. Sent as + // the company account (#1), the same sender the credit-return notes used. Plain text in, HTML out. + const inboxNote = async (memberId, subject, text, kind) => { + if (!memberId) return; + try { + const a = await accounts.byMemberId(memberId); + if (!a || !a.email) return; + const html = '

      ' + String(text).replace(/&/g, '&').replace(//g, '>') + .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

      ').replace(/\n/g, '
      ') + '

      '; + await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], subject, html, kind || 'notice'); + } catch (e) {} + }; + const tell = async (memberId, subject, text, kind) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text, kind); }; + const PCT = { 1: 50, 2: 20, 3: 10 }; + // the Purchase event of the same tx is already indexed (it precedes every payout log), so the + // dollar side of any share is that purchase's price times the tier percentage + const purchaseOf = tx => { try { return chain.recentEvents(1e9).find(e => e.tx === tx && e.type === 'Purchase'); } catch (e) { return null; } }; + const usdShare = (pur, pct) => pur ? (' (about ' + ('$' + (pur.priceCents * pct / 10000).toFixed(2)).replace(/\.00$/, '') + ')') : ''; + const txUrlOf = tx => { const cc = chain.getConfig(); return (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + tx; }; + if (ev.type === 'Purchase') { + const cc = chain.getConfig(); + const txUrl = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; + let bal = ev.creditAmount; + try { bal = await chain.creditBalance(ev.buyerId, ev.creditType); } catch (e) {} + await notify(ev.buyerId, 'Your InstantAdPay purchase is confirmed', + 'Your purchase is complete and settled on-chain.\n\n' + + 'Ad credits added: ' + ev.creditAmount + '\n' + + 'Your ad-credit balance is now: ' + bal + '\n' + + 'Amount paid: ' + weiToPol(ev.paidWei) + ' POL\n\n' + + 'View your transaction on the blockchain:\n' + txUrl); + // tell the buyer's DIRECT sponsor their referral just bought (upline earners + // are separately notified by the TierPaid payout email when they earn) + try { + const buyer = await chain.member(ev.buyerId); + if (buyer && buyer.sponsorId) { + const sp = await accounts.byMemberId(buyer.sponsorId); + if (sp && sp.email) { + const bn = await memberLabel(ev.buyerId); // @username at a glance (Marty, 2026-09-12) + const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, ''); + const qual = ev.priceCents >= 2000 + ? ' This is a $20+ purchase, so it counts toward your qualification.' + : ' (Purchases under $20 do not count toward qualification.)'; + mailer.send(sp.email, bn + ' just bought a ' + usd + ' ad package', + 'Your referral ' + bn + ' (member #' + ev.buyerId + ') just purchased a package (' + usd + ' — ' + ev.creditAmount + ' credits).' + qual + '\n\n' + + 'See your team and the live ledger: https://instantadpay.com/my\n\nInstantAdPay').catch(() => {}); + } + } + } catch (e) {} + } + else if (ev.type === 'TierPaid') { + const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); + let buyer = 'a member on your level ' + ev.tier; try { buyer = await memberLabel(ev.buyerId); } catch (e) {} + const pol = weiToPol(ev.amountWei); + await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on InstantAdPay', + 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 dashboard: https://instantadpay.com/my'); + } + 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 earnings: https://instantadpay.com/my#earnings', 'notice'); + else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on InstantAdPay', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my'); + } + 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 + await tell(ev.skippedId, 'Your wallet rejected a payout on InstantAdPay', 'A level-' + ev.tier + ' payout tried to reach your linked wallet and the wallet refused the transfer, so it passed to the next qualified member. This happens with some smart-contract wallets. Link a regular wallet address (MetaMask, SafePal, Phantom) on the Wallet tab so the next payout lands.\n\nTransaction: ' + txUrlOf(ev.tx)); + if (ADMIN_EMAIL) mailer.send(ADMIN_EMAIL, 'InstantAdPay: payout send-failed for member #' + ev.skippedId, 'A level-' + ev.tier + ' payout to member #' + ev.skippedId + ' failed at the wallet (send-failed) and passed up. Tx: ' + ev.tx + '\n\nThe member has been emailed to link a regular wallet.').catch(() => {}); + } + else if (ev.type === 'PassedUp') { + // Marty (2026-09-15): a member who missed a payout because they were not qualified must be told + // exactly what they missed: who bought, the share in POL and dollars, and how to close the gap. + const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); + let pol = '', buyer = 'a member on your level ' + ev.tier; + try { if (pur) pol = weiToPol((BigInt(pur.paidWei) * BigInt(pct) / 100n).toString()); buyer = await memberLabel(ev.buyerId); } catch (e) {} + let bc = 0; try { bc = (await chain.member(ev.skippedId)).buyerCount || 0; } catch (e) {} + const need = ev.tier === 3 ? 5 : 2, short = Math.max(0, need - bc); + const what = pol ? pol + ' POL' + usdShare(pur, pct) : 'a level-' + ev.tier + ' payout'; + await tell(ev.skippedId, 'You missed ' + (pol ? pol + ' POL' : 'a payout') + ' on InstantAdPay', + buyer + ' just bought an ad package on your level ' + ev.tier + '. Your share was ' + what + ', and it passed you by because level ' + ev.tier + ' is not open on your account yet. The contract paid it to the next qualified person above you.\n\n' + + 'Level ' + ev.tier + ' opens at ' + need + ' qualifying buyers (people you referred who bought a $20 or larger package). You have ' + bc + (short ? ', so you are ' + short + ' buyer' + (short === 1 ? '' : 's') + ' away.' : '.') + '\n\n' + + 'Two ways to close the gap: bring ' + (short || 1) + ' more buyer' + (short === 1 ? '' : 's') + ' from your My line page, or use Qualified Start under Buy packages to be your own buyer today. Every package on level ' + ev.tier + ' pays you ' + pct + ' percent once it is open, and the next one is coming whether you are ready or not.\n\n' + + 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour dashboard: https://instantadpay.com/my', 'alert'); + } +} +// payment-proof Telegram feed (same pattern as the RM Circle proof channel): one compact +// line per event, admin-configured under Settings > Site (telegramBotToken, telegramChatId, +// optional telegramTopicId, telegramEvents = payouts | payouts+purchases | all, telegramCtaUrl) +// A second target, telegramEchoChatId + telegramEchoTopicId (+ telegramEchoEvents), echoes +// the same lines into a shared cross-program payments topic that RM Circle also posts to, +// so every line there carries the program name. +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, ev.toId].filter(Boolean)).catch(() => ({})); + const who = id => '#' + id + (names[id] ? ' @' + names[id] : ''); + // a brand-new chain id is not mapped to its account yet when the activation lands, so the line read bare "#200" (Marty 2026-10-11): name them by wallet + if (ev.type === 'MemberActivated' && ev.id && !names[ev.id] && ev.account) { const a = await accounts.byAddress(ev.account).catch(() => null); if (a && a.username) names[ev.id] = a.username; } + const cc = chain.getConfig(); + const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; + const build = async (mode) => { + let line = null; + // Tier payouts and the purchase itself are no longer posted one by one: they are composed + // into ONE message on AdminPaid, the last event of every purchase tx, so the feed reads + // "who bought what, then who was paid" (Marty, 2026-09-25). In payouts mode a purchase that + // paid no member (root or unsponsored buyer) stays silent, as before. + if (ev.type === 'AdminPaid') { + const txEvents = chain.recentEvents(1e9).filter(x => x.tx === ev.tx); + const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'recipientId', 'skippedId']) if (x[k]) ids.add(x[k]); }); + const nm = await accounts.namesForMembers([...ids]).catch(() => ({})); + line = feedgroup.compose(txEvents, id => '#' + id + (nm[id] ? ' @' + nm[id] : ''), weiToPol, { requirePayout: mode === 'payouts' }); + } + 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 === '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' : ''); + }; + // Missed-payout lines (Marty, 2026-09-16): when a share is passed over, say who missed it and who got it. + // (a) on-chain pass-up: the TierPaid with hops>0 follows the PassedUp events of the same tx, already indexed. + // (b) off-chain walk-up past an unactivated sponsor: recorded by sponsorSyncOnEvent, posted on the Purchase. + let missed = null; + try { + const site = 'https://instantadpay.com/my'; + // (a) on-chain pass-ups: AdminPaid is the last event of every purchase tx, so by then every + // PassedUp and TierPaid of the tx is indexed; one message shows the whole chain (missed.js). + if (ev.type === 'AdminPaid') { + const all = chain.recentEvents(1e9); + const txEvents = all.filter(x => x.tx === ev.tx); + if (txEvents.some(x => x.type === 'PassedUp')) { + const ids = new Set(); txEvents.forEach(x => { for (const k of ['buyerId', 'skippedId', 'recipientId']) if (x[k]) ids.add(x[k]); }); + const nm2 = await accounts.namesForMembers([...ids]).catch(() => ({})); + const who2 = id => '#' + id + (nm2[id] ? ' @' + nm2[id] : ''); + const had = (id, tier) => all.filter(y => y.type === 'BuyerCounted' && y.sponsorId === id && y.block < ev.block).length; + missed = missedNotice.composeMissed(txEvents, who2, had, site); + } + } + if (ev.type === 'Purchase' && movedByTx.has(ev.tx) && !movedByTx.get(ev.tx).posted) { // legacy path; walk-ups now post at activation + const mv = movedByTx.get(ev.tx); movedByTx.delete(ev.tx); + const lostAcct = await refAccount(mv.oldRef); + if (lostAcct) { + const lostName = lostAcct.username ? '@' + lostAcct.username : lostAcct.email.replace(/@.*/, '') + '@'; + const nm3 = await accounts.namesForMembers([mv.toId]).catch(() => ({})); + missed = '\u{1F62C} Missed sale: ' + lostName + ' had not switched on payouts, so ' + who(ev.buyerId) + "'s $" + Math.round(ev.priceCents / 100) + ' purchase routed past them. That buyer, and every payout from them, now belongs to #' + mv.toId + (nm3[mv.toId] ? ' @' + nm3[mv.toId] : '') + ' for good.' + + '\nTwo minutes on the Wallet tab prevents this: ' + site.replace(/^https:\/\//, '') + ''; + } + } + } catch (e) { console.error('missed-payout post', e.message); } + // the main group used to get bare payout lines with no product name: nobody knew what they were from + const brand = t => '\u{1F7E0} InstantAdPay\n' + t; + if (sc.telegramChatId) { const t = await build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, brand(t), sc.telegramTopicId); if (missed && String(sc.telegramEvents || 'payouts') !== 'none') await telegramSend(sc.telegramChatId, missed, sc.telegramTopicId).catch(() => {}); } + if (sc.telegramEchoChatId) { const t = await build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, brand(t), sc.telegramEchoTopicId); } + if (missed && sc.telegramEchoChatId && String(sc.telegramEchoEvents || 'payouts') !== 'none') await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay \u00b7 ' + missed, sc.telegramEchoTopicId).catch(() => {}); +} +// holding-tank arrivals -> one digest line in the shared payments topic (Marty, 2026-09-12): who is +// waiting for a sponsor, by username, so builders go adopt them. Runs every 15 min, posts only +// when someone new landed since the last check. +async function tankNotifyTick() { + const sc = siteConfig(); + if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; + const f = path.join(DATA_DIR, 'tank-notify.json'); + let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} + const since = st.last || (Date.now() - 24 * 3600 * 1000); + const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since); + st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st)); + if (!fresh.length) return; + const named = fresh.filter(w => w.username).map(w => '@' + w.username); + const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : ''; + const text = '\u{1FAA3} InstantAdPay \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who + + '\nAdopt from My line \u203a Holding tank: instantadpay.com/my'; + await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); +} +// one sendMessage call; never throws, never logs the token +async function telegramSend(chatId, text, threadId) { + const sc = siteConfig(); + if (!sc.telegramBotToken || !chatId) return; + discordRelay.mirror({ chatId, threadId, text }); + const body = JSON.stringify(Object.assign({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }, threadId ? { message_thread_id: Number(threadId) } : {})); + await new Promise((resolve) => { + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, r => { + // say what happened: a feed that fails silently is indistinguishable from a quiet day (2026-09-25) + let raw = ''; r.setEncoding('utf8'); r.on('data', d => { raw += d; }); + r.on('end', () => { let j = null; try { j = JSON.parse(raw); } catch (e) {} + if (j && j.ok) console.log('tg-ok chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' message_id=' + (j.result && j.result.message_id)); + else console.error('tg-fail chat=' + chatId + (threadId ? ' thread=' + threadId : '') + ' http=' + r.statusCode + ' ' + ((j && j.description) || raw.slice(0, 160))); + resolve(); }); + }); + rq.on('error', e => { console.error('tg-fail chat=' + chatId + ' network: ' + e.message); resolve(); }); + rq.on('timeout', () => { console.error('tg-fail chat=' + chatId + ' timeout'); rq.destroy(); resolve(); }); rq.end(body); + }); +} + +// photo post (multipart) for the achievement badges (Marty, 2026-09-13); same bot, sendPhoto only +async function telegramSendPhoto(chatId, jpeg, caption, threadId) { + const sc = siteConfig(); + if (!sc.telegramBotToken || !chatId || !jpeg) return false; + discordRelay.mirror({ chatId, threadId, text: caption, photo: jpeg }); + const B = '----iapbadge' + crypto.randomBytes(8).toString('hex'); + const field = (n, v) => Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="' + n + '"\r\n\r\n' + v + '\r\n'); + const parts = [field('chat_id', String(chatId)), field('caption', caption), field('parse_mode', 'HTML')]; + if (threadId) parts.push(field('message_thread_id', String(Number(threadId)))); + parts.push(Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="photo"; filename="badge.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'), jpeg, Buffer.from('\r\n--' + B + '--\r\n')); + const body = Buffer.concat(parts); + return new Promise((resolve) => { + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendPhoto', method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=' + B, 'Content-Length': body.length }, timeout: 20000 }, res => { + let out = ''; res.on('data', c => out += c); res.on('end', () => resolve(res.statusCode === 200)); + }); + rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body); + }); +} +const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'] }; +const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json'); +function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } } +// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the +// automatic Friday Game Pass perk; returns how many chats it reached (0 when already posted or not configured). +async function postBadgeOnce(email, key, note) { + const e = String(email || '').toLowerCase(); const log = badgeLog(); const mine = log[e] || {}; if (mine[key] || !BADGE_META[key]) return 0; + const a = await accounts.byEmail(e); if (!a) return 0; + const who = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member'); + const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; + const [label, sub] = BADGE_META[key]; + const caption = '\u{1F3C6} InstantAdPay · ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + (note ? ' · ' + note : '') + '\n' + link; + const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return 0; + mine[key] = { ts: Date.now(), sent: 0, auto: note || true }; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} // claim first: no double post + const sc = siteConfig(); let sent = 0; + if (sc.telegramBotToken && sc.telegramEchoChatId) { + if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; + if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; + } + mine[key].sent = sent; log[e] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (er) {} + pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); + console.log('badge posted (auto)', e, key, 'sent', sent); + return sent; +} +// Five Dollar Friday Game Pass perk (Marty 2026-10-23: "this should happen automatically every Friday"): a $5+ package on a +// Friday (the Friday bonus landed, so it qualified) also gives the buyer a free 7-day Game Pass, once per member per Friday. +// A purchase that itself started a paid pass gets no second week on top. The Game Pass badge posts only the first time a +// member ever holds a pass. Counts as no sale (comp). Switch: site setting fridayPassPerk '0' turns it off. +async function fridayPassPerk(ev, bonus, gp) { + if (!(Number(bonus) > 0) || gp) return null; + if (String(siteConfig().fridayPassPerk || '1') === '0' || !gamepass.cfg().enabled) return null; + const a = await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; + const ms = Number(ev.ts) > 1e12 ? Number(ev.ts) : (Number(ev.ts) > 0 ? Number(ev.ts) * 1000 : Date.now()); + const day = new Date(ms).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); + if (!(await marks.claim('fdfpass:' + day + ':' + a.email))) return null; // once per member per Friday, across app copies + const r = gamepass.comp(a.email, 'Five Dollar Friday perk ' + day, 'weekly'); + console.log('friday pass perk', a.email, day, 'until', new Date(r.until).toISOString()); + try { + const until = new Date(r.until).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Five Dollar Friday: a free Game Pass week', '

      Your Friday package came with a free 7-day Game Pass, on top of the Friday bonus credits. It runs until ' + until + ' Central, across all nine games.

      ', 'notice'); + } catch (e) { console.error('friday pass notice', e.message); } + try { await postBadgeOnce(a.email, 'gamepass', 'Five Dollar Friday'); } catch (e) { console.error('friday pass badge', e.message); } + return r; +} + +// ---- live feed (SSE) ---- +const feedClients = new Set(); +function pushFeed(ev) { + const line = 'data: ' + JSON.stringify(ev) + '\n\n'; + for (const res of feedClients) { try { res.write(line); } catch (e) { feedClients.delete(res); } } +} + +// ---- server ---- +// -- Drip Runner (2026-09-30): the hand-off, refuel visits and the signed callback to the game. +// Tokens share PolHunter's shape (base64url payload . base64url HMAC) under a separate secret. +const DR_SECRET = () => String(process.env.DR_SSO_SECRET || '').trim(); +const DR_URL = () => String(process.env.DR_URL || 'https://driprunner.saasy.top').replace(/\/+$/, ''); +const drB64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); +const drSign = payload => drB64u(crypto.createHmac('sha256', DR_SECRET()).update(payload).digest()); +function drMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + drSign(payload); } +function drOpen(token) { + if (DR_SECRET().length < 32) return { error: 'Drip Runner is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = drSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That refuel link has expired. Go back to the game and tap Refuel again.' }; + return { ok: true, claims: c }; +} +const refuelTokens = new Map(); // nonce -> { email, memberId, id, title, target, ts, ret, challenge, done } +async function drCallback(body) { + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', DR_SECRET()).update(ts + '\n' + raw).digest('hex'); + try { const r = await fetch(DR_URL() + '/api/refuel/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-DR-Ts': ts, 'X-DR-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } + catch (e) { console.warn('driprunner callback', e.message); return false; } +} + + +// -- Gem Kingdom (2026-10-01): sign-in hand-off + the Crown shop checkout. Same token shape as Drip Runner, its own +// secret GK_SSO_SECRET (also set on the game). The game mints a 'gk-buy' order; this site shows the member what it +// costs, spends the ad credits through ads.gamePurchase (credit log + on-chain burn like any flat buy), then signs a +// 'gk-receipt' back: as a redirect to the game AND as a server-to-server callback, so Crowns land even if they never return. +const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim(); +const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, ''); +const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest()); +function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gkSign(payload); } +function gkOpen(token) { + if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = gkSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That order has expired. Go back to Gem Kingdom and open the shop again.' }; + return { ok: true, claims: c }; +} +const gkOrders = persistedMap('gkorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts } +const gkEsc = s => String(s == null ? '' : s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch])); +function gkPage(res, code, title, inner, head) { + res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); + res.end('' + gkEsc(title) + ' | InstantAdPay' + (head || '') + + '' + + '
      ' + inner + '
      '); +} +function gkFormBody(req) { return new Promise((ok, no) => { let d = ''; req.on('data', ch => { d += ch; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(new URLSearchParams(d))); req.on('error', no); }); } +const gkCookie = (k, v, maxAge) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + maxAge + (IS_PROD ? '; Secure' : ''); +// -- ClutterHunt (2026-10-03): seasonal hidden-object rooms at clutterhunt.com; its own secret SEEK_SSO_SECRET (also on the game) +const SEEK_SECRET = () => String(process.env.SEEK_SSO_SECRET || '').trim(); +const SEEK_URL = () => String(process.env.SEEK_URL || 'https://clutterhunt.com').replace(/\/+$/, ''); +const SEEK_ALT = () => String(process.env.SEEK_ALT_URLS || 'https://www.clutterhunt.com,https://clutterhunt.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); +const seekSign = p => drB64u(crypto.createHmac('sha256', SEEK_SECRET()).update(p).digest()); +function seekMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + seekSign(payload); } +// -- Shards of Valor (2026-10-18): multiplayer RPG at shardsofvalor.com; its own secret SOV_SSO_SECRET (also on the game). +// Same token shape as ClutterHunt; the Game Pass flag rides along (gpClaim). Not in the public games list until launch. +const SOV_SECRET = () => String(process.env.SOV_SSO_SECRET || '').trim(); +const SOV_URL = () => String(process.env.SOV_URL || 'https://shardsofvalor.com').replace(/\/+$/, ''); +const SOV_ALT = () => String(process.env.SOV_ALT_URLS || 'https://www.shardsofvalor.com,https://sov.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); +const sovSign = p => drB64u(crypto.createHmac('sha256', SOV_SECRET()).update(p).digest()); +function sovMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sovSign(payload); } +function seekOpen(token) { + if (SEEK_SECRET().length < 32) return { error: 'ClutterHunt is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = seekSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to ClutterHunt and tap Hint again.' }; + return { ok: true, claims: c }; +} +const seekIsGameUrl = u => [SEEK_URL()].concat(SEEK_ALT()).some(o => String(u || '').startsWith(o + '/')); +async function seekCallback(cbUrl, receipt) { + if (!seekIsGameUrl(cbUrl)) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('clutterhunt callback', e.message); return false; } +} +// -- SpellWheel (2026-10-04): the letter-wheel word game at spellwheel.com; its own secret SW_SSO_SECRET (also on the game) +const SW_SECRET = () => String(process.env.SW_SSO_SECRET || '').trim(); +const SW_URL = () => String(process.env.SW_URL || 'https://spellwheel.com').replace(/\/+$/, ''); +const SW_ALT = () => String(process.env.SW_ALT_URLS || 'https://www.spellwheel.com,https://spellwheel.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); +const swSign = p => drB64u(crypto.createHmac('sha256', SW_SECRET()).update(p).digest()); +function swMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + swSign(payload); } +function swOpen(token) { + if (SW_SECRET().length < 32) return { error: 'SpellWheel is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = swSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That hint link has expired. Go back to SpellWheel and tap Hint again.' }; + return { ok: true, claims: c }; +} +const swIsGameUrl = u => [SW_URL()].concat(SW_ALT()).some(o => String(u || '').startsWith(o + '/')); +// -- PolyBreak (2026-10-13): the brick breaker; its own secret PB_SSO_SECRET (also on the game), same shape as SpellWheel +const PB_SECRET = () => String(process.env.PB_SSO_SECRET || '').trim(); +const PB_URL = () => String(process.env.PB_URL || 'https://polybreak.app').replace(/\/+$/, ''); +const PB_ALT = () => String(process.env.PB_ALT_URLS || 'https://www.polybreak.app,https://polybreak.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); +const pbSign = p => drB64u(crypto.createHmac('sha256', PB_SECRET()).update(p).digest()); +function pbMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pbSign(payload); } +function pbOpen(token) { + if (PB_SECRET().length < 32) return { error: 'PolyBreak is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = pbSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Go back to PolyBreak and tap One more paddle again.' }; + return { ok: true, claims: c }; +} +const pbIsGameUrl = u => [PB_URL()].concat(PB_ALT()).some(o => String(u || '').startsWith(o + '/')); +async function pbCallback(cbUrl, receipt) { + if (!pbIsGameUrl(cbUrl)) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polybreak callback', e.message); return false; } +} +// -- PolyWarriors (2026-10-05): the cyberpunk fighting game at polywarriors.com; its own secret PW_SSO_SECRET (also on the game) +const PW_SECRET = () => String(process.env.PW_SSO_SECRET || '').trim(); +const PW_URL = () => String(process.env.PW_URL || 'https://polywarriors.com').replace(/\/+$/, ''); +const PW_ALT = () => String(process.env.PW_ALT_URLS || 'https://www.polywarriors.com,https://polywarriors.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean); +const pwSign = p => drB64u(crypto.createHmac('sha256', PW_SECRET()).update(p).digest()); +function pwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pwSign(payload); } +async function swCallback(cbUrl, receipt) { + if (!swIsGameUrl(cbUrl)) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spellwheel callback', e.message); return false; } +} +const PW_MINT_COOKIE_S = 4 * 3600; // the dashboard "back to the mint" bar lives this long (was 7 days: people who looked at the price and left saw it for a week, Marty 2026-10-11) +// -- PolyWarriors paid mints (2026-10-05): the first mint is free in the game; later mints cost PW_MINT_CREDITS (100) from +// PURCHASED credits only (package credits on a position; earned credits never count, Marty's rule). The game signs an order +// with PW_SSO_SECRET (kind 'pw-mint'), the member confirms here, ads.gamePurchase(purchasedOnly) charges, and a signed +// receipt goes back to the game twice (server callback + redirect), whichever lands first. The game mints on the receipt. +function pwOpen(token) { + if (PW_SECRET().length < 32) return { error: 'PolyWarriors is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = pwSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: 'That mint order has expired. Tap Mint in PolyWarriors again.' }; + return { ok: true, claims: c }; +} +const pwPasses = persistedMap('pwpasses'); // email -> { n, earned, used, log: [{ at, d, why }] } +const pwPassN = e => ((pwPasses.get(e) || {}).n || 0); +function pwPassAdd(e, d, why) { const c = pwPasses.get(e) || { n: 0, earned: 0, used: 0, log: [] }; const v = { n: Math.max(0, c.n + d), earned: c.earned + Math.max(0, d), used: c.used + Math.max(0, -d), ts: Date.now(), log: [{ at: Date.now(), d, why }].concat(c.log || []).slice(0, 50) }; pwPasses.set(e, v); return v.n; } +const pwPrizes = persistedMap('pwprizes'); // 'YYYY-MM-DD:place' -> { email, credits, at } +const pwOrders = persistedMap('pworders'); // order -> { status: 'waiting'|'paid', email, serial, ret, cb, ts, tx, cents, delivered } +const pwIsGameUrl = x => [PW_URL()].concat(PW_ALT()).some(o => String(x || '').startsWith(o + '/')); +async function pwCallback(cbUrl, receipt) { + if (!pwIsGameUrl(cbUrl)) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('polywarriors callback', e.message); return false; } +} +const pwReceipt = (order, o) => pwMint({ kind: 'pw-mint-receipt', order, email: o.email, serial: o.serial, paid: 5, usd: (o.cents || 500) / 100, ref: o.tx || null }, 3 * 86400000); +async function pwDeliver(order) { // the game mints on the receipt; retried each minute until the game says ok (up to a day) + const o = pwOrders.get(order); if (!o || o.status !== 'paid' || o.delivered) return; + const ok = await pwCallback(o.cb, pwReceipt(order, o)); + const cur = pwOrders.get(order); if (!cur) return; + pwOrders.set(order, Object.assign({}, cur, ok ? { delivered: Date.now() } : { tries: (cur.tries || 0) + 1 })); +} +setInterval(() => { for (const [k, o] of pwOrders) { if (o.status === 'paid' && !o.delivered && (o.tries || 0) < 1440) pwDeliver(k).catch(() => {}); if (o.status === 'waiting' && Date.now() - o.ts > 7 * 86400000) pwOrders.delete(k); } }, 60000).unref(); +async function pwMintOnEvent(ev) { // a package bought while a mint waits earns one mint pass per $5; waiting mints use them first + if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null; + const a = (!IS_PROD && ev.devEmail) ? { email: ev.devEmail } : await accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null; // devEmail: local tests only + const e = String(a.email).toLowerCase(), when = ev.ts || Date.now(), seen = pwPasses.get(e) || {}; + if ((seen.log || []).some(x => x.why === 'buy:' + ev.tx)) return null; // each purchase counts once + const waiting = [...pwOrders.entries()].filter(([k, o]) => o.status === 'waiting' && o.email === e && o.ts <= when + 60000).sort((x, y) => y[1].ts - x[1].ts); // newest first: the warrior the member just tapped Mint on gets the first pass (an old forgotten order took Marty's on 10-06) + if (!waiting.length) return null; // passes come from packages bought for minting + const earned = Math.floor(ev.priceCents / 500); pwPassAdd(e, earned, 'buy:' + ev.tx); + const used = []; + for (const [k, o] of waiting) { if (pwPassN(e) < 1) break; pwPassAdd(e, -1, 'mint:' + k); pwOrders.set(k, Object.assign({}, o, { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() })); used.push(k); } + console.log('polywarriors mint passes', e, '+' + earned, 'from tx', String(ev.tx).slice(0, 12), 'used', used.length, 'left', pwPassN(e)); + for (const k of used) await pwDeliver(k); + return { earned, used, left: pwPassN(e) }; +} +async function gkCallback(cbUrl, receipt) { + if (!String(cbUrl || '').startsWith(GK_URL() + '/')) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; } +} + +// -- Spooky Doors (2026-10-02, the Halloween season game): sign-in hand-off, door visits and the costume shop. Same token +// shape as Drip Runner and Gem Kingdom under its own secret SD_SSO_SECRET (also set on the game, at least 32 characters). +// A door is a verified visit of its own kind ('door', own daily cap doorCapPerDay, never touching refuel or Earn counts). +// The game hears about it twice: a signed server-to-server callback AND a signed receipt on the redirect back, whichever +// lands first. Costumes are bought with ad credits through ads.gamePurchase, exactly like Gem Kingdom Crowns. +const SD_SECRET = () => String(process.env.SD_SSO_SECRET || '').trim(); +const SD_URL = () => String(process.env.SD_URL || 'https://spookydoors.com').replace(/\/+$/, ''); +const SD_SEASON = { start: '2026-10-04', end: '2026-11-01' }; // Central days, end exclusive (through Halloween night); start moved up from 10-17 (Marty, 2026-10-02) +const sdGoldenBonus = () => { const n = Number(ads.rates().goldenBonusCandy); return Number.isFinite(n) && n >= 0 ? Math.round(n) : 2; }; // extra candy on a Golden Door +const sdSign = p => drB64u(crypto.createHmac('sha256', SD_SECRET()).update(p).digest()); +function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sdSign(payload); } +function sdOpen(token, expiredMsg) { + if (SD_SECRET().length < 32) return { error: 'Spooky Doors is not connected yet.' }; + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + const want = sdSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || 'That link has expired. Go back to Spooky Doors and try again.' }; + return { ok: true, claims: c }; +} +// -- Road Agent (2026-10-07): the same door round trip under its own secret; a fuel stop is a door with game: 'roadagent' +const RA_SECRET = () => String(process.env.RA_SSO_SECRET || '').trim(); +const RA_URL = () => String(process.env.RA_URL || 'https://roadagent.app').replace(/\/+$/, ''); +const DOOR_GAMES = () => ({ spookydoors: { name: 'Spooky Doors', secret: SD_SECRET(), url: SD_URL(), hdr: 'SD', back: 'Go back to Spooky Doors and knock again.' }, + roadagent: { name: 'Road Agent', secret: RA_SECRET(), url: RA_URL(), hdr: 'RA', back: 'Go back to Road Agent and fuel up again.' } }); +const gSign = (g, p) => drB64u(crypto.createHmac('sha256', g.secret).update(p).digest()); +function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gSign(g, payload); } +// open a door token from whichever game signed it: { ok, claims, game } or { error } +function doorOpen(token, expiredMsg) { + const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; + let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } + let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; } + const G = DOOR_GAMES(); const key = G[c.game] ? c.game : 'spookydoors'; const g = G[key]; + if (!g.secret || g.secret.length < 32) return { error: g.name + ' is not connected yet.' }; + const want = gSign(g, payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' }; + if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || ('That link has expired. ' + g.back) }; + return { ok: true, claims: c, game: key }; +} +const gameUrlOk = (key, x) => String(x || '').startsWith(DOOR_GAMES()[key].url + '/'); +async function gameCallback(key, body) { // door done -> the game's server, signed over ts + newline + raw body + const g = DOOR_GAMES()[key]; const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', g.secret).update(ts + '\n' + raw).digest('hex'); + const h = { 'Content-Type': 'application/json' }; h['X-' + g.hdr + '-Ts'] = ts; h['X-' + g.hdr + '-Sig'] = sig; + try { const r = await fetch(g.url + '/api/door/callback', { method: 'POST', headers: h, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } + catch (e) { console.warn(key + ' callback', e.message); return false; } +} +const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id, title, target|videoUrl, host, ts, ret, challenge, done, doneRet } +const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts } +const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/'); +const sdJoin = (ret, q) => ret + (String(ret).includes('?') ? '&' : '?') + q; // ret is SD_URL/play?door=, so this appends &... +async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host} (+ house, program on a house ad), X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody) + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', SD_SECRET()).update(ts + '\n' + raw).digest('hex'); + try { const r = await fetch(SD_URL() + '/api/door/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SD-Ts': ts, 'X-SD-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } + catch (e) { console.warn('spookydoors callback', e.message); return false; } +} +async function sdShopCallback(cbUrl, receipt) { + if (!sdIsGameUrl(cbUrl)) return false; + try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spookydoors shop callback', e.message); return false; } +} +// the visited campaign owner's public username ("+12 candy from @host"); null for house ads or members without one +async function sdHost(campaignId) { + try { const c = await ads.campaignById(campaignId); if (!c || !c.owner) return null; const a = await accounts.byEmail(String(c.owner).toLowerCase()); return (a && a.username) || null; } catch (e) { return null; } +} +// house ads (2026-10-02): when a door finds no visit pack and no video, one of Marty's own programs (rates.doorHouseAds) +// instead of "Nobody's home". Never the same one twice in a row for a member; otherwise the one least recently shown to +// them today. The player's own IAP username rides along where the program takes a share link (ref with {u}). +const doorHouse = persistedMap('doorhouse'); // email -> { ts, day, last, shown: { program: ts } } +function doorHouseList() { + const l = ads.rates().doorHouseAds; + return (Array.isArray(l) ? l : []).filter(x => x && String(x.name || '').trim() && /^https:\/\/[^\s"'<>]+$/i.test(String(x.url || ''))).slice(0, 20); +} +async function doorHousePick(email, claimedUsername) { + const list = doorHouseList(); if (!list.length) return null; + const day = todayCT(); const prev = doorHouse.get(email) || {}; const shown = prev.day === day ? Object.assign({}, prev.shown) : {}; + const pool = list.length > 1 ? list.filter(x => x.name !== prev.last) : list; + const h = pool.slice().sort((a, b) => (shown[a.name] || 0) - (shown[b.name] || 0))[0]; // never shown today sorts first, list order breaks ties + shown[h.name] = Date.now(); doorHouse.set(email, { ts: Date.now(), day, last: h.name, shown }); + let username = null; try { const a = await accounts.byEmail(email); username = (a && a.username) || null; } catch (e) {} + if (!username && claimedUsername) username = String(claimedUsername); + const withRef = username && /^[A-Za-z0-9_.-]{1,40}$/.test(username) && /^https:\/\/[^\s"'<>]*\{u\}/i.test(String(h.ref || '')); + return { name: String(h.name).trim().slice(0, 60), title: String(h.title || h.name).trim().slice(0, 120), target: withRef ? String(h.ref).replace('{u}', encodeURIComponent(username)) : String(h.url) }; +} +function sdPage(res, code, title, inner) { + res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); + res.end('' + gkEsc(title) + ' | InstantAdPay' + + '' + + '' + + '
      ' + inner + '
      '); +} + + +// the generic season window (2026-10-02), shared by the Games card and the Promo tools card: 'live' while today (Central) is in +// [start, end), 'preview' before start for the admin only, 'hidden' otherwise (and for everyone from end on) +function seasonState(season, day, admin) { + if (!season) return 'live'; + if (day >= season.end) return 'hidden'; + if (day < season.start) return admin ? 'preview' : 'hidden'; + return 'live'; +} +// game testers: GAMES_TESTERS env = comma list of usernames or emails who may play coming-soon / not-yet-live games from the Games tab +const GAME_TESTERS = () => new Set(String(process.env.GAMES_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); +const isGameTester = (acct, email) => { const T = GAME_TESTERS(); if (!T.size) return false; return T.has(String((acct && acct.username) || '').toLowerCase()) || T.has(String(email || '').toLowerCase()); }; +// -- the games registry (2026-10-01). Add a game here; launch it by adding its slug to site config gamesLive. +function GAMES() { + return withPerks([ + { slug: 'spookydoors', name: 'Spooky Doors', tag: 'Halloween \u00b7 Oct 4 to 31', blurb: 'Trick or treat! Walk the street, knock on doors and fill your candy bucket. Every door is a short visit to a member\u2019s page or ad, and candy climbs a ladder with POL at set levels. Gone after Halloween night.', + art: SD_URL() + '/og-spookydoors.jpg', play: '/api/my/spookydoors', pays: 'POL at set candy levels', season: { start: SD_SEASON.start, end: SD_SEASON.end }, progress: sdProgress }, + { slug: 'roadagent', name: 'Road Agent', tag: 'Night highway shooter', blurb: 'Drive the night highway, shoot the hostiles that hunt you, spare the civilians. Fuel from a sponsor visit brings the weapons truck. Every sector you clear for the first time pays POL.', + art: RA_URL() + '/og-roadagent.jpg', play: '/api/my/roadagent', pays: 'POL for first sector clears and the daily patrol', progress: raProgress, + soon: { opens: '2026-10-15', label: 'Opens Thursday, Oct 15' } }, // Marty 2026-10-07: release Thu Oct 15; testers reach it by direct link meanwhile + { slug: 'driprunner', name: 'Drip Runner', tag: 'Arcade runner', blurb: 'Hop the network, dodge the bots, clear chapters. Each first clear drips POL into your game balance, and a refuel on a member\u2019s page keeps your run alive.', + art: DR_URL() + '/og-driprunner.jpg?v=20261002', artPos: 'left', play: '/api/my/driprunner', pays: 'POL to your wallet at 0.10', progress: drProgress }, + { slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.', + art: GK_URL() + '/fantasy/og-gemkingdom.jpg?v=20261002', play: '/api/my/gemkingdom', cta: 'Play', pays: 'POL for first clears; Crowns from ad credits' }, + { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt', blurb: 'Hunt hidden codes on sites across the network. Every find drips POL straight to your wallet.', + art: 'https://polhunter.com/img/hero-800.webp', play: '/api/my/polhunter', pays: 'POL per find' }, + { slug: 'clutterhunt', name: 'ClutterHunt', tag: 'Hidden objects', blurb: 'Search cozy, cluttered rooms for hidden objects. New rooms every season, starting with the Haunted Manor.', + art: SEEK_URL() + '/og-clutterhunt.jpg?v=c2', play: '/api/my/clutterhunt', pays: 'POL for first clears and 3-star clears' }, + // coming soon (2026-10-04, Marty: "build some anticipation... show that it's coming soon and put the date"): every member sees + // the card with its date and no Play button until `soon.opens` (Central); from then it is an ordinary card, live via gamesLive + { slug: 'spellwheel', name: 'SpellWheel', tag: 'Word game', blurb: 'Swipe the letter wheel to fill the crossword, travel through six cozy places, and solve a new daily puzzle with everyone. Clear levels and chapters to earn POL.', + art: SW_URL() + '/og-spellwheel.jpg?v=1', play: '/api/my/spellwheel', pays: 'POL for levels, chapters and daily puzzles', soon: { opens: '2026-10-10', label: 'Opens Saturday, Oct 10' } }, + // PolyWarriors (Marty 2026-10-05: "put Poly Warriors there as well, saying that it's coming next Monday") + { slug: 'polywarriors', name: 'PolyWarriors', tag: 'Cyberpunk fighting', blurb: 'Turn-based fights with collectible low-poly warriors. Recruit fighters born with rare traits, climb the arena, challenge other members, and mint your warriors as NFTs.', + art: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.jpg', video: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/polywarriors-trailer.mp4', play: '/api/my/polywarriors', pays: 'POL for first wins over arena rivals', soon: { opens: '2026-10-12', label: 'Opens Monday, Oct 12' } }, // live 10-12: trailer poster + 16:9 trailer on the public games page + // PolyBreak (2026-10-13): the brick breaker; first round clears and the purple Polygon gem pay POL + { slug: 'polybreak', name: 'PolyBreak', tag: 'Brick breaker', blurb: 'Break walls of glass jewel bricks with the classic arcade capsules, and catch the purple Polygon gem when it falls. First clears of each round pay POL.', + art: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak-clean.jpg', play: '/api/my/polybreak', pays: 'POL for first round clears and gem catches' }, + ]); +} +// each game's member perk (the $5 welcome offer, 2026-10-05) shown on its card +const withPerks = list => { const st = starter.cfg(); return list.map(g => starter.GAMES[g.slug] && st.on ? Object.assign({}, g, { perk: starter.GAMES[g.slug].perk }) : g); }; +// -- cross-promo strip (2026-10-03): one short line per game and where a signed-out player lands (the game's own page) +const STRIP = () => ({ + spookydoors: { line: 'Halloween only. Run the graveyard, knock on doors, climb the candy ladder to POL.', open: SD_URL() + '/play', host: SD_URL().replace(/^https?:\/\//, '') }, + roadagent: { line: 'Night highway. Shoot the hostiles, clear sectors, get paid in POL.', open: RA_URL() + '/', host: RA_URL().replace(/^https?:\/\//, '') }, + driprunner: { line: 'Hop, dodge the bots, clear chapters. Every first clear drips POL.', open: DR_URL() + '/play', host: DR_URL().replace(/^https?:\/\//, '') }, + gemkingdom: { line: 'Match gems, beat the bosses, rebuild your kingdom. First clears pay POL.', open: GK_URL() + '/play', host: GK_URL().replace(/^https?:\/\//, '') }, + polhunter: { line: 'Find hidden codes on sites across the network. Every find drips POL.', open: 'https://polhunter.com/', host: 'polhunter.com' }, + clutterhunt: { line: 'Search cozy, cluttered rooms for hidden objects. New rooms every season.', open: SEEK_URL() + '/', host: SEEK_URL().replace(/^https?:\/\//, '') }, + polybreak: { line: 'Break the glass jewel wall, catch the capsules and the purple Polygon gem. First clears pay POL.', open: PB_URL() + '/', host: PB_URL().replace(/^https?:\/\//, '') }, + spellwheel: { line: 'Swipe the letter wheel, fill the grid, solve the daily puzzle. Levels and dailies pay POL.', open: SW_URL() + '/', host: SW_URL().replace(/^https?:\/\//, '') }, + polywarriors: { line: 'Recruit one-of-a-kind warriors, fight the arena, challenge members. First wins pay POL.', open: PW_URL() + '/', host: PW_URL().replace(/^https?:\/\//, '') }, +}); +// live for the strip: in gamesLive, and a seasonal game until its season ends (Marty 2026-10-03: Spooky Doors may show before +// its formal announcement; "if someone manages to see it and play it, that's fine") +function stripGames() { + const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); + const day = todayCT(), S = STRIP(); const lbl = d => { const t = new Date(d + 'T12:00:00Z'); t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; + return GAMES().filter(g => live.has(g.slug) && S[g.slug] && !(g.season && day >= g.season.end)) + .map(g => ({ slug: g.slug, name: g.name, tag: g.season ? 'Limited time \u00b7 ends ' + lbl(g.season.end) : g.tag, line: S[g.slug].line, art: g.art, artPos: g.artPos || 'center', seasonal: !!g.season })); +} + +// -- PassiveDrip hand-off (2026-10-01): same token shape as Drip Runner, its own secret (PD_SSO_SECRET, also stored in +// PassiveDrip's site_config iap_sso_secret). PassiveDrip signs the member in or creates the account, carries the sponsor +// over by email, and OFFERS the wallet with one confirm tap; it never writes or overwrites a payout address silently. +const PD_SECRET = () => String(process.env.PD_SSO_SECRET || '').trim(); +const PD_URL = () => String(process.env.PD_URL || 'https://passivedrip.com').replace(/\/+$/, ''); +function pdMint(claims) { const payload = JSON.stringify(Object.assign({ aud: 'passivedrip', iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(16).toString('hex') }, claims)); return drB64u(payload) + '.' + drB64u(crypto.createHmac('sha256', PD_SECRET()).update(payload).digest()); } +async function pdProgress(memberId, email) { + const j = await pdsync.member(memberId, email); if (!j) return null; + if (!j.exists) return { line: 'No PassiveDrip account yet. Open it and one is made for you.' }; + const coins = Math.floor(Number(j.coins) || 0); + return { line: '@' + j.username + ' · ' + coins.toLocaleString('en-US') + ' of ' + Number(j.threshold || 2000).toLocaleString('en-US') + ' coins' + (j.hasWallet ? '' : ' · no payout wallet yet') + (j.paidPol ? ' · ' + Number(j.paidPol).toFixed(2) + ' POL paid out' : '') }; +} +// the player's own line on the Drip Runner card, read from the game with a signed request +async function drProgress(memberId) { + if (DR_SECRET().length < 32) return null; + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', DR_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); + const r = await fetch(DR_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); + if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; + return { line: 'Chapter ' + j.chapter + ' \u00b7 ' + Number(j.unpaid).toFixed(3) + ' POL in your game balance' + (j.paidTotal ? ' \u00b7 ' + Number(j.paidTotal).toFixed(3) + ' POL paid out' : '') }; +} + +// the player's own line on the Road Agent card (signed, like the others) +async function raProgress(memberId) { + if (RA_SECRET().length < 32) return null; + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', RA_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); + const r = await fetch(RA_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); + if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; + return { line: (Number(j.bestDist || 0) / 1000).toFixed(2) + ' km best \u00b7 ' + Number(j.sectors || 0) + ' sector' + (Number(j.sectors) === 1 ? '' : 's') + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') }; +} +// the player's own line on the Spooky Doors card, read from the game with a signed request (same scheme as Drip Runner) +async function sdProgress(memberId) { + if (SD_SECRET().length < 32) return null; + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SD_SECRET()).update('player:' + memberId + ':' + ts).digest('hex'); + const r = await fetch(SD_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) }); + if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' }; + const cap = ads.rates().doorCapPerDay || 15; + return { line: Number(j.candy || 0).toLocaleString('en-US') + ' candy \u00b7 ' + Number(j.doorsToday || 0) + ' of ' + cap + ' doors today' + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') }; +} + +// -- in-game sign-in (Marty, 2026-10-03: "an integrated sign-on that never leaves the game"). The game's own /signin +// page calls these endpoints straight from the player's browser (CORS, no cookies), so the sign-up guard and the +// one-account-per-person checks see the player's real connection. Same email code, same guard and the same account +// as the dashboard; the answer is the game's hand-off token instead of a session cookie, plus a GAME PASS (signed +// here, kept by the game in localStorage, 30 days) that lets the game's "open InstantAdPay" nudges arrive signed in +// (POST /api/game/enter). The IAP device cookie cannot ride a cross-site request, so the game sends its own +// browser id (req.gameDev) for the device checks. +// frames: false = that game's page CSP (default-src 'self', no frame-src) refuses iframes, so its login ad opens in a new tab +const GAME_AUTH = { + driprunner: { name: 'Drip Runner', frames: false, origins: () => [DR_URL()], host: () => DR_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => drMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), wallet: a.address || null, username: a.username || null, + sponsorRef: a.sponsorRef || null, joinedRef: a.joinedRef || null, joinedAt: a.created || null }) }, + seek: { name: 'ClutterHunt', origins: () => [SEEK_URL()].concat(SEEK_ALT()), host: () => SEEK_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => seekMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, + polybreak: { name: 'PolyBreak', frames: false, origins: () => [PB_URL()].concat(PB_ALT()), host: () => PB_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => pbMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null, sponsorRef: a.sponsorRef || null }) }, + spellwheel: { name: 'SpellWheel', origins: () => [SW_URL()].concat(SW_ALT()), host: () => SW_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => swMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, + polywarriors: { name: 'PolyWarriors', origins: () => [PW_URL()].concat(PW_ALT()), host: () => PW_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => pwMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, + shardsofvalor: { name: 'Shards of Valor', frames: false, origins: () => [SOV_URL()].concat(SOV_ALT()), host: () => SOV_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => sovMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, + gemkingdom: { name: 'Gem Kingdom', origins: () => [GK_URL(), 'https://gemkingdom.saasy.top'], host: () => GK_URL().replace(/^https?:\/\//, ''), + mint: (a, memberId) => gkMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) }, +}; +// a game's one-tap link carries the inviter's ?ref to /my, where the viral-link rule sets the sponsor (2026-10-05: only Gem Kingdom and +// Spooky Doors passed it before; signed-out visitors from the other games lost their sponsor) +const refQ = u => { const r = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); return r ? '?ref=' + encodeURIComponent(r) : ''; }; +const devOrigin = o => !IS_PROD && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(o); +// the sign-in login ad, shared by the dashboard (GET /api/ads/slot?type=login) and the games' sign-in kit +// (GET /api/game/ads/login). ads.serve counts the impression and marks lastShownDay, exactly as before; the +// member clicks "Open Ad" (a real, counted click through /api/ads/click) while the countdown runs. Every call +// is tallied per Central day and surface (loginshows.js) so the admin can compare dashboard and game sign-ins. +async function loginAdFor(req, surface) { + const ad = await ads.serve('login', viewerGeo(req)); + let house = false; + if (ad) { + ad.dwell = ads.rates().loginDwellSeconds || 10; + // 2026-10-09: the gate frames the sponsor's page under our bar (timer + way out visible on the ad itself). + // Login campaigns were never frame-checked, so check here, once per campaign, and fall back to a new tab. + const site = await ads.targetOf(ad.id); + ad.siteUrl = site; + ad.frameable = await loginFrameable(ad.id, site, surface !== 'dashboard'); + try { const c = await ads.campaignById(ad.id); house = !!(c && (c.house || c.owner === ads.HOUSE_OWNER)); } catch (e) {} + } + loginShows.record(surface, ad ? { house } : null).catch(() => {}); + return ad; +} +function gameOf(req, slug) { + const g = Object.prototype.hasOwnProperty.call(GAME_AUTH, String(slug || '')) ? GAME_AUTH[slug] : null; if (!g) return null; + const o = String(req.headers.origin || ''); + return g.origins().includes(o) || devOrigin(o) ? g : null; +} +function gameCors(req) { + const o = String(req.headers.origin || ''); + const ok = Object.values(GAME_AUTH).some(g => g.origins().includes(o)) || devOrigin(o); + return ok ? { 'Access-Control-Allow-Origin': o, Vary: 'Origin', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'content-type', 'Access-Control-Max-Age': '600' } : { Vary: 'Origin' }; +} +let gamePassKey = ''; +function gamePassSecret() { + if (gamePassKey) return gamePassKey; + const f = path.join(DATA_DIR, 'game-pass.secret'); + try { gamePassKey = fs.readFileSync(f, 'utf8').trim(); } catch (e) {} + if (gamePassKey.length < 32) { gamePassKey = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, gamePassKey, { mode: 0o600 }); } catch (e) { console.error('game pass secret', e.message); } } + return gamePassKey; +} +const gamePassSign = p => drB64u(crypto.createHmac('sha256', gamePassSecret()).update(p).digest()); +function gamePassMint(email, game) { const p = JSON.stringify({ e: String(email).toLowerCase(), g: game, iat: Date.now(), exp: Date.now() + 30 * 86400000 }); return drB64u(p) + '.' + gamePassSign(p); } +function gamePassOpen(tok) { + const [p, sig] = String(tok || '').split('.'); if (!p || !sig) return null; + let payload; try { payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return null; } + const want = gamePassSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null; + let c; try { c = JSON.parse(payload); } catch (e) { return null; } + return c && c.e && c.exp > Date.now() ? c : null; +} +const gameDevOf = b => { const d = String((b && b.dev) || ''); return /^[a-f0-9]{32}$/.test(d) ? d : ''; }; +async function gameAnswer(g, slug, acct) { // the game token (only once a username exists) + a fresh pass + let memberId = acct.memberId || 0; + if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } + const needUsername = !acct.username; + return { ok: true, needUsername, username: acct.username || null, token: needUsername ? null : g.mint(acct, memberId), pass: gamePassMint(acct.email, slug) }; +} + +const SHARE_HOSTS = String(process.env.SHARE_HOSTS || 'ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); +const server = http.createServer(async (req, res) => { + { const t0 = Date.now(); res.on('finish', () => { const ms = Date.now() - t0; if (ms > 3000) console.warn('slow request', req.method, String(req.url || '').split('?')[0].slice(0, 80), ms + 'ms', res.statusCode); }); } // visibility for member-felt delays (2026-10-12) + try { + const u = new URL(req.url, 'http://x'); + const p = u.pathname; + // share-link domains (ctbgo.com, mylinehq.com): / goes to that member's join page, anything else to the same path + // here. 302 (not 301) so links never get pinned in caches; the query (?v= angle, ?promo=) rides along. + { const sh = String(req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, ''); + if (SHARE_HOSTS.includes(sh)) { + const ref = /^\/([A-Za-z0-9_]{1,40})\/?$/.exec(p); + const to = 'https://instantadpay.com' + (p === '/' ? '/' : ref ? '/join/' + ref[1] : p) + (u.search || ''); + res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end(); + } } + + // -- traffic log: public page views by referring domain (admin > Traffic) + if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']); + // -- viral links (Marty, 2026-09-21): ANY public page + ?ref= is that member's + // referral link. Same 30-day last-touch sponsor cookie as /join, the view counts under the + // "page" hook in link stats. Served IN PLACE, not redirected (2026-09-21): Facebook's crawler follows + // redirects and canonicalizes a share to og:url, so the redirect (and a clean og:url) dropped the member's + // name from every share. og:url now carries the ref; rel=canonical stays clean for search engines. + // /join, /from and the APIs keep their own meaning of ?ref. + if ((req.method === 'GET' || req.method === 'HEAD') && u.searchParams.has('ref') && !p.startsWith('/api/') && !p.startsWith('/admin') && !/^\/(join|from)\//.test(p) && !/\.[a-z0-9]{2,5}$/i.test(p)) { + const raw = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); + const tok = JOIN_ALIASES[raw] || raw; + u.searchParams.delete('ref'); + const clean = p + (u.searchParams.toString() ? '?' + u.searchParams.toString() : ''); + let known = false; + if (/^[a-z0-9_]{1,20}$/.test(tok)) { try { known = !!((await accounts.byCode(tok)) || (await accounts.byUsername(tok)) || (/^\d+$/.test(tok) && (await accounts.byMemberId(Number(tok))))); } catch (e) {} } + const set = []; + if (known) { + req.viralTok = tok; // later routes (bare /join) can use the sponsor even before the cookie round-trips + const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; + set.push('iap.sponsor=' + tok + cookieTail); // last touch wins, exactly like /join + set.push('iap.angle=page' + cookieTail); // the join shows under the "any page" hook + if (!parseCookies(req)['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source + if (req.method === 'GET') coach.recordView(tok, 'page', req.headers.referer); + } + if (known) { + const wh = res.writeHead.bind(res); let html = false; + res.writeHead = function (code, headers) { + headers = Object.assign({}, headers || {}); + if (set.length) headers['Set-Cookie'] = [].concat(headers['Set-Cookie'] || [], set); + html = /text\/html/i.test(String(headers['Content-Type'] || '')); if (html) delete headers['Content-Length']; + return wh(code, headers); + }; + const end = res.end.bind(res); + res.end = function (chunk, enc, cb) { + if (html && chunk) { + let s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk); + s = s.replace(/( a + url + (url.includes('?') ? '&' : '?') + 'ref=' + encodeURIComponent(tok) + c); + return end(s, 'utf8', cb); + } + return end(chunk, enc, cb); + }; + } + req.url = clean; // the routes below see the clean path; u already has the ref removed + } + // -- join links: /join/ — LAST-touch cookie (Marty, + // 2026-09-10): the link a visitor opened most recently is the sponsor shown + // and used, and it locks the moment the account is created (accounts.ensure + // never changes an existing account's sponsor; the contract binds the buyer at + // their first purchase). Codes resolve LATE (at buy time) to whatever chain id + // the referrer has by then, so free members refer from day one. + // Bare /join (Diann 2026-10-11: the games page's "Join free" and the Friday/Wednesday pages linked to /join and got + // "Not found"): send the visitor to the sponsored join page. ?ref= has already been folded into the iap.sponsor cookie by + // the viral-link handler above, so the cookie decides; nobody known -> the company position, like the partner kit. + if ((p === '/join' || p === '/join/') && (req.method === 'GET' || req.method === 'HEAD')) { + const clean = s => String(s || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); + const refQ = clean(u.searchParams.get('ref') || req.viralTok); const spon = (refQ && (JOIN_ALIASES[refQ] || refQ)) || clean(parseCookies(req)['iap.sponsor']); // ?ref= wins, then the cookie + u.searchParams.delete('ref'); const qs = u.searchParams.toString(); + res.writeHead(302, baseHeaders({ Location: '/join/' + (spon || 'company') + (qs ? '?' + qs : ''), 'Cache-Control': 'no-store' })); return res.end(); + } + let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'HEAD')) { + // lead-capture page: email first, wallet later. ?v= picks the hook + // copy and is remembered so the account records which angle converted. + // partner placement: instantadpay.com/join/company (or /top) places the visitor directly under + // member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit) + const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase(); + const cookies = parseCookies(req); + const angle = String(u.searchParams.get('v') || '').toLowerCase(); + const ang = JOIN_ANGLES[angle] || null; + if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source + const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit + const set = []; + set.push('iap.sponsor=' + tok + cookieTail); // last touch wins + if (u.searchParams.get('from') === 'polhunter') set.push('iap.return=polhunter' + cookieTail); // came through a PolHunter share link: send them back after the wallet step + if (u.searchParams.get('from') === 'driprunner') set.push('iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=7200' + (IS_PROD ? '; Secure' : '')); // a Drip Runner share link: back into the game once they have a username + const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup + if (promo) { const pref = String(req.headers.referer || '').replace(/^https?:\/\//, '').split('/')[0].toLowerCase().slice(0, 80); if (pref) set.push('iap.promoref=' + encodeURIComponent(pref) + cookieTail); } // which partner page it came from + if (ang) set.push('iap.angle=' + angle + cookieTail); + // First-touch source. A PolHunter share link carries ?from=polhunter in the URL itself, which + // survives the referrer being stripped (in-app browsers, a link pasted into chat). PolHunter + // pays a referral bounty only for people it actually sent, so that proof has to be reliable + // rather than dependent on a header (Marty, 2026-09-24: "not just members that come on board + // IAP and work their way over to POL Hunter"). + if (!cookies['iap.ref']) { + const host = u.searchParams.get('from') === 'polhunter' ? 'polhunter.com' : u.searchParams.get('from') === 'driprunner' ? 'driprunner.saasy.top' : coach.refHost(req.headers.referer); + set.push('iap.ref=' + encodeURIComponent(host) + cookieTail); + } + return serveJoinPage(res, tok, ang ? angle : '', ang, set); + } + // -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page + // with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding + // tank for adoption), the angle remembered so the welcome-back grant fires at signup, and + // a forced first-touch source so link stats / admin can see the legacy arrivals. + m = /^\/from\/(faucetwave|tieroneads|socialpix)$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'HEAD')) { + const brand = m[1]; + // SocialPix arrivals came to POST ads, so their default copy is the advertiser one (?seg=earn flips it); + // the closed EvolutionScript brands default to the earner copy (?seg=advertiser flips it). + const seg = String(u.searchParams.get('seg') || '').toLowerCase(); + const prefix = { faucetwave: 'fw', tieroneads: 't1', socialpix: 'sp' }[brand]; + const key = prefix + (brand === 'socialpix' ? (seg.startsWith('earn') ? '-earn' : '-adv') : (seg.startsWith('adv') ? '-adv' : '-earn')); + const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; + const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page + const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail]; + return serveJoinPage(res, '', key, JOIN_ANGLES[key], set); + } + if (p === '/unsubscribe' && (req.method === 'GET' || req.method === 'POST')) { // POST = RFC 8058 one-click from the mail client + const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t')); + const msg = r.error ? r.error : 'Done. You will not get any more emails from InstantAdPay, apart from sign-in codes you ask for and receipts for payments to or from your account. Your account is unchanged.'; + res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); + return res.end('InstantAdPay
      InstantAdPay

      ' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

      ' + msg + '

      Member area

      '); + } + + // -- public API + if (p === '/api/friday' && req.method === 'GET') return json(res, 200, friday.view(), { 'Cache-Control': 'public, max-age=60' }); + // member welcome offer from the games: public numbers for the game cards, the member's own view, and the 'came from' mark + if (p === '/api/starter/public' && req.method === 'GET') return json(res, 200, starter.publicView(), { 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); + if (p === '/api/starter' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (req.method === 'POST') { const b = await readBody(req); starter.setFrom(s.email, String(b.game || '')); } + const acct = await accounts.byEmail(s.email); + return json(res, 200, await starter.view(s.email, Number((acct && acct.memberId) || s.memberId || 0))); + } + if (p === '/api/wednesday' && req.method === 'GET') return json(res, 200, wednesday.view(), { 'Cache-Control': 'public, max-age=60' }); + if (p === '/api/admin/pdsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, pdsync.status()); } + if (p === '/api/admin/pdsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await pdsync.sync()); } + if (p === '/api/admin/wednesday-previews' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, wednesday.previews()); } + if (p === '/api/admin/wednesday/kick' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = await wednesday.kickNow(); return json(res, r.error ? 400 : 200, r); } + // -- the pages a member can turn into a viral link (promo tools > Viral links) + if (p === '/api/pages' && req.method === 'GET') { + const pages = [{ path: '/', title: 'Home page' }, { path: '/blog', title: 'Blog' }, { path: '/earning', title: 'How earning works' }, { path: '/games', title: 'Games that pay POL' }, { path: '/ledger', title: 'Live ledger' }, { path: '/leaderboard', title: 'Leaderboard' }, { path: '/contract', title: 'The contract' }, { path: '/plays', title: 'Team-building plays' }, { path: '/wallets', title: 'Wallet guide' }, { path: '/friday', title: 'Five Dollar Friday' }, { path: '/whats-new', title: "What's new" }, { path: '/shorts', title: 'Shorts' }, { path: '/presentation', title: 'The presentation (narrated video)' }]; + try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {} + return json(res, 200, { pages }); + } + if (p === '/api/config' && req.method === 'GET') { + const c = chain.getConfig(); + // public copy of the site settings: never anything that looks like a credential + const pubSite = {}; + for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies) + return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId, + chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0], + emailAuth: mailer.hasKey() || !IS_PROD }, pubSite)); + } + if (p === '/api/moonpay-url' && req.method === 'GET') { + // Card on-ramp deep link. With MoonPay keys set — PUBLIC key via + // MOONPAY_PUBLIC_KEY env or site config, SECRET key via MOONPAY_SECRET_KEY + // env ONLY (never site config, since /api/config exposes siteConfig) — + // returns a SIGNED checkout URL prefilled with the buyer's own wallet and + // a POL amount; otherwise a generic MoonPay buy page. Zero custody either + // way: MoonPay is merchant of record and the crypto goes straight to the + // buyer's wallet — this site never touches or holds anyone's money. + const addr = (u.searchParams.get('address') || '').trim(); + let pol = Math.round(Number(u.searchParams.get('pol')) || 0); + if (!pol || pol < 30) pol = 30; + if (pol > 100000) pol = 100000; + const pk = (process.env.MOONPAY_PUBLIC_KEY || siteConfig().moonpayPublicKey || '').trim(); + const sk = (process.env.MOONPAY_SECRET_KEY || '').trim(); + if (pk && sk && /^0x[0-9a-fA-F]{40}$/.test(addr)) { + const qs = '?apiKey=' + encodeURIComponent(pk) + '¤cyCode=pol_polygon&walletAddress=' + encodeURIComponent(addr) + '"eCurrencyAmount=' + pol; + const sig = crypto.createHmac('sha256', sk).update(qs).digest('base64'); + return json(res, 200, { url: 'https://buy.moonpay.com/' + qs + '&signature=' + encodeURIComponent(sig), signed: true, pol }); + } + return json(res, 200, { url: 'https://www.moonpay.com/buy/matic', signed: false, pol }); // MoonPay's Polygon page still lives at the old slug; /buy/pol renders their 404 (same fix as RM Circle) + } + if (p === '/api/catalog' && req.method === 'GET') { + // five live quotes per call: serve a 20-second cache so pages that load the + // ladder (join, home, buy) are not waiting on the RPC every time + // stale-while-revalidate (2026-10-19): serve the cached ladder at once and refresh it in the background after + // 20 s, one refresh at a time; only wait for a fresh read when there is none or it is over 2 minutes old + const age = catalogCache.at ? Date.now() - catalogCache.at : Infinity; + if (age > 20000 && !catalogCache.busy) { + catalogCache.busy = chain.catalog().then(pr => { catalogCache.products = pr; catalogCache.at = Date.now(); }) + .catch(e => console.error('catalog refresh', e.message)).finally(() => { catalogCache.busy = null; }); + } + if (!catalogCache.products || age > 120000) { + try { await catalogCache.busy; } catch (e) {} + if (!catalogCache.products) throw new Error('catalog unavailable'); + } + return json(res, 200, { products: catalogCache.products }); + } + if (p === '/api/feed' && req.method === 'GET') { + return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) }); + } + if (p === '/api/feed/live' && req.method === 'GET') { + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' })); + res.write(': connected\n\n'); + feedClients.add(res); + req.on('close', () => feedClients.delete(res)); + return; + } + m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p); + if (m && req.method === 'GET') { + // tx relay so the browser never talks to the RPC directly (CSP stays 'self'). + // Serves both the wallet's waitTx poll (found/status) and the built-in + // /tx/ viewer (full details + decoded events). + try { + const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]); + if (!r) return json(res, 200, { found: false }); + const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed }; + try { + const t = await chain.rpc('eth_getTransactionByHash', [m[1]]); + if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); } + } catch (e) {} + try { + const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]); + if (blk) out.ts = blk.timestamp; + } catch (e) {} + try { + out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean) + .map(ev => Object.assign(ev, { tx: m[1] }))); + } catch (e) { out.events = []; } + return json(res, 200, out); + } catch (e) { return json(res, 200, { found: false, rpcError: true }); } + } + if (p === '/api/sponsor' && req.method === 'GET') { + // The account's stored sponsor is authoritative — it persists across + // devices, cleared cookies, and return visits. Fall back to the first-touch + // cookie only for anonymous visitors with no account sponsor yet. (Reading + // the cookie alone was orphaning buyers to root when the cookie was absent.) + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; + const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || ''; + const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id; + let sponsorBlocked = null; // set only for transient/unknown failures now: the client refuses the transaction + let sponsorRouted = null; // set when an unactivated sponsor was walked past: the client tells the buyer, then proceeds + if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'notActivated') { + const w = await walkUpActivatedSponsor(tok); + if (w.reason === 'rpc') sponsorBlocked = 'rpc'; + else { + const catchId = Number(siteConfig().defaultSponsorId) || 1; + sponsorId = w.id; + sponsorRouted = { from: spd.name || null, to: w.id ? w.name : 'the company (#' + catchId + ')', toId: w.id || catchId, skipped: w.skipped.map(x => x.name) }; + if (u.searchParams.get('intent') === 'buy') sponsorRoutedAlert(acct.email, spd, sponsorRouted, w.skipped); // the dashboard's display-only pre-check never alerts (Marty, 2026-09-21) + } + } else if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; if (u.searchParams.get('intent') === 'buy') sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); } + if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; } + // orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands + // the new member under the configured catch position (#1) instead of root + if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1; + let name = null, avatarUrl = null, own = false; + // the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own + // sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13) + let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase(); + if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok]; + const nameTok = showTok || tok; + if (nameTok) { + const t = nameTok.toLowerCase(); + let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); + if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok)); + if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} } + } + // "You're joining the line of X" must only greet someone who is actually about to + // join. The last-touch sponsor cookie lives 30 days, so an EXISTING member who once + // clicked a teammate's link was being told on the sign-in page that logging in would + // place them under that person (Marty, 2026-09-17). Alarming, and untrue: their + // sponsor locked at their first purchase and nothing here can move it. + // Show it when they just arrived through a link (?ref= in the URL), or when the cookie + // is there AND this browser has never had an account. Attribution itself is untouched. + let invited = !!showTok; + if (!invited && tok) { try { invited = !(await fraud.hasAccountOnDevice(req)); } catch (e) { invited = true; } } + if (acct) invited = false; // already a member: they are not joining anybody's line + return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited, name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand }); + } + if (p === '/api/stats' && req.method === 'GET') { + let members = 0; try { members = await chain.memberCount(); } catch (e) {} + return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count() }, chain.totals())); + } + + // -- 24/7 assistant + if (p === '/api/chat' && req.method === 'POST') { + const ip = req.socket.remoteAddress || 'x'; + if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' }); + const b = await readBody(req); + const r = await chatbot.answer(b.message, b.history); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // qa/chatbot-sync.mjs: the newest knowledge-base change (Central day) and the entry count + return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' }); + } + + // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off + if (p === '/api/inbound/email' && req.method === 'POST') { // SendGrid Inbound Parse: secret key in the URL, always 200 once it matches + const k = inbound.key(); + if (!k || u.searchParams.get('k') !== k) { req.resume(); return json(res, 403, { error: 'forbidden' }); } + const chunks = []; let n = 0, tooBig = false; + await new Promise(done => { req.on('data', c => { n += c.length; if (n > 12e6) tooBig = true; else chunks.push(c); }); req.on('end', done); req.on('error', done); }); + if (tooBig) { console.log('inbound email: too big, dropped'); return json(res, 200, { ok: true }); } + try { console.log('inbound email:', await inbound.handle(Buffer.concat(chunks), req.headers['content-type'])); } catch (e) { console.error('inbound email', e.message); } + return json(res, 200, { ok: true }); + } + if (p === '/api/telegram/support' && req.method === 'POST') { // the support bot's webhook: secret header checked inside, always 200 + let b = {}; try { b = await readBody(req); } catch (e) {} + try { await supportbot.handle(req, b); } catch (e) { console.error('supportbot', e.message); } + return json(res, 200, { ok: true }); + } + if (p === '/api/support' && req.method === 'POST') { + const b = await readBody(req); + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; // signed in: the ticket is theirs, whatever was typed + const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' }); + if (!acct) { const iss = await newEmailIssue(email); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } // replies must reach them + const guard = supportGuard(req, b, email); + if (guard) return json(res, guard.status, guard.body); + const r = await tickets.create({ source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body }); + if (r.error) return json(res, 400, r); + return json(res, 200, { ok: true, ref: r.ticket.ref, token: r.token, member: !!acct }); + } + m = /^\/api\/support\/t\/([A-Za-z0-9_.-]{20,80})(\/reply)?$/.exec(p); + if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { + const t = await tickets.byToken(m[1]); + if (!t) return json(res, 404, { error: 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' }); + if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); + const b = await readBody(req); + if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); + const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: 'link' }); + return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); + } + if (p === '/api/support/chatbot' && req.method === 'POST') { + const b = await readBody(req); + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; + const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true }); + if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your dashboard to add to one.' }); } + else { const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); } + const tr = Array.isArray(b.transcript) ? b.transcript : []; + const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6); + const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim()); + const note = String(b.note || '').trim().slice(0, 2000); + const body = (note ? note + '\n\n' : '') + (turns.length ? 'From the chat assistant:\n' + turns.join('\n') : '(sent from the chat assistant)'); + const r = await tickets.create({ source: 'chatbot', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, category: 'Other', + subject: 'Chat: ' + (firstQ ? String(firstQ.text).replace(/\s+/g, ' ').trim().slice(0, 100) : 'question for support'), body }); + if (r.error) return json(res, 400, r); + return json(res, 200, { ok: true, ref: r.ticket.ref, member: !!acct, link: acct ? '/my#help?t=' + r.ticket.ref : '/support/t/' + r.token }); + } + + // -- accounts: email + password is the normal join path (wallet comes + // out only at purchase / payout-activation time and gets linked then) + if (p === '/api/signup' && req.method === 'POST') { + const b = await readBody(req); + if (fraud.isBlocked(b.email)) return json(res, 403, { error: 'This address cannot open an account.' }); + { const iss = await newEmailIssue(String(b.email || '').trim().toLowerCase()); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } + const pendS = pendingSponsor.get(String(b.email || '').trim().toLowerCase()); + const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pendS && pendS.ref) || ''; // last-touch attribution, locked at account creation + const r = await accounts.signup(b.email, b.password, ref); + if (r.error) return json(res, 400, r); + pendingSponsor.del(String(b.email || '').trim().toLowerCase()); + // sponsor is notified once the new member picks a username (onboarding), + // so the email can name them — see /api/my/profile + if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent + const token = await auth.mintSession({ email: r.account.email }); + return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); + } + if (p === '/api/login' && req.method === 'POST') { + const b = await readBody(req); + const r = await accounts.login(b.email, b.password); + if (r.error) return json(res, 400, r); + let memberId = 0; + if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} } + const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); + return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); + } + + // -- passwordless: email code sign-in (signup and login are the same act) + if (p === '/api/auth/email/start' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + const devHdr = fraud.deviceOf(req) ? undefined : { 'Set-Cookie': fraud.deviceCookie(fraud.newDeviceId(), IS_PROD) }; // browser id for one-account-per-person checks + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }); + if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }); + { const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }); } + const prev = emailCodes.get(e); + if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, devHdr); } + const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited + if (guard) return json(res, guard.status, guard.body, devHdr); + const code = String(Math.floor(100000 + Math.random() * 900000)); + emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); + { const ck = parseCookies(req); const bound = pageTok(b.ref) || ck['iap.sponsor'] || ''; + if (bound && !(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: bound, via: pageTok(b.ref) ? (String(b.angle || '').toLowerCase().slice(0, 20) || ck['iap.angle'] || 'page') : (ck['iap.angle'] || ''), joinedRef: decodeURIComponent(ck['iap.ref'] || '') || null }); } + if (mailer.hasKey()) { + try { await mailer.sendCode(e, code); } catch (err) { + console.error('sendCode failed', err.message); + return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, devHdr); + } + return json(res, 200, { ok: true, sent: true }, devHdr); + } + if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, devHdr); + return json(res, 503, { error: 'Email sign-in is not configured yet.' }); + } + if (p === '/api/auth/email/verify' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + const rec = emailCodes.get(e); + if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); + rec.tries += 1; + if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } + if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); + emailCodes.delete(e); + const pend = pendingSponsor.get(e); + const ref = pageTok(b.ref) || parseCookies(req)['iap.sponsor'] || (pend && pend.ref) || ''; + const via = parseCookies(req)['iap.angle'] || (pend && pend.via) || ''; + const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || (pend && pend.joinedRef) || null; + if (ref && !parseCookies(req)['iap.sponsor']) console.log('sponsor recovered without cookie', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'ref', ref, pageTok(b.ref) ? '(page token)' : '(remembered from the code request)'); + if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }); + let fraudFlags = []; + const existing = await accounts.byEmail(e); + const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up + if (!existing || claim) { // anti-fraud checks apply to NEW accounts only (Marty, 2026-09-16: one account per person) + let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(String(ref).toLowerCase()); if (!spAcct) spAcct = await accounts.byUsername(String(ref).toLowerCase()); } catch (err) {} } + const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); + fraudFlags = fc.flags; + // an approved exception is worth a log line: it is the difference between "the guard + // is broken" and "Marty said yes to this person" + if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy); + if (fc.block) { console.log('signup blocked', fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }); } + } + const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged + if (r.error) return json(res, 400, r); + if (r.created) pendingSponsor.del(e); + if (claim) await claimShell(e, existing, ref); + if (r.created || claim) { fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } + else fraud.recordSeen(e, req).catch(() => {}); + // the lead is in the door: queue the getting-started sequence (opt-in box is pre-checked on both forms) + if (r.created && (b.followups || b.newsletter)) drip.enqueue(e, ref, via).catch(() => {}); + // a wallet-only session (signed with a wallet, no account) finishing setup: + // adopt that wallet into the email account so member #, purchases and + // payouts stay attached, then retire the wallet-only session + const prior = await auth.fromRequest(req); + if (prior && prior.address && !prior.email) { + const lr = await accounts.linkWallet(e, prior.address); + if (lr.error) return json(res, 400, lr); + r.account = lr.account || await accounts.byEmail(e); + await auth.logout(req); + } + if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile) + // partner promo code carried on the join link: redeem once per account (ignored if invalid/used) + try { + const pc = parseCookies(req)['iap.promo']; + if (pc) { + const pref = parseCookies(req)['iap.promoref'] ? decodeURIComponent(parseCookies(req)['iap.promoref']) : ''; + const g = await promos.redeem(pc, e, 'link', pref); + if (g.ok) { const paid = await payPromo(e, todayCT()); console.log('promo redeemed', g.code, 'day 1:', paid.map(x => x.amount).join('+') || 0, 'of', g.credits, e, pref ? 'from ' + pref : ''); } + } + } catch (err) { console.error('promo redeem', err.message); } + // legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once + if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) { + try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits, { log: { kind: 'grant', note: 'Welcome-back credits (' + g.brand + ')' } }); console.log('legacy grant', g.brand, g.seg, g.credits, e); } } + catch (err) { console.error('legacy grant', err.message); } + } + if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only + let memberId = 0; + if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} } + const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); + return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30) + } + + // -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies. + if (p.startsWith('/api/game/auth/') && req.method === 'OPTIONS') { res.writeHead(204, gameCors(req)); return res.end(); } + // the login ad inside a game's sign-in kit, after a fresh sign-in (2026-10-18). CORS only for the GAME_AUTH + // origins of the named game (dev mode: localhost); the dashboard route stays same-origin. + if (p === '/api/game/ads/login' && (req.method === 'GET' || req.method === 'OPTIONS')) { + const g = gameOf(req, u.searchParams.get('game')); + const cors = g ? Object.assign(gameCors(req), { 'Access-Control-Allow-Methods': 'GET, OPTIONS' }) : { Vary: 'Origin' }; + if (req.method === 'OPTIONS') { res.writeHead(204, cors); return res.end(); } + if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); + const ad = await loginAdFor(req, String(u.searchParams.get('game'))); + if (ad && g.frames === false) ad.frameable = false; + return json(res, 200, { ad }, cors); + } + if (p === '/api/game/auth/start' && req.method === 'POST') { + const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); + if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); + req.gameDev = gameDevOf(b); + const e = String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }, cors); + if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }, cors); + { const iss = await newEmailIssue(e); if (iss) return json(res, 400, { error: iss.error, suggestion: iss.suggestion }, cors); } + const prev = emailCodes.get(e); + if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, cors); + const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited + if (guard) return json(res, guard.status, guard.body, cors); + const code = String(Math.floor(100000 + Math.random() * 900000)); + emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); + const ref = pageTok(b.ref); + const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); // paid-traffic source the game saw (2026-10-03) + if (!(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: ref || '', via: String(b.game), joinedRef: g.host() + (srcTag ? '/' + srcTag : '') }); + console.log('game-signin code', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'ref ' + ref : ''); + if (mailer.hasKey()) { + try { await mailer.sendCode(e, code); } catch (err) { console.error('sendCode failed', err.message); return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, cors); } + return json(res, 200, { ok: true, sent: true }, cors); + } + if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, cors); + return json(res, 503, { error: 'Email sign-in is not configured yet.' }, cors); + } + if (p === '/api/game/auth/verify' && req.method === 'POST') { + const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); + if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); + req.gameDev = gameDevOf(b); + const e = String(b.email || '').trim().toLowerCase(); + const rec = emailCodes.get(e); + if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }, cors); + rec.tries += 1; + if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); } + if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors); + emailCodes.delete(e); + if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors); + const pend = pendingSponsor.get(e); + const ref = pageTok(b.ref) || (pend && pend.ref) || ''; + const via = String(b.game); const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); + const joinedRef = (pend && pend.joinedRef) || (g.host() + (srcTag ? '/' + srcTag : '')); // e.g. driprunner.app/adsterra + let fraudFlags = []; + const existing = await accounts.byEmail(e); + const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up + if (!existing || claim) { // one account per person, exactly as on the dashboard + let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} } + const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); + fraudFlags = fc.flags; + if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy); + if (fc.block) { console.log('signup blocked (game)', b.game, fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }, cors); } + } + const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged + if (r.error) return json(res, 400, r, cors); + if (claim) { await claimShell(e, existing, ref); fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } + if (r.created) { + pendingSponsor.del(e); + fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); + if (b.newsletter) { drip.enqueue(e, ref, via).catch(() => {}); sendy.subscribe(e, '').catch(() => {}); } + sendWelcome(e, ref).catch(() => {}); + console.log('game-signin new account', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'sponsor ' + ref : 'no sponsor'); + } else fraud.recordSeen(e, req).catch(() => {}); + const acct = r.account || await accounts.byEmail(e); + return json(res, 200, Object.assign(await gameAnswer(g, b.game, acct), { created: !!r.created }), cors); + } + if (p === '/api/game/auth/username' && req.method === 'POST') { + const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); + if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); + const pass = gamePassOpen(b.pass); if (!pass) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors); + const before = await accounts.byEmail(pass.e); if (!before) return json(res, 404, { error: 'Account not found.' }, cors); + if (!before.username) { + const r = await accounts.setUsername(pass.e, b.username); + if (r.error) return json(res, 400, r, cors); + const acct = await accounts.byEmail(pass.e); // first username: the sponsor hears now, as from the dashboard + notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); + if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); + } + return json(res, 200, await gameAnswer(g, b.game, await accounts.byEmail(pass.e)), cors); + } + // remembered sign-in (2026-10-19): the kit's 29-day pass for this game becomes a fresh hand-off token, no code + if (p === '/api/game/auth/resume' && req.method === 'POST') { + const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game); + if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors); + const pass = gamePassOpen(b.pass); + if (!pass || (pass.g && pass.g !== b.game)) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors); + if (fraud.isSuspended(pass.e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors); + const acct = await accounts.byEmail(pass.e); if (!acct) return json(res, 404, { error: 'Account not found. Start again with your email.' }, cors); + return json(res, 200, await gameAnswer(g, b.game, acct), cors); + } + // the game's nudges ("Add your wallet", "Level up") post the pass here in a new tab: signed in on arrival + if (p === '/api/game/enter' && req.method === 'POST') { + let f; try { f = new URLSearchParams((await readRaw(req, 4096)).toString('utf8')); } catch (e) { f = new URLSearchParams(); } + const pass = gamePassOpen(f.get('p')); + const to = ['overview', 'wallet', 'buy', 'earn', 'promo', 'games', 'profile', 'campaigns'].includes(f.get('to')) ? f.get('to') : 'overview'; + if (!pass || fraud.isSuspended(pass.e)) { res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store' }); return res.end(); } + const acct = await accounts.byEmail(pass.e); if (!acct) { res.writeHead(303, { Location: '/my', 'Cache-Control': 'no-store' }); return res.end(); } + let memberId = acct.memberId || 0; + if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } + const token = await auth.mintSession({ email: acct.email, address: acct.address, memberId }); + res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store', 'Set-Cookie': auth.sessionCookie(token) }); return res.end(); + } + + // -- wallet auth: link-to-account when an email session exists, or + // wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session + // is walked to the email card, which adopts the wallet on verify) + if (p === '/api/auth/challenge' && req.method === 'POST') { + const b = await readBody(req); + const r = auth.makeChallenge(b.address); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/auth/verify' && req.method === 'POST') { + const b = await readBody(req); + const r = await auth.verifyChallenge(b.address, b.signature); + if (r.error) return json(res, 400, r); + let memberId = 0; + try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {} + const s = await auth.fromRequest(req); + if (s && s.email && b.asPosition) { + // Qualified Start: a second (third…) wallet on the same account. It becomes + // its own on-chain member under this member's id when it buys; the session + // stays on the main wallet. + // policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a + // wallet that is already registered on-chain under anything other than this account's main + // member is refused (a position-under-position chain would recapture 70% of a self-buy) + const MAX_POS = 5; + const have = await accounts.positions(s.email); + if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS) + return json(res, 400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' }); + if (memberId) { + const mainId = await auth.refreshMemberId(s); + let mm = null; try { mm = await chain.member(memberId); } catch (e) {} + if (mm && mainId && mm.sponsorId !== mainId) + return json(res, 400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' }); + } + const pr = await accounts.addPosition(s.email, r.address); + if (pr.error) return json(res, 400, pr); + if (memberId) await accounts.setPositionMember(r.address, memberId); + return json(res, 200, { ok: true, position: true, address: r.address, memberId }); + } + if (s && s.email) { + const lr = await accounts.linkWallet(s.email, r.address); + if (lr.error) return json(res, 400, lr); + await auth.updateSession(s.token, { address: r.address, memberId }); + return json(res, 200, { ok: true, linked: true, address: r.address, memberId, next: parseCookies(req)['iap.return'] === 'polhunter' ? '/api/my/polhunter' : null }); + } + const acct = await accounts.byAddress(r.address); + if (!acct && await accounts.positionOwner(r.address)) + return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' }); + const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId }); + return json(res, 200, { ok: true, address: r.address, memberId }, + { 'Set-Cookie': auth.sessionCookie(token) }); + } + if (p === '/api/auth/logout' && req.method === 'POST') { + await auth.logout(req); + return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() }); + } + if (p === '/api/gas' && req.method === 'GET') { + try { return json(res, 200, await chain.suggestedFees()); } + catch (e) { return json(res, 200, {}); } + } + + if (p === '/api/me' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 200, { signedIn: false }); + const memberId = await auth.refreshMemberId(s); + const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; + const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id; + let sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null; + let sponsorRouted = null; + if (sponsorBlocked === 'notActivated') { // never hold a buyer for an unactivated sponsor: walk up the line + const w = await walkUpActivatedSponsor(acct.sponsorRef); + if (w.reason === 'rpc') sponsorBlocked = 'rpc'; + else { sponsorBlocked = null; sponsorId = w.id; sponsorRouted = { from: spdMe.name || null, to: w.id ? w.name : 'the company', toId: w.id || (Number(siteConfig().defaultSponsorId) || 1) }; } + } + if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0; + const _defSpon = Number(siteConfig().defaultSponsorId) || 1; + if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) + if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); + const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null, + address: s.address || (acct && acct.address) || null, memberId, + username: (acct && acct.username) || null, + refCode: (acct && acct.code) || null, sponsorId, + // profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned) + avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null, + socials: (acct && acct.socials) || null, + wallOffers: parseWallOffers(acct), + lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null }; + if (memberId) { + try { + const mm = await chain.member(memberId); + out.buyerCount = mm.buyerCount; + out.onchainSponsorId = mm.sponsorId; + const bal = await ads.balances((await myMemberIds(s)).ids, s.email); + out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; + } catch (e) { out.chainReadError = true; } + } + return json(res, 200, out); + } + + if (p === '/api/my/dashboard' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; + if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); + let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12) + try { + if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() }; + const tw = tankWaitCache.list; + tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok }; + } catch (e) {} + const sc0 = siteConfig(); + const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null, + pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' }, + address: s.address || (acct && acct.address) || null, + username: (acct && acct.username) || null, + refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0, + earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 }; + if (out.email) { + // welcome credits unlock via the welcome tour when an upline with a + // line banner exists; members with no tour to walk get them instantly + const welcomed = await ads.welcomeGranted(out.email); + const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl); + if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add + else { out.welcomeCredits = 0; out.gauntletPending = true; } + } + if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too + if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor + accounts.touchSeen(out.email).catch(() => {}); + out.chatUnread = await messages.chatUnread(out.email); + out.chatAvailable = (acct && acct.chatAvailable !== false); + const spon = await accounts.sponsorOf(out.email); + if (spon && spon.email) out.sponsor = { + email: spon.email, + name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'), + online: (Date.now() - (spon.lastSeen || 0)) < 60000, + available: spon.chatAvailable !== false }; + } + if (out.email) { // the one modal that interrupts: a human broadcast, or a money-at-stake alert + const un = await messages.newestUnread(out.email); + if (un) { + const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {}; + out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body, kind: un.kind || 'broadcast', + fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') }; + } + } + if (memberId) { + try { + const mm = await chain.member(memberId); + out.buyerCount = mm.buyerCount; + const mine = await myMemberIds(s); + // linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14) + out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0; + for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} } + out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone + const bal = await ads.balances(mine.ids, s.email); + out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.earnedReserved = bal.earnedReserved; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; + } catch (e) { out.chainReadError = true; } + let earned = 0n, n = 0; + for (const ev of chain.recentEvents(1e9)) { // whole history, not the last 600 + if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) { + earned += BigInt(ev.amountWei); n += 1; + } + } + out.earnedWei = earned.toString(); + out.earnCount = n; + } + // achievement milestones (same ladder as the Overview stepper) + one-time credit + // bonuses — computed AFTER buyerCount is read from chain above (else always 0) + { + const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0); + const reached = []; + if (out.memberId) reached.push('payouts'); + if (bc >= 1) reached.push('firstBuyer'); + if (bc >= 2) reached.push('level2'); + if (bc >= 5) reached.push('level3'); + try { if (out.memberId && friday.earnedBadge(out.memberId)) reached.push('fridays'); } catch (e) {} // five Five Dollar Fridays in a row + try { if (out.email && gamepass.flag(out.email).until) reached.push('gamepass'); } catch (e) {} // ever held a Game Pass (2026-10-22) + try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned + out.milestonesReached = reached; + if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached); + } + // who joined through this member: their invite link uses username when set, + // else code, and the numeric id once on-chain — match all three + const refs = []; + if (acct && acct.code) refs.push(acct.code); + if (acct && acct.username) refs.push(acct.username); + if (memberId) refs.push(String(memberId)); + const joined = await accounts.listByReferrer(refs); + const rTot = await ads.earnedTotals(joined.map(r => r.email)); // surf earnings per referral (Marty, 2026-09-29) + out.referrals = joined.map(r => ({ + name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask + joined: r.created, + lastSeen: r.lastSeen || 0, + wallet: !!r.address, activated: !!r.memberId, + earned: (rTot[r.email] || {}).earned || 0, balance: (rTot[r.email] || {}).balance || 0, + status: r.memberId ? 'payouts on' : r.address ? 'wallet linked' : 'joined free' + })); + out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link + out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own + return json(res, 200, out); + } + // -- linked positions (Qualified Start): list, refresh from chain, unlink + if (p === '/api/my/positions' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const acct = await accounts.byEmail(s.email); + const mainId = await auth.refreshMemberId(s); + const list = await accounts.positions(s.email); + const out = []; + const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean); + let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {} + // every position's chain reads run side by side (2026-10-19: one after another took 3-8 s for members with several) + out.push(...await Promise.all(list.map(async pos => { + let id = pos.memberId; + if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} } + const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created }; + if (id) { + const [mm, blocked] = await Promise.all([chain.member(id).catch(() => null), payoutChainBlocked(id, 3).catch(() => false)]); + if (mm) { row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; } + row.credits = balPer[id] != null ? balPer[id] : 0; + row.noPayout = blocked; // linkage only: a buy from here would pay a listed wallet + } + return row; + }))); + const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 }; + if (mainId) { + main.credits = balPer[mainId] != null ? balPer[mainId] : 0; + try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {} + main.noPayout = await payoutChainBlocked(mainId, 3); + } + // live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog + const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } }; + if (main.address) main.balanceWei = await bal(main.address); + for (const row of out) row.balanceWei = await bal(row.address); + let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} + return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited }); + } + if (p === '/api/my/positions/remove' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await accounts.removePosition(s.email, b.address); + return json(res, r.error ? 400 : 200, r); + } + // -- coaching: every direct's ladder rung, stalled flag, and what to say + // -- holding tank: waiting members, my adoptions, adopt, release (pay it forward) + // -- promo code typed on the dashboard + if (p === '/api/my/promo/redeem' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const g = await promos.redeem(b.code, s.email, 'dashboard', ''); + if (g.error) return json(res, 400, g); + const paid = await payPromo(s.email, todayCT()); + return json(res, 200, { ok: true, credits: g.credits, now: paid.reduce((n, x) => n + x.amount, 0), step: g.step, steps: g.steps, code: g.code, partner: g.partner }); + } + // -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet; + // PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13) + if (p === '/api/admin/member' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const q = u.searchParams.get('q') || u.searchParams.get('email') || ''; + const a = await adminMember.resolve(q); + if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' }); + return json(res, 200, Object.assign(await adminMember.view(a.email), { pwPasses: pwPasses.get(String(a.email).toLowerCase()) || null })); // mint passes on the card (2026-10-10) + } + if (p === '/api/admin/member' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); + if (!acct) return json(res, 404, { error: 'No such member.' }); + if (b.username !== undefined) { + const un = String(b.username || '').trim().toLowerCase(); + if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' }); + const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r); + console.log('admin username', e, un); + } + if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to LinkSpin until bound + if (b.address !== undefined) { + const a = String(b.address || '').trim().toLowerCase(); + if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' }); + const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r); + let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} } + await accounts.setMemberId(e, mid); + if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {}); + console.log('admin wallet swap', e, a || '(none)', 'member', mid); + } + if (b.grantCredits !== undefined) { + const n = Math.round(Number(b.grantCredits)); + if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' }); + // The member sees this note in their Credit activity, so let the reason travel with + // the grant. A correction that reads "granted by admin" explains nothing; one that + // names itself is the difference between a refund and a mystery (Marty, 2026-09-17). + const why = String(b.note || '').trim().slice(0, 120) || 'Credits granted by admin'; + // purchased: true returns PURCHASED credits (a refund of money the member paid) at purchase grade, so they keep their + // money value; without it the grant is ordinary earned credits (2026-10-04, the Shift AI refunds) + if (b.purchased === true) await ads.addEarned(e, n, { purchased: true, log: { kind: 'credit', note: why } }); + else await ads.addEarned(e, n, { log: { kind: 'grant', note: why } }); + console.log('admin credits', e, n, String(b.note || '').slice(0, 100)); + } + return json(res, 200, await adminMember.view(e)); + } + if (p === '/api/admin/member' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); + if (!acct) return json(res, 404, { error: 'No such member.' }); + if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' }); + const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' }); + const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r); + if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {}); + console.log('admin removed account', e); + return json(res, 200, { ok: true }); + } + // -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14) + if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView()); + // -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance + if (p === '/api/my/toolkit' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.status(s.email)); + } + if (p === '/api/my/toolkit/generate' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const memberId = await auth.refreshMemberId(s); + const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.split(s.email)); + } + if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.videos(s.email)); + } + if (p === '/api/my/toolkit/video' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.makeVideo(s.email, String(b.slug || '')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.team(s.email)); + } + if (p === '/api/my/toolkit/nudge' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const memberId = await auth.refreshMemberId(s); + const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || '')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/grant' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0); + if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() }); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/promo' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/toolkit' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await toolkit.adminUsage()); + } + if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row + const s = await auth.fromRequest(req); + const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; + return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null)); + } + if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const since = updates.lastSentAt(); + return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: updates.countsSnapshot(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status())); + } + if (p === '/api/admin/updates/draft' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) }); + } + if (p === '/api/admin/updates/preview' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' })); + } + if (p === '/api/admin/updates/send' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, image: b.image, imageLink: b.imageLink, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test }); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/releases' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES }); + } + if (p === '/api/admin/releases' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/releases' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || ''))); + } + // -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12) + if (p === '/api/admin/blog' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const slug = u.searchParams.get('slug'); + if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); } + return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) }); + } + if (p === '/api/admin/blog' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const before = b.existingSlug ? await blog.get(b.existingSlug) : null; + const r = await blog.save(b, b.existingSlug || null); + if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) { + // first time this article goes live: push it to X + Instagram (never repeated for the same slug) + syndicate.publish(r.post).catch(e => console.error('syndication', e.message)); + r.syndicating = syndicate.enabled(); + } + r.syndicated = syndicate.statusOf(r.post.slug); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const post = await blog.get(String(b.slug || '')); + if (!post) return json(res, 404, { error: 'No such post.' }); + if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' }); + if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' }); + const st = await syndicate.publish(post, { force: !!b.force }); + return json(res, 200, { ok: true, syndicated: st }); + } + if (p === '/api/admin/blog' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' }); + return json(res, 200, await blog.remove(slug)); + } + // -- admin: promo codes (create/update, switch on/off, redemptions) + if (p === '/api/admin/promos' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await promos.adminView()); + } + if (p === '/api/admin/promos' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await promos.create(b); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/promos' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await promos.setActive(b.code, !!b.active); + return json(res, r.error ? 400 : 200, r); + } + // -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique + if (p === '/api/my/username-suggest' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18); + if (!/[a-z]/.test(base)) base = 'member' + base; + if (base.length < 3) base = (base + 'xyz').slice(0, 3); + let pick = base; + for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i; + return json(res, 200, { suggest: pick }); + } + if (p === '/api/my/tank' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await tank.view(s.email)); + } + // -- achievement badge -> Telegram (payments topic + the main group), once per badge per member. + // The browser composes the personalised image (canvas, same as Share) and posts it here. + if (p === '/api/my/badge-post' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const key = String(u.searchParams.get('key') || ''); + if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); + if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' }); + let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } + if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); + const held = await ads.milestonesOf(s.email); + if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); + const log = badgeLog(); const mine = log[s.email] || {}; + if (mine[key]) return json(res, 200, { ok: true, already: true }); + // manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock + if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' }); + const a = await accounts.byEmail(s.email); + const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member'); + const link = a && a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; + const [label, sub] = BADGE_META[key]; + const caption = '\u{1F3C6} InstantAdPay \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; + // the server draws the card (a phone's canvas can come out blank: cryptomonk, 2026-09-16); the upload is the fallback + try { const srv = await badge.render(key, a && a.username ? a.username : (a && a.memberId ? 'member #' + a.memberId : '')); if (srv) jpeg = srv; } catch (e) {} + const sc = siteConfig(); let sent = 0; + if (sc.telegramBotToken && sc.telegramEchoChatId) { + if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic + if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General) + } + mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} + pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); + console.log('badge posted', s.email, key, 'sent', sent); + return json(res, 200, { ok: true, sent }); + } + // -- member's own share: store the composed badge so a public page can carry it as the preview image + if (p === '/api/my/badge-image' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const key = String(u.searchParams.get('key') || ''); + if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); + let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } + if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); + if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); + const a = await accounts.byEmail(s.email); + if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' }); + try { const srv = await badge.render(key, a.username); if (srv) jpeg = srv; } catch (e) {} + fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg); + return json(res, 200, { ok: true, page: 'https://instantadpay.com/b/' + a.username + '/' + key, image: 'https://instantadpay.com/badge-img/' + a.username + '/' + key + '.jpg' }); + } + if (p === '/api/admin/badge-repost' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); const key = String(b.key || ''); const a = await accounts.byEmail(String(b.email || '').toLowerCase()); + if (!a || !BADGE_META[key]) return json(res, 400, { error: 'Unknown member or badge.' }); + if (!(await ads.milestonesOf(a.email)).includes(key) && !(key === 'gamepass' && gamepass.flag(a.email).until)) return json(res, 400, { error: 'That member has not unlocked that badge.' }); // the Game Pass badge is earned by holding a pass, recorded or not yet + const jpeg = await badge.render(key, a.username || ('member #' + a.memberId)); if (!jpeg) return json(res, 500, { error: 'Render failed.' }); + const who = a.username ? '@' + a.username : 'member #' + a.memberId; const link = a.username ? 'instantadpay.com/join/' + a.username : 'instantadpay.com'; + const [label, sub] = BADGE_META[key]; + const caption = '\u{1F3C6} InstantAdPay \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; + const sc = siteConfig(); let sent = 0; + if (sc.telegramBotToken && sc.telegramEchoChatId) { + if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; + if (String(sc.telegramBadgeGeneral || '1') !== '0' && b.general !== false && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; + } + const log = badgeLog(); const mine = log[a.email] || {}; mine[key] = { ts: Date.now(), sent, repost: true }; log[a.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} + return json(res, 200, { ok: true, sent, bytes: jpeg.length }); + } + if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL }); + } + if (p === '/api/my/tank/adopt' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' }); + const r = await tank.adopt(s.email, b.who, b.note); + if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12) + pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() }); + try { + const sc = siteConfig(); + const clean = t => String(t || '').replace(/[<>&]/g, ''); + if (sc.telegramBotToken && sc.telegramEchoChatId) + telegramSend(sc.telegramEchoChatId, '\u{1F91D} InstantAdPay \u00b7 ' + clean(r.adopterName) + ' picked up ' + clean(r.adopteeName) + ' from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {}); + } catch (e) {} + } + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/tank/release' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.release(s.email, b.email); + if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13) + pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() }); + try { + const sc = siteConfig(); + const clean = t => String(t || '').replace(/[<>&]/g, ''); + if (sc.telegramBotToken && sc.telegramEchoChatId) + telegramSend(sc.telegramEchoChatId, '\u{1FAA3} InstantAdPay \u00b7 ' + clean(r.ownerName) + ' returned ' + clean(r.memberName) + ' to the holding tank', sc.telegramEchoTopicId); + } catch (e) {} + } + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.markContacted(s.email, b.email); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.recordGift(s.email, b.email, b.tx, b.pol); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); } + if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); } + if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); } + if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView() })); } + if (p === '/api/admin/lsinbound' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lsinbound.adminView()); } + // -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET + // over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing + // accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js). + if (p === '/api/partner/registry' && req.method === 'POST') { + const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const b = sg.body; + const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : []; + return json(res, 200, Object.assign({ ok: true }, await lsinbound.receive(rows))); + } + // -- sponsor check between InstantAdPay and LinkSpin (2026-10-22, sponsorfollow.js). Partner side: LinkSpin reads our + // facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here). + if (p === '/api/partner/sponsor-facts' && req.method === 'POST') { + const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null; + return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'instantadpay', rows: await follow.facts(emails), view: followStore.view() }); + } + if (p === '/api/partner/sponsor-apply' && req.method === 'POST') { + const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on LinkSpin').slice(0, 120) }); + console.log('sponsor check (from LinkSpin)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok'); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/sponsor-check' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const mine = await follow.facts(); let peer = null, peerError = null; + try { peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; } + const mm = peer ? SF.mismatches(mine, peer.rows || []) : { shared: 0, same: 0, rows: [] }; + return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'instantadpay', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' }); + } + if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase(); + if (!email) return json(res, 400, { error: 'Which member?' }); + let r; + if (b.use === 'linkspin') { // LinkSpin's sponsor, applied HERE (refused when bound here) + const peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message })); + if (peer.error) return json(res, 502, { error: 'Could not read LinkSpin: ' + peer.error }); + const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' }); + r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used LinkSpin's sponsor" }); + } else if (b.use === 'instantadpay') { // our sponsor, applied ON LINKSPIN (LinkSpin refuses when bound there) + const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' }); + r = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on InstantAdPay: used InstantAdPay's sponsor" }, 30000).catch(e => ({ error: e.message })); + } else return json(res, 400, { error: 'use must be instantadpay or linkspin' }); + console.log('sponsor check resolve', email, b.use, r.error || 'ok'); + return json(res, r.error ? 400 : 200, r); + } + // -- help desk for LinkSpin (2026-10-16): LinkSpin has no desk of its own; its Help screen, /support page, private ticket + // link and chat hand-off all proxy here, signed like the registry rows. LinkSpin runs the person-facing guards (sign-in, + // honeypot, form age, icon check) and vouches for the email; this side only ever touches platform 'linkspin' tickets + // (LS- refs). Replies to the requester point at LinkSpin (tickets.js BRAND), never an InstantAdPay notice. + m = /^\/api\/partner\/support\/(create|list|view|reply|token|token-reply)$/.exec(p); + if (m && req.method === 'POST') { + const sg = await readLsSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const b = sg.body, op = m[1]; + const email = String(b.email || '').trim().toLowerCase(); + const mine = async () => { const t = await tickets.byRef(b.ref); return t && t.platform === 'linkspin' && t.email === email ? t : null; }; + const byTok = async () => { const t = await tickets.byToken(b.token); return t && t.platform === 'linkspin' ? t : null; }; + if (op === 'create') { + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' }); + if (supportFlood('ls:' + email, 8, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Add to one of those instead.' }); // backstop behind LinkSpin's own limits + const r = await tickets.create({ platform: 'linkspin', source: ['form', 'public', 'chatbot'].includes(b.source) ? b.source : 'public', email, name: b.name, username: b.username, subject: b.subject, category: b.category, body: b.body }); + return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref, token: r.token }); + } + if (op === 'list') return json(res, 200, { tickets: await tickets.memberList(email, 'linkspin'), unread: await tickets.memberUnread(email, 'linkspin'), categories: tickets.CATEGORIES }); + const t = op === 'view' || op === 'reply' ? await mine() : await byTok(); + if (!t) return json(res, 404, { error: op.startsWith('token') ? 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' : 'Ticket not found.' }); + if (op === 'view' || op === 'token') return json(res, 200, await tickets.memberView(t)); + if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); + const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: op === 'token-reply' ? 'link' : 'web' }); + return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); + } + if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); } + if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); } + if (p === '/api/admin/tank' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await tank.adminView()); + } + // -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring + // domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12) + // login-ad showings per Central day, dashboard vs games (2026-10-18: a week of combined sign-ins before the cap decision) + if (p === '/api/admin/login-shows' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { days: await loginShows.report(Number(u.searchParams.get('days')) || 14), slots: await ads.loginSlots() }); + } + if (p === '/api/admin/traffic' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30)); + const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10); + const hosts = {}, paths = {}, daily = {}, angles = {}; + const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 }); + const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 }); + for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; } + for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; } + const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId); + for (const a of await accounts.listAll(5000)) { + if (!a.created || a.created < since) continue; + const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1; + Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1; + const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1; + } + const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10)); + return json(res, 200, { starter: starter.adminView(), days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits), + angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1), + totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } }); + } + if (p === '/api/my/coach' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const cv = await coach.coachView(s.email); + for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock + return json(res, 200, cv); + } + // -- link stats: views, joins and buyers per angle link + if (p === '/api/my/linkstats' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await coach.linkStats(s.email)); + } + // -- prospects: the member's own follow-up list + // -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor) + if (p === '/api/my/pipeline' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const sc = siteConfig(); + if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' }); + const b = await pipeline.board(s.email); + return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/pipeline/note' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' }); + const r = await pipeline.save(s.email, await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/prospects' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES }); + } + if (p === '/api/my/prospects' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await coach.saveProspect(s.email, await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/prospects/remove' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await coach.removeProspect(s.email, b.id); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/profile' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const before = await accounts.byEmail(s.email); + // a username is permanent once set: the invite link, the public wall and every + // banner already printed carry it (Marty, 2026-09-10) + if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) + return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support (instantadpay.com/support) if it truly has to change.' }); + const r = await accounts.setUsername(s.email, b.username); + // First time a username is set (onboarding): now there's a real name to + // show, so notify the sponsor here rather than at signup (where it'd just + // say "a new member"). Fires once — only on the empty→set transition. + if (!r.error && before && !before.username && b.username) { + const acct = await accounts.byEmail(s.email); + notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); + // everyone's dashboard: "@name just joined" (and whether they are waiting in the tank) + if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); + } + return json(res, r.error ? 400 : 200, r); + } + // -- earn credits by viewing ads (attention-gated daily claim) + if (p === '/api/my/earn' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await ads.viewStatus(s.email)); + } + // fraud-guarded view flow: the server issues a single-use token when it + // serves the ad, and only counts the view if the dwell elapsed on the + // SERVER clock. Client-side focus tracking pauses the countdown; this is + // the floor a script cannot cheat past. + if (p === '/api/my/earnview' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.viewStatus(s.email); + if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status }); + const type = String(u.searchParams.get('type') || 'banner'); + // members never see (or earn from) their own campaigns in the viewer + const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req))); + if (!ad) return json(res, 200, { ad: null, status }); + const token = crypto.randomBytes(16).toString('hex'); + // the viewer tab frames the advertiser's REAL url (no click counted for a paid view) + earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id, + targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null }); + return json(res, 200, { ad, token, viewUrl: '/view/' + token, status }); + } + // the viewer tab asks where to point the frame (does not consume the token) + if (p === '/api/my/viewinfo' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = earnTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) + return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' }); + return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null, + dwell: ads.rates().viewDwellSeconds || 10 }); + } + // human check: handed out only once the dwell has elapsed on the SERVER clock + if (p === '/api/my/viewchallenge' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = earnTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) + return json(res, 400, { error: 'That view is no longer open.' }); + const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/my/adview' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = earnTokens.get(s.email); + const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' }); + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' }); + if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } + // the human check must be solved on the same token + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { + t.attempts = (t.attempts || 0) + 1; + t.challenge = null; // force a fresh challenge for the next try + if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); } + return json(res, 400, { error: 'Wrong pick.', retry: true }); + } + earnTokens.delete(s.email); // single use + return json(res, 200, await ads.recordView(s.email)); + } + // -- Friday Bonus Hunts (2026-09-26). The member's own progress, for the Earn tab card. + if (p === '/api/my/friday-bank' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await fridaybank.bankFor(s.email)); + } + // PolHunter asks, server to server, signed with the same shared secret as the hand-off: + // sig = HMAC-SHA256(HUNT_SSO_SECRET, 'fridaybank:' + email + ':' + ts), ts within 5 minutes. + if (p === '/api/hunt/friday-bank' && req.method === 'GET') { + const secret = String(process.env.HUNT_SSO_SECRET || '').trim(); + if (secret.length < 32) return json(res, 503, { error: 'not connected' }); + const q = new URL(req.url, 'http://x').searchParams; + const email = String(q.get('email') || '').trim().toLowerCase(), ts = Number(q.get('ts') || 0), sig = String(q.get('sig') || ''); + if (!email || !ts || Math.abs(Date.now() - ts) > 300000) return json(res, 400, { error: 'stale or missing' }); + const want = crypto.createHmac('sha256', secret).update('fridaybank:' + email + ':' + ts).digest('hex'); + if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'bad signature' }); + return json(res, 200, await fridaybank.bankFor(email)); + } + // -- PolHunter hand-off (2026-09-19): sign the member across; polhunter.com verifies with the shared secret + if (p === '/api/my/polhunter' && req.method === 'GET') { gamestats.handoff('polhunter'); + const s = await auth.fromRequest(req); + // not signed in: to sign-in, keeping a PolHunter share link's ?ref so the newcomer's sponsor holds (the viral-link rule on /my sets it) + if (!s || !s.email) { const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); res.writeHead(302, { Location: '/my' + (ref ? '?ref=' + ref : '') }); return res.end(); } + const secret = String(process.env.HUNT_SSO_SECRET || '').trim(); const huntUrl = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, ''); + if (secret.length < 32) return json(res, 503, { error: 'PolHunter is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const memberId = (acct && acct.memberId) || s.memberId || 0; + if (!memberId) { res.writeHead(302, { Location: '/my#wallet' }); return res.end(); } + const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); + // the sponsor rides across too (Marty, 2026-09-23): PolHunter pays a referral bounty, and the + // person who gets it has to be the one this member actually joined under here, not a cookie + // PolHunter guessed at. sponsorRef is the upline's username or code, matching /join/. + let sponsorRef = (acct && acct.sponsorRef) || ''; + const payload = JSON.stringify({ iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(12).toString('hex'), memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, sponsorRef: sponsorRef || null, joinedAt: (acct && acct.created) || null, + // where they first arrived from, so PolHunter can pay a bounty only for people it sent + joinedRef: (acct && acct.joinedRef) || null, gamePass: gamepass.flag(s.email) }); + const tok = b64u(payload) + '.' + b64u(crypto.createHmac('sha256', secret).update(payload).digest()); + res.writeHead(302, { Location: huntUrl + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); // the loop is closed + } + // -- Drip Runner hand-off (2026-09-30): sign the member across, the game verifies with the shared secret + if (p === '/api/my/driprunner' && req.method === 'GET') { gamestats.handoff('driprunner'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=driprunner; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight back into the game + if (DR_SECRET().length < 32) return json(res, 503, { error: 'Drip Runner is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const memberId = (acct && acct.memberId) || s.memberId || 0; + const tok = drMint({ memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, + sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }); // the game credits referrals to the IAP sponsor + res.writeHead(302, { Location: DR_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); + } + // -- PolyWarriors hand-off (2026-10-05): sign the member across; the game verifies with PW_SSO_SECRET + // PolyWarriors weekly member-fight season prizes (Marty 2026-10-05): the game signs one claim per week and place; InstantAdPay + // decides the amount (setting pwWeeklyPrize, default '1000,500,250' earned credits) and pays each week+place once. + // admin: credit or remove PolyWarriors mint passes on an account (support fixes), logged in the pass history + if (p === '/api/admin/pw/pass' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(), n = Math.round(Number(b.n) || 0); + if (!e || !n || Math.abs(n) > 20) return json(res, 400, { error: 'email and n (1-20, or negative to remove) required' }); + const left = pwPassAdd(e, n, 'admin:' + String(b.why || 'support').slice(0, 80)); + console.log('polywarriors admin pass', e, n > 0 ? '+' + n : n, 'left', left, b.why || ''); + return json(res, 200, { ok: true, email: e, passes: left }); + } + if (p === '/api/game/pw/prize' && req.method === 'POST') { + const b = await readBody(req); const r = pwOpen(b.t); + if (r.error) return json(res, 400, { error: r.error }); + const c = r.claims, place = Number(c.place), week = String(c.week || ''); + if (c.kind !== 'pw-prize' || !(place >= 1 && place <= 3) || !/^\d{4}-\d{2}-\d{2}$/.test(week) || !c.email) return json(res, 400, { error: 'bad claim' }); + if (Math.abs(Date.now() - new Date(week + 'T12:00:00Z').getTime()) > 14 * 86400000) return json(res, 400, { error: 'stale week' }); + const k = week + ':' + place; if (pwPrizes.get(k)) return json(res, 200, { ok: true, already: true }); + const acct = await accounts.byEmail(String(c.email).toLowerCase()); if (!acct) return json(res, 404, { error: 'no account' }); + const amts = String(siteConfig().pwWeeklyPrize || '1000,500,250').split(',').map(x => Math.max(0, Math.round(Number(x) || 0))); + const credits = Math.min(amts[place - 1] || 0, 5000); if (!credits) return json(res, 200, { ok: true, credits: 0 }); + pwPrizes.set(k, { email: acct.email, credits, at: Date.now() }); + await ads.addEarned(acct.email, credits, { log: { kind: 'bonus', note: 'PolyWarriors weekly season: #' + place + ' (week of ' + week + ')', ref: 'pwprize:' + k } }); + console.log('polywarriors weekly prize', k, acct.email, credits); + return json(res, 200, { ok: true, credits }); + } + if (p === '/api/my/polywarriors' && req.method === 'GET') { gamestats.handoff('polywarriors'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polywarriors', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (PW_SECRET().length < 32) return json(res, 503, { error: 'PolyWarriors is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = pwMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); + res.writeHead(302, { Location: PW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- SpellWheel hand-off (2026-10-04): sign the member across; the game verifies with SW_SSO_SECRET + if (p === '/api/my/polybreak' && req.method === 'GET') { gamestats.handoff('polybreak'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'polybreak', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (PB_SECRET().length < 32) return json(res, 503, { error: 'PolyBreak is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = pbMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorRef: (acct && acct.sponsorRef) || null }); + res.writeHead(302, { Location: PB_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + if (p === '/api/my/spellwheel' && req.method === 'GET') { gamestats.handoff('spellwheel'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'spellwheel', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (SW_SECRET().length < 32) return json(res, 503, { error: 'SpellWheel is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = swMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); + res.writeHead(302, { Location: SW_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- ClutterHunt hand-off (2026-10-03): sign the member across; the game verifies with SEEK_SSO_SECRET + if (p === '/api/my/clutterhunt' && req.method === 'GET') { gamestats.handoff('clutterhunt'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'clutterhunt', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (SEEK_SECRET().length < 32) return json(res, 503, { error: 'ClutterHunt is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = seekMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); + res.writeHead(302, { Location: SEEK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- Shards of Valor hand-off (2026-10-18): sign the member across; the game verifies with SOV_SSO_SECRET + if (p === '/api/my/shardsofvalor' && req.method === 'GET') { gamestats.handoff('shardsofvalor'); + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': gkCookie('iap.return', 'shardsofvalor', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (SOV_SECRET().length < 32) return json(res, 503, { error: 'Shards of Valor is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = sovMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); + res.writeHead(302, { Location: SOV_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- Gem Kingdom hand-off (2026-10-01): sign the member across; the game verifies with GK_SSO_SECRET + if (p === '/api/my/gemkingdom' && req.method === 'GET') { gamestats.handoff('gemkingdom'); + const s = await auth.fromRequest(req); + // a newcomer from a Gem Kingdom feed post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor + const gkRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (gkRef ? '?ref=' + encodeURIComponent(gkRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'gemkingdom', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (GK_SECRET().length < 32) return json(res, 503, { error: 'Gem Kingdom is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = gkMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null }); + res.writeHead(302, { Location: GK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- the Crown shop checkout: confirm, spend the credits, sign a receipt back to the game + if (p === '/gk/shop' && req.method === 'GET') { + const t = u.searchParams.get('t') || ''; const r = gkOpen(t); + if (r.error) return gkPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      Back to Gem Kingdom'); + const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '

      That is not a Crown order

      '); + const done = gkOrders.get(c.order); + if (done && done.status === 'paid') { const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: c.email, crowns: c.crowns, credits: c.credits, paid: done.paid != null ? done.paid : c.credits, ref: done.campaignId }, 24 * 3600000); res.writeHead(302, { Location: c.ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); } + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.gkshop', t, 7200), gkCookie('iap.return', 'gkshop', 1800)] }); return res.end(); } + if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '

      Different account

      This order was started by the Gem Kingdom player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.

      Back to Gem Kingdom'); + const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email); + const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 }; + const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail); + const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0); + const head = '

      Gem Kingdom · Crown Shop

      ' + gkEsc(c.label || 'Crowns') + '

      ' + Number(c.crowns) + ' Crowns
      ' + + '
      Price' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')
      ' + + '
      Your available credits' + Number(bal.available || 0).toLocaleString('en-US') + '
      '; + if (can) { + const csrf = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); + return gkPage(res, 200, 'Confirm your Crowns', head + '
      ' + + 'Cancel and go back

      Crowns are game items. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.

      '); + } + const need = c.credits - usable; + return gkPage(res, 200, 'More credits needed', head + '

      You need ' + need.toLocaleString('en-US') + ' more credits for this pack' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.

      ' + + 'Buy a credit packagePick a smaller pack' + + '

      A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.

      '); + } + // ---- PolyWarriors paid mints: every mint after the free first one comes with a new $5+ package purchase + if (p === '/pw/mint' && req.method === 'GET') { + const t = u.searchParams.get('t') || ''; const r = pwOpen(t); + if (r.error) return gkPage(res, 400, 'Mint problem', '

      That mint did not work

      ' + gkEsc(r.error) + '

      Back to PolyWarriors'); + const c = r.claims; if (c.kind !== 'pw-mint' || !c.order || !(c.serial > 0)) return gkPage(res, 400, 'Mint problem', '

      That is not a mint order

      '); + const done = pwOrders.get(c.order); + if (done && done.status === 'paid') { + // a visible hand-back instead of a silent redirect chain (Zachary's iPad sat on the mint form after a pass mint, + // 2026-10-12): the page says the mint is done, returns to the game by itself, and keeps a button in case it does not. + const rc = pwReceipt(c.order, done); const back = (pwIsGameUrl(done.ret) ? done.ret : PW_URL() + '/api/iap/mint-receipt') + '?t=' + rc; + res.setHeader('Set-Cookie', gkCookie('iap.pwmint', '', 0)); + return gkPage(res, 200, 'Minted', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(done.label || ('Warrior #' + done.serial)) + '

      Minting now
      ' + + '

      Your warrior is on its way to the wallet on your InstantAdPay account. Taking you back to the game.

      ' + + 'Back to PolyWarriors' + + '

      If this page stays, tap the button. The game shows the warrior as On Polygon once the transaction confirms, usually within a minute.

      ', ''); + } + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S), gkCookie('iap.return', 'pwmint', 1800)] }); return res.end(); } + if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '

      Different account

      This mint was started by the PolyWarriors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account and tap Mint again.

      '); + // the order waits here until a new package purchase from this account lands on chain (oldest waiting order first) + if (!done) pwOrders.set(c.order, { status: 'waiting', email: String(s.email).toLowerCase(), serial: Number(c.serial), label: String(c.label || '').slice(0, 60), ret: c.ret, cb: c.cb, ts: Date.now() }); + res.setHeader('Set-Cookie', gkCookie('iap.pwmint', t, PW_MINT_COOKIE_S)); + const have = pwPassN(String(s.email).toLowerCase()); + if (have > 0) { + const csrf = pwSign('pass:' + c.order + ':' + String(s.email).toLowerCase()); + return gkPage(res, 200, 'Mint your warrior', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(c.label || ('Warrior #' + c.serial)) + '

      ' + have + ' mint pass' + (have === 1 ? '' : 'es') + '
      ' + + '
      ' + + 'Cancel and go back

      You earned these passes with your package purchases: one mint for every $5. The game pays the network fee.

      '); + } + return gkPage(res, 200, 'Mint your warrior', '

      PolyWarriors · Mint to your wallet

      ' + gkEsc(c.label || ('Warrior #' + c.serial)) + '

      Comes with a $5 package
      ' + + '

      Your first mint was free. After that, every $5 of new ad packages earns one mint: $5 mints this warrior, $10 earns 2 mints, $20 earns 4, and any extra mints stay on your account for next time. You keep every package\'s ad credits.

      ' + + 'Buy a $5 packageBack to PolyWarriors' + + '

      Buy while this mint is waiting and it mints to your wallet automatically. Credits you already have cannot be used for mints. The game pays the network fee.

      '); + } + if (!IS_PROD && p === '/api/dev/pw-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await pwMintOnEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email }) }); } // local tests only + if (p === '/pw/mint/pass' && req.method === 'POST') { + const f = await gkFormBody(req); const t = f.get('t') || ''; const r = pwOpen(t); + if (r.error) return gkPage(res, 400, 'Mint problem', '

      That mint did not work

      ' + gkEsc(r.error) + '

      '); + const c = r.claims; const s = await auth.fromRequest(req); const e = s && s.email ? String(s.email).toLowerCase() : ''; + if (!e || e !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); + const want = pwSign('pass:' + c.order + ':' + e), got = String(f.get('csrf') || ''); + if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Mint problem', '

      That form expired

      Try again'); + const o = pwOrders.get(c.order); + // the redirect goes out at once; the game is told in the background (and the GET below hands the member's own browser the + // receipt too, so the mint never waits on this callback). Marty's phone sat on this form on 2026-10-09 while the mint had + // already gone through. + if (o && o.status === 'waiting' && pwPassN(e) > 0) { pwPassAdd(e, -1, 'mint:' + c.order); pwOrders.set(c.order, Object.assign({}, o, { status: 'paid', tx: 'pass', cents: 500, paidAt: Date.now() })); pwDeliver(c.order).catch(() => {}); } + res.writeHead(303, Object.assign({ Location: '/pw/mint?t=' + encodeURIComponent(t), 'Cache-Control': 'no-store' }, pwOrders.get(c.order) && pwOrders.get(c.order).status === 'paid' ? { 'Set-Cookie': gkCookie('iap.pwmint', '', 0) } : {})); return res.end(); + } + if (p === '/pw/mint/leave' && req.method === 'GET') { res.writeHead(302, { Location: PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the waiting order stays; a later package still completes the mint + if (p === '/pw/mint/dismiss' && req.method === 'POST') { res.writeHead(204, { 'Set-Cookie': [gkCookie('iap.pwmint', '', 0), gkCookie('iap.return', '', 0)] }); return res.end(); } // the dashboard bar's x + if (p === '/pw/mint/resume' && req.method === 'GET') { const t = parseCookies(req)['iap.pwmint']; res.writeHead(302, { Location: t ? '/pw/mint?t=' + encodeURIComponent(t) : PW_URL() + '/play', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); } + if (p === '/gk/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back + const t = u.searchParams.get('t') || ''; if (gkOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); } + res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', t, 7200) }); return res.end(); + } + if (p === '/gk/shop/resume' && req.method === 'GET') { + const t = parseCookies(req)['iap.gkshop']; res.writeHead(302, { Location: t ? '/gk/shop?t=' + encodeURIComponent(t) : GK_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + if (p === '/gk/shop/confirm' && req.method === 'POST') { + const f = await gkFormBody(req); const t = f.get('t') || ''; const r = gkOpen(t); + if (r.error) return gkPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      '); + const c = r.claims; const s = await auth.fromRequest(req); + if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); + const want = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || ''); + if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Order problem', '

      That form expired

      Try again'); + const prev = gkOrders.get(c.order); + if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } + gkOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() }); + const { ids } = await myMemberIds(s); + const out = await ads.gamePurchase(s.email, ids, c.credits, 'Gem Kingdom: ' + c.crowns + ' Crowns', GK_URL()); + if (out.error) { gkOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } return gkPage(res, 500, 'Order problem', '

      Something went wrong

      ' + gkEsc(out.error) + '

      '); } + gkOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() }); + console.log('gemkingdom crowns', s.email, c.crowns, 'for', c.credits, 'credits (' + out.paid + ' purchased), campaign', out.campaignId); + const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: String(c.email).toLowerCase(), crowns: Number(c.crowns), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000); + gkCallback(c.cb, rc); // the server copy; the redirect below is the fast path + const ret = String(c.ret || '').startsWith(GK_URL() + '/') ? c.ret : GK_URL() + '/api/iap/receipt'; + // a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site (the page just sat there) + const back = gkEsc(ret + '?t=' + rc); + res.setHeader('Set-Cookie', gkCookie('iap.gkshop', '', 0)); + return gkPage(res, 200, 'Crowns added', '

      Gem Kingdom · Crown Shop

      Paid!

      +' + Number(c.crowns).toLocaleString('en-US') + ' Crowns

      Taking you back to your kingdom...

      Back to Gem Kingdom'); + } + // -- Spooky Doors hand-off (2026-10-02): sign the member across; the game verifies with SD_SSO_SECRET + // -- Spooky Doors promo card in Promo tools (2026-10-02): shown on the same season window as the Games card (admin preview + // before the start). The member's link is SD_URL/?ref=, built in the page from their own username. + if (p === '/api/my/spookydoors/promo' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); + const ss = seasonState(SD_SEASON, todayCT(), admin); + if (ss === 'hidden') return json(res, 200, { show: false }); + return json(res, 200, { show: true, preview: ss === 'preview', base: SD_URL(), image: SD_URL() + '/og-spookydoors.jpg', season: { start: SD_SEASON.start, end: SD_SEASON.end } }); + } + if (p === '/api/my/spookydoors' && req.method === 'GET') { gamestats.handoff('spookydoors'); + const s = await auth.fromRequest(req); + // a newcomer from a Spooky Doors post carries the poster's ?ref through to /my, where the viral-link rule sets the sponsor + const sdRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (sdRef ? '?ref=' + encodeURIComponent(sdRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'spookydoors', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (SD_SECRET().length < 32) return json(res, 503, { error: 'Spooky Doors is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = sdMint({ kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null, + sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000); + res.writeHead(302, { Location: SD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- Road Agent hand-off (2026-10-07): sign the member across; the game verifies with RA_SSO_SECRET + if (p === '/api/my/roadagent' && req.method === 'GET') { gamestats.handoff('roadagent'); + const s = await auth.fromRequest(req); + const raRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (raRef ? '?ref=' + encodeURIComponent(raRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'roadagent', 1800), 'Cache-Control': 'no-store' }); return res.end(); } + if (RA_SECRET().length < 32) return json(res, 503, { error: 'Road Agent is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const tok = gMint(DOOR_GAMES().roadagent, { kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null, + sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000); + res.writeHead(302, { Location: RA_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + // -- the Spooky Doors costume shop checkout: the Crown shop flow with a Halloween coat (confirm, spend, signed receipt back) + if (p === '/sd/shop' && req.method === 'GET') { + const t = u.searchParams.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.'); + if (r.error) return sdPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      Back to Spooky Doors'); + const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0) || !c.email) return sdPage(res, 400, 'Order problem', '

      That is not a costume order

      Back to Spooky Doors'); + const label = String(c.label || c.item).slice(0, 60); + const done = sdOrders.get(c.order); + if (done && done.status === 'paid') { const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: done.paid != null ? done.paid : Number(c.credits), ref: done.campaignId }, 24 * 3600000); const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); } + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.sdshop', t, 7200), gkCookie('iap.return', 'sdshop', 1800)] }); return res.end(); } + if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Different account', '

      Different account

      This order was started by the Spooky Doors player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.

      Back to Spooky Doors'); + const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email); + const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 }; + const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail); + const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0); + const head = '

      Spooky Doors · Costume shop

      ' + gkEsc(label) + '

      ' + + '
      Price' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')
      ' + + '
      Your available credits' + Number(bal.available || 0).toLocaleString('en-US') + '
      '; + if (can) { + const csrf = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); + return sdPage(res, 200, 'Confirm your costume', head + '
      ' + + 'Cancel and go back

      Costumes are game items for this Halloween season. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.

      '); + } + const need = c.credits - usable; + return sdPage(res, 200, 'More credits needed', head + '

      You need ' + need.toLocaleString('en-US') + ' more credits for this costume' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.

      ' + + 'Buy a credit packageBack to the costume shop' + + '

      A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.

      '); + } + if (p === '/sd/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back + const t = u.searchParams.get('t') || ''; if (sdOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); } + res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.sdshop', t, 7200) }); return res.end(); + } + if (p === '/sd/shop/resume' && req.method === 'GET') { + const t = parseCookies(req)['iap.sdshop']; res.writeHead(302, { Location: t ? '/sd/shop?t=' + encodeURIComponent(t) : SD_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end(); + } + if (p === '/sd/shop/confirm' && req.method === 'POST') { + const f = await gkFormBody(req); const t = f.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.'); + if (r.error) return sdPage(res, 400, 'Order problem', '

      That order did not work

      ' + gkEsc(r.error) + '

      '); + const c = r.claims; if (c.kind !== 'sd-buy' || !c.order || !c.item || !(Number(c.credits) > 0)) return sdPage(res, 400, 'Order problem', '

      That is not a costume order

      '); + const s = await auth.fromRequest(req); + if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return sdPage(res, 403, 'Sign in', '

      Please sign in again

      Continue'); + const want = sdSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || ''); + if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return sdPage(res, 403, 'Order problem', '

      That form expired

      Try again'); + const prev = sdOrders.get(c.order); + if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } + sdOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() }); + const label = String(c.label || c.item).slice(0, 60); + const { ids } = await myMemberIds(s); + const out = await ads.gamePurchase(s.email, ids, Number(c.credits), 'Spooky Doors: ' + label, SD_URL()); + if (out.error) { sdOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/sd/shop?t=' + encodeURIComponent(t) }); return res.end(); } return sdPage(res, 500, 'Order problem', '

      Something went wrong

      ' + gkEsc(out.error) + '

      '); } + sdOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, paid: out.paid, ts: Date.now() }); + console.log('spookydoors costume', s.email, c.item, 'for', c.credits, 'credits, campaign', out.campaignId); + const rc = sdMint({ kind: 'sd-receipt', order: c.order, email: String(c.email).toLowerCase(), item: String(c.item), credits: Number(c.credits), paid: Number(out.paid), ref: out.campaignId }, 24 * 3600000); + sdShopCallback(c.cb, rc); // the server copy; the redirect below is the fast path + const ret = sdIsGameUrl(c.ret) ? c.ret : SD_URL() + '/api/iap/receipt'; + // a 200 page, not a 302: CSP form-action 'self' blocks a form POST from redirecting to another site + const back = gkEsc(ret + '?t=' + rc); + res.setHeader('Set-Cookie', gkCookie('iap.sdshop', '', 0)); + return sdPage(res, 200, 'Costume ready', '

      Spooky Doors · Costume shop

      Paid!

      ' + gkEsc(label) + '

      Taking you back to the street...

      Back to Spooky Doors'); + } + // -- PassiveDrip card on the Earn tab (Marty, 2026-10-01: "It's an earning site", not a game). Members see it when + // site config passivedripLive is 'on'; until then only the admin sees it, marked preview. + if (p === '/api/my/passivedrip/card' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const live = String(siteConfig().passivedripLive || 'off') === 'on'; + const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); + if ((!live && !admin) || PD_SECRET().length < 32) return json(res, 200, { show: false }); + const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0; + let progress = null; try { progress = await pdProgress(memberId, s.email); } catch (e) {} + return json(res, 200, { show: true, preview: !live, line: progress && progress.line || null }); + } + // -- PassiveDrip hand-off (2026-10-01): sign the member across; PassiveDrip verifies with the shared secret. + // wallet = the signature-verified main wallet (accounts.linkWallet runs only after /api/auth/verify), offered there, never imposed. + if (p === '/api/my/passivedrip' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) { res.writeHead(302, { Location: '/my' + refQ(u), 'Set-Cookie': 'iap.return=passivedrip; Path=/; SameSite=Lax; Max-Age=1800' + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } // sign in first, then straight across + if (PD_SECRET().length < 32) return json(res, 503, { error: 'PassiveDrip is not connected yet.' }); + const acct = await accounts.byEmail(s.email); + const memberId = (acct && acct.memberId) || s.memberId || 0; + let sponsorEmail = null; try { const up = await uplineSlides(s.email, 1); sponsorEmail = (up[0] && up[0].email) || null; } catch (e) {} + const tok = pdMint({ memberId: Number(memberId), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null, sponsorEmail }); + res.writeHead(302, { Location: PD_URL() + '/iap-signin.php?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); + } + // -- Drip Runner refuel: a real verified visit (advertiser charged as usual); the player gets fuel, not credits + if (p === '/api/refuel/open' && req.method === 'GET') { + // Drip Runner refuels and Gem Kingdom continues (2026-10-03) share this flow; the token's secret says which game + let r = drOpen(u.searchParams.get('t')), game = 'driprunner'; + if (r.error) { const g = gkOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'gemkingdom') { r = g; game = 'gemkingdom'; } } + if (r.error) { const g = seekOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'seek') { r = g; game = 'seek'; } } + if (r.error) { const g = swOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'spellwheel') { r = g; game = 'spellwheel'; } } + if (r.error) { const g = pbOpen(u.searchParams.get('t')); if (!g.error && g.claims.game === 'polybreak') { r = g; game = 'polybreak'; } } + if (r.error) return json(res, 400, { error: r.error }); + const c = r.claims; if (c.kind !== 'refuel' || !c.nonce || !c.email || !c.ret) return json(res, 400, { error: 'That is not a refuel link.' }); + if (game === 'gemkingdom' && !String(c.ret).startsWith(GK_URL() + '/')) return json(res, 400, { error: 'That is not a Gem Kingdom link.' }); + if (game === 'seek' && !seekIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a ClutterHunt link.' }); + if (game === 'spellwheel' && !swIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a SpellWheel link.' }); + if (game === 'polybreak' && !pbIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a PolyBreak link.' }); + const G = game === 'polybreak' ? { game: 'PolyBreak', label: 'one more paddle' } : game === 'gemkingdom' ? { game: 'Gem Kingdom', label: 'continue' } : game === 'seek' ? { game: 'ClutterHunt', label: 'hint' } : game === 'spellwheel' ? { game: 'SpellWheel', label: 'hint' } : { game: 'Drip Runner', label: 'refuel' }; + for (const [n, v] of refuelTokens) if (v.ts + 30 * 60000 < Date.now()) refuelTokens.delete(n); + let t = refuelTokens.get(c.nonce); + if (t && t.done) return json(res, 200, Object.assign({ done: true, ret: t.doneRet || t.ret }, G)); + if (!t) { + const email = String(c.email).toLowerCase(); + const status = await ads.visitStatus(email, 'refuel'); // refuels have their own daily allowance + if (status.count >= status.cap) return json(res, 200, Object.assign({ none: true, why: 'cap', ret: c.ret }, G)); + const ad = await ads.serveVisit(email, viewerGeo(req)); + if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId), id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + else { // every visit pack already visited: a member video ad instead (2026-09-30) + const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req))); + if (!v) return json(res, 200, Object.assign({ none: true, why: 'empty', ret: c.ret }, G)); + t = { kind: 'video', email, memberId: Number(c.memberId), id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + } + t.game = game; t.cb = c.cb || null; + refuelTokens.set(c.nonce, t); + } + if (t.kind === 'video') return json(res, 200, Object.assign({ mode: 'video', title: t.title, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G)); + return json(res, 200, Object.assign({ mode: 'visit', title: t.title, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }, G)); + } + if (p === '/api/refuel/challenge' && req.method === 'GET') { + const t = refuelTokens.get(String(u.searchParams.get('n') || '')); + if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' }); + const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/refuel/done' && req.method === 'POST') { + const b = await readBody(req); const nonce = String(b.n || ''); const t = refuelTokens.get(nonce); + if (!t || t.done) return json(res, 400, { error: 'That refuel is no longer open.' }); + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } + let credits; + if (t.kind === 'video') { + const st = await ads.visitStatus(t.email, 'refuel'); if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s refuels. More at midnight Central.' }); + if (!(await ads.markRefuelVideo(t.email, t.id))) return json(res, 400, { error: 'You already refuelled on this video. Go back and try again for another.' }); + const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab + if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try again.' }); + await ads.markVideoSeen(t.email, t.id); credits = tier.cost; + } else { + const r = await ads.completeVisit(t.email, t.id, { reward: false, note: t.game === 'polybreak' ? 'PolyBreak paddle' : t.game === 'gemkingdom' ? 'Gem Kingdom continue' : t.game === 'seek' ? 'ClutterHunt hint' : t.game === 'spellwheel' ? 'SpellWheel hint' : 'Drip Runner refuel' }); + if (r.error) return json(res, 400, r); + credits = ads.rates().visitCostPerVisit || 3; + { const camp = await ads.campaignById(t.id).catch(() => null); if (camp && camp.house) credits = 0; } // a house ad costs nobody anything: no POL pool income (2026-10-03) + } + t.done = true; + if (t.game === 'polybreak') { // PolyBreak one more paddle: signed receipt to the game's callback and on the ret page + const receipt = pbMint({ kind: 'pb-paddle', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); + const posted = await pbCallback(t.cb, receipt); + t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); + return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'PolyBreak', label: 'one more paddle' }); + } + if (t.game === 'spellwheel') { // SpellWheel hint: signed receipt to the game's callback and on the ret page + const receipt = swMint({ kind: 'sw-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); + const posted = await swCallback(t.cb, receipt); + t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); + return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'SpellWheel', label: 'hint' }); + } + if (t.game === 'seek') { // ClutterHunt hint: signed receipt to the game's callback and on the ret page + const receipt = seekMint({ kind: 'seek-hint', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); + const posted = await seekCallback(t.cb, receipt); + t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); + return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'ClutterHunt', label: 'hint' }); + } + if (t.game === 'gemkingdom') { // signed receipt to the game's callback (server copy) and on the ret page (fast path) + const receipt = gkMint({ kind: 'gk-continue', nonce, email: t.email, campaignId: t.id, credits }, 15 * 60000); + const posted = await gkCallback(t.cb || (GK_URL() + '/api/continue/callback'), receipt); + t.doneRet = t.ret + (t.ret.includes('?') ? '&' : '?') + 'ok=1&r=' + encodeURIComponent(receipt); + return json(res, 200, { ok: true, posted, ret: t.doneRet, game: 'Gem Kingdom', label: 'continue' }); + } + const posted = await drCallback({ nonce, memberId: t.memberId, campaignId: t.id, credits }); + const receipt = drMint({ kind: 'refuel-receipt', nonce, campaignId: t.id, credits }, 15 * 60000); + t.doneRet = t.ret + '&ok=1&r=' + encodeURIComponent(receipt); + return json(res, 200, { ok: true, posted, ret: t.doneRet }); + } + // -- Spooky Doors door: a real verified visit of kind 'door' (own daily cap, advertiser charged as usual); the player gets candy, not credits + if (p === '/api/door/open' && req.method === 'GET') { + const r = doorOpen(u.searchParams.get('t')); if (r.error) return json(res, 400, { error: r.error }); + const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !gameUrlOk(r.game, c.ret)) return json(res, 400, { error: 'That is not a door link.' }); + for (const [n, v] of doorTokens) if (v.ts + 30 * 60000 < Date.now()) doorTokens.delete(n); + let t = doorTokens.get(c.nonce); + if (t && t.done) return json(res, 200, { done: true, ret: t.doneRet || t.ret }); + const email = String(c.email).toLowerCase(); + const status = await ads.visitStatus(email, 'door'); // doors have their own daily allowance + if (!t) { + if (status.count >= status.cap) return json(res, 200, { none: true, why: 'cap', ret: sdJoin(c.ret, 'cap=1') }); + // door packs + Golden Doors first (golden, then doors; once per player per Central day), then the existing chain + const pack = await ads.serveDoorPack(email, viewerGeo(req)); + const ad = pack || await ads.serveVisit(email, viewerGeo(req), { kind: 'door' }); // doors may repeat a campaign after doorRepeatDays + if (ad) t = { kind: 'visit', game: r.game, email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false, + credits: pack ? pack.credits : (ads.rates().visitCostPerVisit || 3), golden: !!(pack && pack.golden), bonus: (pack && pack.golden) ? sdGoldenBonus() : 0 }; + else { // every visit pack already visited: a member video ad instead, one door per video per person + const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req))); + if (v) t = { kind: 'video', game: r.game, email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + else { // nothing left on the street: a house ad (one of Marty's programs, a smaller treat); none=1 only when the list is empty + const h = await doorHousePick(email, c.username); + if (!h) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') }); + t = { kind: 'house', game: r.game, email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + } + } + t.host = t.kind === 'house' ? null : await sdHost(t.id); + doorTokens.set(c.nonce, t); + } + const doors = { used: status.count, cap: status.cap, game: t.game || 'spookydoors', gameName: DOOR_GAMES()[t.game || 'spookydoors'].name }; + if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); + if (t.kind === 'house') return json(res, 200, { mode: 'visit', house: true, program: t.program, title: t.title, host: null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); + return json(res, 200, Object.assign({ mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000), credits: t.credits || (ads.rates().visitCostPerVisit || 3) }, t.golden ? { golden: true, bonus: t.bonus } : {})); + } + if (p === '/api/door/challenge' && req.method === 'GET') { + const n = String(u.searchParams.get('n') || ''); const t = doorTokens.get(n); + if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' }); + const dwellMs = (t.kind === 'video' ? t.secs : (ads.rates().visitDwellSeconds || 8)) * 1000; const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + const pick = DOOR_CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; doorTokens.set(n, t); + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/door/done' && req.method === 'POST') { + const b = await readBody(req); const nonce = String(b.n || ''); const t = doorTokens.get(nonce); + if (!t || t.done) return json(res, 400, { error: 'That door is no longer open.' }); + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; doorTokens.set(nonce, t); return json(res, 400, { error: 'Wrong pick.', retry: true }); } + const st = await ads.visitStatus(t.email, 'door'); + if (st.count >= st.cap) return json(res, 400, { error: 'That is today\u2019s doors. More at midnight Central.', cap: true, ret: sdJoin(t.ret, 'cap=1') }); + let credits; + if (t.kind === 'video') { + if (!(await ads.markRefuelVideo(t.email, t.id, 'door'))) return json(res, 400, { error: 'You already knocked on this video. Go back and try another door.' }); + const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab + if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try another door.' }); + await ads.markVideoSeen(t.email, t.id); credits = tier.cost; + } else if (t.kind === 'house') { // no advertiser and no campaign imps, but it uses one of today's doors + const r = await ads.markHouseDoor(t.email); + if (r.error) return json(res, 400, { error: r.error, cap: true, ret: sdJoin(t.ret, 'cap=1') }); + credits = 0; + } else { + const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: 'door', note: 'Spooky Doors door' }); + if (r.error) return json(res, 400, r); + credits = r.unit || ads.rates().visitCostPerVisit || 3; // the per-door price actually charged (door pack 4, Golden Door 6, a visit pack 3) + if (t.golden && r.golden === false) t.golden = false; // the season closed between open and done: an ordinary door + } + t.done = true; + const host = t.host || null; + const house = t.kind === 'house' ? { house: true, program: t.program } : {}; // a house ad: credits 0, host null, campaignId 0 + const gold = (t.kind === 'visit' && t.golden) ? { golden: true, bonus: t.bonus } : {}; // a Golden Door: the game adds `bonus` candy + const gk = t.game || 'spookydoors'; + const posted = await gameCallback(gk, Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold)); + const receipt = gMint(DOOR_GAMES()[gk], Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold), 24 * 3600000); + t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt)); + doorTokens.set(nonce, t); + return json(res, 200, Object.assign({ ok: true, posted, host, credits, ret: t.doneRet }, house, gold)); + } + // -- cross-promo strip (2026-10-03): the list every game reads, and the counted hop between games + // -- the public games page (2026-10-10, Marty: a page to send people): every game, open ones first, dated ones after + // featured PolyWarriors listings for the games page, fetched server-side (the page CSP allows no cross-origin calls), cached 60 s + if (p === '/api/public/pw-featured' && req.method === 'GET') { + const now = Date.now(); if (!global.__pwFeat || now - global.__pwFeat.at > 60000) { try { const r = await fetch(String(process.env.PW_URL || 'https://www.polywarriors.com').replace(/\/+$/, '') + '/api/public/featured', { signal: AbortSignal.timeout(6000) }); global.__pwFeat = { at: now, body: r.ok ? await r.json() : { featured: [] } }; } catch (e) { global.__pwFeat = { at: now, body: { featured: [] } }; } } + return json(res, 200, global.__pwFeat.body, { 'Cache-Control': 'public, max-age=60' }); + } + if (p === '/api/public/games/all' && req.method === 'GET') { + const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); + const day = todayCT(), S = STRIP(); const lbl = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; + const out = []; + for (const g of GAMES()) { + if (g.season && day >= g.season.end) continue; // a finished season is gone + const soon = !!(g.soon && day < g.soon.opens), preSeason = !!(g.season && day < g.season.start); + const isLive = !soon && !preSeason && live.has(g.slug); + if (!isLive && !soon && !preSeason) continue; // not live and no date: not announced yet + out.push({ slug: g.slug, name: g.name, tag: g.tag, blurb: g.blurb, pays: g.pays, art: /^https?:/.test(g.art) ? g.art : 'https://instantadpay.com' + g.art, artPos: g.artPos || 'center', live: isLive, video: isLive && g.video ? g.video : null, + opens: soon ? g.soon.label : preSeason ? 'Opens ' + lbl(g.season.start) : null, season: g.season && isLive ? { ends: lbl(g.season.end, true) } : null, open: S[g.slug] ? S[g.slug].open : null, host: S[g.slug] ? S[g.slug].host : null }); + } + return json(res, 200, { games: out }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' }); + } + // Today's POL price in US dollars for the member pages (Marty, 2026-10-22, Brian's ask): the same rate the contract prices + // packages with (its Chainlink POL/USD feed), cached 5 minutes on the server, so browsers never call a price service. + if (p === '/api/public/polusd' && req.method === 'GET') { let usd = 0; try { usd = await polUsdLive(); } catch (e) {} return json(res, 200, { usd, at: polUsdCache.at || Date.now() }, { 'Cache-Control': 'public, max-age=60' }); } + if (p === '/api/public/games' && req.method === 'GET') return json(res, 200, { games: stripGames() }, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=300' }); + { const mg = /^\/g\/([a-z]{3,20})$/.exec(p); if (mg && req.method === 'GET') { + const g = GAMES().find(x => x.slug === mg[1]); const S = STRIP()[mg[1]]; + if (!g || !S) { res.writeHead(302, { Location: '/my#games', 'Cache-Control': 'no-store' }); return res.end(); } + const from = String(u.searchParams.get('from') || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 20); const src = STRIP()[from]; + traffic.hit('/g/' + g.slug, req.headers.referer || (src ? 'https://' + src.host + '/' : ''), req.headers['user-agent']); // Traffic tab: host = sending game, path g/ + const s = await auth.fromRequest(req); + res.writeHead(302, { Location: (s && s.email) ? g.play : S.open, 'Cache-Control': 'no-store' }); return res.end(); // signed in here: straight into the game, signed in + } } + // -- Game Pass + account-wide POL caps (2026-10-16, docs/GAME-PASS.md section 3a) -------------------------------------------- + // Partner auth: each game signs with the shared secret it already holds (its *_SSO_SECRET), 10-minute window. + // GET ...?game=&m=&e=&ts=&sig=hex sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts), who = memberId when > 0, else the lowercased email + // POST JSON body with `game`, headers X-Game-Ts (ms) + X-Game-Sig sig = HMAC-SHA256(secret, ts + '\n' + rawBody) + // The pass is per ACCOUNT (email): a linked position's member id resolves to the owner's account. Games fail closed. + if (p === '/api/partner/player' && req.method === 'GET') { + const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); + if (chk.error) return json(res, chk.code, { error: chk.error }); + const m = Number(u.searchParams.get('m')) || 0, e = String(u.searchParams.get('e') || '').trim().toLowerCase(), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); + if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:' + (m > 0 ? String(m) : e) + ':' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); + const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null, tier: null, tiers: { weekly: null, explorer: null, champion: null } } }); + const now = gpDevNow(u.searchParams.get('devDay')); + return json(res, 200, { ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email), + pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled }); + } + if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') { + let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); } + let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } + const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error }); + const ts = String(req.headers['x-game-ts'] || ''), sig = String(req.headers['x-game-sig'] || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); + if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update(ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); + if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); } + const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' }); + const now = gpDevNow(b.devDay); + if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref })); + if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later + const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now }); + if (!out.error && out.capHit && !out.repeat) console.log('gamepass cap hit', out.capHit, game, r.email.replace(/^(.).*(@.*)$/, '$1***$2'), out.pass ? 'pass' : 'free', out.enforced ? 'enforced' : 'recorded'); + return json(res, out.error ? 400 : 200, out); + } + if (p === '/api/partner/tournament/pending' && req.method === 'GET') { // prize rows the games still have to pay out in POL (admin session may read too) + if (!isAdmin(req)) { + const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error }); + const ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); + if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); + } + const rows = gamepass.pending(); + return json(res, 200, { ok: true, rows, pending: rows }); // `rows` is what the games' polgrant.js tournamentPending() reads; `pending` is the admin pane's name + } + if (p === '/api/my/gamepass' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay')), { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL })); + } + if (p === '/api/my/gamepass/buy' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (fraud.isSuspended(s.email)) return json(res, 403, { error: 'This account is suspended.' }); + const b = await readBody(req); + // 2026-10-22 (Marty): no pass is ever bought with credits. Buy only opens a waiting order; a FRESH package purchase of at least the + // tier price, by one of this member's own positions, fulfils it (gamepass.onEvent), so the sponsor and team are paid as usual. + // tier: weekly (missing) | explorer | champion | sovereign | legend; every tier above weekly is refused unless sovTiers is on, except for the ADMIN_EMAIL account (testing) + const r = gamepass.buy(s.email, gpDevNow(b.devDay), b.tier, { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL }); + return json(res, r.error ? 400 : 200, r); + } + if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: /^0x[0-9a-f]{64}$/.test(String(b.tx || '')) ? b.tx : '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email, devMinedAt: Number(b.minedAt) || 0, devNow: Number(b.now) || 0 }) }); } // local tests only (minedAt fakes the block time, now the fulfilment time, tx replays a hash) + if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); } + if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); + const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' }); + const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80), tier); console.log('gamepass comp', tier, e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r)); + } + if (p === '/api/admin/gamepass/revoke' && req.method === 'POST') { // support refund only: ends one tier now (never automatic); the record keeps what it was + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); + const r = gamepass.revoke(e, String(b.tier || '').toLowerCase(), String(b.why || 'support').slice(0, 80)); if (!r.error) console.log('gamepass revoke', r.tier, e, b.why || ''); + return json(res, r.error ? 400 : 200, Object.assign({ email: e }, r)); + } + if (p === '/api/admin/gamepass/tournament/run' && req.method === 'POST') { // settle a week by hand (the Monday job normally does this) + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); + const at = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? Date.parse(b.week + 'T17:00:00Z') : Date.now() - 7 * 86400000; + const r = await gamepass.runTournament(at, { force: !!b.force }); return json(res, r.error ? 400 : 200, r); + } + // -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive) + if (p === '/api/my/games' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const sc = siteConfig(); const live = new Set(String(sc.gamesLive == null ? 'polhunter' : sc.gamesLive).split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); + const admin = !!(ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL); + const acct = await accounts.byEmail(s.email); const memberId = (acct && acct.memberId) || s.memberId || 0; + const out = []; const day = todayCT(); + const dayLabel = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); }; + for (const g of GAMES()) { + // a seasonal game (2026-10-02) shows only while today (Central) is in [start, end); before start the admin sees a preview, after end nobody + // testers (env GAMES_TESTERS, usernames or emails; Marty 2026-10-07) get the Play button on a coming-soon game before it opens + const tester = isGameTester(acct, s.email); + if (g.soon && day < g.soon.opens && !tester) { out.push(Object.assign({}, g, { live: false, preview: false, soon: g.soon.label, play: null })); continue; } // coming soon: shown to all, not playable + if (g.soon && day < g.soon.opens && tester) { out.push(Object.assign({}, g, { live: false, preview: true, previewNote: 'testing · ' + g.soon.label.toLowerCase(), soon: null })); continue; } // soon cleared: the client prints a soon card's label where the Play button goes + const ss = seasonState(g.season, day, admin); if (ss === 'hidden') continue; + const seasonPreview = ss === 'preview'; + const isLive = live.has(g.slug); if (!isLive && !admin && !tester) continue; + // soon: null once the opening day arrives: the registry's {opens,label} object must not reach the client, which prints x.soon + // as the button label (SpellWheel showed "[object Object]" on the morning of 2026-10-10) + const card = Object.assign({}, g, { live: isLive, preview: !isLive || seasonPreview, soon: null }); + if (g.season) { card.season = Object.assign({}, g.season, { opens: dayLabel(g.season.start), ends: dayLabel(g.season.end, true) }); if (seasonPreview) card.previewNote = 'preview, opens ' + card.season.opens; } + if (g.progress && (memberId || g.slug === 'passivedrip')) { try { card.progress = await g.progress(memberId, s.email); } catch (e) {} } + out.push(card); + } + return json(res, 200, { games: out.map(g => { const c = Object.assign({}, g); if (typeof c.progress === 'function') delete c.progress; return c; }) }); + } + if (p === '/api/my/claim' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.claimDaily(s.email); + if (!r.error) { try { const paid = await payPromo(s.email, todayCT()); if (paid.length) r.promo = paid; } catch (e) { console.error('promo drip', e.message); } } + return json(res, r.error ? 400 : 200, r); + } + // -- downline lineage: 3 levels, usernames+IDs; email only for directs + if (p === '/api/my/line' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const levels = await accounts.downline(s.email, 3); + // what each person has paid THIS member so far: sum of TierPaid events where + // this member is the recipient and that person is the buyer (all indexed events) + // ...counting payouts to every position this account owns (main id + linked positions) + const myId = await auth.refreshMemberId(s); + const own = (await accounts.positions(s.email)).filter(p => p.memberId); + const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean)); + const earnedBy = {}; + const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($20+) + if (myIds.size) { + for (const ev of chain.recentEvents(1e9)) { + if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId) + earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString(); + if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId); + } + } + // who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself + const meAcct = await accounts.byEmail(s.email); const byTok = {}; + const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'); + for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; } + const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); }; + // a member's linked positions are theirs too: a qualifying buy from one of them lights their chip + const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } } + const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean); + // Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $20+ buy (counted for their own + // sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short + const lTot = await ads.earnedTotals(levels.flatMap(L => L.members.map(m => m.email))); // surf earnings per person (Marty, 2026-09-29) + const onchain = {}; + for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; } + const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({ + bought: onchain[m.email].bought, buyers: onchain[m.email].buyers, + memberId: m.memberId || 0, + sponsor: sponsorOf(m), + name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member', + ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels + email: L.level === 1 ? m.email : null, // directs only + joined: m.created, + lastSeen: m.lastSeen || 0, + wallet: !!m.address, activated: !!m.memberId, + earned: (lTot[m.email] || {}).earned || 0, balance: (lTot[m.email] || {}).balance || 0, + qualified: idsOf(m).some(id => qualified.has(id)), + earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) })); + // the member's own linked positions sit on level 1 too, labelled as theirs + if (own.length) { + if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] }); + const L1 = out.find(L => L.level === 1); + own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true, + email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' })); + } + return json(res, 200, { levels: out, counts: out.map(L => L.members.length) }); + } + // -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14) + if (p === '/api/my/line/activity' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); + const a = ref ? await accounts.byCode(ref) : null; + if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' }); + const now = Date.now(); + const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 }; + try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {} + try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {} + try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {} + try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {} + try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; } + try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; } + try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; } + return json(res, 200, out); + } + // -- broadcast a message to your downline (1/day), on-site inbox + email + if (p === '/api/my/broadcast' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const subject = String(b.subject || '').trim().slice(0, 160); + const body = ads.sanitizeRich(b.body); + const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); + if (!subject) return json(res, 400, { error: 'Give your message a subject.' }); + if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' }); + const last = await messages.lastBroadcastAt(s.email); + if (Date.now() - last < 24 * 3600 * 1000) + return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' }); + const depth = b.scope === 'direct' ? 1 : 3; + const levels = await accounts.downline(s.email, depth); + const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))]; + if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' }); + const memberId = s.memberId || await auth.refreshMemberId(s); + await messages.deliver(memberId, s.email, recipients, subject, body); + // email each recipient too (best-effort; never blocks the on-site delivery) + if (mailer.hasKey()) { + const who = (await accounts.byEmail(s.email)); + const from = who && who.username ? '@' + who.username : 'your sponsor'; + for (const to of recipients) { + mailer.send(to, 'Message from ' + from + ': ' + subject, + plain + '\n\n— sent via your InstantAdPay upline. Read it in your dashboard: https://instantadpay.com/my#line') + .catch(() => {}); + } + } + return json(res, 200, { ok: true, sent: recipients.length }); + } + // -- help desk, member side (2026-10-16): the Help pane lists, opens and answers this member's tickets + if (p === '/api/my/support' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (req.method === 'GET') return json(res, 200, { tickets: await tickets.memberList(s.email, 'iap'), unread: await tickets.memberUnread(s.email, 'iap'), categories: tickets.CATEGORIES }); // LinkSpin tickets live in LinkSpin's Help + const b = await readBody(req); + if (supportFlood('em:' + String(s.email).toLowerCase(), 5, 3600000)) return json(res, 429, { error: 'You have opened several tickets in the last hour. Add to one of those instead.' }); + const a = await accounts.byEmail(s.email); + const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments }); + return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref }); + } + m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); + if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = await tickets.byRef(m[1]); + if (!t || t.email !== String(s.email).toLowerCase() || t.platform !== 'iap') return json(res, 404, { error: 'Ticket not found.' }); + if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); + const b = await readBody(req); + if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); + const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, attachments: b.attachments }); + return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); + } + // -- sponsor messages: this member's inbox from their upline + if (p === '/api/my/messages' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const items = await messages.inbox(s.email); + const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]); + for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember] + : i.fromMember ? 'member #' + i.fromMember : 'your upline'; + return json(res, 200, { items, unread: items.filter(i => !i.read).length }); + } + m = /^\/api\/my\/messages\/(\d+)\/read$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await messages.markRead(s.email, m[1])); + } + + // ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ── + const chatOnline = ts => (Date.now() - (ts || 0)) < 60000; + const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member')); + // lightweight presence heartbeat (called on a timer while the dashboard is open) + if (p === '/api/my/ping' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 }); + accounts.touchSeen(s.email).catch(() => {}); + return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) }); + } + // training center content (admin-curated via data/training.json) + if (p === '/api/training' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + let items = []; + try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {} + // a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15) + const scT = siteConfig(); const launched = scT.launchAt && Date.now() >= new Date(scT.launchAt).getTime(); // feature:'polhunter' waits for the launch moment (Marty, 2026-09-20) + items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL)) || (it.feature === 'polhunter' && launched)); + if (!items.length) items = [{ title: 'Getting started with InstantAdPay', + desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.', + docUrl: 'https://instantadpay.com/' }]; + return json(res, 200, { items }); + } + // daily login bonus (once/day, gentle streak) — granted after the login flow + if (p === '/api/my/login-bonus' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const cfg = siteConfig(); // comebackBonus (250) after comebackDays (7) away; 0 switches it off + return json(res, 200, await ads.grantLoginBonus(s.email, { comeback: cfg.comebackBonus == null ? 250 : Number(cfg.comebackBonus), comebackDays: cfg.comebackDays == null ? 7 : Number(cfg.comebackDays) })); + } + // -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL + // (anvil_setBalance, no key needed). Rehearsal-only, rate-limited. + if (p === '/api/my/faucet' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' }); + const b = await readBody(req); + const addr = String(b.address || '').trim().toLowerCase(); + if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' }); + // Amoy is a public testnet: testers fund their own connected wallet from + // the public Amoy faucet (no server-minted balance). We just echo the + // address + faucet link; the client copies the address and opens it. + let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {} + return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() }); + } + // -- report an ad (auto-approved ads need a safety valve): store + notify admin + if (p === '/api/report-ad' && req.method === 'POST') { + const b = await readBody(req); + if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' }); + const s = await auth.fromRequest(req); + const who = (s && s.email) || ''; + const rec = await reports.add(b.campaignId, who, b.reason, b.note); + try { + const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config + if (adminEmail && mailer.hasKey()) { + mailer.send(adminEmail, 'Ad reported on InstantAdPay (campaign #' + rec.campaignId + ')', + 'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason + + '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)') + + '\n\nPause or review it from the admin.').catch(() => {}); + } + } catch (e) {} + return json(res, 200, { ok: true }); + } + if (p === '/api/my/chat/send' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const me = s.email.toLowerCase(); + const b = await readBody(req); + const to = String(b.to || '').trim().toLowerCase(); + const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim(); + if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' }); + if (!text) return json(res, 400, { error: 'Write a message first.' }); + const target = await accounts.byEmail(to); + if (!target) return json(res, 404, { error: 'No such member.' }); + // authorize: existing thread, my direct sponsor, or someone in my downline + let ok = (await messages.thread(me, to, 0, 1)).length > 0; + if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); } + if (!ok) ok = await accounts.isDownlineOf(me, to); + if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' }); + if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me)) + return json(res, 403, { error: 'They are not accepting messages from you right now.' }); + const memberId = s.memberId || await auth.refreshMemberId(s); + const msg = await messages.sendChat(memberId, me, to, text); + // email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam) + try { + if (mailer.hasKey() && !chatOnline(target.lastSeen)) { + const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me); + const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0; + if (Date.now() - lastMineTs > 10 * 60 * 1000) { + const who = await accounts.byEmail(me); + const from = who && who.username ? '@' + who.username : 'someone in your InstantAdPay line'; + mailer.send(to, 'New message from ' + from, + text.slice(0, 400) + '\n\n— reply in your dashboard: https://instantadpay.com/my').catch(() => {}); + } + } + } catch (e) {} + return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } }); + } + if (p === '/api/my/chat/thread' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const me = s.email.toLowerCase(); + const other = String(u.searchParams.get('with') || '').trim().toLowerCase(); + const after = Number(u.searchParams.get('after')) || 0; + if (!other) return json(res, 400, { error: 'Who with?' }); + // may view a thread I'm party to (existing), or one I'm allowed to start + let ok = (await messages.thread(me, other, 0, 1)).length > 0; + if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); } + if (!ok) ok = await accounts.isDownlineOf(me, other); + if (!ok) return json(res, 403, { error: 'Not your conversation.' }); + const msgs = await messages.thread(me, other, after, 300); + await messages.markChatRead(me, other); + accounts.touchSeen(me).catch(() => {}); + const oa = await accounts.byEmail(other); + const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other); + const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me); + return json(res, 200, { + messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })), + otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false, + available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe, + canMute: await accounts.isDownlineOf(me, other) }); + } + if (p === '/api/my/chat/threads' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const list = await messages.threadList(s.email.toLowerCase()); + for (const t of list) { + const a = await accounts.byEmail(t.email); + t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false; + } + list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0)); + const meAcct = await accounts.byEmail(s.email); + return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true }); + } + if (p === '/api/my/chat/available' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available)); + } + if (p === '/api/my/chat/mute' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const target = String(b.email || '').trim().toLowerCase(); + if (!target) return json(res, 400, { error: 'Who?' }); + const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0; + if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' }); + return json(res, 200, await accounts.setMute(s.email, target, !!b.muted)); + } + // -- featured rotation: the live featured links + dilution stats + if (p === '/api/featured' && req.method === 'GET') { + const items = await ads.serveFeatured(viewerGeo(req)); + try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour) + const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]); + for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null); + return json(res, 200, { items }); + } + if (p === '/api/featured/stats' && req.method === 'GET') { + return json(res, 200, await ads.featuredStats()); + } + // -- QR code (SVG) for any InstantAdPay URL — used on bio/wall pages + if (p === '/api/qr' && req.method === 'GET') { + const data = String(u.searchParams.get('d') || '').slice(0, 300); + if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); } + try { + const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240, + color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning + res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' })); + return res.end(svg); + } catch (e) { res.writeHead(500, baseHeaders()); return res.end(); } + } + // -- profile: avatar + bio + if (p === '/api/my/profile-details' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim(); + if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar)) + return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' }); + const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600); + // socials: {platform: url}; keep only known platforms with valid https urls + let socials; + if (b.socials !== undefined) { + const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; + const clean = {}; + for (const p of PLAT) { + const v = String((b.socials && b.socials[p]) || '').trim(); + if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v; + } + // intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only + if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video)) + return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' }); + socials = Object.keys(clean).length ? JSON.stringify(clean) : null; + } + const r = await accounts.setProfile(s.email, avatar, bio, socials); + return json(res, r.error ? 400 : 200, r); + } + // -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers + if (p === '/api/my/wall-offers' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : []; + const out = []; + for (let i = 0; i < 2; i++) { + const o = src[i] || {}; + const targetUrl = String(o.targetUrl || '').trim(); + const bannerUrl = String(o.bannerUrl || '').trim(); + const title = String(o.title || '').trim().slice(0, 60); + if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' }); + if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' }); + out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null); + } + const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null); + return json(res, r.error ? 400 : 200, r); + } + // -- line banner: the member's viral slot on welcome tours + their wall + if (p === '/api/my/linebanner' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const target = String(b.targetUrl || '').trim(); + if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' }); + const fc = await frameCheck(target); // welcome tours frame it full screen + if (!fc.ok) return json(res, 400, { error: fc.reason }); + const banner = String(b.bannerUrl || '').trim(); + if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner)) + return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' }); + const r = await accounts.setLineBanner(s.email, banner || null, target); + return json(res, r.error ? 400 : 200, r); + } + // -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits + if (p === '/api/my/gauntlet' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false }); + const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl) + .map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member', + bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl })); + if (!slides.length) return json(res, 200, { pending: false }); + const token = crypto.randomBytes(16).toString('hex'); + gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length }); + return json(res, 200, { pending: true, slides, dwell: 10, token }); + } + if (p === '/api/my/gauntlet/complete' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = gauntletTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' }); + if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' }); + gauntletTokens.delete(s.email); + await ads.grantWelcome(s.email); + return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 }); + } + // -- public banner wall + m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m && req.method === 'GET') { + const tok = m[1].toLowerCase(); + let a = await accounts.byUsername(tok); + if (!a) a = await accounts.byCode(tok); + if (!a) return json(res, 404, { error: 'No wall under that name.' }); + const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member'; + let bc = 0; + if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} } + const unlocked = wallUnlockedFor(bc); + const offers = parseWallOffers(a); + // uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty) + const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl) + .map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member', + bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true })); + const adAds = getAdminWallAds(); let ai = 0; + const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'InstantAdPay', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || 'https://instantadpay.com/', admin: true }; }; + const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }]; + for (let i = 1; i < 3; i++) { + const o = offers[i - 1]; + if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; } + const u = ups.shift(); if (u) { ladder.push(u); continue; } + const h = houseAd(); if (h) ladder.push(h); + } + const finalLadder = ladder.slice(0, 3); + // the wall owner's achievement badge (their highest reached tier) + let badge = null; + if (a.memberId) { + const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark']; + badge = { img: '/badges/badge-' + t[0] + '.jpg?v=2', label: t[1] }; + } + const joinPath = '/join/' + (a.username || a.code); + let socials = null; try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} + return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), + avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials, badge, + joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent('https://instantadpay.com' + joinPath), ladder: finalLadder, unlocked, buyerCount: bc }); + } + // -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch + if (p === '/api/my/videos' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.videoStatus(s.email); + if (status.left <= 0) return json(res, 200, { ad: null, status }); + const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab + const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video + if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13) + let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {} + // this surface is empty but the other one may not be: the Watch tab holds the landscape + // videos and Shorts holds the portrait ones, and they share one daily cap, so a member + // who runs the tab dry still has clips waiting (Marty, 2026-09-22) + let otherFormat = null; + if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) { + const alt = orientation === 'landscape' ? 'portrait' : 'landscape'; + try { if (await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation: alt }, viewerGeo(req)))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {} + } + return json(res, 200, { ad: null, status, allWatched, otherFormat }); + } + const token = crypto.randomBytes(16).toString('hex'); + videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs }); + return json(res, 200, { ad, token, status }); + } + if (p === '/api/my/videowatch' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = videoTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' }); + const age = Date.now() - t.ts; + if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' }); + if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); } + videoTokens.delete(s.email); // single use + if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning + return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true }); + const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry + if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true }); + await ads.addEarned(s.email, tier.reward, { log: { kind: 'earn', note: 'Watched a video (' + tier.secs + 's)' } }); + await ads.markVideoSeen(s.email, t.id); + const status = await ads.recordVideoWatch(s.email); + return json(res, 200, { ok: true, credited: tier.reward, status }); + } + // -- verified visits: view a member's site (new tab) for the dwell, pass a + // human check, and it counts as one guaranteed unique visit for the pack + if (p === '/api/my/visits' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.visitStatus(s.email); + if (status.count >= status.cap) return json(res, 200, { ad: null, status }); + const ad = await ads.serveVisit(s.email, viewerGeo(req)); + if (!ad) return json(res, 200, { ad: null, status }); + const token = crypto.randomBytes(16).toString('hex'); + visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id }); + return json(res, 200, { ad, token, status }); + } + if (p === '/api/my/visitchallenge' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = visitTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' }); + const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); } + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/my/visitdone' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = visitTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' }); + const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; + if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' }); + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } + visitTokens.delete(s.email); + const r = await ads.completeVisit(s.email, t.id); + if (r.error) return json(res, 400, r); + return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) })); + } + // -- onsite solo ads: member inbox with read rewards + if (p === '/api/my/inbox' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.inboxList(s.email, viewerGeo(req)); + const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]); + for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId] + : i.fromMemberId ? 'member #' + i.fromMemberId : 'a member'; + return json(res, 200, r); + } + m = /^\/api\/my\/inbox\/(\d+)$/.exec(p); + if (m && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.inboxOpen(s.email, m[1]); + if (!r.error) { + const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {}; + r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId] + : r.fromMemberId ? 'member #' + r.fromMemberId : 'a member'; + } + return json(res, r.error ? 404 : 200, r); + } + // media upload for solo ads: raw body, size-capped, magic-byte verified + if (p === '/api/my/upload' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return handleUpload(req, res, s.email); + } + m = /^\/api\/my\/inbox\/(\d+)\/visit$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.markSoloVisit(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/inbox\/(\d+)\/claim$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.claimSoloRead(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/activity' && req.method === 'GET') { + const s = await auth.fromRequest(req); + 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(1e9); // whole history (was the last 600 events: older members saw three empty boxes) + return json(res, 200, { + memberId: id, + earnings: (await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id)).slice(0, 300))) + .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 + purchases: await attachNames(evs.filter(e => e.type === 'Purchase' && e.buyerId === id).slice(0, 300)), + referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id)).slice(0, 300)) + }); + } + + // -- ad engine (spec §8b v1: banners, text, login ads) + if (p === '/api/ads/slot' && req.method === 'GET') { + const t = String(u.searchParams.get('type') || 'banner'); + if (t === 'login') return json(res, 200, { ad: await loginAdFor(req, 'dashboard') }); + const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req))); + return json(res, 200, { ad }); + } + m = /^\/api\/ads\/click\/(\d+)$/.exec(p); + if (m && req.method === 'GET') { + // an advertiser opening their own ad's link (from Campaigns, a preview, a test) is not a click: relay it uncounted (Marty, 2026-09-30) + let own = false; + try { const s = await auth.fromRequest(req); if (s && s.email) { const cm = await ads.campaignById(m[1]); own = !!(cm && cm.owner && String(cm.owner).toLowerCase() === String(s.email).toLowerCase()); } } catch (e) {} + const target = own ? await ads.targetOf(m[1]) : await ads.click(m[1]); + if (!target) { res.writeHead(404, baseHeaders()); return res.end(); } + if (!own) coach.recordClick(m[1], req.headers.referer); // where the click happened + res.writeHead(302, baseHeaders({ Location: target })); + return res.end(); + } + if (p === '/api/my/trace' && req.method === 'GET') { // payment trace for yourself or anyone within 3 levels of you, either direction + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const mine = (await myMemberIds(s)).ids.filter(Boolean); + const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase(); + let target = /^\d+$/.test(who) ? Number(who) : 0; + if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (a && a.memberId) target = a.memberId; } + if (!target && !who && mine.length) target = mine[0]; + if (!target) return json(res, 400, { error: who ? 'No activated member called "' + who.slice(0, 40) + '". Use a member number or a username of someone who has bought a package.' : 'Enter a member number or username.' }); + if (!mine.length) return json(res, 403, { error: 'Link a wallet and buy a package first; the trace works on chain positions.' }); + const smap = sponsorMapFromIndex(chain.recentEvents(1e9)); + const ok = mine.includes(target) || uplineIds(smap, target, 3).some(x => mine.includes(x)) || mine.some(m => uplineIds(smap, m, 3).includes(target)); + if (!ok) return json(res, 403, { error: 'You can trace yourself, anyone up to 3 levels below you, and your own 3 uplines.' }); + return json(res, 200, await tracePurchases(target, 30)); + } + if (p === '/api/my/credits/activity' && req.method === 'GET') { // credit ledger: every earn and spend with a reason, newest first + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { items: await ads.creditActivity(s.email, 40) }); + } + if (p === '/api/my/campaigns' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const all = await ads.listCampaigns(s.email); + // archived ones keep their full stats but leave the working list (Marty, 2026-09-23) + const out = { campaigns: all.filter(c => c.status !== 'archived'), archived: all.filter(c => c.status === 'archived'), + rates: ads.rates(), bannerSizes: ads.bannerSizes() }; + const ids = all.map(c => c.id); // archived included: their numbers are the whole point of keeping them + out.clickSources = await coach.clickSources(ids); + out.hours = await ads.hoursFor(ids); // on-site views per UTC hour, last 7 days + out.geo = await ads.geoFor(ids); // on-site serves per viewer country + out.doorStats = await ads.doorStats(all.filter(c => c.type === 'visits').map(c => c.id)); // Spooky Doors: doors opened + unique players per pack + { const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; } + const pool = await ads.balances((await myMemberIds(s)).ids, s.email); + out.purchasedCredits = pool.total; + out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position + out.positionCount = pool.per.length; + out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits) + out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold + out.earnedReserved = pool.earnedReserved; + out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns + out.availableCredits = pool.available; + out.loginLine = await ads.loginQueueView(s.email); // login-ad slots: open now, the paid line, this member's places + estimated starts + return json(res, 200, out); + } + if (p === '/api/my/campaigns' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text + const b = await readBody(req); + if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player + if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } + const fc = await frameCheck(b.targetUrl); + if (!fc.ok) return json(res, 400, { error: fc.reason }); + } + if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } + { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } + { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } + // charge the best-funded of the member's positions (main + Qualified Start + // wallets). A campaign burns from one member id, so the budget must fit inside it. + const ids = (await myMemberIds(s)).ids; + const pool = await ads.balances(ids, s.email); + const fundId = pool.best.memberId || memberId; + const earnedNow = String(b.type) !== 'login' ? pool.earned : 0; + const budget = Math.floor(Number(b.budget) || 0); + if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow) + return json(res, 400, { error: 'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' }); + const r = await ads.createCampaign(s.email, fundId, b, ids); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const b = await readBody(req); + const positions = [memberId, ...(await accounts.positions(s.email).catch(() => [])).map(x => x.memberId)].filter(Boolean); + const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits, { positions, switchTo: Number(b.switchTo) || 0 }); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/extend$/.exec(p); // featured links: book more days (flat, charged now) + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const b = await readBody(req); + const r = await ads.extendFeatured(s.email, memberId, m[1], b.days); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/(archive|unarchive)$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = m[2] === 'archive' ? await ads.archive(s.email, m[1]) : await ads.unarchive(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active'); + return json(res, r.error ? 400 : 200, r); + } + // prepaid login-ad line (2026-10-23): cancel a reservation before it starts (full refund), or edit it for free + m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.cancelLoginReservation(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/edit-reservation$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + if (b.targetUrl !== undefined) { + const t = String(b.targetUrl || '').trim(); + { const sb = await sbcheck.check(t); if (!sb.ok) return json(res, 400, { error: sb.reason }); } + { const rc = await reach.check(t); if (!rc.ok) return json(res, 400, { error: rc.reason }); } + } + if (b.imageUrl) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } + const r = await ads.editLoginReservation(s.email, m[1], b); + return json(res, r.error ? 400 : 200, r); + } + + // -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL + if (p === '/api/admin/auth/start' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' }); + if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); + const k = 'admin:' + e; + const prev = emailCodes.get(k); + if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); + const code = String(Math.floor(100000 + Math.random() * 900000)); + emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); + if (mailer.hasKey()) { + try { await mailer.sendCode(e, code); } catch (err) { + console.error('admin sendCode failed', err.message); + return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); + } + return json(res, 200, { ok: true, sent: true }); + } + if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); + return json(res, 503, { error: 'Email sign-in is not configured yet.' }); + } + if (p === '/api/admin/auth/verify' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + const k = 'admin:' + e; + const rec = emailCodes.get(k); + if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); + rec.tries += 1; + if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } + if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); + emailCodes.delete(k); + if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); + const token = mintAdminSession(e); + return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) }); + } + if (p === '/api/admin/auth/logout' && req.method === 'POST') { + dropAdminSession(req); + return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() }); + } + if (p === '/api/admin/me' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 200, { admin: false }); + return json(res, 200, { admin: true, email: ADMIN_EMAIL }); + } + // -- level-4 override (2026-10-17 dry run, payer 2026-10-23): ?week=YYYY-MM-DD (any day in the week) or ?from=&to= (ms); rows=1 adds + // every purchase. The answer carries the week's payout status (not planned / planning / planned / paying / held / paid, rows + // pending / sending / sent / paid / carried / rolled / review / failed) and the payer state (mode, ready, address, balance). + 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' }); + } + // "pay this week now": only when the live payer is ready; settles every closed week up to the one asked, in order + 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 })); + } + // a stuck row (review / failed): 'carry' after checking the payer wallet shows nothing went out, or 'paid' with the verified tx + 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); + } + // -- help desk, admin side (2026-10-16): the Support pane + if (p === '/api/admin/support/telegram/register' && req.method === 'POST') { // point @CTBTickets_bot's webhook at this server + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await supportbot.register('https://instantadpay.com/api/telegram/support')); + } + if (p === '/api/admin/support' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, Object.assign(await tickets.adminList({ status: u.searchParams.get('status'), platform: u.searchParams.get('platform'), category: u.searchParams.get('category'), q: u.searchParams.get('q') }), + { categories: tickets.CATEGORIES, platforms: tickets.PLATFORMS })); + } + if (p === '/api/admin/support/counts' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await tickets.counts()); + } + if (p === '/api/admin/support/templates' && (req.method === 'GET' || req.method === 'PUT')) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const read = () => { const v = siteConfig().supportTemplates; let a = v; if (typeof v === 'string') { try { a = JSON.parse(v); } catch (e) { a = null; } } return Array.isArray(a) && a.length ? a : tickets.DEFAULT_TEMPLATES; }; + if (req.method === 'GET') return json(res, 200, { templates: read() }); + const b = await readBody(req); + const list = (Array.isArray(b.templates) ? b.templates : []).map(t => ({ name: String((t && t.name) || '').trim().slice(0, 60), body: String((t && t.body) || '').trim().slice(0, 3000) })).filter(t => t.name && t.body).slice(0, 30); + const cur = siteConfig(); cur.supportTemplates = list; fs.writeFileSync(SITE_FILE, JSON.stringify(cur, null, 2)); + return json(res, 200, { ok: true, templates: read() }); + } + // -- the assistant's knowledge base (2026-10-20, kb.js): Admin > Knowledge base, and "Save as KB entry" on a ticket reply + if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' }); + const r = await kb.create(await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/kb/test' && req.method === 'POST') { // which entry would answer this question, and what would ride along to the AI + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, await kb.test(b.question)); + } + m = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p); + if (m) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') { const e = await kb.get(m[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); } + if (req.method === 'PUT') { const r = await kb.update(m[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); } + if (req.method === 'DELETE') { const r = await kb.remove(m[1]); return json(res, r.error ? 404 : 200, r); } + return json(res, 405, { error: 'method' }); + } + m = /^\/api\/admin\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); + if (m) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const t = await tickets.byRef(m[1]); + if (!t) return json(res, 404, { error: 'Ticket not found.' }); + if (m[2] && req.method === 'POST') { const b = await readBody(req); const r = await tickets.addMessage(t.id, { author: 'admin', body: b.body, internal: !!b.internal, status: b.status, attachments: b.attachments }); if (r.error) return json(res, 400, r); } + else if (!m[2] && req.method === 'PATCH') { const r = await tickets.setFields(t.id, await readBody(req)); if (r.error) return json(res, 400, r); } + else if (m[2] || req.method !== 'GET') return json(res, 405, { error: 'method' }); + const v = await tickets.adminView(t.id); + const a = await accounts.byEmail(v.ticket.email); + v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email }; + return json(res, 200, v); + } + if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, refill.stats()); + } + if (p === '/api/admin/refill/reset' && req.method === 'POST') { // re-decide conversions under a corrected rule + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, refill.resetConversions(Array.isArray(b.kinds) ? b.kinds : null)); + } + if (p === '/api/admin/refill/run' && req.method === 'POST') { // send the next batch now instead of waiting for the tick + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await refill.tick()); + } + if (p === '/api/admin/overview' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const camps = await ads.adminList(); + const byStatus = {}, byType = {}; + for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; } + let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {} + const cc = chain.getConfig(); + return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length, + house: camps.filter(c => c.house).length, byStatus, byType, + openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length, + followups: await drip.stats(), + chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer }, + site: siteConfig(), rates: ads.rates() }); + } + if (p === '/api/admin/members' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const members = await accounts.listAll(5000, { shells: true }); // waiting LinkSpin accounts included (2026-10-15); was 500: older members (igor147, joined 09-12) vanished from the table and its search once the site passed 500 accounts (Marty, 2026-09-29) + // resolve each sponsor token (username, share code or member #) to the sponsor's name + // the lookup covers EVERY account, not the page's slice: built from `members` it called every + // sponsor who joined before the newest 500 a dead link (144 of them, Marty 2026-09-23) + const byTok = {}; + for (const m of await accounts.identities()) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m; + for (const m of members) { + const t = String(m.sponsorRef || '').toLowerCase(); + const sp = t ? byTok[t] : null; + m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null; + m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : ''); + } + for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } } + for (const m of members) { try { const sg = await fraud.get(m.email); m.flags = sg ? sg.flags : []; m.suspended = !!(sg && sg.suspended); m.lastIp = sg ? sg.lastIp : ''; } catch (e) { m.flags = []; m.suspended = false; } } + return json(res, 200, { members }); + } + if (p === '/api/admin/members' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + if (!b.email) return json(res, 400, { error: 'Which member?' }); + if (b.suspend !== undefined) { // anti-fraud switch: suspended accounts cannot sign in; flags keep them off the leaderboard and out of adoptions + if (b.suspend) await fraud.suspend(b.email, b.reason || 'duplicate account'); else await fraud.unsuspend(b.email); + if (b.flags) await fraud.addFlags(b.email, [].concat(b.flags)); + return json(res, 200, { ok: true, signals: await fraud.get(b.email) }); + } + if (b.flags !== undefined) { const f = b.flags === null ? (await fraud.clearFlags(b.email), []) : await fraud.addFlags(b.email, [].concat(b.flags)); return json(res, 200, { ok: true, flags: f }); } + const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to LinkSpin until bound + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/fraud' && req.method === 'GET') { // duplicate signals: shared browsers / IPs, flagged and suspended accounts + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, Object.assign(await fraud.report(), { allow: fraud.allowList(), block: fraud.blockList() })); + } + // Approved exceptions: people Marty has okayed to hold more than one account. Adding an + // address here stops the duplicate checks blocking or hard-flagging them, and stops them + // being dropped from the leaderboard or barred from adopting. + if (p === '/api/admin/fraud/block' && req.method === 'POST') { + const b = await readBody(req); + const r = b.remove ? fraud.blockRemove(b.email) : fraud.blockAdd(b.email, b.note, ADMIN_EMAIL || 'admin'); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/fraud/allow' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = b.remove ? fraud.allowRemove(b.email) : fraud.allowAdd(b.email, b.note, ADMIN_EMAIL || 'admin'); + if (r.error) return json(res, 400, r); + console.log('fraud exception ' + (b.remove ? 'removed' : 'added') + ': ' + String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); + return json(res, 200, r); + } + // stop a member's campaign for good (2026-10-04, Marty: Shift AI closed, stop its ads): pause it on every rail, then archive it. + // Reserved budget is computed from active/paused campaigns, so archiving releases the unspent remainder to the member at + // once; flat up-front buys (visit packs) are refunded separately through /api/admin/member grantCredits. + if (p === '/api/admin/campaign/stop' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); const c = await ads.campaignById(Number(b.id)); if (!c) return json(res, 404, { error: 'No such campaign.' }); + const owner = c.owner || c.ownerEmail || c.owner_email; + if (c.status === 'active') { const r = await ads.setStatus(owner, c.id, 'paused'); if (r && r.error) return json(res, 400, r); } + const a = (c.status === 'archived') ? { ok: true, already: true, freed: 0 } : await ads.archive(owner, c.id); + console.log('admin stop campaign', c.id, owner, String(b.reason || '').slice(0, 80), JSON.stringify({ freed: a.freed })); + return json(res, a.error ? 400 : 200, Object.assign({ id: c.id, owner }, a)); + } + if (p === '/api/admin/login-queue' && req.method === 'GET') { // the prepaid login-ad line, oldest paid first (2026-10-23) + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await ads.adminLoginQueue()); + } + m = /^\/api\/admin\/login-queue\/(\d+)\/cancel$/.exec(p); + if (m && req.method === 'POST') { // admin cancel = the same full refund the owner would get + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await ads.cancelLoginReservation(null, m[1], { admin: true }); + if (!r.error) console.log('admin cancelled login reservation', r.id, String(r.owner || '').replace(/^(.).*(@.*)$/, '$1***$2'), 'refunded', r.refunded); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/campaigns' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER }); + } + if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + // A house video was never checked: videoCheck guarded the member path only, so a bad + // source pasted here would hand every viewer a black player exactly as #146 did. + if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } + { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } + { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } + if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { + if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } + const fc = await frameCheck(b.targetUrl); + if (!fc.ok) return json(res, 400, { error: fc.reason }); + } + const r = await ads.createHouseCampaign(b); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active'); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await audit.run()); + } + if (p === '/api/admin/sponsor-resolve' && req.method === 'GET') { // support: where would a buy under ?ref= land right now? + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const ref = String(u.searchParams.get('ref') || '').trim(); + const detailed = await resolveSponsorDetailed(ref); + const walk = detailed.reason === 'notActivated' ? await walkUpActivatedSponsor(ref) : null; + return json(res, 200, { ref, detailed, walk, catchId: Number(siteConfig().defaultSponsorId) || 1 }); + } + if (p === '/api/admin/trace' && req.method === 'GET') { // payment trace for any member + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const who = String(u.searchParams.get('who') || '').trim().replace(/^[@#]/, '').toLowerCase(); + let target = /^\d+$/.test(who) ? Number(who) : 0; + if (!target && who) { let a = await accounts.byUsername(who); if (!a) a = await accounts.byCode(who); if (!a && who.includes('@')) a = await accounts.byEmail(who); if (a && a.memberId) target = a.memberId; } + if (!target) return json(res, 400, { error: 'No activated member matches "' + who.slice(0, 40) + '".' }); + return json(res, 200, await tracePurchases(target, 60)); + } + if (p === '/api/admin/chain/rescan' && req.method === 'POST') { // rebuild the full event history from the deploy block + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await chain.rescan()); + } + if (p === '/api/admin/chain/status' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { events: chain.eventCount(), historyComplete: chain.historyComplete(), totals: chain.totals() }); + } + if (p === '/api/admin/reports' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { reports: await reports.list(200) }); + } + m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p); + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await reports.resolve(m[1])); + } + if (p === '/api/admin/upload' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return handleUpload(req, res, 'admin'); + } + if (p === '/api/admin/rates' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { rates: ads.rates() }); + } + if (p === '/api/admin/drip' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() }); + } + if (p === '/api/admin/drip' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' }); + if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' }); + try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); } + catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); } + } + // wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists + if (p === '/api/admin/wall-ads' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {} + return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length }); + } + if (p === '/api/admin/wall-ads' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : []; + const out = []; + for (const o of src) { + const name = String((o && o.name) || '').trim().slice(0, 60); + const targetUrl = String((o && o.targetUrl) || '').trim(); + const bannerUrl = String((o && o.bannerUrl) || '').trim(); + if (!targetUrl) continue; + if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' }); + if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' }); + out.push({ name: name || 'InstantAdPay', targetUrl, bannerUrl: bannerUrl || null }); + } + const file = path.join(DATA_DIR, 'admin-wall-ads.json'); + if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} } + return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length }); + } + // -- growth snapshot: preview the post, or send it now + if (p === '/api/admin/snapshot' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { text: await snapshot.preview() }); + } + if (p === '/api/admin/snapshot/send' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r); + } + // -- 1,000-member drop: view, mode (off|dry|armed via site config), snapshot now, pay now, resend the missed-it notices, reset (only before any payment) + if (p === '/api/admin/milestone') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') return json(res, 200, await milestone.view()); + const b = await readBody(req); const act = String(b.action || ''); + if (act === 'mode') { const m = ['off', 'dry', 'armed'].includes(b.mode) ? b.mode : 'off'; const cur = siteConfig(); fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, { milestoneMode: m }, b.target ? { milestoneTarget: Number(b.target) } : {}, b.pol ? { milestonePol: Number(b.pol) } : {}), null, 2)); return json(res, 200, await milestone.view()); } + if (act === 'snapshot') { await milestone.snapshot(!!b.force); return json(res, 200, await milestone.view()); } + if (act === 'recheck') { await milestone.recheck(); return json(res, 200, await milestone.view()); } + if (act === 'pay') { const r = await milestone.pay(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } + if (act === 'settle') { await milestone.settle(); return json(res, 200, await milestone.view()); } + if (act === 'notify-missed') { const r = await milestone.notifyMissed(); return json(res, 200, Object.assign({ result: r }, await milestone.view())); } + if (act === 'reset') { const v = await milestone.view(); if (v.paid || v.sent) return json(res, 400, { error: 'Payments exist; the record stays.' }); milestone.reset(); return json(res, 200, await milestone.view()); } + return json(res, 400, { error: 'Unknown action.' }); + } + if (p === '/api/admin/site' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { site: siteConfig() }); + } + // -- profit and loss from the chain index: volume, platform fees, member payouts, + // pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee + // wallets' live balances and an admin-entered fixed monthly cost + if (p === '/api/admin/pnl' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const hunt = await huntLedger(); // marketing spend that never touches this contract + let gamesAll = null; try { gamesAll = await gamestats.allTime(); } catch (e) { gamesAll = { error: e.message }; } // every game wallet's payouts, all time, from Polygon + const days = Math.max(0, Number(u.searchParams.get('days') || 30)); + let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {} + const fromBlock = days ? latest - Math.round(days * 43200) : 0; + const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock); + const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n); + const pol = wei => Number(BigInt(wei) / 10n ** 12n) / 1e6; // 6-decimal POL, no float drift + const purchases = evs.filter(e => e.type === 'Purchase'); + const tier = evs.filter(e => e.type === 'TierPaid'); + const admin = evs.filter(e => e.type === 'AdminPaid'); + const passed = evs.filter(e => e.type === 'PassedUp'); + const byTier = {}; + for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString(); + const byPkg = {}; + for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; } + let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} + const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null }; + const balances = {}; + for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } } + return json(res, 200, { days, fromBlock, latest, polUsd, + purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg }, + platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier, + passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length }, + wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status(), polhunter: hunt, gamesAll, + // hand-entered movements in and out of the receivers: draws the chain cannot explain, and + // outside income (a ClickBaitPays withdrawal, say) that is not an AdminPaid event + ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'), + reconcile: ledger.reconcile(pol(sum(admin, e => e.amountWei)), pol(BigInt(balances.feeA || '0')), 'feeA') } }); + } + // tax summary (2026-10-04, Marty: "show what I spent in advertising versus income" at tax time). Income = the platform's cut + // of every package sale (AdminPaid), valued in dollars at that sale's own price (Purchase.priceCents / paidWei in the same + // transaction), minus sales to Marty's own positions (site config ownMemberIds, default "1": his own money moving around is + // not income), plus outside revenue lines. Costs = ledger 'cost' lines by category. Draws and transfers are listed apart: + // they are owner money, not expenses. Dates are the blocks' REAL timestamps (2026-10-04: a 2-second-per-block + // estimate drifted weeks and put September sales in August), read once from the chain and kept in DATA_DIR/blocktimes.json. + if (p === '/api/admin/tax' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const year = String(Number(u.searchParams.get('year')) || new Date().getFullYear()); + const own = new Set(String(siteConfig().ownMemberIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean)); + const evs = chain.recentEvents(1e9); + const bt = blockTimes(); const need = Array.from(new Set(evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).map(e => e.block))); + for (let i = 0; i < need.length; i += 8) await Promise.all(need.slice(i, i + 8).map(async blk => { try { const b = await chain.rpc('eth_getBlockByNumber', ['0x' + blk.toString(16), false]); if (b && b.timestamp) bt[blk] = parseInt(b.timestamp, 16) * 1000; } catch (e) {} })); + if (need.length) saveBlockTimes(bt); + const missing = evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).length; + if (missing) return json(res, 503, { error: missing + ' sale dates could not be read from the chain right now. Try again in a minute.' }); + const dayOf = blk => new Date(bt[blk]).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); + const buys = new Map(); for (const e of evs) if (e.type === 'Purchase') buys.set(e.tx, e); + const months = {}; let incomeUsd = 0, incomePol = 0, ownUsd = 0, sales = 0; + for (const e of evs) { + if (e.type !== 'AdminPaid') continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; + const b = buys.get(e.tx); const pol = Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6; + const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0; + if (own.has(Number(e.buyerId))) { ownUsd += usd; continue; } + incomeUsd += usd; incomePol += pol; sales++; const m = day.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; months[m].incomeUsd += usd; + } + const lines = ledger.entriesFor(year); let outsideUsd = 0; const costs = {}; const draws = []; const transfers = []; + for (const l of lines) { + const m = l.date.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; + if (l.kind === 'revenue') { outsideUsd += l.usd; months[m].incomeUsd += l.usd; } + else if (l.kind === 'cost') { const c = l.category || 'other', v = l.dir === 'out' ? l.usd : -l.usd; costs[c] = (costs[c] || 0) + v; months[m].costUsd[c] = (months[m].costUsd[c] || 0) + v; } + else if (l.kind === 'draw') draws.push(l); else transfers.push(l); + } + const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.games || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0); + const csv = [['Section', 'Date', 'Category', 'Description', 'POL', 'USD', 'Transaction'].join(',')]; + const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"'; + for (const e of evs) { if (e.type !== 'AdminPaid' || own.has(Number(e.buyerId))) continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; const b = buys.get(e.tx); + const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0; + csv.push(['Income', day, 'Platform share of package sale', 'Member #' + e.buyerId + (b ? ' bought the $' + Math.round(b.priceCents / 100) + ' package' : ''), (Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6).toFixed(6), usd.toFixed(2), e.tx].map(q).join(',')); } + for (const l of lines) { const sec = l.kind === 'revenue' ? 'Income' : l.kind === 'cost' ? 'Expense' : l.kind === 'draw' ? 'Owner draw (not an expense)' : 'Transfer (not income or expense)'; + csv.push([sec, l.date, l.kind === 'cost' ? (ledger.CATS[l.category] || l.category) : l.kind, l.note, (l.dir === 'out' ? -1 : 1) * l.amount, (l.kind === 'cost' && l.dir === 'out' ? -1 : 1) * l.usd, l.tx].map(q).join(',')); } + csv.push(''); csv.push(q('Sale dates are the Polygon block timestamps, in US Central time. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out. USD values are each sale\'s own package price.')); + return json(res, 200, { year, ownMemberIds: Array.from(own), + income: { platformUsd: r2(incomeUsd), platformPol: Math.round(incomePol * 1e4) / 1e4, sales, outsideUsd: r2(outsideUsd), totalUsd: r2(incomeUsd + outsideUsd), ownSalesExcludedUsd: r2(ownUsd) }, + expenses: { byCategory: Object.fromEntries(Object.entries(costs).map(([k, v]) => [k, r2(v)])), labels: ledger.CATS, advertisingAndPromotionUsd: r2(adPromo), totalUsd: r2(allCosts) }, + netUsd: r2(incomeUsd + outsideUsd - allCosts), draws: draws.length, transfers: transfers.length, + months: Object.fromEntries(Object.keys(months).sort().map(k => [k, { incomeUsd: r2(months[k].incomeUsd), costUsd: r2(Object.values(months[k].costUsd).reduce((n, v) => n + v, 0)) }])), + csv: csv.join('\n') }); + } + if (p === '/api/admin/ledger' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = ledger.put(b); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/ledger/delete' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = ledger.remove(String(b.id || '')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/videosweep' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, await videosweep.run({ dry: !!b.dry })); + } + if (p === '/api/admin/sbcheck' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, await sbcheck.run({ dry: !!b.dry })); + } + if (p === '/api/admin/burner' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, burner.status()); + } + if (p === '/api/admin/burner/run' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await burner.tick()); + } + + // -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session) + if (p === '/api/admin/burns' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { pending: await ads.pendingBurns() }); + } + if (p === '/api/admin/burns/mark' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await ads.markBurned(b.id, b.tx); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/rates' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, { ok: true, rates: ads.setRates(b) }); + } + + if (p === '/api/admin/site' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const cur = siteConfig(); + fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2)); + return json(res, 200, { ok: true, site: siteConfig() }); + } + if (p === '/api/admin/chain' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const file = path.join(DATA_DIR, 'config.json'); + let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {} + fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2)); + chain.reloadConfig(); + return json(res, 200, { ok: true, config: chain.getConfig() }); + } + + // -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body) + if (req.method === 'GET' || req.method === 'HEAD') { + if (p === '/') { + // arrived from PolHunter: remember it for 30 days so the dashboard can send them back once a wallet is linked + if (u.searchParams.get('from') === 'polhunter') { res.writeHead(302, { Location: '/', 'Set-Cookie': 'iap.return=polhunter; Path=/; SameSite=Lax; Max-Age=' + (30 * 24 * 3600) + (IS_PROD ? '; Secure' : ''), 'Cache-Control': 'no-store' }); return res.end(); } + return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); + } + if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html')); + if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html')); + if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html')); + if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html')); + if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html')); + if (p === '/facts') return sendFile(res, path.join(PUBLIC_DIR, 'facts.html')); // verified platform facts (2026-10-06), linked from every footer + if (p === '/llms.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(fs.readFileSync(path.join(PUBLIC_DIR, 'llms.txt'))); } + if (p === '/my') return sendFile(res, path.join(PUBLIC_DIR, 'my.html')); + if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); + if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html')); + if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html')); + if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12) + if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); + if (p === '/games') return sendFile(res, path.join(PUBLIC_DIR, 'games.html')); + if (p === '/presentation') return sendFile(res, path.join(PUBLIC_DIR, 'presentation.html')); // narrated Build Wide presentation, captions in 6 languages (2026-10-15) // public games list (2026-10-10) // member guide: how earning works (2026-09-12) + // -- badge share page + image: /b// (OG preview = the member's composed badge) (Marty, 2026-09-13) + m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p); + if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg')); + m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p); + if (m) { + const un = m[1].toLowerCase(), key = m[2]; + const a = await accounts.byUsername(un); + const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg'); + if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const [label, sub] = BADGE_META[key]; + const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const url = 'https://instantadpay.com/b/' + un + '/' + key, img = 'https://instantadpay.com/badge-img/' + un + '/' + key + '.jpg'; + const title = '@' + un + ' unlocked ' + label + ' on InstantAdPay'; + const desc = label + ': ' + sub + '. InstantAdPay pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.'; + const html = '' + esc(title) + '' + + '' + + '' + + '' + + '' + + '' + + '
      ' + esc(label) + ' badge for @' + esc(un) + '

      @' + esc(un) + ' unlocked ' + label + '

      ' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

      ' + + 'Join @' + esc(un) + '\u2019s line free

      Advertising with a performance referral program. Not an investment; no income is guaranteed.

      ' + + ''; + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); + return res.end(html); + } + // -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12) + if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) { + const posts = await blog.listPublished(); + const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1; + const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null; + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); + return res.end(blog.renderIndex(posts, pg, tag)); + } + m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p); + if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); } + if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); } + if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); } + if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); } + if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); } + if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); } + m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p); + if (m) { + const post = await blog.get(m[1]); + const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL + if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('', '<title>Not found | ')); } + if (!preview && req.method === 'GET') blog.bumpViews(post.slug); + const related = blog.relatedFor(post, await blog.listPublished()); + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' })); + return res.end(blog.renderPost(post, related)); + } + if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html')); + if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link + if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html')); + if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html')); + if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Drip Runner refuel visit (2026-09-30) + if (p === '/door') return sendFile(res, path.join(PUBLIC_DIR, 'door.html')); // Spooky Doors door visit (2026-10-02) + // per-partner kit pages (Marty, 2026-09-29): /partners/<slug> serves public/kits/<slug>.html, one file per reviewer or site owner + { const mk = p.match(/^\/partners\/([a-z0-9-]{2,40})$/); if (mk) { const f = path.join(PUBLIC_DIR, 'kits', mk[1] + '.html'); if (fs.existsSync(f)) return sendFile(res, f); } } + if (p === '/plan-lab') return sendFile(res, path.join(PUBLIC_DIR, 'plan-lab.html')); // Reach Ladder simulator for Marty's planning group: unlisted, shared by link (2026-09-27) + if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html')); + if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html')); + m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p); + if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1])); + if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html')); + m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS) + try { + const tok = m[1].toLowerCase(); + let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok); + let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8'); + if (a) { + const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0); + const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const title = nm + ' on InstantAdPay'; + const desc = a.bio ? esc(a.bio).slice(0, 200) : 'Join ' + nm + '’s line on InstantAdPay — instant on-chain ad payouts, free to join.'; + const img = a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : 'https://instantadpay.com/banners/iap-hero-1200x630.png'; + const url = 'https://instantadpay.com/wall/' + (a.username || a.code); + const og = [ + '<meta property="og:type" content="profile">', + '<meta property="og:site_name" content="InstantAdPay">', + '<meta property="og:url" content="' + url + '">', + '<meta property="og:title" content="' + esc(title) + '">', + '<meta property="og:description" content="' + desc + '">', + '<meta property="og:image" content="' + esc(img) + '">', + '<meta name="twitter:card" content="summary_large_image">', + '<meta name="twitter:title" content="' + esc(title) + '">', + '<meta name="twitter:description" content="' + desc + '">', + '<meta name="twitter:image" content="' + esc(img) + '">', + '<meta name="description" content="' + desc + '">', + '<link rel="canonical" href="' + url + '">' + ].join('\n'); + html = html.replace('<title>Banner wall | InstantAdPay', '' + esc(title) + '').replace('', og); + } + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); + return res.end(html); + } catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); } + } + const safe = path.normalize(p).replace(/^([.\\/])+/, ''); + const file = path.join(PUBLIC_DIR, safe); + if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file); + } + + res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); + res.end('Not found'); + } catch (e) { + console.error('request error', req.url, e.message); + try { json(res, 500, { error: 'server error' }); } catch (_) {} + } +}); +boot().then(() => { + server.listen(PORT, () => console.log(`InstantAdPay site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}`)); +}).catch(e => { console.error('boot failed:', e.message); process.exit(1); });