From 73b6cf74dbc7fddf727900169b2b67ea42b83943 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 16 Oct 2026 09:11:27 -0500 Subject: [PATCH] Game Pass bridge (GAMEPASS=on): finds and Ad Detective cases via InstantAdPay polgrant (daily, fail closed), 5 missions + 2 cases perks, Pass Tournament prize payer from this faucet (claims before send, dry run, alerts), tests Co-Authored-By: Claude Fable 5.1 --- lib/detective.js | 34 +++++++--- lib/faucet.js | 19 +++++- lib/polgrant.js | 160 ++++++++++++++++++++++++++++++++++++++++++++++ lib/rewards.js | 45 ++++++++----- lib/tournament.js | 73 +++++++++++++++++++++ package.json | 2 +- public/app.html | 2 +- public/app.js | 6 +- server.js | 50 ++++++++++++--- test/gamepass.js | 136 +++++++++++++++++++++++++++++++++++++++ 10 files changed, 488 insertions(+), 39 deletions(-) create mode 100644 lib/polgrant.js create mode 100644 lib/tournament.js create mode 100644 test/gamepass.js diff --git a/lib/detective.js b/lib/detective.js index 3fe46b5..67623e8 100644 --- a/lib/detective.js +++ b/lib/detective.js @@ -83,7 +83,9 @@ function order(box, q) { return q.options.map((o, i) => ({ i, k: h(box.id + ':' // ---- the box ---------------------------------------------------------------------------------- const boxId = (memberId, day) => Number(memberId) + ':' + day; -function getBox(memberId, day) { return store.read('boxes', {})[boxId(memberId, day || ctDay())] || null; } +// the day's current box: the second one (the Game Pass perk, id '::2') once it exists, else the first +function getBox(memberId, day) { const all = store.read('boxes', {}), id = boxId(memberId, day || ctDay()); return all[id + ':2'] || all[id] || null; } +const closed = b => !!b && (b.status === 'won' || b.status === 'missed'); function putBox(b) { store.update('boxes', {}, all => { all[b.id] = b; return all; }); return b; } function patchBox(id, patch) { let out = null; store.update('boxes', {}, all => { if (all[id]) { Object.assign(all[id], patch); out = all[id]; } return all; }); return out; } @@ -105,13 +107,16 @@ function view(me) { return out; } -function open(me) { +// pass = the Game Pass perk (GAME-PASS.md 4): a second case a day once the first is closed; the first case stays the rule for everyone else +function open(me, pass) { if (!earned(me)) return { error: 'Finish today’s Code Hunts first. The box unlocks when your last one is found.' }; - const day = ctDay(); const cur = getBox(me.memberId, day); if (cur) return { ok: true, box: cur }; + const day = ctDay(); const cur = getBox(me.memberId, day); + const second = !!(pass && cur && closed(cur) && !/:2$/.test(cur.id)); + if (cur && !second) return { ok: true, box: cur }; const c = pickCase(me.memberId, day); if (!c) return { error: 'No cases are open right now. Check back tomorrow.' }; let made = null; // idempotent per member per day: a double tap or two tabs can never mint a second box - store.update('boxes', {}, all => { const id = boxId(me.memberId, day); if (!all[id]) all[id] = { id, memberId: Number(me.memberId), day, missionId: c.missionId, qid: c.qid, pol: settings().pol, status: 'open', openedAt: Date.now() }; made = all[id]; return all; }); + store.update('boxes', {}, all => { const id = boxId(me.memberId, day) + (second ? ':2' : ''); if (!all[id]) all[id] = { id, memberId: Number(me.memberId), day, missionId: c.missionId, qid: c.qid, pol: settings().pol, status: 'open', openedAt: Date.now(), second: second || undefined }; made = all[id]; return all; }); return { ok: true, box: made }; } @@ -134,7 +139,9 @@ function visited(rec) { store.update('boxes', {}, all => { const b = all[rec.boxId]; if (b && b.status === 'started' && b.token === rec.t) { b.status = 'visited'; b.visitedAt = Date.now(); } return all; }); } -function answer(me, choice) { +// gate (the Game Pass, GAME-PASS.md 3a): { ask(pol, ref) -> IAP's answer, wait(rowId, pol, ref) } set by server.js when GAMEPASS=on; +// the case is scored first (the answer is final either way), then InstantAdPay decides what the account-wide cap allows +async function answer(me, choice, gate) { const b = getBox(me.memberId, ctDay()); if (!b) return { error: 'No case open today.' }; if (b.status === 'won' || b.status === 'missed') return { error: 'You already answered today’s case.' }; if (b.status !== 'visited') return { error: 'Visit the site first. The question unlocks once your visit is recorded.' }; @@ -147,17 +154,26 @@ function answer(me, choice) { if (!claimed) return { error: 'You already answered today’s case.' }; const correct = ord[n] === 0; const at = Date.now(); store.update('answers', [], all => { all.push({ memberId: Number(me.memberId), boxId: b.id, missionId: b.missionId, qid: q.id, correct, picked: q.options[ord[n]], at, ms: b.shownAt ? at - b.shownAt : null }); return all; }); - let g = null; + let g = null, note = null; try { if (correct) { const m = missions.get(b.missionId) || { id: b.missionId, site: b.missionId }; - g = rewards.grantFixed(me, { missionId: 'detective:' + m.id, site: m.site, pol: b.pol, detective: { boxId: b.id, qid: q.id } }); + const t = { missionId: 'detective:' + m.id, site: m.site, pol: b.pol, detective: { boxId: b.id, qid: q.id } }; + if (gate) { // the Game Pass: a case is a repeatable ('daily') reward; what the account-wide cap does not allow is dropped, not deferred + const ref = 'detective:' + b.id, r = await gate.ask(b.pol, ref); + if (r.retry) { t.status = 'gp-wait'; t.gp = { ref, kind: 'daily', nominal: b.pol, pending: true }; t.nominal = b.pol; } + else { t.pol = r.allowed; t.nominal = b.pol; t.gp = { ref, kind: 'daily', nominal: b.pol, pass: !!r.pass, capHit: r.capHit || null }; } + note = r.note || null; + g = rewards.grantFixed(me, t); + if (r.retry && g && g.rec) gate.wait(g.rec.id, b.pol, ref); + } else g = rewards.grantFixed(me, t); } } finally { // the answer is final either way; a grant that failed shows in the admin as a won box with no payout patchBox(b.id, { status: correct ? 'won' : 'missed', answeredAt: at, payoutId: g && g.rec ? g.rec.id : null }); } - return { ok: true, correct, pol: correct ? b.pol : 0, queued: !!(g && g.queued), rec: g && g.rec, answer: q.options[0] }; + const paid = correct && g && g.rec && g.rec.status !== 'gp-wait' ? g.rec.pol : 0; // a gp-wait row holds the nominal amount until IAP answers: nothing is paid yet + return { ok: true, correct, pol: paid, nominal: b.pol, note, queued: !!(g && g.queued), waiting: !!(g && g.waiting), capped: !!(g && g.capped), rec: g && g.rec, answer: q.options[0] }; } // ---- stats for the admin ------------------------------------------------------------------------- @@ -173,4 +189,4 @@ function stats() { }; } -module.exports = { init, bank, saveQuestion, setActive, view, open, start, answer, visited, stats, pickCase, earned }; +module.exports = { init, bank, saveQuestion, setActive, view, open, start, answer, visited, stats, pickCase, earned, getBox }; diff --git a/lib/faucet.js b/lib/faucet.js index 7077a07..310662c 100644 --- a/lib/faucet.js +++ b/lib/faucet.js @@ -91,4 +91,21 @@ async function tick(notify) { return { paid }; } -module.exports = { enabled, init, address, balance, tick }; +// one plain POL transfer for a non-drip payment (the weekly Pass Tournament prizes, lib/tournament.js): the same wallet, the same +// RPC rotation on a node hiccup. onHash fires the moment the chain has the transaction, BEFORE the receipt wait, so the caller can +// record the hash durably and never send the same prize twice. Returns { tx, ok } or { tx, pending: true } when the wait timed out. +async function send(to, pol, onHash) { + if (!wallet) throw new Error('faucet is off (HUNT_WALLET_KEY / HUNT_RPC)'); + if (!to || !/^0x[a-f0-9]{40}$/i.test(to)) throw new Error('bad wallet'); + if (!(Number(pol) > 0)) throw new Error('bad amount'); + try { + const tx = await wallet.sendTransaction({ to, value: ethers.parseEther(String(pol)) }); + if (onHash) { try { await onHash(tx.hash); } catch (e) {} } + let rc = null; try { rc = await tx.wait(1, 90000); } catch (e) { if (e && e.code === 'TIMEOUT') return { tx: tx.hash, pending: true }; throw e; } + return { tx: tx.hash, ok: !!(rc && rc.status === 1) }; + } catch (e) { const msg = String(e && e.message || e); if (TRANSIENT.test(msg)) rotate(msg); throw e; } +} +// HUNT_DRY_RUN=on: the tournament payer records what it would pay and sends nothing (the find faucet is not affected) +const dry = () => String(process.env.HUNT_DRY_RUN || 'off').trim().toLowerCase() !== 'off'; + +module.exports = { enabled, init, address, balance, tick, send, dry }; diff --git a/lib/polgrant.js b/lib/polgrant.js new file mode 100644 index 0000000..67096dc --- /dev/null +++ b/lib/polgrant.js @@ -0,0 +1,160 @@ +// polgrant.js: the Game Pass bridge to InstantAdPay (GAME-PASS.md section 3a + its "Built" clarifications). The SAME file lives +// in every network game; change it in one place and copy it to the others. +// +// IAP is the single source of truth for the pass and for the account-wide daily caps. Before any POL grant to a signed-in +// player the game asks `grant({ memberId, email, kind, pol, ref })` and pays only what comes back as `allowed`. +// - kind 'daily' = a repeatable reward (a find, a patrol, a gem): what the cap does not allow is DROPPED, never deferred +// - kind 'progress' = a one-time reward (a boss, a sector, a chapter): what the cap does not allow is DEFERRED on IAP and +// paid on a later day inside `allowed` (the answer says `carried`), so nothing is ever lost +// - the same ref twice gets the same answer (IAP is idempotent on ref, `repeat: true`), so a retry can never double-pay +// - FAIL CLOSED: when IAP cannot be reached (network, 5xx, bad JSON, bad auth) the answer is { allowed: 0, retry: true } +// and the game queues the ref: retried every 5 minutes for up to 48 hours, then the admin chat is told once +// - a player who has not linked a wallet has memberId 0 in every hand-off token: send the email too, IAP resolves the account +// (the pass and the caps are per ACCOUNT); `who` below is the member id when > 0, else the lowercased email +// +// Feature switch: GAMEPASS=on|off (default off: every game keeps its current behaviour, so deploying before launch is safe). +// Env: IAP_URL (default https://instantadpay.com). Auth = the game's own shared sign-in secret (its *_SSO_SECRET): +// POST: JSON body with `game: `, headers X-Game-Ts (ms) and X-Game-Sig = hex HMAC-SHA256(secret, ts + "\n" + rawBody) +// GET /api/partner/player?game=&m=&e=&ts=&sig= with sig = hex HMAC-SHA256(secret, 'player:' + who + ':' + ts) +// GET /api/partner/tournament/pending?game=&ts=&sig= with who = 'tournament' +// The hand-off token carries the flag as claims.gamePass = { active, until }; grant and player answers refresh it. +'use strict'; +const crypto = require('crypto'); + +const PASS_URL = 'https://instantadpay.com/my#games?pass=1'; +const RETRY_MS = 5 * 60000, GIVE_UP_MS = 48 * 3600000, PASS_TTL = 10 * 60000; +let cfg = { game: '', secret: '', iap: 'https://instantadpay.com', store: null, notify: null, fetch: null, log: console, queueKey: 'polgrantq', passKey: 'gamepass' }; +// use({ game, secret, iap, store: { read, write, update }, notify(kind, payload), fetch? }) +function use(o) { cfg = Object.assign(cfg, o || {}); cfg.iap = String(cfg.iap || process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); return cfg; } +const on = () => String(process.env.GAMEPASS || 'off').trim().toLowerCase() === 'on'; +const ctDay = t => new Date(t || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); +const r4 = n => Math.round(Number(n) * 10000) / 10000; +const doFetch = (u, o) => (cfg.fetch || globalThis.fetch)(u, o); +const ready = () => !!(cfg.store && cfg.secret && String(cfg.secret).length >= 32); +// the account key IAP and this module agree on: the member id when linked, else the email ('' = nobody signed in) +const whoOf = (memberId, email) => Number(memberId) > 0 ? String(Number(memberId)) : String(email || '').trim().toLowerCase(); +const hmac = s => crypto.createHmac('sha256', String(cfg.secret)).update(s).digest('hex'); + +async function post(path, body) { + const raw = JSON.stringify(Object.assign({ game: cfg.game }, body)), ts = String(Date.now()); + const r = await doFetch(cfg.iap + path, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game': cfg.game, 'X-Game-Ts': ts, 'X-Game-Sig': hmac(ts + '\n' + raw) }, body: raw, signal: AbortSignal.timeout(6000) }); + const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {} + return { status: r.status, json }; +} +async function get(path, who, params) { + const ts = String(Date.now()); const q = new URLSearchParams(Object.assign({ game: cfg.game }, params || {}, { ts, sig: hmac('player:' + who + ':' + ts) })); + const r = await doFetch(cfg.iap + path + '?' + q.toString(), { signal: AbortSignal.timeout(6000) }); + const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {} + return { status: r.status, json }; +} + +// the one call that matters -> { allowed, deferred, carried, pass, day, capHit, enforced, repeat, retry: false } +// or { allowed: 0, retry: true, error }. Never throws. +async function grant({ memberId, email, game, kind, pol, ref }) { + const body = { memberId: Number(memberId) || 0, email: String(email || '').trim().toLowerCase() || undefined, game: game || cfg.game, kind: kind === 'daily' ? 'daily' : 'progress', pol: r4(Math.max(0, Number(pol) || 0)), ref: String(ref || '') }; + if (!whoOf(body.memberId, body.email) || !body.ref) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: false, error: 'bad request' }; + if (!ready()) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'polgrant not configured' }; + try { + const { status, json } = await post('/api/partner/polgrant', body); + if (status !== 200 || !json || typeof json.allowed !== 'number') return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'http ' + status + (json && json.error ? ': ' + json.error : '') }; + const out = { allowed: r4(Math.max(0, json.allowed)), deferred: r4(Math.max(0, Number(json.deferred) || 0)), carried: r4(Math.max(0, Number(json.carried) || 0)), pass: !!(json.pass && (json.pass === true || json.pass.active)), day: json.day || ctDay(), capHit: json.capHit || null, enforced: json.enforced !== false, repeat: !!json.repeat, suspended: !!json.suspended, retry: false }; + rememberPass(body.memberId, body.email, json.pass, json.passUntil || (json.pass && json.pass.until)); + return out; + } catch (e) { return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: String(e && e.message || e).slice(0, 120) }; } +} +// the game decided not to pay after all (rare): tell IAP so that ref's own share comes back. Best effort. +async function voidGrant({ memberId, email, game, ref }) { + if (!ready() || !whoOf(memberId, email) || !ref) return { ok: false }; + try { const { status } = await post('/api/partner/polgrant/void', { memberId: Number(memberId) || 0, email: String(email || '').toLowerCase() || undefined, game: game || cfg.game, ref: String(ref) }); return { ok: status === 200 }; } catch (e) { return { ok: false, error: String(e && e.message || e) }; } +} + +// ---- the pass flag: from the sign-in hand-off (claims.gamePass), every grant answer, or a signed GET to IAP ---------------- +function passOf(memberId, email) { + const who = whoOf(memberId, email), all = cfg.store && who ? cfg.store.read(cfg.passKey, {}) : {}, p = all[who] || null; + if (!p) return { active: false, until: null, at: 0 }; + const active = !!p.active && (!p.until || p.until > Date.now()); + return { active, until: p.until || null, at: p.at || 0 }; +} +// pass = true/false or { active, until }; until = ms when known +function rememberPass(memberId, email, pass, until) { + const who = whoOf(memberId, email); if (!cfg.store || !who || pass == null) return; + const active = pass === true || !!(pass && pass.active); const u = Number(until || (pass && pass.until)) || null; + cfg.store.update(cfg.passKey, {}, all => { const cur = all[who] || {}; all[who] = { active, until: active ? (u || cur.until || null) : null, at: Date.now() }; return all; }); +} +// refresh from IAP when the cached answer is stale; fail-soft (display only, the grant answers are the truth for money) +async function fetchPass(memberId, email) { + const who = whoOf(memberId, email), cur = passOf(memberId, email); if (!ready() || !who) return cur; + if (Date.now() - cur.at < PASS_TTL) return cur; + try { + const { status, json } = await get('/api/partner/player', who, { m: Number(memberId) || 0, e: String(email || '').toLowerCase() }); + if (status !== 200 || !json) throw new Error('http ' + status); + if (json.pass != null) rememberPass(memberId, email, json.pass, json.pass && json.pass.until); + return passOf(memberId, email); + } catch (e) { return cur; } +} +// what the lobby shows: { on, active, until, untilText, url } +function view(memberId, email) { + const p = whoOf(memberId, email) ? passOf(memberId, email) : { active: false, until: null }; + return { on: on(), active: p.active, until: p.until, untilText: p.until ? new Date(p.until).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' }) : null, url: PASS_URL }; +} + +// ---- the player-facing truth for a grant answer ------------------------------------------------------------------------ +function note(resp, kind, nominal) { + nominal = r4(nominal); + if (!resp) return null; + if (resp.retry) return 'Your reward is recorded and pays as soon as InstantAdPay confirms it.'; + if (kind === 'progress' && resp.deferred > 0) return resp.deferred + ' POL is yours; it pays out over the next days (daily cap).'; + if (kind === 'daily' && resp.allowed + 1e-9 < nominal) return resp.pass ? 'Daily cap reached for today.' : 'Daily cap reached for today. Get the Pass for a higher cap.'; + return null; +} + +// ---- the retry queue (fail closed, never lost): persisted, every 5 minutes, 48 hours, then the admin chat ---------------- +function enqueue(item) { + if (!cfg.store) return null; + const row = Object.assign({}, item, { memberId: Number(item.memberId) || 0, email: String(item.email || '').toLowerCase(), ref: String(item.ref), at: item.at || Date.now(), tries: 0, nextAt: Date.now() + RETRY_MS, stuck: false }); + row.who = whoOf(row.memberId, row.email); + cfg.store.update(cfg.queueKey, [], q => { if (!q.some(x => (x.who || whoOf(x.memberId, x.email)) === row.who && x.ref === row.ref)) q.push(row); return q; }); + return row; +} +const queue = () => cfg.store ? cfg.store.read(cfg.queueKey, []) : []; +const same = (x, memberId, email, ref) => (x.who || whoOf(x.memberId, x.email)) === whoOf(memberId, email) && x.ref === String(ref); +const queued = (memberId, email, ref) => queue().some(x => same(x, memberId, email, ref)); // waiting on IAP: do not ask again +const dequeue = (memberId, email, ref) => cfg.store && cfg.store.update(cfg.queueKey, [], q => q.filter(x => !same(x, memberId, email, ref))); +// pay(item, resp) settles the answer in the game's own ledger. Returns { tried, paid, stuck }. +async function retry(pay, now) { + now = now || Date.now(); const out = { tried: 0, paid: 0, stuck: 0 }; + if (!cfg.store || !on()) return out; + for (const item of queue()) { + if (item.stuck || item.nextAt > now) continue; + out.tried++; + const r = await grant({ memberId: item.memberId, email: item.email, kind: item.kind, pol: item.pol, ref: item.ref }); + if (r.retry) { + const stuck = now - item.at >= GIVE_UP_MS; + cfg.store.update(cfg.queueKey, [], q => { const x = q.find(y => same(y, item.memberId, item.email, item.ref)); if (x) { x.tries = (x.tries || 0) + 1; x.nextAt = now + RETRY_MS; x.lastError = r.error || null; if (stuck) x.stuck = true; } return q; }); + if (stuck) { out.stuck++; if (cfg.notify) { try { await cfg.notify('gpstuck', { memberId: item.memberId, email: item.email, ref: item.ref, pol: item.pol, kind: item.kind, since: item.at, error: r.error || null }); } catch (e) {} } } + continue; + } + dequeue(item.memberId, item.email, item.ref); + try { await pay(item, r); out.paid++; } catch (e) { if (cfg.log) cfg.log.error('polgrant pay', item.ref, e && e.message); } + } + return out; +} +let timer = null; +function startRetry(pay, everyMs) { if (timer) return timer; timer = setInterval(() => { retry(pay).catch(e => cfg.log && cfg.log.error('polgrant retry', e && e.message)); }, everyMs || RETRY_MS); if (timer.unref) timer.unref(); return timer; } +function stopRetry() { if (timer) clearInterval(timer); timer = null; } + +// ---- the weekly Pass Tournament prize seam (3a item 8): IAP records the winners, a game's faucet pays them ------------------ +// -> { ok, rows: [{ id?, week, place, email, memberId, wallet, pol }] } or { ok: false, retry: true, error } +async function tournamentPending() { + if (!ready()) return { ok: false, retry: true, error: 'polgrant not configured', rows: [] }; + try { const { status, json } = await get('/api/partner/tournament/pending', 'tournament', {}); if (status !== 200 || !json) return { ok: false, retry: true, error: 'http ' + status, rows: [] }; return { ok: true, rows: Array.isArray(json.rows) ? json.rows : Array.isArray(json) ? json : [] }; } + catch (e) { return { ok: false, retry: true, error: String(e && e.message || e).slice(0, 120), rows: [] }; } +} +// the row leaves IAP's unpaid list once the game reports the tx (sends id when the row has one, and week + place always) +async function tournamentPaid(row, tx) { + if (!ready()) return { ok: false, error: 'polgrant not configured' }; + try { const { status, json } = await post('/api/partner/tournament/paid', { id: row.id, week: row.week, place: row.place, memberId: row.memberId, email: row.email, tx }); return { ok: status === 200 && !(json && json.error), status, error: json && json.error }; } + catch (e) { return { ok: false, error: String(e && e.message || e).slice(0, 120) }; } +} + +module.exports = { use, on, whoOf, grant, voidGrant, passOf, rememberPass, fetchPass, view, note, enqueue, queue, queued, dequeue, retry, startRetry, stopRetry, tournamentPending, tournamentPaid, PASS_URL, RETRY_MS, GIVE_UP_MS, ctDay, r4, _cfg: () => cfg }; diff --git a/lib/rewards.js b/lib/rewards.js index e5f2cb9..3129869 100644 --- a/lib/rewards.js +++ b/lib/rewards.js @@ -35,13 +35,16 @@ function draw(min, max, skew) { // day defaults to today: called without it the comparison was against undefined and silently // returned 0 for everyone, which would read as "no finds yet" to any new caller function findsToday(memberId, day) { const d = day || ctDay(); return store.read('payouts', []).filter(p => p.memberId === Number(memberId) && p.day === d && p.status !== 'failed' && !p.prize && !p.ref && !p.detective).length; } -function daily(memberId, doneIds, bonus) { const s = settings(); const base = Math.max(1, Number(s.missionsPerDay) || 3); +// passExtra: the Game Pass perk, +2 missions a day while the member's pass is active (GAME-PASS.md 4: 3 -> 5); 0 otherwise +function daily(memberId, doneIds, bonus, passExtra) { const s = settings(); const base = Math.max(1, Number(s.missionsPerDay) || 3); // every live paid mission this hunter has not done yet adds one, because the company is not // funding that completion let extra = 0; try { extra = require('./paid').extraAllowance(doneIds); } catch (e) {} // Friday Bonus Hunts: extra hunts banked Sat-Thu on InstantAdPay, usable on Friday only (lib/fridaybank.js) - const fb = Math.max(0, Number(bonus) || 0); - const limit = base + extra + fb; const done = findsToday(memberId, ctDay()); return { limit, done, left: Math.max(0, limit - done), base, friday: fb }; } + const fb = Math.max(0, Number(bonus) || 0), pe = Math.max(0, Number(passExtra) || 0); + const limit = base + extra + fb + pe; const done = findsToday(memberId, ctDay()); return { limit, done, left: Math.max(0, limit - done), base, friday: fb, pass: pe }; } +// the nominal amount a completion of `mission` would pay (the Game Pass asks InstantAdPay about it before grant() records it) +function quote(mission) { const s = settings(); return mission.paid ? Math.round(Number(mission.hunterPol || 0) * 10000) / 10000 : draw(Number(s.minPol), Number(s.maxPol)); } // What the COMPANY has spent today. Advertiser-funded completions are excluded on purpose: the // hunter is paid out of what the advertiser already put in the faucet, so counting it here would // let a paid mission use up the house budget (Marty, 2026-09-24). @@ -62,28 +65,37 @@ function doneToday(memberId, wallet) { return new Set(store.read('payouts', []).filter(p => p.day === day && p.status !== 'failed' && !p.prize && !p.ref && !p.detective && (p.memberId === Number(memberId) || (w && p.wallet && String(p.wallet).toLowerCase() === w))).map(p => p.missionId)); } -// record a completion; decide paid-today vs queued -function grant(member, mission) { - const s = settings(); +// record a completion; decide paid-today vs queued. +// opts (the Game Pass, GAME-PASS.md 3a): { pol, status, gp, nominal }: `pol` is what InstantAdPay allowed (0 = the account-wide daily +// cap is reached: the find is recorded with status 'capped', pays nothing, and still counts as today's find); status 'gp-wait' = IAP +// could not be reached, the row holds the nominal amount and is settled by settleQueued() when the retry queue gets an answer. +function grant(member, mission, opts) { + opts = opts || {}; const s = settings(); // An advertiser-funded mission pays exactly what the advertiser set, every time. No draw, so // the reserve taken at purchase is exact and can never come up short. const isPaid = !!mission.paid; - const pol = isPaid ? Math.round(Number(mission.hunterPol || 0) * 10000) / 10000 - : draw(Number(s.minPol), Number(s.maxPol)); + const pol = opts.pol != null ? Math.round(Number(opts.pol) * 10000) / 10000 : quote(mission); const day = ctDay(); const budgetLeft = mission.budget ? mission.budget - store.read('payouts', []).filter(p => p.missionId === mission.id && p.status !== 'failed').length : Infinity; if (budgetLeft <= 0) return { error: 'This mission has paid out all it was funded for.' }; // the house cap governs house spend only; a paid completion is already funded - const overCap = !isPaid && (paidToday(day) + pol > Number(s.dailyCapPol)); + const overCap = pol > 0 && !isPaid && (paidToday(day) + pol > Number(s.dailyCapPol)); const rec = { id: Date.now().toString(36) + Math.random().toString(36).slice(2, 8), memberId: Number(member.memberId), email: member.email, wallet: member.wallet, username: member.username || null, missionId: mission.id, site: mission.site, pol, day, at: Date.now(), paid: isPaid || undefined, // marks advertiser-funded spend so the house accounting skips it - status: overCap ? 'queued' : 'due', tx: null, paidAt: null, error: null, + status: opts.status || (pol > 0 ? (overCap ? 'queued' : 'due') : 'capped'), tx: null, paidAt: null, error: null, + gp: opts.gp || undefined, nominal: opts.nominal != null ? opts.nominal : undefined, }; store.update('payouts', [], all => { all.push(rec); return all; }); - return { ok: true, rec, queued: overCap }; + return { ok: true, rec, queued: rec.status === 'queued', capped: rec.status === 'capped', waiting: rec.status === 'gp-wait' }; +} +// a 'gp-wait' row gets InstantAdPay's answer: pay what was allowed (due, or queued past the house cap), or record the cap hit +function settleQueued(id, allowed, gp) { + const s = settings(); const pol = Math.round(Number(allowed) * 10000) / 10000; let row = null; + store.update('payouts', [], all => { const p = all.find(x => x.id === id); if (p && p.status === 'gp-wait') { const over = pol > 0 && !p.paid && (paidToday(p.day) + pol - (p.pol || 0) > Number(s.dailyCapPol)); Object.assign(p, { pol, status: pol > 0 ? (over ? 'queued' : 'due') : 'capped', gp: Object.assign({}, p.gp || {}, gp || {}, { pending: false }) }); row = p; } return all; }); + return row; } // A fixed, disclosed amount for a non-find task (an Ad Detective case). House money, so it sits inside @@ -91,16 +103,17 @@ function grant(member, mission) { // of the daily limit, the leaderboard, prizes, referral matches and the find badges). function grantFixed(member, t) { const s = settings(); const day = ctDay(); const pol = Math.round(Number(t.pol) * 10000) / 10000; - if (!(pol > 0)) return { error: 'no reward set' }; - const overCap = paidToday(day) + pol > Number(s.dailyCapPol); + if (!(pol > 0) && !t.gp) return { error: 'no reward set' }; // the Game Pass may record a 0 (account-wide cap reached), see grant() + const overCap = pol > 0 && paidToday(day) + pol > Number(s.dailyCapPol); const rec = { id: Date.now().toString(36) + Math.random().toString(36).slice(2, 8), memberId: Number(member.memberId), email: member.email, wallet: member.wallet, username: member.username || null, missionId: t.missionId, site: t.site, pol, day, at: Date.now(), detective: t.detective || true, - status: overCap ? 'queued' : 'due', tx: null, paidAt: null, error: null, + status: t.status || (pol > 0 ? (overCap ? 'queued' : 'due') : 'capped'), tx: null, paidAt: null, error: null, + gp: t.gp || undefined, nominal: t.nominal != null ? t.nominal : undefined, }; store.update('payouts', [], all => { all.push(rec); return all; }); - return { ok: true, rec, queued: overCap }; + return { ok: true, rec, queued: rec.status === 'queued', capped: rec.status === 'capped', waiting: rec.status === 'gp-wait' }; } // what the faucet should pay now: due entries, then queued ones as long as today's cap allows @@ -141,4 +154,4 @@ function totals() { return { paid: paid.length, pol: Math.round(paid.reduce((n, p) => n + p.pol, 0) * 10000) / 10000, queued: all.filter(p => p.status === 'queued').length, today: paidToday(ctDay()), hunters: new Set(paid.map(p => p.memberId)).size }; } -module.exports = { settings, setSettings, draw, grant, grantFixed, completed, doneToday, payable, mark, ledger, mine, totals, paidToday, pool, nextResetAt, daily, findsToday, unposted }; +module.exports = { settings, setSettings, draw, quote, grant, grantFixed, settleQueued, completed, doneToday, payable, mark, ledger, mine, totals, paidToday, pool, nextResetAt, daily, findsToday, unposted }; diff --git a/lib/tournament.js b/lib/tournament.js new file mode 100644 index 0000000..2466c90 --- /dev/null +++ b/lib/tournament.js @@ -0,0 +1,73 @@ +// The weekly Pass Tournament prizes (GAME-PASS.md 3a item 8, Marty 2026-10-16: PolHunter's faucet pays them). +// +// InstantAdPay ranks the week's pass holders and records the winners; this job, every 10 minutes behind GAMEPASS=on, pulls the +// unpaid rows (`GET /api/partner/tournament/pending`, signed), pays each from PolHunter's hot wallet through the faucet's own send +// path (same wallet, same RPC rotation, same low-balance alert), and reports the hash (`POST /api/partner/tournament/paid`) so the +// row leaves IAP's list. Prizes are not finds: they bypass the per-find daily cap and the payout threshold. +// +// Never twice (the deploy-overlap rule: two app copies run for ~30 s on every deploy): a durable claim per row is written to +// `tourney-claims` on the volume BEFORE anything is sent; the tx hash is written the moment the chain has it (before the receipt +// wait); on restart a claimed row with a hash is only re-reported, never re-sent; a claim without a hash is retried only after +// CLAIM_TTL (the other copy had its chance). A send failure leaves the row pending on IAP and alerts the admin chat. +// HUNT_DRY_RUN=on: record what would be paid, send nothing. Admin visibility: `state()` (last run, paid rows, failures) in /api/admin/state. +'use strict'; +const store = require('./store'); +const gp = require('./polgrant'); + +const EVERY_MS = 10 * 60000, CLAIM_TTL = 10 * 60000, KEEP = 200; +let deps = { faucet: null, notify: null, dry: () => false }; // faucet: { send(to, pol, onHash), balance(), address() } +function init(d) { deps = Object.assign(deps, d || {}); } +const ctDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); +const r4 = n => Math.round(Number(n) * 10000) / 10000; +const keyOf = row => row.id != null ? 'id:' + row.id : 'wk:' + row.week + ':' + row.place; +const claims = () => store.read('tourney-claims', {}); +function claim(k, row, now) { let got = false; store.update('tourney-claims', {}, all => { const c = all[k]; if (!c || (!c.tx && !c.dry && now - (c.claimedAt || 0) >= CLAIM_TTL)) { all[k] = { claimedAt: now, week: row.week, place: row.place, memberId: row.memberId || 0, email: row.email || null, wallet: row.wallet, pol: r4(row.pol), tries: ((c && c.tries) || 0) + 1 }; got = true; } return all; }); return got; } +const mark = (k, patch) => store.update('tourney-claims', {}, all => { if (all[k]) Object.assign(all[k], patch); return all; }); +const release = (k, patch) => store.update('tourney-claims', {}, all => { if (all[k] && !all[k].tx) { Object.assign(all[k], patch || {}); all[k].claimedAt = 0; } return all; }); // free for the next run +let running = false; + +async function run(now) { + now = now || Date.now(); + const st = { lastRun: now, on: gp.on(), dry: deps.dry(), pending: 0, paid: 0, acked: 0, skipped: 0, wouldPay: 0, failures: [] }; + if (!gp.on()) { save(st); return st; } + if (running) { st.skipped = -1; return st; } running = true; + try { + const list = await gp.tournamentPending(); + if (!list.ok) { st.error = list.error || 'pending unreachable'; save(st); return st; } + st.pending = list.rows.length; + for (const row of list.rows) { + const k = keyOf(row), c = claims()[k], pol = r4(row.pol); + if (!row.wallet || !/^0x[a-f0-9]{40}$/i.test(row.wallet) || !(pol > 0)) { st.failures.push({ k, error: 'no wallet or no amount' }); continue; } + if (c && c.tx) { // paid before (this copy or the other one, or before a restart): IAP still lists it, so report the hash again + const ack = await gp.tournamentPaid(row, c.tx); if (ack.ok) { mark(k, { acked: now }); st.acked++; } else st.failures.push({ k, error: 'paid report failed: ' + (ack.error || ack.status) }); continue; + } + if (c && c.dry) { st.skipped++; st.wouldPay = r4(st.wouldPay + pol); continue; } // recorded in a dry run already + if (c && !c.tx && now - (c.claimedAt || 0) < CLAIM_TTL) { st.skipped++; continue; } // the other app copy is on it right now + if (!claim(k, row, now)) { st.skipped++; continue; } // claimed BEFORE anything is sent + if (deps.dry()) { mark(k, { dry: true, wouldPay: pol, at: now }); st.wouldPay = r4(st.wouldPay + pol); continue; } + let bal = null; try { bal = await deps.faucet.balance(); } catch (e) {} + if (bal != null && bal < pol + 0.005) { release(k, { error: 'low balance' }); await lowOnce(bal, pol); st.failures.push({ k, error: 'low balance ' + bal }); break; } + try { + const res = await deps.faucet.send(row.wallet, pol, hash => mark(k, { tx: hash, sentAt: Date.now() })); + if (!res || !res.tx) throw new Error('no transaction hash'); + mark(k, { tx: res.tx, sentAt: Date.now(), ok: res.ok !== false, pending: !!res.pending }); st.paid++; + const ack = await gp.tournamentPaid(row, res.tx); if (ack.ok) { mark(k, { acked: Date.now() }); st.acked++; } else st.failures.push({ k, error: 'paid report failed: ' + (ack.error || ack.status) }); // retried next run from the claim's tx + if (deps.notify) { try { await deps.notify('tourneypaid', Object.assign({}, row, { pol, tx: res.tx })); } catch (e) {} } + } catch (e) { + const error = String(e && e.message || e).slice(0, 200); + if (claims()[k] && claims()[k].tx) { st.failures.push({ k, error: 'sent, receipt unknown: ' + error }); continue; } // the chain has it: never re-send; the next run reports the hash + release(k, { error }); st.failures.push({ k, error }); + if (deps.notify) { try { await deps.notify('tourneyfail', Object.assign({}, row, { pol, error })); } catch (e2) {} } + } + } + } finally { running = false; } + save(st); return st; +} +async function lowOnce(bal, need) { const day = ctDay(); let first = false; store.update('tourney-state', {}, x => { if (x.lowAlertDay !== day) { x.lowAlertDay = day; first = true; } return x; }); if (first && deps.notify) { try { await deps.notify('low', { balance: bal, threshold: need, address: deps.faucet.address ? deps.faucet.address() : null, tournament: true }); } catch (e) {} } } +function save(st) { store.update('tourney-state', {}, x => { Object.assign(x, { last: st }); x.history = [].concat(x.history || [], [{ at: st.lastRun, paid: st.paid, acked: st.acked, pending: st.pending, failures: st.failures.length, dry: st.dry, error: st.error || null }]).slice(-KEEP); if (st.paid) x.paidTotal = (x.paidTotal || 0) + st.paid; return x; }); } +// for the admin: last run, totals, the open claims +function state() { const x = store.read('tourney-state', {}), cl = claims(); return { on: gp.on(), dry: deps.dry(), last: x.last || null, paidTotal: x.paidTotal || 0, recent: (x.history || []).slice(-10).reverse(), claims: Object.keys(cl).map(k => Object.assign({ key: k }, cl[k])).sort((a, b) => (b.sentAt || b.claimedAt || 0) - (a.sentAt || a.claimedAt || 0)).slice(0, 30) }; } +let timer = null; +function start() { if (timer) return timer; timer = setInterval(() => run().catch(e => console.error('tournament', e && e.message)), EVERY_MS); if (timer.unref) timer.unref(); setTimeout(() => run().catch(() => {}), 20000).unref(); return timer; } + +module.exports = { init, run, state, start, keyOf, EVERY_MS, CLAIM_TTL }; diff --git a/package.json b/package.json index d7f9abd..2284292 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "start": "node server.js", "dev": "node --watch server.js", - "test": "node test/run.js" + "test": "node test/gamepass.js && node test/run.js" }, "engines": { "node": ">=20" diff --git a/public/app.html b/public/app.html index 1cb5191..bda3cdf 100644 --- a/public/app.html +++ b/public/app.html @@ -58,6 +58,6 @@ - + diff --git a/public/app.js b/public/app.js index 5c01b20..31e0616 100644 --- a/public/app.js +++ b/public/app.js @@ -114,7 +114,9 @@ document.addEventListener('click', e => { if (e.target.id === 'shareClose' || e.target.id === 'shareModal') $('shareModal').hidden = true; }); function render() { badgeStrip(); - $('who').innerHTML = ' ' + esc(board.me.username ? '@' + board.me.username : '#' + board.me.memberId) + (board.me.wallet ? '' : ' · no wallet linked'); + $('who').innerHTML = ' ' + esc(board.me.username ? '@' + board.me.username : '#' + board.me.memberId) + (board.me.wallet ? '' : ' · no wallet linked') + // Game Pass (InstantAdPay, all nine games): active until , or the link to get it; opens a new tab (the game may be framed) + + (board.gamepass && board.gamepass.on ? ' · ' + (board.gamepass.active ? '\u{1F3AB} Game Pass active' + (board.gamepass.untilText ? ' until ' + esc(board.gamepass.untilText) : '') + ' (5 missions a day, 2 Ad Detective cases)' : '\u{1F3AB} Get the Game Pass: higher daily POL caps, 5 missions a day, 2 cases') : ''); const r = board.missions[0] && board.missions[0].reward; if (r) $('rangeLine').textContent = 'Each find pays a random drip between ' + r.minPol + ' and ' + r.maxPol + ' POL. Your codes are yours alone.'; const pool = board.pool || {}; @@ -263,6 +265,8 @@ $('submit').disabled = true; const r = await api('/api/my/submit', { token: open.token, code }); const m = $('msg'); m.className = 'msg ' + (r.error ? 'bad' : 'ok'); m.textContent = r.error || r.message; + if (!r.error && r.gamepass) board.gamepass = r.gamepass; // the Game Pass flag refreshes with every grant answer + if (!r.error && /Get the Pass/.test(r.message || '') && board.gamepass && board.gamepass.on && !board.gamepass.active) m.innerHTML = esc(r.message) + ' Get the Game Pass'; // the cap-hit nudge, in a new tab (the page may be framed) if (r.error) toast(esc(r.error), 'bad'); else toast('\u{1F389} Found it! ' + r.pol + ' POL is on its way to your wallet.', 'big'); if (!r.error) { const a = document.createElement('a'); a.href = '#share'; a.textContent = ' Share this find \u2197'; a.style.marginLeft = '6px'; m.appendChild(a); delete $('sharetext').dataset.touched; } // an achievement unlocked by this find: celebrate it once the board has reloaded diff --git a/server.js b/server.js index ace0a8e..f9dd068 100644 --- a/server.js +++ b/server.js @@ -45,6 +45,21 @@ const signupsOpen = () => process.env.SIGNUPS === 'open'; store.init(DATA_DIR); const faucetOn = faucet.init(); detective.init(); +// ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide daily cap decides what a hunter is paid; the house +// cap and the per-hunter daily limit stay as backstops. Finds and Ad Detective cases are repeatable ('daily'): what the cap does not +// allow is dropped and the hunter is told. Advertiser-funded missions are NOT gated: the advertiser already paid for that completion. +const gp = require('./lib/polgrant'), tournament = require('./lib/tournament'); +const IAP_URL = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); +gp.use({ game: 'polhunter', secret: String(process.env.HUNT_SSO_SECRET || '').trim(), iap: IAP_URL, store, notify: (kind, p) => notify(kind, p) }); +const passActive = me => !!(gp.on() && me && gp.passOf(me.memberId, me.email).active); +const passExtra = me => passActive(me) ? 2 : 0; // the perk: 5 missions a day instead of 3 +// one reward through IAP: ask(pol, ref) -> IAP's answer (+ the player-facing note), wait(rowId, pol, ref) -> queue the ref (fail closed) +const gpGate = me => ({ + ask: async (pol, ref) => { const r = await gp.grant({ memberId: me.memberId, email: me.email, kind: 'daily', pol, ref }); r.note = gp.note(r, 'daily', pol); return r; }, + wait: (rowId, pol, ref) => gp.enqueue({ memberId: me.memberId, email: me.email, ref, kind: 'daily', pol, rowId }), +}); +const payQueued = async (item, r) => { rewards.settleQueued(item.rowId, r.allowed, { pass: !!r.pass, capHit: r.capHit || null }); }; // a queued ref finally answered +tournament.init({ faucet, notify: (kind, p) => notify(kind, p), dry: faucet.dry }); // Badges added after launch count work already done, so on the day they ship many hunters hold them at once. // Those are marked as announced without posting, or the badge sweep would flood Telegram with old news. // Badges earned from here on are announced as usual. Runs once per new badge id. @@ -91,7 +106,10 @@ async function notifyPaid(p) { { const ok = await telegram('\u{1F3AF} PolHunter · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' found it on ' + p.site + ' and got ' + fmt(p.pol) + ' POL · verify\nHunt yours'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; } } async function notifyOther(kind, p) { - if (kind === 'low') return telegram('⚠️ PolHunter faucet is low: ' + fmt(p.balance) + ' POL left in ' + p.address + ' (alert threshold ' + fmt(p.threshold) + '). Top up from Receiver B.'); + if (kind === 'low') return telegram('⚠️ PolHunter faucet is low: ' + fmt(p.balance) + ' POL left in ' + p.address + ' (alert threshold ' + fmt(p.threshold) + ').' + (p.tournament ? ' A Pass Tournament prize is waiting on it.' : '') + ' Top up from Receiver B.'); + if (kind === 'gpstuck') return telegram('⚠️ PolHunter Game Pass grant stuck 48 h: member #' + p.memberId + ' ' + (p.email || '') + ' ref ' + p.ref + ' (' + fmt(p.pol) + ' POL, ' + p.kind + '). InstantAdPay /api/partner/polgrant unreachable: ' + (p.error || '?')); + if (kind === 'tourneypaid') return telegram('\u{1F3C6} Pass Tournament prize paid from the PolHunter faucet: week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · ' + fmt(p.pol) + ' POL · verify'); + if (kind === 'tourneyfail') return telegram('❌ Pass Tournament prize NOT paid (row stays pending on InstantAdPay): week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · ' + fmt(p.pol) + ' POL · ' + p.error); if (kind === 'failed') return telegram('❌ PolHunter · drip to #' + p.memberId + ' failed: ' + p.error); // a bounty is the one payout that advertises the mission itself, so it goes to the room if (kind === 'referral') { const d = p.drip; return telegram('\u{1F91D} PolHunter · ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' brought ' + d.ref.forName + ' in and they are hunting · ' + fmt(d.pol) + ' POL bounty on the way\nBring yours'); } @@ -229,6 +247,7 @@ const server = http.createServer(async (req, res) => { let sid = cur && cur.memberId === Number(v.claims.memberId) ? cur.sid : null; if (sid) sso.refresh(sid, v.claims); else sid = sso.startSession(v.claims); referrals.seen(v.claims); // keep the hunter directory (and the sponsor behind it) current on every sign-in + if (v.claims.gamePass != null) gp.rememberPass(v.claims.memberId, v.claims.email, v.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7) res.writeHead(302, { Location: '/app', 'Set-Cookie': sso.cookie(sid), 'Cache-Control': 'no-store' }); return res.end(); } if (p === '/logout') { const s = sso.fromRequest(req); if (s) sso.endSession(s.sid); res.writeHead(302, { Location: '/', 'Set-Cookie': sso.clearCookie() }); return res.end(); } @@ -254,9 +273,10 @@ const server = http.createServer(async (req, res) => { const me = sso.fromRequest(req); if (!me) return json(res, 401, { error: 'Open PolHunter from your InstantAdPay dashboard to sign in.' }); if (p === '/api/my/board') { const fbank = await fbFor(me); + if (gp.on()) gp.fetchPass(me.memberId, me.email).catch(() => {}); // keep the Game Pass flag fresh (display + perks; grant answers carry the truth) referrals.seen(me); // hunters already signed in never pass through /auth again, so keep the directory fresh here too const done = rewards.doneToday(me.memberId, me.wallet); const wdone = done; // today's finds, by member id or wallet - return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, missions: missions.forMember(me.memberId).map(m => Object.assign(pubMission(m), { done: done.has(m.id) || wdone.has(m.id) })), drips: rewards.mine(me.memberId).slice(0, 20), faucet: { on: faucetOn }, pool: rewards.pool(), daily: rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fbank.bonus), fridayBank: fbank, + return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet }, missions: missions.forMember(me.memberId).map(m => Object.assign(pubMission(m), { done: done.has(m.id) || wdone.has(m.id) })), drips: rewards.mine(me.memberId).slice(0, 20), faucet: { on: faucetOn }, pool: rewards.pool(), daily: rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fbank.bonus, passExtra(me)), fridayBank: fbank, gamepass: gp.view(me.memberId, me.email), badges: social.badgesFor(me.memberId), badgeCards: (() => { const got = new Set(social.badgesFor(me.memberId).map(b => b.id)); const who = social.nameOf(me); return social.BADGES.map(b => ({ id: b.id, name: b.name, icon: b.icon, why: b.why, art: '/badges/badge-' + b.id + '.jpg', earned: got.has(b.id), page: got.has(b.id) ? SITE + '/b/' + who + '/' + b.id : null, image: got.has(b.id) ? SITE + '/badge-img/' + who + '/' + b.id + '.jpg' : null })); })(), rank: { week: social.rankOf(me.memberId, 'week'), month: social.rankOf(me.memberId, 'month'), all: social.rankOf(me.memberId, 'all') }, share: { link: social.shareLink(SITE, me), joinUrl: 'https://instantadpay.com/join/' + encodeURIComponent(String(me.username || me.memberId)) + '?from=polhunter' }, referral: referrals.state(me), box: detective.view(me) }); @@ -266,7 +286,7 @@ const server = http.createServer(async (req, res) => { if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the drip has somewhere to land, then open PolHunter again.' }); if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' }); { const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); } - { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } + { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } if (limited('start:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Twenty starts an hour is plenty.' }); const t = missions.issue(me.memberId, m.id); // a mission URL may place the token itself with {token} (a Telegram Mini App takes it in @@ -282,9 +302,15 @@ const server = http.createServer(async (req, res) => { const m = missions.get(c.rec.missionId); if (!m) return json(res, 404, { error: 'That mission is gone.' }); if (rewards.completed(me.memberId, m.id, me.wallet)) return json(res, 400, { error: 'You already completed this one.' }); { const pool = rewards.pool(); if (pool.spent) return json(res, 400, { error: SPENT_MSG, spent: true, resetsAt: pool.resetsAt }); } - { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } + { const fb = await fbFor(me); const d = rewards.daily(me.memberId, rewards.doneToday(me.memberId, me.wallet), fb.bonus, passExtra(me)); if (!d.left) return json(res, 400, { error: dailyMsg(d), dailyDone: true, resetsAt: rewards.pool().resetsAt }); } const before = new Set(social.badgesFor(me.memberId).map(b => b.id)); - const g = rewards.grant(me, m); if (g.error) return json(res, 400, g); + let g, note = null; + if (gp.on() && !m.paid) { // the Game Pass: IAP's account-wide daily cap first (a paid mission is the advertiser's money, not gated) + const quote = rewards.quote(m), ref = 'find:' + m.id + ':' + missions.ctDay(), r = await gpGate(me).ask(quote, ref); note = r.note; + if (r.retry) { g = rewards.grant(me, m, { pol: quote, status: 'gp-wait', nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pending: true } }); if (!g.error) gpGate(me).wait(g.rec.id, quote, ref); } + else g = rewards.grant(me, m, { pol: r.allowed, nominal: quote, gp: { ref, kind: 'daily', nominal: quote, pass: !!r.pass, capHit: r.capHit || null } }); + } else g = rewards.grant(me, m); + if (g.error) return json(res, 400, g); // whoever brought this hunter gets paid for it: the bounty on their first find, a match while they are new let refDrips = []; try { refDrips = referrals.onFind(me, g.rec); } catch (e) { console.error('referral', e.message); } @@ -292,10 +318,11 @@ const server = http.createServer(async (req, res) => { // achievements unlocked by this find: told to the board, posted to Telegram (gated) const unlocked = social.badgesFor(me.memberId).filter(b => !before.has(b.id)); for (const b of unlocked) notify('badge', { me, id: b.id }).catch(() => {}); - return json(res, 200, { ok: true, pol: g.rec.pol, queued: g.queued, unlocked: unlocked.map(b => b.id), message: g.queued ? 'Found it. Today’s POL is spoken for, so yours is queued and pays out next.' : 'Found it. ' + fmt(g.rec.pol) + ' POL is on its way to your wallet.' }); + return json(res, 200, { ok: true, pol: g.waiting ? 0 : g.rec.pol, nominal: g.rec.nominal, queued: g.queued, capped: g.capped, waiting: g.waiting, note, gamepass: gp.view(me.memberId, me.email), + message: g.waiting ? 'Found it. ' + note : g.capped ? 'Found it. ' + note : g.queued ? 'Found it. Today’s POL is spoken for, so yours is queued and pays out next.' : 'Found it. ' + fmt(g.rec.pol) + ' POL is on its way to your wallet.' + (note ? ' ' + note : '') }); } // ---- Mystery Hunt Box + Ad Detective - if (p === '/api/my/box/open' && req.method === 'POST') { const r = detective.open(me); return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, box: detective.view(me) }); } + if (p === '/api/my/box/open' && req.method === 'POST') { const r = detective.open(me, passActive(me)); return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, box: detective.view(me) }); } // pass: a second case a day if (p === '/api/my/box/start' && req.method === 'POST') { if (!me.wallet) return json(res, 400, { error: 'Link a wallet on InstantAdPay first so the reward has somewhere to land.' }); if (limited('boxstart:' + me.memberId, 20, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); @@ -305,11 +332,11 @@ const server = http.createServer(async (req, res) => { const b = await readBody(req); if (limited('boxans:' + me.memberId, 10, 3600000)) return json(res, 429, { error: 'Easy. Try again in a little while.' }); const before = new Set(social.badgesFor(me.memberId).map(x => x.id)); - const r = detective.answer(me, b.choice); if (r.error) return json(res, 400, r); + const r = await detective.answer(me, b.choice, gp.on() ? gpGate(me) : null); if (r.error) return json(res, 400, r); const unlocked = r.correct ? social.badgesFor(me.memberId).filter(x => !before.has(x.id)) : []; for (const x of unlocked) notify('badge', { me, id: x.id }).catch(() => {}); const msg = r.correct ? (r.queued ? 'Case solved. Today\u2019s POL is spoken for, so your ' + fmt(r.pol) + ' POL is queued and pays out next.' : 'Case solved. ' + fmt(r.pol) + ' POL is on its way to your wallet.') : 'Not this time. The answer was: ' + r.answer + '. A new box unlocks tomorrow.'; - return json(res, 200, { ok: true, correct: r.correct, pol: r.pol, queued: r.queued, unlocked: unlocked.map(x => x.id), message: msg, box: detective.view(me) }); + return json(res, 200, { ok: true, correct: r.correct, pol: r.pol, nominal: r.nominal, queued: r.queued, capped: r.capped, waiting: r.waiting, note: r.note || null, unlocked: unlocked.map(x => x.id), message: msg + (r.note ? ' ' + r.note : ''), box: detective.view(me), gamepass: gp.view(me.memberId, me.email) }); } return json(res, 404, { error: 'No such call.' }); } @@ -317,7 +344,7 @@ const server = http.createServer(async (req, res) => { // ---- admin (key) if (p.startsWith('/api/admin/')) { if (!admin(req)) return json(res, 401, { error: 'Admin key required.' }); - if (p === '/api/admin/state') return json(res, 200, { missions: missions.list(), settings: rewards.settings(), totals: rewards.totals(), referrals: referrals.totals(), referralPool: referrals.refPool(), faucet: { on: faucetOn, address: faucet.address(), state: store.read('faucet-state', {}) }, payouts: store.read('payouts', []).slice(-100).reverse(), gates: { outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN, sso: sso.enabled() } }); + if (p === '/api/admin/state') return json(res, 200, { missions: missions.list(), settings: rewards.settings(), totals: rewards.totals(), referrals: referrals.totals(), referralPool: referrals.refPool(), faucet: { on: faucetOn, address: faucet.address(), state: store.read('faucet-state', {}) }, payouts: store.read('payouts', []).slice(-100).reverse(), gates: { outbound: outbound(), signups: signupsOpen(), curtain: !!CURTAIN, sso: sso.enabled() }, gamepass: { on: gp.on(), iap: IAP_URL, queue: gp.queue().length, stuck: gp.queue().filter(x => x.stuck).length }, tournament: tournament.state() }); if (p === '/api/admin/mission' && req.method === 'POST') { const b = await readBody(req); const id = String(b.id || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40); if (!id) return json(res, 400, { error: 'id required' }); @@ -355,6 +382,9 @@ const server = http.createServer(async (req, res) => { // the faucet pays every two minutes; nothing outward leaves unless OUTBOUND=on (telegram checks) if (faucetOn) setInterval(() => faucet.tick(notify).catch(e => console.error('faucet', e.message)), 2 * 60000); +// Game Pass: refs that could not reach InstantAdPay retry every 5 minutes (lib/polgrant.js); the weekly Pass Tournament prizes are +// paid from this faucet every 10 minutes (lib/tournament.js). Both are inert unless GAMEPASS=on; prizes need the faucet wallet too. +gp.startRetry(payQueued); if (faucetOn) tournament.start(); // Every completed mission reaches Telegram (Marty, 2026-09-21): a find is posted when its drip is paid, and // this sweep posts any paid find that is not marked posted yet (the pre-live gate, Telegram down, a restart). // Only finds made after HUNT_POST_SINCE count, so rehearsal drips from before the doors opened stay quiet. diff --git a/test/gamepass.js b/test/gamepass.js new file mode 100644 index 0000000..5dd53ea --- /dev/null +++ b/test/gamepass.js @@ -0,0 +1,136 @@ +// Game Pass checks for PolHunter (docs/GAME-PASS.md 3a), all local: a stub InstantAdPay on 127.0.0.1 answers polgrant and the +// tournament endpoints; a mocked faucet records sends. Covers the grant client (fail closed, the retry queue, the 48 h alert), +// finds and Ad Detective cases as 'daily' rewards (dropped at the cap, paid missions not gated, 'gp-wait' rows settled by the +// queue), the perks (5 missions a day, a second case) and the Pass Tournament payer (pending -> paid, duplicate ignored, restart +// re-report, send failure leaves the row pending and alerts, dry run, low balance). Production is never contacted. +// Run: node test/gamepass.js +'use strict'; +const http = require('http'), crypto = require('crypto'), fs = require('fs'), os = require('os'), path = require('path'); +process.env.GAMEPASS = 'on'; process.env.HUNT_SSO_SECRET = 'x'.repeat(48); delete process.env.HUNT_DRY_RUN; +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ph-gp-')); +const store = require('../lib/store'); store.init(dir); +const gp = require('../lib/polgrant'), rewards = require('../lib/rewards'), detective = require('../lib/detective'), tournament = require('../lib/tournament'), missions = require('../lib/missions'); +const SECRET = 'test-secret-'.padEnd(40, 'x'), GAME = 'polhunter'; +let pass = 0, fail = 0; +const ok = (name, cond, info) => { if (cond) { pass++; console.log(' ok ', name); } else { fail++; console.log(' FAIL', name, info === undefined ? '' : JSON.stringify(info)); } }; + +(async () => { + // ---- the stub IAP: polgrant (scripted by ref), tournament pending (a list we control) and paid (records the acks) + const seen = [], acks = []; let mode = 'ok', pendingRows = []; const script = {}; + const stub = http.createServer((req, res) => { let raw = ''; req.on('data', c => raw += c); req.on('end', () => { + const u = new URL(req.url, 'http://x'); + if (req.method === 'GET') { // the signed GET forms: player and tournament/pending + const who = u.pathname.endsWith('/tournament/pending') ? 'tournament' : (Number(u.searchParams.get('m')) > 0 ? u.searchParams.get('m') : u.searchParams.get('e')); + const want = crypto.createHmac('sha256', SECRET).update('player:' + who + ':' + u.searchParams.get('ts')).digest('hex'); + if (want !== u.searchParams.get('sig') || u.searchParams.get('game') !== GAME) { res.writeHead(401); return res.end('{"error":"bad sig"}'); } + if (mode === '500') { res.writeHead(500); return res.end('boom'); } + res.writeHead(200, { 'Content-Type': 'application/json' }); + if (u.pathname.endsWith('/tournament/pending')) return res.end(JSON.stringify({ rows: pendingRows.filter(r => !acks.some(a => a.id === r.id)) })); + return res.end(JSON.stringify({ pass: { active: true, until: Date.now() + 86400000 }, memberId: 7 })); + } + const sig = crypto.createHmac('sha256', SECRET).update(req.headers['x-game-ts'] + '\n' + raw).digest('hex'); + if (sig !== req.headers['x-game-sig']) { res.writeHead(401, { 'Content-Type': 'application/json' }); return res.end('{"error":"bad signature"}'); } + if (mode === '500') { res.writeHead(500); return res.end('boom'); } + const b = JSON.parse(raw); if (b.game !== GAME) { res.writeHead(400); return res.end('{"error":"wrong game"}'); } + if (u.pathname.endsWith('/tournament/paid')) { if (mode === 'ackfail') { res.writeHead(500); return res.end('x'); } acks.push(b); res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end('{"ok":true}'); } + seen.push(b); const s = script[b.ref] || { allowed: b.pol, deferred: 0 }; + res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ allowed: s.allowed, deferred: s.deferred || 0, carried: 0, pass: !!s.pass, capHit: s.capHit || null, day: '2026-10-16' })); + }); }); + await new Promise(r => stub.listen(0, '127.0.0.1', r)); const port = stub.address().port; + const alerts = []; const notify = async (k, p) => { alerts.push([k, p]); }; + gp.use({ game: GAME, secret: SECRET, iap: 'http://127.0.0.1:' + port, store, notify }); + + // ---- the client + let r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:1' }); ok('daily inside the cap: allowed = pol', r.allowed === 0.3 && r.retry === false); + script['d:2'] = { allowed: 0.1, capHit: 'daily' }; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:2' }); ok('daily over the cap: dropped, capHit carried, the nudge names the Pass', r.allowed === 0.1 && r.capHit === 'daily' && /Get the Pass/.test(gp.note(r, 'daily', 0.3))); + r = await gp.grant({ memberId: 0, email: 'nowallet@example.com', kind: 'daily', pol: 0.1, ref: 'd:e' }); ok('a wallet-less member is sent by email, memberId 0', r.allowed === 0.1 && seen.at(-1).email === 'nowallet@example.com'); + mode = '500'; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:5' }); ok('a 5xx fails closed', r.allowed === 0 && r.retry === true); mode = 'ok'; + gp.use({ iap: 'http://127.0.0.1:9' }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:8' }); ok('an unreachable IAP fails closed', r.allowed === 0 && r.retry === true); gp.use({ iap: 'http://127.0.0.1:' + port }); + gp.use({ secret: 'wrong-secret-'.padEnd(40, 'y') }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:7' }); ok('a rejected signature fails closed', r.allowed === 0 && r.retry === true); gp.use({ secret: SECRET }); + ok('a fresh cached flag is not refetched (10-minute TTL)', (await gp.fetchPass(7, 'hugh@example.com')).active === false); + store.write('gamepass', {}); const p0 = await gp.fetchPass(7, 'hugh@example.com'); ok('with no cached flag the signed player GET fetches it', p0.active === true && gp.passOf(7, '').active); + mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:old', kind: 'daily', pol: 0.2, at: Date.now() - gp.GIVE_UP_MS - 1000 }); const rr = await gp.retry(async () => {}, Date.now() + gp.RETRY_MS + 1); + ok('48 h without an answer: stuck, the admin chat told once', rr.stuck === 1 && alerts.some(a => a[0] === 'gpstuck')); gp.dequeue(7, '', 'q:old'); mode = 'ok'; alerts.length = 0; + + // ---- finds: 'daily'; the account-wide cap decides; a 0 is recorded as a capped find (still today's find); paid missions are not gated + rewards.setSettings({ minPol: 0.05, maxPol: 1, dailyCapPol: 20, missionsPerDay: 3 }); + const me = { memberId: 7, email: 'hugh@example.com', username: 'hugh', wallet: '0x' + 'a'.repeat(40) }, day = missions.ctDay(); + const m1 = { id: 'm1', site: 'example.com' }, m2 = { id: 'm2', site: 'two.com' }, mpaid = { id: 'adv', site: 'adv.com', paid: true, hunterPol: 0.2 }; + const q1 = rewards.quote(m1); ok('the quote is the draw inside the range', q1 >= 0.05 && q1 <= 1); + let g = rewards.grant(me, m1, { pol: 0.03, nominal: q1, gp: { ref: 'find:m1:' + day, kind: 'daily' } }); + ok('a find pays what IAP allowed, due for the faucet', g.ok && g.rec.pol === 0.03 && g.rec.status === 'due' && g.rec.nominal === q1 && g.rec.gp.ref === 'find:m1:' + day); + g = rewards.grant(me, m2, { pol: 0, nominal: 0.2, gp: { ref: 'find:m2:' + day, kind: 'daily', capHit: 'daily' } }); + ok('a find at the cap: recorded as capped, pays nothing, never reaches the faucet', g.capped && g.rec.status === 'capped' && g.rec.pol === 0 && !rewards.payable().some(p => p.id === g.rec.id)); + ok('a capped find still counts as today\'s find and completes the mission', rewards.findsToday(7) === 2 && rewards.completed(7, 'm2', me.wallet) && rewards.daily(7, new Set(), 0, 0).left === 1); + const gw = rewards.grant(me, { id: 'm3', site: 'three.com' }, { pol: 0.4, status: 'gp-wait', nominal: 0.4, gp: { ref: 'find:m3:' + day, kind: 'daily', pending: true } }); + ok('IAP unreachable: the find is recorded as gp-wait, not payable yet', gw.waiting && gw.rec.status === 'gp-wait' && !rewards.payable().some(p => p.id === gw.rec.id)); + rewards.settleQueued(gw.rec.id, 0.25, { pass: false }); const settled = store.read('payouts', []).find(p => p.id === gw.rec.id); + ok('the queue answer settles it: pays the allowed part, due', settled.pol === 0.25 && settled.status === 'due' && settled.gp.pending === false); + rewards.settleQueued(gw.rec.id, 0.9, {}); ok('a settled row is not settled twice', store.read('payouts', []).find(p => p.id === gw.rec.id).pol === 0.25); + const gpaid = rewards.grant(me, mpaid); ok('an advertiser-funded mission pays the advertiser\'s amount, ungated (no gp on the row)', gpaid.rec.pol === 0.2 && !gpaid.rec.gp && gpaid.rec.paid === true); + ok('the perk: +2 missions a day with the pass', rewards.daily(7, new Set(), 0, 2).limit === 5 && rewards.daily(7, new Set(), 0, 0).limit === 3); + + // ---- Ad Detective: the case is scored first, then IAP decides; a second case a day with the pass + rewards.setSettings({ detectiveOn: 1, detectivePol: 0.15 }); + const gate = { ask: async (pol, ref) => { const a = await gp.grant({ memberId: 7, email: me.email, kind: 'daily', pol, ref }); a.note = gp.note(a, 'daily', pol); return a; }, wait: (rowId, pol, ref) => gp.enqueue({ memberId: 7, email: me.email, ref, kind: 'daily', pol, rowId }) }; + const mkBox = (id, status) => store.update('boxes', {}, all => { all[id] = { id, memberId: 7, day, missionId: 'm1', qid: 'q1', pol: 0.15, status, openedAt: Date.now(), shownAt: Date.now() }; return all; }); + store.update('detective-bank', [], all => { all.push({ id: 'q1', missionId: 'm1', q: 'What color?', options: ['Blue', 'Red', 'Green'], active: true }); return all; }); + mkBox('7:' + day, 'visited'); + const b1 = detective.getBox(7, day); const bank = store.read('detective-bank', [])[0]; + // find the choice index that maps to the right answer (option 0) under the box's shuffled order + const orderOf = (box) => bank.options.map((o, i) => ({ i, k: crypto.createHmac('sha256', String(process.env.HUNT_CODE_SECRET || process.env.HUNT_SSO_SECRET || 'dev').trim()).update('det:' + box.id + ':' + bank.id + ':' + i).digest().readUInt32BE(0) })).sort((a, b) => a.k - b.k).map(x => x.i); + script['detective:' + b1.id] = { allowed: 0.05, capHit: 'daily' }; + let a = await detective.answer(me, orderOf(b1).indexOf(0), gate); + ok('a solved case pays what IAP allowed and tells the truth', a.ok && a.correct && a.pol === 0.05 && a.nominal === 0.15 && /Daily cap reached/.test(a.note) && seen.at(-1).ref === 'detective:' + b1.id && seen.at(-1).kind === 'daily', a); + ok('no pass: the day\'s case is closed, no second box', detective.open(me, false).ok === true && detective.getBox(7, day).id === '7:' + day); + // the perk: a second case once the first is closed (needs a live mission with an active question; fake the one check open() makes) + store.update('missions', [], all => { all.push({ id: 'm1', site: 'example.com', name: 'Example', active: true, dwell: 30 }); return all; }); + store.update('payouts', [], all => { for (let i = 0; i < 3; i++) all.push({ id: 'f' + i, memberId: 7, day, missionId: 'x' + i, pol: 0.05, status: 'paid', at: Date.now() }); return all; }); // 3 finds today -> the box is earned + const o2 = detective.open(me, true); ok('pass active: a second case opens with its own id', o2.ok && o2.box && o2.box.id === '7:' + day + ':2' && o2.box.second === true, o2); + ok('the second box is now the current one, and a third is refused', detective.getBox(7, day).id === '7:' + day + ':2' && detective.open(me, true).box.id === '7:' + day + ':2'); + mode = '500'; store.update('boxes', {}, all => { all['7:' + day + ':2'].status = 'visited'; all['7:' + day + ':2'].shownAt = Date.now(); return all; }); + a = await detective.answer(me, orderOf(detective.getBox(7, day)).indexOf(0), gate); + ok('IAP down while a case is solved: recorded as gp-wait, queued, the hunter told', a.ok && a.correct && a.waiting && a.pol === 0 && /recorded/.test(a.note) && gp.queued(7, me.email, 'detective:7:' + day + ':2')); + mode = 'ok'; script['detective:7:' + day + ':2'] = { allowed: 0.15 }; + await gp.retry(async (item, resp) => { rewards.settleQueued(item.rowId, resp.allowed, {}); }, Date.now() + gp.RETRY_MS + 1); + ok('the queued case pays on retry', !gp.queued(7, me.email, 'detective:7:' + day + ':2') && store.read('payouts', []).some(p => p.id === a.rec.id && p.pol === 0.15 && p.status === 'due')); + process.env.GAMEPASS = 'off'; ok('GAMEPASS=off: a plain answer path still works', (await detective.answer(me, 0, null)).error === 'You already answered today’s case.'); process.env.GAMEPASS = 'on'; + + // ---- the Pass Tournament payer: PolHunter's faucet pays IAP's pending rows, never twice + const sends = []; let sendMode = 'ok', bal = 10; + const faucet = { address: () => '0x' + 'f'.repeat(40), balance: async () => bal, send: async (to, pol, onHash) => { if (sendMode === 'fail') throw new Error('nonce too low'); if (sendMode === 'hashThenCrash') { await onHash('0xhash-crash'); throw new Error('receipt lost'); } const tx = '0xtx' + sends.length; sends.push({ to, pol }); await onHash(tx); return { tx, ok: true }; } }; + let dry = false; tournament.init({ faucet, notify, dry: () => dry }); + pendingRows = [{ id: 'p1', week: '2026-W42', place: 1, email: 'a@example.com', memberId: 11, wallet: '0x' + '1'.repeat(40), pol: 0.5 }, { id: 'p2', week: '2026-W42', place: 2, email: 'b@example.com', memberId: 12, wallet: '0x' + '2'.repeat(40), pol: 0.3 }, { id: 'p3', week: '2026-W42', place: 3, email: 'c@example.com', memberId: 13, wallet: null, pol: 0.2 }]; + let st = await tournament.run(); + ok('pending rows are paid from the faucet and reported to IAP; the row without a wallet is a failure, not a payment', st.paid === 2 && st.acked === 2 && sends.length === 2 && sends[0].pol === 0.5 && sends[1].to === '0x' + '2'.repeat(40) && acks.length === 2 && acks[0].id === 'p1' && acks[0].tx === '0xtx0' && st.failures.length === 1 && /no wallet/.test(st.failures[0].error), st); + ok('the claims file holds the hash per row', store.read('tourney-claims', {})['id:p1'].tx === '0xtx0' && store.read('tourney-claims', {})['id:p1'].acked > 0); + ok('the admin chat heard about each prize', alerts.filter(a => a[0] === 'tourneypaid').length === 2); + st = await tournament.run(); ok('a second run pays nothing new (IAP no longer lists them)', st.paid === 0 && sends.length === 2); + // IAP still lists a row that was paid (its ack was lost): re-report the hash, never re-send + acks.length = 0; st = await tournament.run(); ok('a paid row IAP still lists is re-reported, not re-sent', sends.length === 2 && st.acked === 2 && st.paid === 0 && acks.length === 2); + // a fresh row while the send fails: the row stays pending, the claim is released, the admin chat alerted + pendingRows.push({ id: 'p4', week: '2026-W43', place: 1, email: 'd@example.com', memberId: 14, wallet: '0x' + '4'.repeat(40), pol: 0.4 }); sendMode = 'fail'; alerts.length = 0; + st = await tournament.run(); ok('a send failure leaves the row pending and alerts', st.paid === 0 && st.failures.some(f => /nonce too low/.test(f.error)) && alerts.some(a => a[0] === 'tourneyfail') && !acks.some(a => a.id === 'p4') && !store.read('tourney-claims', {})['id:p4'].tx); + sendMode = 'ok'; st = await tournament.run(); ok('the next run pays it (the claim was released)', st.paid === 1 && acks.some(a => a.id === 'p4')); + // a fresh claim by "another app copy" within the TTL is respected (deploy overlap) + pendingRows.push({ id: 'p5', week: '2026-W43', place: 2, email: 'e@example.com', memberId: 15, wallet: '0x' + '5'.repeat(40), pol: 0.1 }); + store.update('tourney-claims', {}, all => { all['id:p5'] = { claimedAt: Date.now(), week: '2026-W43', place: 2, wallet: '0x' + '5'.repeat(40), pol: 0.1 }; return all; }); + st = await tournament.run(); ok('a row another copy claimed moments ago is skipped, not paid twice', st.skipped >= 1 && !sends.some(s => s.to === '0x' + '5'.repeat(40))); + store.update('tourney-claims', {}, all => { all['id:p5'].claimedAt = Date.now() - tournament.CLAIM_TTL - 1; return all; }); + st = await tournament.run(); ok('after the claim TTL with no hash, the row is paid', sends.some(s => s.to === '0x' + '5'.repeat(40)) && acks.some(a => a.id === 'p5')); + // the chain has the hash but the receipt was lost: never re-sent, reported next run + pendingRows.push({ id: 'p6', week: '2026-W43', place: 3, email: 'f@example.com', memberId: 16, wallet: '0x' + '6'.repeat(40), pol: 0.1 }); sendMode = 'hashThenCrash'; + st = await tournament.run(); ok('a hash recorded before the crash is kept', store.read('tourney-claims', {})['id:p6'].tx === '0xhash-crash' && st.failures.some(f => /receipt unknown/.test(f.error))); + sendMode = 'ok'; const n0 = sends.length; st = await tournament.run(); ok('the next run only reports that hash', sends.length === n0 && acks.some(a => a.id === 'p6' && a.tx === '0xhash-crash')); + // dry run and low balance + dry = true; pendingRows.push({ id: 'p7', week: '2026-W44', place: 1, email: 'g@example.com', memberId: 17, wallet: '0x' + '7'.repeat(40), pol: 0.9 }); + st = await tournament.run(); ok('HUNT_DRY_RUN: records what it would pay, sends nothing', st.wouldPay === 0.9 && st.paid === 0 && !sends.some(s => s.to === '0x' + '7'.repeat(40)) && store.read('tourney-claims', {})['id:p7'].dry === true); + st = await tournament.run(); ok('a dry-run row is not re-claimed', st.skipped >= 1 && st.wouldPay === 0.9); + dry = false; store.update('tourney-claims', {}, all => { delete all['id:p7']; return all; }); bal = 0.5; alerts.length = 0; + st = await tournament.run(); ok('a low balance leaves the row pending and alerts once', st.paid === 0 && st.failures.some(f => /low balance/.test(f.error)) && alerts.some(a => a[0] === 'low' && a[1].tournament) && !store.read('tourney-claims', {})['id:p7'].tx); + bal = 10; st = await tournament.run(); ok('topped up: paid', acks.some(a => a.id === 'p7')); + process.env.GAMEPASS = 'off'; st = await tournament.run(); ok('GAMEPASS=off: the payer is inert', st.on === false && st.pending === 0); process.env.GAMEPASS = 'on'; + const view = tournament.state(); ok('the admin sees last run, totals and claims', view.last && view.paidTotal >= 5 && view.claims.length >= 6 && view.recent.length >= 1); + + stub.close(); console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0); +})().catch(e => { console.error(e); process.exit(1); });