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 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-16 09:11:27 -05:00
parent 816417d172
commit 73b6cf74db
10 changed files with 488 additions and 39 deletions
+25 -9
View File
@@ -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 '<member>:<day>: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 };
+18 -1
View File
@@ -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 };
+160
View File
@@ -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: <slug>`, 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 };
+29 -16
View File
@@ -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 };
+73
View File
@@ -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 };