From 34a1de0b15f4126a5621c24210c18a53b615c377 Mon Sep 17 00:00:00 2001 From: martbost Date: Sun, 18 Oct 2026 07:11:25 -0500 Subject: [PATCH] P&L: Game payouts card, an all-time running total of every game wallet's payouts read from Polygon (incremental, cached); PolHunter ledger detail folded under it Co-Authored-By: Claude Opus 5.5 --- gamestats.js | 47 ++++++++++++++++++++++++++++++++++++++++-- public/admin.html | 10 +++++---- public/assets/admin.js | 18 +++++++++++++++- server.js | 3 ++- 4 files changed, 70 insertions(+), 8 deletions(-) diff --git a/gamestats.js b/gamestats.js index 3ed5653..7e27379 100644 --- a/gamestats.js +++ b/gamestats.js @@ -10,7 +10,7 @@ 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 NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip', polybreak: 'PolyBreak' }; 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 @@ -55,4 +55,47 @@ async function gather(since) { 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 }; +// ---- all-time running total of game payouts, for the admin P&L (Marty 2026-10-18) ---- +// Every outgoing POL send from each game wallet to a player, from the wallet's first transaction. +// Kept in DATA_DIR/game-payouts-alltime.json per wallet { block, count, wei, players[] } and topped up +// incrementally (only blocks after the last one seen), so after the first scan a refresh is one call per game. +const AT_FILE = () => path.join(R.dataDir, 'game-payouts-alltime.json'); +let atState = null, atAt = 0, atBusy = null; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +function atLoad() { if (!atState) { try { atState = JSON.parse(fs.readFileSync(AT_FILE(), 'utf8')); } catch (e) { atState = {}; } } return atState; } +function atSave() { try { fs.writeFileSync(AT_FILE() + '.tmp', JSON.stringify(atState)); fs.renameSync(AT_FILE() + '.tmp', AT_FILE()); } catch (e) {} } +async function atScan(slug, addr) { + const st = atLoad(); let w = st[slug]; + if (!w || w.addr !== addr) w = st[slug] = { addr, block: 0, count: 0, wei: '0', players: [] }; + const skip = SKIP(), players = new Set(w.players); let wei = BigInt(w.wei), count = w.count, maxBlock = w.block; // committed only when the scan finishes, so a failed page never double-counts + for (let page = 1; page <= 10; page++) { // Etherscan caps page*offset at 10,000; the next refresh carries on from the last block + const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=' + (w.block + 1) + '&endblock=99999999&sort=asc&page=' + page + '&offset=1000&apikey=' + KEY(); + const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json(); + if (!Array.isArray(j.result)) { if (/no transactions/i.test(String(j.message || ''))) break; throw new Error(String(j.result || j.message || 'etherscan')); } + for (const x of j.result) { + const b = Number(x.blockNumber); if (b > maxBlock) maxBlock = b; + if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue; + const to = String(x.to).toLowerCase(); if (skip.has(to)) continue; + count++; wei += BigInt(x.value); players.add(to); + } + if (j.result.length < 1000) break; + await sleep(400); + } + w.block = maxBlock; w.count = count; w.wei = wei.toString(); w.players = [...players]; delete w.error; +} +async function atRefresh() { + const W = wallets(); + for (const [slug, addr] of Object.entries(W)) { try { await atScan(slug, addr); } catch (e) { (atLoad()[slug] || {}).error = e.message; } await sleep(400); } + atSave(); atAt = Date.now(); +} +// { games: [{ slug, name, count, wei, players }], totals, at }; refreshed at most every 10 minutes, never blocks the page past 25 s +async function allTime() { + if (!KEY()) return { error: 'ETHERSCAN_KEY not set' }; + if (Date.now() - atAt > 600000 && !atBusy) atBusy = atRefresh().finally(() => { atBusy = null; }); + if (atBusy && !atAt) await Promise.race([atBusy, sleep(25000)]); + const st = atLoad(), W = wallets(), games = []; + for (const slug of Object.keys(W)) { const w = st[slug]; if (!w) continue; games.push({ slug, name: NAMES[slug] || slug, count: w.count, wei: w.wei, players: w.players.length, error: w.error || null }); } + games.sort((a, b) => (BigInt(b.wei) > BigInt(a.wei) ? 1 : -1)); + return { games, at: atAt || null, scanning: !!atBusy }; +} +module.exports = { init, handoff, gather, allTime, NAMES }; diff --git a/public/admin.html b/public/admin.html index 9d51782..7af8735 100644 --- a/public/admin.html +++ b/public/admin.html @@ -462,9 +462,11 @@
-

PolHunter payouts

all time, its own faucet
-
-

Marketing spend, paid in POL from the PolHunter wallet. None of it passes through the ad contract, so it is not in the lines above.

+

Game payouts

all time, running total
+
+

Marketing spend: every POL send from each game's own payout wallet to a player, read from Polygon since the wallet's first transaction. Top-ups, moves between our wallets and returns to the fee wallets are left out. None of it passes through the ad contract, so it is not in the lines to the left.

+
PolHunter detail (its own ledger) +

Wallets

live balances
@@ -566,6 +568,6 @@
- + diff --git a/public/assets/admin.js b/public/assets/admin.js index 4872c7b..2812bc3 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -762,7 +762,23 @@ + 'Hunters paid' + Number(t.hunters || 0) + 'today ' + Number(t.today || 0).toFixed(3) + ' POL'; } } - $('pnlSplit').innerHTML = 'LinePOLUSD now' + // 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' diff --git a/server.js b/server.js index dd4f222..170a6f6 100644 --- a/server.js +++ b/server.js @@ -4904,6 +4904,7 @@ const server = http.createServer(async (req, res) => { 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; @@ -4926,7 +4927,7 @@ const server = http.createServer(async (req, res) => { 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, + 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'),