Files
instantadpay/gamestats.js
T
martbost a058fd515d Warp & Wares integration, gated (2026-10-29): the 30-day Trade Wars-style season game, same protocol as POL Miner and Turkey Drop. WW_SSO_SECRET / WW_URL (default https://warpwares.saasy.top, staging for now) / WW_ALT_URLS / WW_SEASON_START + WW_SEASON_END (default 2026-11-30..2026-12-30, Central, end exclusive) with wwMint/wwOpen/wwIsGameUrl/wwCallback (code defaults only, no env set); GAME_AUTH warpwares (in-game sign-in kit); /api/my/warpwares hand-off + iap.return + my.js redirect; a new visit kind 'dock' in ads.js VISIT_KINDS with its own daily cap (dockCapPerDay, default 10; repeats after the cooldown like refuels; house visits count toward it) and the refuel rail serving game 'warpwares' with that kind (label 'sponsor dock', receipt kind ww-dock, note 'Warp & Wares sponsor dock', refuel.js done text 'Your bonus turns are waiting on the bridge'); GAMES() card with the season window (hidden until 'warpwares' is in gamesLive, its 'Opens' date shown only once live, gone after the season) and STRIP line; growth snapshot counts a season start only when live; walletnudge entry (idle until the secret is set); gamestats + gamepass GAMES/NAMES + GP_SECRETS; Game Pass perks row 'the Season Pass' shown only while the game is in the public games list (gpShown, the Turkey Drop pattern); cap-nudge names; promo tools Games entry (warpwares.saasy.top/?ref=, 3 posts) shown only while live; chatbot CANNED warpwares + fact follow gamesLive and the season window (coming-soon and season-over answers, KB answer kept out of the prompt unless live), KNOWLEDGE_DATE 2026-10-29b; my.js?v=20261029ww, promo.js?v=20261029ww, refuel.js?v=20261029ww. qa/warpwares.mjs (bash qa/run.sh warpwares): 21 checks on a local copy with a mock game (card gating, the hand-off token, a sponsor dock open/challenge/done with receipt + callback, the dock cap separate from refuels, chatbot gating), all passing. Not merged, not deployed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 16:43:49 -05:00

102 lines
7.8 KiB
JavaScript

// 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/<game>), 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/.<game>-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', polybreak: 'PolyBreak', polminer: 'POL Miner', warpwares: 'Warp & Wares', shardsofvalor: 'Shards of Valor' };
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 };
}
// ---- 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 };