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
+40 -10
View File
@@ -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} <b>PolHunter</b> · ' + (p.username ? '@' + p.username : '#' + p.memberId) + ' found it on ' + p.site + ' and got <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>\n<a href="' + SITE + '">Hunt yours</a>'); if (ok && p.id) rewards.mark(p.id, { posted: Date.now() }); return ok; }
}
async function notifyOther(kind, p) {
if (kind === 'low') return telegram('⚠️ <b>PolHunter faucet is low</b>: ' + fmt(p.balance) + ' POL left in ' + p.address + ' (alert threshold ' + fmt(p.threshold) + '). Top up from Receiver B.');
if (kind === 'low') return telegram('⚠️ <b>PolHunter faucet is low</b>: ' + 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('⚠️ <b>PolHunter</b> 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} <b>Pass Tournament</b> prize paid from the PolHunter faucet: week ' + p.week + ' place ' + p.place + ' · ' + (p.email || '#' + p.memberId) + ' · <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>');
if (kind === 'tourneyfail') return telegram('❌ <b>Pass Tournament</b> 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('❌ <b>PolHunter</b> · 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} <b>PolHunter</b> · ' + (d.username ? '@' + d.username : '#' + d.memberId) + ' brought ' + d.ref.forName + ' in and they are hunting · <b>' + fmt(d.pol) + ' POL</b> bounty on the way\n<a href="' + SITE + '">Bring yours</a>'); }
@@ -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.