diff --git a/gamestats.js b/gamestats.js new file mode 100644 index 0000000..3ed5653 --- /dev/null +++ b/gamestats.js @@ -0,0 +1,58 @@ +// Game figures for the daily snapshot (Marty 2026-10-08: one card for the whole ecosystem, games as their own block). +// Two live sources, no estimates: +// players sent in — counted here every time InstantAdPay hands a member into a game (/api/my/), per UTC hour, +// so "last 24 h" is exact and survives restarts (DATA_DIR/game-handoffs.json) +// payouts + POL — read from Polygon: outgoing transfers from each game's payout wallet in the last 24 h (Etherscan v2, +// the same query the hourly wallet watcher on core uses). Our own wallets and the fee wallets are skipped. +// Env: GAME_WALLETS = "slug:0x…,slug:0x…" (set from the /root/.-address files on core), ETHERSCAN_KEY. +'use strict'; +const fs = require('fs'); +const path = require('path'); + +let R = null; +const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip' }; +const wallets = () => Object.fromEntries(String(process.env.GAME_WALLETS || '').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [k, a] = x.split(':'); return [String(k).toLowerCase(), String(a || '').toLowerCase()]; }).filter(([k, a]) => k && /^0x[0-9a-f]{40}$/.test(a))); +const KEY = () => String(process.env.ETHERSCAN_KEY || '').trim(); +// money never flows to these from a game wallet as a payout: Marty's fee wallets, the other game wallets +const SKIP = () => new Set(['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', '0xcbe203312e0ea3b542da7a2e7f0a8a09db948f75'].concat(Object.values(wallets()))); +const FILE = () => path.join(R.dataDir, 'game-handoffs.json'); +function load() { try { return JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { return {}; } } +function init(deps) { R = deps; } +const hourKey = t => new Date(t || Date.now()).toISOString().slice(0, 13); +// a member was handed into a game: one tick in this hour's bucket (buckets older than 3 days are dropped) +function handoff(slug) { + try { + const h = load(), k = hourKey(); h[k] = h[k] || {}; h[k][slug] = (h[k][slug] || 0) + 1; + const cut = hourKey(Date.now() - 3 * 86400000); for (const key of Object.keys(h)) if (key < cut) delete h[key]; + fs.writeFileSync(FILE(), JSON.stringify(h)); + } catch (e) { /* counting must never break a hand-off */ } +} +function sentIn(since) { const h = load(), out = {}; const k0 = hourKey(since); for (const [k, m] of Object.entries(h)) if (k >= k0) for (const [slug, c] of Object.entries(m)) out[slug] = (out[slug] || 0) + c; return out; } +// outgoing payouts from one game wallet since `since` (ms): { count, wei } +async function payoutsFor(addr, since) { + const out = { count: 0, wei: 0n }; if (!KEY()) return out; + const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=0&endblock=99999999&sort=desc&page=1&offset=500&apikey=' + KEY(); + const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json(); const rows = Array.isArray(j.result) ? j.result : []; + const skip = SKIP(), sinceS = Math.floor(since / 1000); + for (const x of rows) { + if (Number(x.timeStamp) < sinceS) break; // sorted newest first + if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue; + if (skip.has(String(x.to).toLowerCase())) continue; + out.count++; out.wei += BigInt(x.value); + } + return out; +} +// everything the card needs: per game and totals, last 24 h +async function gather(since) { + const W = wallets(), sent = sentIn(since), games = []; + const slugs = new Set([...Object.keys(W), ...Object.keys(sent)]); + for (const slug of slugs) { + const g = { slug, name: NAMES[slug] || slug, sentIn: sent[slug] || 0, payouts: 0, wei: 0n, error: null }; + if (W[slug]) { try { const p = await payoutsFor(W[slug], since); g.payouts = p.count; g.wei = p.wei; } catch (e) { g.error = e.message; } } + games.push(g); + } + games.sort((a, b) => (b.sentIn - a.sentIn) || (Number(b.wei - a.wei))); + const totals = games.reduce((t, g) => ({ sentIn: t.sentIn + g.sentIn, payouts: t.payouts + g.payouts, wei: t.wei + g.wei }), { sentIn: 0, payouts: 0, wei: 0n }); + return { games, totals, chainChecked: !!KEY() && Object.keys(W).length > 0 }; +} +module.exports = { init, handoff, gather, NAMES }; diff --git a/server.js b/server.js index 652eecb..edb8028 100644 --- a/server.js +++ b/server.js @@ -40,6 +40,7 @@ const videosweep = require('./videosweep'); const sbcheck = require('./sbcheck'); const reach = require('./reach'); const lssync = require('./lssync'); +const gamestats = require('./gamestats'); const marks = require('./marks'); 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'); @@ -506,7 +507,8 @@ async function boot() { coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); badge.init({ publicDir: PUBLIC_DIR }); - snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, 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 }); @@ -2928,7 +2930,7 @@ const server = http.createServer(async (req, res) => { 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') { + 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(); } @@ -2949,7 +2951,7 @@ const server = http.createServer(async (req, res) => { 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') { + 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.' }); @@ -2986,7 +2988,7 @@ const server = http.createServer(async (req, res) => { console.log('polywarriors weekly prize', k, acct.email, credits); return json(res, 200, { ok: true, credits }); } - if (p === '/api/my/polywarriors' && req.method === 'GET') { + 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.' }); @@ -2995,7 +2997,7 @@ const server = http.createServer(async (req, res) => { 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/spellwheel' && req.method === 'GET') { + 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.' }); @@ -3004,7 +3006,7 @@ const server = http.createServer(async (req, res) => { 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') { + 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.' }); @@ -3013,7 +3015,7 @@ const server = http.createServer(async (req, res) => { res.writeHead(302, { Location: SEEK_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') { + 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); @@ -3129,7 +3131,7 @@ const server = http.createServer(async (req, res) => { 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') { + 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); @@ -3141,7 +3143,7 @@ const server = http.createServer(async (req, res) => { 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') { + 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(); } diff --git a/snapshot.js b/snapshot.js index a97c68e..44c52c7 100644 --- a/snapshot.js +++ b/snapshot.js @@ -1,194 +1,206 @@ -// Growth snapshot (Marty, 2026-09-15): once a day, a short "how the site is doing" post in the Telegram -// payments feed (and the shared payments topic), so members watching the payout lines also see the -// whole picture: sign-ups, purchases, POL paid out, campaigns posted, ads viewed. Every number comes -// from the same tables and chain index the dashboards read. Settings: snapshotEnabled (1/0), -// snapshotHourUtc (default 14 = 9 AM Central), snapshotTargets (feed,echo). State: snapshot-state.json. -const fs = require('fs'); -const path = require('path'); - -let X = {}; -const DAY = 86400000; -function init(opts) { X = opts || {}; } -const STATE = () => path.join(X.dataDir, 'snapshot-state.json'); -function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return {}; } } -function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} } -const n = v => Number(v || 0).toLocaleString('en-US'); -const pol = w => { try { return (Number(BigInt(w) / (10n ** 16n)) / 100).toLocaleString('en-US', { maximumFractionDigits: 0 }); } catch (e) { return '0'; } }; - -async function gather(now = Date.now()) { - const since = now - DAY, prior = now - 2 * DAY; - const s = { signups: 0, signupsPrior: 0, members: 0, wallets: 0, payoutsOn: 0, seen24h: 0, - campaigns: 0, advertisers: 0, active: 0, activeAdvertisers: 0, imps: 0, viewers: 0, views: 0, - buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0, - creditsHandedOut: 0, creditsEarned: 0, creditsSpent: 0 }; - if (X.db && X.db.enabled()) { - const q = (a, b) => X.db.q(a, b || []); - const a = (await q('SELECT COUNT(*) total, SUM(created>=?) s24, SUM(created>=? AND created0) payouts, SUM(last_seen>=?) seen FROM accounts', [since, prior, since, since]))[0] || {}; - s.members = Number(a.total || 0); s.signups = Number(a.s24 || 0); s.signupsPrior = Number(a.sPrior || 0); s.wallets = Number(a.wallet || 0); s.payoutsOn = Number(a.payouts || 0); s.seen24h = Number(a.seen || 0); - const c = (await q('SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND created>=?', [since]))[0] || {}; - s.campaigns = Number(c.n || 0); s.advertisers = Number(c.owners || 0); - const ac = (await q("SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND status='active'"))[0] || {}; - s.active = Number(ac.n || 0); s.activeAdvertisers = Number(ac.owners || 0); - // impressions in the last 24 hours: camp_hours is keyed by UTC day + hour - const d0 = new Date(since).toISOString().slice(0, 10), h0 = new Date(since).getUTCHours(), d1 = new Date(now).toISOString().slice(0, 10); - const im = (await q('SELECT SUM(n) imps FROM camp_hours WHERE (day=? AND hour>=?) OR (day>? AND day<=?)', [d0, h0, d0, d1]))[0] || {}; - s.imps = Number(im.imps || 0); - const v = (await q('SELECT COUNT(*) viewers, SUM(views) views FROM daily_views WHERE day=? AND views>0', [d1]))[0] || {}; - s.viewers = Number(v.viewers || 0); s.views = Number(v.views || 0); - // where the credits came from (Marty, 2026-09-19): handed out = grants, partner codes and - // bonuses; earned = viewing; spent = everything that left a balance for ad delivery or a buy - const cl = (await q("SELECT SUM(CASE WHEN delta>0 AND kind IN ('grant','promo','bonus') THEN delta ELSE 0 END) handed, SUM(CASE WHEN delta>0 AND kind='earn' THEN delta ELSE 0 END) earned, SUM(CASE WHEN delta<0 THEN -delta ELSE 0 END) spent FROM credit_log WHERE ts>=?", [since]))[0] || {}; - s.creditsHandedOut = Number(cl.handed || 0); s.creditsEarned = Number(cl.earned || 0); s.creditsSpent = Number(cl.spent || 0); - } - try { - for (const ev of X.chain.recentEvents(1e9)) { - if (ev.type === 'Purchase') { s.lifeBuys++; if (ev.ts >= since) { s.buys++; s.usd += ev.priceCents / 100; } else if (ev.ts >= prior) s.buysPrior++; } - else if (ev.type === 'MemberActivated' && ev.ts >= since) s.activations++; - else if (ev.type === 'TierPaid' || ev.type === 'AwardPaid') { s.lifePayouts++; s.lifePaidWei += BigInt(ev.amountWei); if (ev.ts >= since) s.paidWei += BigInt(ev.amountWei); } - } - // the index keeps a bounded event list; lifetime totals come from its running tally when present - const t = X.chain.totals ? X.chain.totals() : null; - if (t) { if (t.purchases) s.lifeBuys = Number(t.purchases); if (t.payoutWei) s.lifePaidWei = BigInt(t.payoutWei); if (t.payouts) s.lifePayouts = Number(t.payouts); } - } catch (e) {} - return s; -} - -// One block per subject, a blank line between them, and no line long enough for a phone to wrap it -// into a wall of text (Marty, 2026-09-22 — the single-paragraph version was unreadable on mobile). -function compose(s, cta) { - const up = (cur, prev) => cur > prev ? ', up from ' + n(prev) + ' yesterday' - : cur < prev ? ', down from ' + n(prev) + ' yesterday' : ''; - const plural = (c, word) => n(c) + ' ' + word + (Number(c) === 1 ? '' : 's'); - const day = new Date().toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'long', month: 'long', day: 'numeric' }); - const B = []; - B.push('\u{1F4C8} InstantAdPay · 24-hour snapshot\n' + day + ''); - B.push('\u{1F465} Sign-ups\n' - + '' + n(s.signups) + ' new' + up(s.signups, s.signupsPrior) + '\n' - + n(s.activations) + ' switched on payouts'); - B.push('\u{1F9FE} Purchases\n' - + '' + n(s.buys) + ' for $' + n(Math.round(s.usd)) + '' + up(s.buys, s.buysPrior) + '\n' - + '' + pol(s.paidWei) + ' POL paid to members\nin the same transactions'); - B.push('\u{1F4E3} Campaigns\n' - + '' + n(s.campaigns) + ' posted by ' + plural(s.advertisers, 'advertiser') + '\n' - + n(s.active) + ' running · ' + n(s.imps) + ' impressions'); - B.push('\u{1F440} Earning\n' - + '' + n(s.viewers) + ' members viewed ads today\n' - + n(s.seen24h) + ' signed in'); - B.push('\u{1F4B3} Credits\n' - + '' + n(s.creditsHandedOut) + ' handed out · ' + n(s.creditsEarned) + ' earned\n' - + n(s.creditsSpent) + ' spent on ads'); - B.push('\u{1F3C1} So far\n' - + '' + n(s.members) + ' members · ' + n(s.wallets) + ' wallets linked\n' - + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' buys\n' - + '' + pol(s.lifePaidWei) + ' POL paid in ' + n(s.lifePayouts) + ' payouts\n' - + 'All of it on the public ledger.'); - B.push('Live ledger' + (cta ? ' · Join free' : '')); - return B.join('\n\n'); -} - -async function post() { - const sc = X.siteConfig(); - if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' }; - const s = await gather(); const text = compose(s, sc.telegramCtaUrl); - const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim()); - let sent = 0; - if (targets.includes('feed') && sc.telegramChatId) { if (await X.send(sc.telegramChatId, text, sc.telegramTopicId)) sent++; } - if (targets.includes('echo') && sc.telegramEchoChatId) { if (await X.send(sc.telegramEchoChatId, text, sc.telegramEchoTopicId)) sent++; } - const st = state(); st.lastPost = Date.now(); st.lastDay = new Date().toISOString().slice(0, 10); setState(st); - return { ok: true, sent, text }; -} - -// every 10 minutes: post once a day at or after snapshotHourUtc (a restart never double-posts) -async function tick() { - try { await milestoneTick(); } catch (e) { console.error('milestone', e.message); } - const sc = X.siteConfig(); - if (String(sc.snapshotEnabled || '1') !== '1' || !sc.telegramBotToken) return; - const hour = Number(sc.snapshotHourUtc == null || sc.snapshotHourUtc === '' ? 14 : sc.snapshotHourUtc); - const now = new Date(); const day = now.toISOString().slice(0, 10); - if (now.getUTCHours() < hour) return; - if (state().lastDay === day) return; - await post(); -} - -async function preview() { const sc = X.siteConfig(); return compose(await gather(), sc.telegramCtaUrl); } - -// ---- membership milestones: one celebratory post per mark, the moment it is crossed. -// Every 100 members since 2026-09-22 (Marty), with the fuller write-up saved for the round -// thousands and the half-thousands so the small ones stay a quick cheer, not a repeated speech. -const STEP = 100; -const isBig = m => m % 500 === 0; -const marksUpTo = count => { const out = []; for (let m = STEP; m <= count; m += STEP) out.push(m); return out; }; -const MILESTONES = marksUpTo(10000); // kept for callers that want the ladder - -function composeMilestone(mark, s, cta) { - const ledger = 'Live ledger' + (cta ? ' \u00b7 Join free' : ''); - const B = []; - B.push('\u{1F389} ' + n(mark) + ' members on InstantAdPay'); - if (isBig(mark)) { - B.push(n(mark) + ' people have joined. Here is what that looks like right now:'); - B.push('' + n(s.wallets) + ' wallets linked\n' - + '' + n(s.payoutsOn) + ' with payouts switched on\n' - + '' + n(s.lifeBuys) + ' purchases\n' - + '' + pol(s.lifePaidWei) + ' POL paid to members\nin the same transactions'); - B.push('Every one of those payments is on the public ledger.'); - B.push('Thank you to every member who brought someone in. That is the whole engine, and it is working.'); - B.push('The next ' + n(mark) + ' start today.'); - } else { - B.push('Another hundred through the door.'); - B.push('' + n(s.wallets) + ' wallets linked\n' - + '' + n(s.payoutsOn) + ' with payouts on\n' - + '' + pol(s.lifePaidWei) + ' POL paid to members'); - B.push('Every payment on the public ledger.'); - B.push('Next stop: ' + n(mark + STEP) + '.'); - } - B.push(ledger); - return B.join('\n\n'); -} -async function memberCount() { - if (!(X.db && X.db.enabled())) return 0; - const r = await X.db.q('SELECT COUNT(*) n FROM accounts'); return Number((r[0] || {}).n || 0); -} -// runs from tick(): announce the highest newly crossed mark, once, whatever snapshotEnabled says -async function milestoneTick() { - const sc = X.siteConfig(); if (!sc.telegramBotToken) return null; - const st = state(); const done = st.milestones || {}; - const count = await memberCount(); - // presence of the key is what counts, never its value: a mark recorded as 0 (or any other - // falsy stamp) must stay done, or the ladder back-posts a number the site passed long ago - const due = marksUpTo(count).filter(m => !Object.prototype.hasOwnProperty.call(done, m)); - if (!due.length) return null; - const mark = due[due.length - 1]; - const text = composeMilestone(mark, await gather(), sc.telegramCtaUrl); - const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim()); - // A milestone read as plain text in a busy topic and got scrolled straight past (Marty, - // 2026-09-24), so it goes out as a card now. The cards are pre-rendered for the whole ladder - // and deliberately carry NO live figures: the numbers stay in the caption, where they cannot - // go stale between rendering and the mark actually being reached. - let jpeg = null; - try { jpeg = fs.readFileSync(path.join(X.publicDir || '', 'milestones', mark + '.jpg')); } catch (e) {} - const caption = text.length <= 1024 ? text : null; // Telegram caps a photo caption at 1024 - let sent = 0; - const post = async (chat, thread) => { - if (jpeg && caption && X.sendPhoto && await X.sendPhoto(chat, jpeg, caption, thread)) return true; - return X.send(chat, text, thread); - }; - // A target that is listed but has no chat id used to fail silently, so the feed half of every - // milestone and every daily snapshot went nowhere for weeks without a line in the log. - // Three destinations, all in the same forum on different topics (Marty, 2026-09-24): the main - // group, the InstantAdPay support topic, and the shared payments topic. The RM Circle proof - // channel is deliberately NOT one of them: that channel is RM Circle only. - for (const [name, chat, thread] of [['feed', sc.telegramChatId, sc.telegramTopicId], - ['support', sc.telegramSupportChatId, sc.telegramSupportTopicId], - ['echo', sc.telegramEchoChatId, sc.telegramEchoTopicId]]) { - if (!targets.includes(name)) continue; - if (!chat) { console.warn('snapshot: target "' + name + '" is listed but has no chat id, nothing sent'); continue; } - if (await post(chat, thread)) sent++; - } - for (const m of due) done[m] = Date.now(); // lower marks crossed in the same jump are marked too, so they never post late - st.milestones = done; setState(st); - console.log('milestone posted', mark, 'members', count, 'sent', sent); - return { ok: true, mark, count, sent, text }; -} -async function previewMilestone(mark) { const sc = X.siteConfig(); return composeMilestone(Number(mark) || 500, await gather(), sc.telegramCtaUrl); } - -module.exports = { init, gather, compose, post, tick, preview, milestoneTick, previewMilestone, composeMilestone, memberCount, MILESTONES, STEP }; +// Growth snapshot (Marty, 2026-09-15): once a day, a short "how the site is doing" post in the Telegram +// payments feed (and the shared payments topic), so members watching the payout lines also see the +// whole picture: sign-ups, purchases, POL paid out, campaigns posted, ads viewed. Every number comes +// from the same tables and chain index the dashboards read. Settings: snapshotEnabled (1/0), +// snapshotHourUtc (default 14 = 9 AM Central), snapshotTargets (feed,echo). State: snapshot-state.json. +const fs = require('fs'); +const path = require('path'); + +let X = {}; +const DAY = 86400000; +function init(opts) { X = opts || {}; } +const STATE = () => path.join(X.dataDir, 'snapshot-state.json'); +function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return {}; } } +function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} } +const n = v => Number(v || 0).toLocaleString('en-US'); +const pol = w => { try { return (Number(BigInt(w) / (10n ** 16n)) / 100).toLocaleString('en-US', { maximumFractionDigits: 0 }); } catch (e) { return '0'; } }; + +async function gather(now = Date.now()) { + const since = now - DAY, prior = now - 2 * DAY; + const s = { signups: 0, signupsPrior: 0, members: 0, wallets: 0, payoutsOn: 0, seen24h: 0, + campaigns: 0, advertisers: 0, active: 0, activeAdvertisers: 0, imps: 0, viewers: 0, views: 0, + buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0, + creditsHandedOut: 0, creditsEarned: 0, creditsSpent: 0 }; + if (X.db && X.db.enabled()) { + const q = (a, b) => X.db.q(a, b || []); + const a = (await q('SELECT COUNT(*) total, SUM(created>=?) s24, SUM(created>=? AND created0) payouts, SUM(last_seen>=?) seen FROM accounts', [since, prior, since, since]))[0] || {}; + s.members = Number(a.total || 0); s.signups = Number(a.s24 || 0); s.signupsPrior = Number(a.sPrior || 0); s.wallets = Number(a.wallet || 0); s.payoutsOn = Number(a.payouts || 0); s.seen24h = Number(a.seen || 0); + const c = (await q('SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND created>=?', [since]))[0] || {}; + s.campaigns = Number(c.n || 0); s.advertisers = Number(c.owners || 0); + const ac = (await q("SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND status='active'"))[0] || {}; + s.active = Number(ac.n || 0); s.activeAdvertisers = Number(ac.owners || 0); + // impressions in the last 24 hours: camp_hours is keyed by UTC day + hour + const d0 = new Date(since).toISOString().slice(0, 10), h0 = new Date(since).getUTCHours(), d1 = new Date(now).toISOString().slice(0, 10); + const im = (await q('SELECT SUM(n) imps FROM camp_hours WHERE (day=? AND hour>=?) OR (day>? AND day<=?)', [d0, h0, d0, d1]))[0] || {}; + s.imps = Number(im.imps || 0); + const v = (await q('SELECT COUNT(*) viewers, SUM(views) views FROM daily_views WHERE day=? AND views>0', [d1]))[0] || {}; + s.viewers = Number(v.viewers || 0); s.views = Number(v.views || 0); + // where the credits came from (Marty, 2026-09-19): handed out = grants, partner codes and + // bonuses; earned = viewing; spent = everything that left a balance for ad delivery or a buy + const cl = (await q("SELECT SUM(CASE WHEN delta>0 AND kind IN ('grant','promo','bonus') THEN delta ELSE 0 END) handed, SUM(CASE WHEN delta>0 AND kind='earn' THEN delta ELSE 0 END) earned, SUM(CASE WHEN delta<0 THEN -delta ELSE 0 END) spent FROM credit_log WHERE ts>=?", [since]))[0] || {}; + s.creditsHandedOut = Number(cl.handed || 0); s.creditsEarned = Number(cl.earned || 0); s.creditsSpent = Number(cl.spent || 0); + } + try { + for (const ev of X.chain.recentEvents(1e9)) { + if (ev.type === 'Purchase') { s.lifeBuys++; if (ev.ts >= since) { s.buys++; s.usd += ev.priceCents / 100; } else if (ev.ts >= prior) s.buysPrior++; } + else if (ev.type === 'MemberActivated' && ev.ts >= since) s.activations++; + else if (ev.type === 'TierPaid' || ev.type === 'AwardPaid') { s.lifePayouts++; s.lifePaidWei += BigInt(ev.amountWei); if (ev.ts >= since) s.paidWei += BigInt(ev.amountWei); } + } + // the index keeps a bounded event list; lifetime totals come from its running tally when present + const t = X.chain.totals ? X.chain.totals() : null; + if (t) { if (t.purchases) s.lifeBuys = Number(t.purchases); if (t.payoutWei) s.lifePaidWei = BigInt(t.payoutWei); if (t.payouts) s.lifePayouts = Number(t.payouts); } + } catch (e) {} + // the games (2026-10-08): members sent in (counted at hand-off) + payouts read from each game wallet on Polygon + try { s.games = X.games ? await X.games.gather(since) : null; } catch (e) { s.games = null; } + try { s.launches = X.launchesToday ? X.launchesToday() : []; } catch (e) { s.launches = []; } + return s; +} + +// One block per subject, a blank line between them, and no line long enough for a phone to wrap it +// into a wall of text (Marty, 2026-09-22 — the single-paragraph version was unreadable on mobile). +function compose(s, cta) { + const up = (cur, prev) => cur > prev ? ', up from ' + n(prev) + ' yesterday' + : cur < prev ? ', down from ' + n(prev) + ' yesterday' : ''; + const plural = (c, word) => n(c) + ' ' + word + (Number(c) === 1 ? '' : 's'); + const day = new Date().toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'long', month: 'long', day: 'numeric' }); + const B = []; + B.push('\u{1F4C8} InstantAdPay · 24-hour snapshot\n' + day + ''); + B.push('\u{1F465} Sign-ups\n' + + '' + n(s.signups) + ' new' + up(s.signups, s.signupsPrior) + '\n' + + n(s.activations) + ' switched on payouts'); + B.push('\u{1F9FE} Purchases\n' + + '' + n(s.buys) + ' for $' + n(Math.round(s.usd)) + '' + up(s.buys, s.buysPrior) + '\n' + + '' + pol(s.paidWei) + ' POL paid to members\nin the same transactions'); + B.push('\u{1F4E3} Campaigns\n' + + '' + n(s.campaigns) + ' posted by ' + plural(s.advertisers, 'advertiser') + '\n' + + n(s.active) + ' running · ' + n(s.imps) + ' impressions'); + B.push('\u{1F440} Earning\n' + + '' + n(s.viewers) + ' members viewed ads today\n' + + n(s.seen24h) + ' signed in'); + B.push('\u{1F4B3} Credits\n' + + '' + n(s.creditsHandedOut) + ' handed out · ' + n(s.creditsEarned) + ' earned\n' + + n(s.creditsSpent) + ' spent on ads'); + if (s.games && (s.games.totals.sentIn || s.games.totals.payouts || (s.launches && s.launches.length))) { + const G = s.games, live = G.games.filter(g => g.sentIn || g.payouts); + let gl = '\u{1F3AE} Games\n'; + if (s.launches && s.launches.length) gl += '\u{1F680} ' + s.launches.join(' and ') + ' opened today\n'; + gl += '' + n(G.totals.sentIn) + ' members played' + (G.chainChecked ? ' \u00b7 ' + pol(G.totals.wei) + ' POL paid in ' + plural(G.totals.payouts, 'payout') : '') + '\n'; + gl += live.slice(0, 6).map(g => g.name + ': ' + n(g.sentIn) + (g.payouts ? ' \u00b7 ' + pol(g.wei) + ' POL' : '')).join('\n'); + if (live.length) gl += '\nBusiest: ' + live[0].name; + B.push(gl.trim()); + } + B.push('\u{1F3C1} So far\n' + + '' + n(s.members) + ' members · ' + n(s.wallets) + ' wallets linked\n' + + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' buys\n' + + '' + pol(s.lifePaidWei) + ' POL paid in ' + n(s.lifePayouts) + ' payouts\n' + + 'All of it on the public ledger.'); + B.push('Live ledger' + (cta ? ' · Join free' : '')); + return B.join('\n\n'); +} + +async function post() { + const sc = X.siteConfig(); + if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' }; + const s = await gather(); const text = compose(s, sc.telegramCtaUrl); + const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim()); + let sent = 0; + if (targets.includes('feed') && sc.telegramChatId) { if (await X.send(sc.telegramChatId, text, sc.telegramTopicId)) sent++; } + if (targets.includes('echo') && sc.telegramEchoChatId) { if (await X.send(sc.telegramEchoChatId, text, sc.telegramEchoTopicId)) sent++; } + const st = state(); st.lastPost = Date.now(); st.lastDay = new Date().toISOString().slice(0, 10); setState(st); + return { ok: true, sent, text }; +} + +// every 10 minutes: post once a day at or after snapshotHourUtc (a restart never double-posts) +async function tick() { + try { await milestoneTick(); } catch (e) { console.error('milestone', e.message); } + const sc = X.siteConfig(); + if (String(sc.snapshotEnabled || '1') !== '1' || !sc.telegramBotToken) return; + const hour = Number(sc.snapshotHourUtc == null || sc.snapshotHourUtc === '' ? 14 : sc.snapshotHourUtc); + const now = new Date(); const day = now.toISOString().slice(0, 10); + if (now.getUTCHours() < hour) return; + if (state().lastDay === day) return; + await post(); +} + +async function preview() { const sc = X.siteConfig(); return compose(await gather(), sc.telegramCtaUrl); } + +// ---- membership milestones: one celebratory post per mark, the moment it is crossed. +// Every 100 members since 2026-09-22 (Marty), with the fuller write-up saved for the round +// thousands and the half-thousands so the small ones stay a quick cheer, not a repeated speech. +const STEP = 100; +const isBig = m => m % 500 === 0; +const marksUpTo = count => { const out = []; for (let m = STEP; m <= count; m += STEP) out.push(m); return out; }; +const MILESTONES = marksUpTo(10000); // kept for callers that want the ladder + +function composeMilestone(mark, s, cta) { + const ledger = 'Live ledger' + (cta ? ' \u00b7 Join free' : ''); + const B = []; + B.push('\u{1F389} ' + n(mark) + ' members on InstantAdPay'); + if (isBig(mark)) { + B.push(n(mark) + ' people have joined. Here is what that looks like right now:'); + B.push('' + n(s.wallets) + ' wallets linked\n' + + '' + n(s.payoutsOn) + ' with payouts switched on\n' + + '' + n(s.lifeBuys) + ' purchases\n' + + '' + pol(s.lifePaidWei) + ' POL paid to members\nin the same transactions'); + B.push('Every one of those payments is on the public ledger.'); + B.push('Thank you to every member who brought someone in. That is the whole engine, and it is working.'); + B.push('The next ' + n(mark) + ' start today.'); + } else { + B.push('Another hundred through the door.'); + B.push('' + n(s.wallets) + ' wallets linked\n' + + '' + n(s.payoutsOn) + ' with payouts on\n' + + '' + pol(s.lifePaidWei) + ' POL paid to members'); + B.push('Every payment on the public ledger.'); + B.push('Next stop: ' + n(mark + STEP) + '.'); + } + B.push(ledger); + return B.join('\n\n'); +} +async function memberCount() { + if (!(X.db && X.db.enabled())) return 0; + const r = await X.db.q('SELECT COUNT(*) n FROM accounts'); return Number((r[0] || {}).n || 0); +} +// runs from tick(): announce the highest newly crossed mark, once, whatever snapshotEnabled says +async function milestoneTick() { + const sc = X.siteConfig(); if (!sc.telegramBotToken) return null; + const st = state(); const done = st.milestones || {}; + const count = await memberCount(); + // presence of the key is what counts, never its value: a mark recorded as 0 (or any other + // falsy stamp) must stay done, or the ladder back-posts a number the site passed long ago + const due = marksUpTo(count).filter(m => !Object.prototype.hasOwnProperty.call(done, m)); + if (!due.length) return null; + const mark = due[due.length - 1]; + const text = composeMilestone(mark, await gather(), sc.telegramCtaUrl); + const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim()); + // A milestone read as plain text in a busy topic and got scrolled straight past (Marty, + // 2026-09-24), so it goes out as a card now. The cards are pre-rendered for the whole ladder + // and deliberately carry NO live figures: the numbers stay in the caption, where they cannot + // go stale between rendering and the mark actually being reached. + let jpeg = null; + try { jpeg = fs.readFileSync(path.join(X.publicDir || '', 'milestones', mark + '.jpg')); } catch (e) {} + const caption = text.length <= 1024 ? text : null; // Telegram caps a photo caption at 1024 + let sent = 0; + const post = async (chat, thread) => { + if (jpeg && caption && X.sendPhoto && await X.sendPhoto(chat, jpeg, caption, thread)) return true; + return X.send(chat, text, thread); + }; + // A target that is listed but has no chat id used to fail silently, so the feed half of every + // milestone and every daily snapshot went nowhere for weeks without a line in the log. + // Three destinations, all in the same forum on different topics (Marty, 2026-09-24): the main + // group, the InstantAdPay support topic, and the shared payments topic. The RM Circle proof + // channel is deliberately NOT one of them: that channel is RM Circle only. + for (const [name, chat, thread] of [['feed', sc.telegramChatId, sc.telegramTopicId], + ['support', sc.telegramSupportChatId, sc.telegramSupportTopicId], + ['echo', sc.telegramEchoChatId, sc.telegramEchoTopicId]]) { + if (!targets.includes(name)) continue; + if (!chat) { console.warn('snapshot: target "' + name + '" is listed but has no chat id, nothing sent'); continue; } + if (await post(chat, thread)) sent++; + } + for (const m of due) done[m] = Date.now(); // lower marks crossed in the same jump are marked too, so they never post late + st.milestones = done; setState(st); + console.log('milestone posted', mark, 'members', count, 'sent', sent); + return { ok: true, mark, count, sent, text }; +} +async function previewMilestone(mark) { const sc = X.siteConfig(); return composeMilestone(Number(mark) || 500, await gather(), sc.telegramCtaUrl); } + +module.exports = { init, gather, compose, post, tick, preview, milestoneTick, previewMilestone, composeMilestone, memberCount, MILESTONES, STEP };