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 <noreply@anthropic.com>
This commit is contained in:
+45
-2
@@ -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 };
|
||||
|
||||
+6
-4
@@ -462,9 +462,11 @@
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlSplit"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>PolHunter payouts</h3><span class="sub">all time, its own faucet</span></div>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div>
|
||||
<p class="small muted" style="margin:10px 0 0">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.</p>
|
||||
<div class="card-head"><h3>Game payouts</h3><span class="sub">all time, running total</span></div>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlGames"></table></div>
|
||||
<p class="small muted" style="margin:10px 0 0">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.</p>
|
||||
<details style="margin-top:10px"><summary class="small">PolHunter detail (its own ledger)</summary>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div></details>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Wallets</h3><span class="sub">live balances</span></div>
|
||||
@@ -566,6 +568,6 @@
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/admin.js?v=20261018ls"></script>
|
||||
<script src="/assets/admin.js?v=20261018gp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+17
-1
@@ -762,7 +762,23 @@
|
||||
+ '<tr><td class="muted small">Hunters paid</td><td class="mono">' + Number(t.hunters || 0) + '</td><td class="muted small">today ' + Number(t.today || 0).toFixed(3) + ' POL</td></tr>';
|
||||
}
|
||||
}
|
||||
$('pnlSplit').innerHTML = '<tr><th>Line</th><th>POL</th><th>USD now</th></tr>'
|
||||
// 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 = '<tr><td colspan="4" class="muted small">' + (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) + ')' : '') + '.') + '</td></tr>';
|
||||
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) => '<tr' + (cls ? ' class="' + cls + '"' : '') + '><td>' + name + '</td><td class="mono">' + wp(w).toFixed(4) + '</td><td class="mono">$' + (wp(w) * px).toFixed(2) + '</td><td class="mono small">' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + '</td></tr>';
|
||||
const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0);
|
||||
gaEl.innerHTML = '<tr><th>Game</th><th>POL</th><th>USD now</th><th>Payouts to players</th></tr>'
|
||||
+ games.map(g => row(esc(g.name) + (g.error ? ' <span class="chip flat">stale</span>' : ''), g.wei, g.count, g.players)).join('')
|
||||
+ '<tr><td><b>All game payouts</b></td><td class="mono"><b>' + wp(tw).toFixed(4) + '</b></td><td class="mono"><b>$' + (wp(tw) * px).toFixed(2) + '</b></td><td class="mono small">' + tn.toLocaleString() + ' payouts</td></tr>'
|
||||
+ (pd ? row('<span class="muted">PassiveDrip (not a game)</span>', pd.wei, pd.count, pd.players) : '')
|
||||
+ '<tr><td colspan="4" class="muted small">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.</td></tr>';
|
||||
}
|
||||
}
|
||||
$('pnlSplit').innerHTML ='<tr><th>Line</th><th>POL</th><th>USD now</th></tr>'
|
||||
+ [['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 => '<tr><td>' + x[0] + '</td><td class="mono">' + pol(x[1]) + '</td><td class="mono">' + usdOf(x[1], px) + '</td></tr>').join('');
|
||||
const W = r.wallets || {}, B = r.balances || {};
|
||||
$('pnlWallets').innerHTML = '<tr><th>Wallet</th><th>Address</th><th>Balance</th></tr>'
|
||||
|
||||
@@ -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'),
|
||||
|
||||
Reference in New Issue
Block a user