Game Pass bridge (GAMEPASS=on): chapter first clears via InstantAdPay polgrant (wallet-less members by email), shield at run start perk, lobby line + clear note, tests
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
+7
-5
@@ -44,8 +44,10 @@ function start(me, W, H) {
|
||||
const p = updPlayer(me.memberId, x => { x.runs++; });
|
||||
// any live run this member left open is closed; a player has one run at a time
|
||||
store.update('runs', {}, all => { for (const k of Object.keys(all)) if (all[k].memberId === Number(me.memberId) && all[k].status === 'live') all[k].status = 'abandoned'; return all; });
|
||||
const armed = { magnet: !!p.items.magnet, shield: !!p.items.shield, slow: !!p.items.slow };
|
||||
updPlayer(me.memberId, x => { delete x.items.magnet; delete x.items.shield; delete x.items.slow; }); // one-run items are consumed now
|
||||
// Game Pass perk (GAMEPASS=on, the member's pass active): a shield at the start of every run; a bought Shield Core is kept for a later run
|
||||
const passShield = ledger.passActive(me);
|
||||
const armed = { magnet: !!p.items.magnet, shield: !!p.items.shield || passShield, slow: !!p.items.slow, passShield };
|
||||
updPlayer(me.memberId, x => { delete x.items.magnet; if (!passShield) delete x.items.shield; delete x.items.slow; }); // one-run items are consumed now
|
||||
const r = { id: crypto.randomBytes(8).toString('hex'), memberId: Number(me.memberId), seed: crypto.randomInt(1, 2 ** 31), W, H,
|
||||
speed: spawn.speedFor(p.chapter), chapter: p.chapter, goal: spawn.goalFor(p.chapter), startedAt: Date.now(), t: 0, drips: 0, chapDrips: 0,
|
||||
collected: [], bad: 0, refuels: 0, status: 'live', armed, ship: p.items.ship ? 2 : 1, flagged: false, cleared: [] };
|
||||
@@ -66,7 +68,7 @@ function dripInfo(r, i, t) {
|
||||
}
|
||||
|
||||
// the client's batch of claims for a live run
|
||||
function events(me, runId, t, list, wantGoal) {
|
||||
async function events(me, runId, t, list, wantGoal) { // async since the Game Pass: with GAMEPASS=on InstantAdPay is asked before a member is paid (ledger.chapterDripGated)
|
||||
const r = run(runId);
|
||||
if (!r || r.memberId !== Number(me.memberId)) return { error: 'That run is not yours or no longer exists.' };
|
||||
if (r.status !== 'live') return { error: 'That run is over.', over: true };
|
||||
@@ -94,12 +96,12 @@ function events(me, runId, t, list, wantGoal) {
|
||||
if (out.chapDrips < out.goal) { res.cleared = null; res.short = out.goal - out.chapDrips; return res; }
|
||||
const ch = out.chapter; const p = player(me.memberId);
|
||||
const first = !(p.cleared || {})[ch];
|
||||
const grant = me.guest ? { pol: 0, reason: 'guest' } : ledger.chapterDrip(me, ch, first && !out.flagged);
|
||||
const grant = me.guest ? { pol: 0, reason: 'guest' } : await ledger.chapterDripGated(me, ch, first && !out.flagged);
|
||||
if (first && out.flagged) grant.reason = 'flagged';
|
||||
if (me.guest && first && !out.flagged) updPlayer(me.memberId, x => { x.pending = Array.from(new Set([...(x.pending || []), ch])); }); // paid when they sign in
|
||||
updPlayer(me.memberId, x => { x.cleared[ch] = true; if (x.chapter <= ch) x.chapter = ch + 1; });
|
||||
updRun(runId, x => { x.cleared.push(ch); x.chapter = ch + 1; x.chapDrips = 0; x.goal = spawn.goalFor(ch + 1); });
|
||||
res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) };
|
||||
res.cleared = { chapter: ch, first, pol: grant.pol, reason: grant.reason, note: grant.note || null, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) }; // note = the Game Pass truth
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
+53
-2
@@ -105,6 +105,57 @@ function spend(me, item, pol) {
|
||||
return { ok: true, pol };
|
||||
}
|
||||
|
||||
// ---- Game Pass (GAMEPASS=on, docs/GAME-PASS.md 3a): InstantAdPay's account-wide caps decide what a member is paid; the
|
||||
// local cap and pool above stay as a backstop and are never raised. The only POL Drip Runner pays is a chapter's first clear,
|
||||
// once per member, so every reward here is 'progress': what today's cap does not allow is deferred on IAP and folded into a
|
||||
// later answer. A member with no wallet has a negative local id (sso.emailId): IAP gets memberId 0 and the email instead.
|
||||
const gp = require('./polgrant');
|
||||
const kindOf = key => 'progress'; // refs: chapter:<n>
|
||||
const iapId = me => Number(me.memberId) > 0 ? Number(me.memberId) : 0;
|
||||
const passActive = me => !!(gp.on() && me && !me.guest && gp.passOf(iapId(me), me.email).active);
|
||||
// the same checks as chapterDrip() up to (not including) the ledger write -> { pol, key, chapter } or { pol: 0, reason }
|
||||
function quote(me, chapter, eligible) {
|
||||
const s = settings(); const pol = r4(Number(s.dripPol));
|
||||
if (!eligible) return { pol: 0, reason: 'replay' };
|
||||
if (!(pol > 0)) return { pol: 0, reason: 'none' };
|
||||
const p = pool(); if (p.capLeft < pol) return { pol: 0, reason: 'cap' }; if (p.available < pol) return { pol: 0, reason: 'pool' };
|
||||
return { pol, key: 'chapter:' + chapter, chapter };
|
||||
}
|
||||
// IAP answered: the ledger gets exactly what was allowed (0 included, so the chapter counts as handled); `carried` (inside
|
||||
// allowed) is what IAP paid from an earlier deferral; the account tracks what IAP still owes.
|
||||
function settleGrant(me, q, r, gkind) {
|
||||
const allowed = r4(r.allowed), extra = r.carried > 0 ? r4(r.carried) : r4(Math.max(0, allowed - q.pol));
|
||||
const row = { id: id(), memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, pol: allowed, chapter: q.chapter, day: ctDay(), ts: Date.now(), status: 'granted', gp: { kind: gkind, ref: q.key, nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass } };
|
||||
store.update('drips', [], all => { if (!all.some(d => d.memberId === row.memberId && d.gp && d.gp.ref === q.key)) all.push(row); return all; });
|
||||
if (allowed > 0) poolAdd('out', allowed);
|
||||
updAccount(me.memberId, a => { a.unpaid += allowed; a.earnedTotal = r4((a.earnedTotal || 0) + allowed); a.wallet = me.wallet || a.wallet || null; a.username = me.username || a.username || null; a.email = me.email || a.email || null; a.gpOwed = r4(Math.max(0, (a.gpOwed || 0) + (Number(r.deferred) || 0) - extra)); });
|
||||
return { pol: allowed, reason: allowed > 0 ? 'paid' : (gkind === 'daily' ? 'capday' : 'deferred'), nominal: q.pol, deferred: r4(r.deferred || 0), pass: !!r.pass, note: gp.note(r, gkind, q.pol), id: row.id };
|
||||
}
|
||||
// chapterDrip() with IAP in front of it. Switch off, or a guest: the plain chapterDrip, unchanged. Fail closed: no answer from
|
||||
// IAP = nothing paid now, the ref queued and retried (polgrant.js), the player told it is recorded.
|
||||
async function chapterDripGated(me, chapter, eligible) {
|
||||
if (!gp.on() || me.guest || !gp.whoOf(iapId(me), me.email)) return chapterDrip(me, chapter, eligible);
|
||||
const q = quote(me, chapter, eligible); if (q.reason) return q;
|
||||
if (gp.queued(iapId(me), me.email, q.key)) return { pol: 0, reason: 'iap', nominal: q.pol };
|
||||
const gkind = kindOf(q.key), r = await gp.grant({ memberId: iapId(me), email: me.email, kind: gkind, pol: q.pol, ref: q.key });
|
||||
if (r.retry) { gp.enqueue({ memberId: iapId(me), email: me.email, ref: q.key, kind: gkind, pol: q.pol, me: { memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, email: me.email || null }, q }); return { pol: 0, reason: 'iap', nominal: q.pol, note: gp.note(r, gkind, q.pol) }; }
|
||||
return settleGrant(me, q, r, gkind);
|
||||
}
|
||||
const payQueued = (item, r) => settleGrant(item.me, item.q, r, item.kind); // a queued ref finally answered
|
||||
// once a Central day per account IAP still owes: a zero-POL progress call collects the carry-forward (IAP folds it into `allowed`)
|
||||
async function carrySweep() {
|
||||
if (!gp.on()) return 0; const today = ctDay(), accts = store.read('accounts', {}); let got = 0;
|
||||
for (const k of Object.keys(accts)) {
|
||||
const a = accts[k]; if (!(a.gpOwed > 0) || a.gpCarryDay === today) continue;
|
||||
const me = { memberId: a.memberId, email: a.email || null, username: a.username, wallet: a.wallet };
|
||||
if (!gp.whoOf(iapId(me), me.email)) continue;
|
||||
const r = await gp.grant({ memberId: iapId(me), email: me.email, kind: 'progress', pol: 0, ref: 'carry:' + today }); if (r.retry) continue;
|
||||
updAccount(a.memberId, x => { x.gpCarryDay = today; });
|
||||
if (r.allowed > 0) { settleGrant(me, { pol: 0, key: 'carry:' + today, chapter: 0 }, r, 'progress'); got += r.allowed; }
|
||||
}
|
||||
return got;
|
||||
}
|
||||
|
||||
// ---- payouts ----------------------------------------------------------------------------------
|
||||
// a member whose unpaid balance reached the threshold gets one payout row for the whole amount;
|
||||
// the balance moves to the row so drips earned meanwhile start a fresh count
|
||||
@@ -136,7 +187,7 @@ function mark(pid, patch) {
|
||||
function balance(memberId) {
|
||||
const a = account(memberId); const s = settings();
|
||||
const hist = []
|
||||
.concat(store.read('drips', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'drip', label: 'Chapter ' + d.chapter + ' · first clear', pol: d.pol })))
|
||||
.concat(store.read('drips', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'drip', label: !d.chapter ? 'Carried-over reward paid' : 'Chapter ' + d.chapter + ' · first clear' + (d.gp && d.gp.deferred > 0 ? ' (' + d.gp.deferred + ' POL paying out over the next days)' : ''), pol: d.pol })))
|
||||
.concat(store.read('spends', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'spend', label: 'Hangar · ' + d.item, pol: -d.pol })))
|
||||
.concat(store.read('refslices', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'ref', label: 'Referral · ' + (d.fromUsername ? '@' + d.fromUsername : 'a player') + ' refuelled', pol: d.pol })))
|
||||
.concat(store.read('payouts', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'payout', label: d.status === 'paid' ? 'Paid to your wallet' : d.status === 'failed' ? 'Payout failed: ' + (d.error || '') : 'Payout on its way', pol: d.pol, status: d.status, tx: d.tx || null })))
|
||||
@@ -144,4 +195,4 @@ function balance(memberId) {
|
||||
return { unpaid: r4(a.unpaid), paidTotal: r4(a.paidTotal || 0), spentTotal: r4(a.spentTotal || 0), earnedTotal: r4(a.earnedTotal || 0), refTotal: r4(a.refTotal || 0), refSharePct: Number(s.refSharePct) || 0, threshold: Number(s.thresholdPol), history: hist, wallet: a.wallet || null };
|
||||
}
|
||||
|
||||
module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, spend, sweep, payable, mark, balance, usdPerPol, r4 };
|
||||
module.exports = { DEFAULTS, settings, setSettings, ctDay, pool, refuel, refuelsToday, account, chapterDrip, chapterDripGated, quote, settleGrant, kindOf, passActive, iapId, payQueued, carrySweep, gp, spend, sweep, payable, mark, balance, usdPerPol, r4 };
|
||||
|
||||
+160
@@ -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 };
|
||||
Reference in New Issue
Block a user