Files
polhunter/lib/tournament.js
T

74 lines
7.0 KiB
JavaScript

// 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 };