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 };
|
||||
+1
-1
@@ -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" },
|
||||
"dependencies": { "ethers": "^6.13.0" }
|
||||
|
||||
+1
-1
@@ -205,6 +205,6 @@ canvas#game{position:absolute;inset:0;width:100%;height:100%;display:block;touch
|
||||
<script src="https://instantadpay.com/assets/game-signin.js?v=20261003a" async></script>
|
||||
<script src="https://instantadpay.com/assets/game-strip.js?v=20261003a"></script>
|
||||
<script src="/spawn.js"></script>
|
||||
<script src="/play.js?v=20261005b"></script>
|
||||
<script src="/play.js?v=20261016gp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+8
-2
@@ -45,7 +45,7 @@ function f3(n) { return Number(n || 0).toFixed(3); }
|
||||
|
||||
/* ---------- lobby / me ---------- */
|
||||
var ME_EXTRA = {};
|
||||
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals, perk: r.perk || ME_EXTRA.perk || null }; return r; }); } // perk: the one-time member message, kept for this page load
|
||||
function loadMe() { return api('/api/me').then(function (r) { if (r._status !== 200) throw r; ME = r.me; P = r.player; BAL = r.balance; POOL = r.pool; IAP = r.iap || IAP; TIPS = r.tips || []; ME_EXTRA = { signin: r.signin, share: r.share, referrals: r.referrals, perk: r.perk || ME_EXTRA.perk || null, gamepass: r.gamepass || null }; return r; }); } // perk: the one-time member message, kept for this page load
|
||||
// share: the phone's share sheet where there is one, else copy the link
|
||||
function share(text) {
|
||||
var url = ME_EXTRA.share; if (!url) return toast('Set a username on InstantAdPay to get a share link.');
|
||||
@@ -61,6 +61,10 @@ function lobby() {
|
||||
$('lIap').href = IAP + '/my'; $('bLevel').href = IAP + '/my#buy'; tip('lTip');
|
||||
try { if (BAL && BAL.unpaid > 0 && ME && !ME.wallet && !ME.guest && !sessionStorage.getItem('dr.walletnudge')) { sessionStorage.setItem('dr.walletnudge', '1'); toast(f3(BAL.unpaid) + ' POL is waiting. Link a wallet on InstantAdPay to get paid.'); } } catch (e) {}
|
||||
$('lPerk').hidden = !ME_EXTRA.perk; $('lPerk').textContent = ME_EXTRA.perk || ''; // member perk (2026-10-05)
|
||||
// Game Pass (InstantAdPay, all nine games): active until <date>, or the link to get it; opens a new tab (the game may be framed)
|
||||
(function () { var g = ME_EXTRA.gamepass, el = $('lPass'); if (!el) { el = document.createElement('p'); el.id = 'lPass'; el.className = 'fine'; $('lPool').parentNode.insertBefore(el, $('lPool').nextSibling); }
|
||||
if (!g || !g.on) { el.hidden = true; return; } el.hidden = false;
|
||||
el.innerHTML = g.active ? '🎫 Game Pass active' + (g.untilText ? ' until ' + esc(g.untilText) : '') + ' · a shield at the start of every run' : '🎫 <a href="' + esc(g.url) + '" target="_blank" rel="noopener">Get the Game Pass</a> · higher daily POL caps across all nine games, a shield every run here'; })();
|
||||
$('bHangar').textContent = P.freeUpgrades > 0 ? 'Hangar · ' + P.freeUpgrades + ' free' : 'Hangar';
|
||||
// signed in through the game: these open InstantAdPay already signed in (in-game sign-in pass, 2026-10-03)
|
||||
if (window.IAPGames && !$('moreGames').dataset.done) { $('moreGames').dataset.done = 1; IAPGames.strip($('moreGames'), { current: 'driprunner', title: 'More games that pay POL' }); } // cross-promo strip (2026-10-03)
|
||||
@@ -152,7 +156,9 @@ function cleared() {
|
||||
var why = { paid: 'First clear, verified. Added to your game balance.', replay: c.first ? 'Verified.' : 'You cleared this one before. Only the first clear pays.', pool: 'The POL pool is empty right now. Refuel visits fill it, so this clear counts but pays nothing.', cap: 'Today’s pool cap is spent. Chapter counts, no POL today.', flagged: 'This run was flagged by the server check, so it pays nothing.', guest: 'You are playing as a guest. Sign in with InstantAdPay and this clear pays ' + f3(POOL.dripPol) + ' POL into your balance. Your progress comes with you.' };
|
||||
$('bShareClear').hidden = !!ME.guest || !ME_EXTRA.share; $('bShareClear').dataset.text = 'I just cleared Chapter ' + c.chapter + ' in Drip Runner' + (c.pol ? ' and it paid ' + f3(c.pol) + ' POL' : '') + '. Hop the network, dodge the bots:';
|
||||
$('bClearSignin').hidden = !ME.guest; if (ME.guest) $('bClearSignin').href = ME_EXTRA.signin || '/signin';
|
||||
$('cText').textContent = why[c.reason] || ''; $('cChip').className = 'chip ' + (c.pol ? 'ok' : 'sig'); $('cChip').textContent = (c.pol ? 'verified' : c.reason) + ' · ' + tm + ' play time';
|
||||
$('cText').textContent = why[c.reason] || '';
|
||||
// the Game Pass truth (deferred to later days, or recorded while InstantAdPay confirms) + the nudge, in a new tab (the game may be framed)
|
||||
if (c.note) { var gpp = ME_EXTRA.gamepass; $('cText').innerHTML = esc(c.note) + (gpp && gpp.on && !gpp.active && /Get the Pass/.test(c.note) ? ' <a href="' + esc(gpp.url) + '" target="_blank" rel="noopener">Get the Game Pass</a>' : ''); } $('cChip').className = 'chip ' + (c.pol ? 'ok' : 'sig'); $('cChip').textContent = (c.pol ? 'verified' : c.reason) + ' · ' + tm + ' play time';
|
||||
R.chapter = c.next; R.goal = c.nextGoal; R.chapDrips = 0; if (r.pool != null) POOL.available = r.pool;
|
||||
tip('cTip'); setTimeout(function () { show('ovClear'); if (r.starterOffer) starterOffer(r.starterOffer); }, 500); // the offer card fades in under the result (CSS delay)
|
||||
});
|
||||
|
||||
@@ -42,6 +42,8 @@ const IS_PROD = process.env.NODE_ENV === 'production';
|
||||
store.init(DATA_DIR);
|
||||
badge.init({ publicDir: PUBLIC_DIR, dataDir: DATA_DIR });
|
||||
const faucetOn = faucet.init();
|
||||
// Game Pass bridge (GAMEPASS=on, docs/GAME-PASS.md 3a): signed calls to InstantAdPay's polgrant with the same shared secret; stuck grants alert like the faucet
|
||||
ledger.gp.use({ game: 'driprunner', secret: SECRET, iap: IAP, store, notify: (kind, p) => notify(kind, p) });
|
||||
|
||||
// ---- Telegram to Marty (outward: gated) -------------------------------------------------------
|
||||
async function telegram(text) {
|
||||
@@ -98,6 +100,7 @@ async function notify(kind, p) {
|
||||
if (kind === 'paid') { announcePaid(p); return telegram('\u{1F3AE} <b>Drip Runner</b> · paid ' + who + ' <b>' + fmt(p.pol) + ' POL</b> · <a href="' + explorer() + '/tx/' + p.tx + '">verify</a>'); }
|
||||
if (kind === 'failed') return telegram('❌ <b>Drip Runner</b> · payout to ' + who + ' failed: ' + p.error);
|
||||
if (kind === 'low') return telegram('⚠️ <b>Drip Runner wallet is low</b>: ' + fmt(p.balance) + ' POL in ' + p.address + ' (needs ' + fmt(p.threshold) + ').');
|
||||
if (kind === 'gpstuck') return telegram('⚠️ <b>Drip Runner</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 === 'refused') return telegram('\u{1F6AB} <b>Drip Runner</b> \u00b7 ' + who + ' (' + p.email + ') tried to sign in but is not on the tester list. Add them under Admin > Settings > Testers: ' + SITE + '/admin');
|
||||
if (kind === 'signin') return telegram('\u{1F44B} <b>Drip Runner</b> · first sign-in: ' + who + ' (' + (p.wallet ? 'wallet on file' : 'NO wallet yet') + ')');
|
||||
if (kind === 'refuel') return telegram('⛽ <b>Drip Runner</b> · ' + who + ' refuelled on campaign #' + p.campaignId + ': +' + fmt(p.pol) + ' POL to the pool (' + p.credits + ' credits, $' + p.share + ' share)');
|
||||
@@ -214,8 +217,9 @@ const server = http.createServer(async (req, res) => {
|
||||
game.updPlayer(r.claims.memberId, x => { x.email = String(r.claims.email).toLowerCase(); x.username = r.claims.username || x.username || null; x.wallet = r.claims.wallet ? String(r.claims.wallet).toLowerCase() : x.wallet || null; x.lastSeen = Date.now(); });
|
||||
game.updPlayer(r.claims.memberId, x => { if (!x.sponsorRef && r.claims.sponsorRef) x.sponsorRef = String(r.claims.sponsorRef).toLowerCase(); if (r.claims.joinedRef && !x.joinedRef) x.joinedRef = r.claims.joinedRef; });
|
||||
starter.grantPerk(r.claims.memberId); // a member (memberId > 0) gets one free hangar upgrade, once per account (2026-10-05)
|
||||
const meNow = { memberId: Number(r.claims.memberId), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null };
|
||||
for (const ch of pendingClears) { const g = ledger.chapterDrip(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now
|
||||
if (r.claims.gamePass != null) ledger.gp.rememberPass(ledger.iapId(r.claims), r.claims.email, r.claims.gamePass); // the Game Pass flag rides on the hand-off as gamePass:{active,until} (GAME-PASS.md 3a item 7)
|
||||
const meNow = { memberId: Number(r.claims.memberId), email: String(r.claims.email || '').toLowerCase(), username: r.claims.username || null, wallet: r.claims.wallet ? String(r.claims.wallet).toLowerCase() : null };
|
||||
for (const ch of pendingClears) { const g = await ledger.chapterDripGated(meNow, ch, true); if (g.pol) announceChapter(meNow, ch, g.pol); } // clears made as a guest pay now
|
||||
{ const t = srctrack.fromRequest(req); if (t) {
|
||||
srctrack.bump(t.src, 'signins', r.claims.memberId); game.updPlayer(r.claims.memberId, x => { if (!x.src) x.src = t.src; });
|
||||
if (r.claims.joinedAt && Date.now() - Number(r.claims.joinedAt) < 30 * 60000) { srctrack.bump(t.src, 'signups', r.claims.memberId); srctrack.postback(t, r.claims.memberId).catch(() => {}); } } }
|
||||
@@ -367,15 +371,17 @@ async function memberApi(req, res, u, p, me) {
|
||||
{
|
||||
if (p === '/api/me' && req.method === 'GET') {
|
||||
const pl = ledger.pool();
|
||||
if (!me.guest && ledger.gp.on()) ledger.gp.fetchPass(ledger.iapId(me), me.email).catch(() => {}); // keep the Game Pass flag fresh (display + the shield perk; grant answers carry the truth)
|
||||
const refs = me.guest ? [] : game.referralsOf(me);
|
||||
return json(res, 200, { me: { memberId: me.memberId, username: me.username, wallet: me.wallet, guest: !!me.guest }, player: game.view(me), balance: ledger.balance(me.memberId), pool: { available: pl.available, capLeft: pl.capLeft, dripPol: Number(ledger.settings().dripPol) }, iap: IAP, site: SITE, tips: await tips.list(ledger.settings()),
|
||||
signin: me.guest ? signinUrl(req) : null, share: (!me.guest && me.username) ? SITE + '/r/' + encodeURIComponent(me.username) : null, referrals: { count: refs.length, clicks: (store.read('share-hits', {})[String(me.username || '').toLowerCase()] || 0), earned: ledger.balance(me.memberId).refTotal, pct: Number(ledger.settings().refSharePct) || 0 },
|
||||
perk: me.guest ? null : starter.takeNotice(me.memberId) }); // the member perk's one-time message (2026-10-05)
|
||||
perk: me.guest ? null : starter.takeNotice(me.memberId), // the member perk's one-time message (2026-10-05)
|
||||
gamepass: me.guest ? null : ledger.gp.view(ledger.iapId(me), me.email) }); // Game Pass: active until <date>, or the link to get it
|
||||
}
|
||||
if (p === '/api/balance' && req.method === 'GET') return json(res, 200, ledger.balance(me.memberId));
|
||||
if (p === '/api/run/start' && req.method === 'POST') { const { body } = await readBody(req); { const t = srctrack.fromRequest(req); if (t) srctrack.bump(t.src, 'runs', me.memberId); } const r = game.start(me, body.W, body.H); return json(res, 200, { runId: r.id, seed: r.seed, W: r.W, H: r.H, speed: r.speed, chapter: r.chapter, goal: r.goal, armed: r.armed, ship: r.ship }); }
|
||||
// a chapter clear may carry the member welcome offer: after a win only, once a Central day, signed-in non-members (lib/starter.js)
|
||||
if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); const so = await starter.offerFor(me); if (so) r.starterOffer = so; } return json(res, r.error ? 400 : 200, r); }
|
||||
if (p === '/api/run/events' && req.method === 'POST') { const { body } = await readBody(req); const r = await game.events(me, String(body.runId || ''), body.t, body.events, !!body.goal); if (r.cleared) { r.pool = ledger.pool().available; if (r.cleared.first && !me.guest) announceChapter(me, r.cleared.chapter, r.cleared.pol); const so = await starter.offerFor(me); if (so) r.starterOffer = so; } return json(res, r.error ? 400 : 200, r); }
|
||||
if (p === '/api/run/end' && req.method === 'POST') { const { body } = await readBody(req); return json(res, 200, game.end(me, String(body.runId || ''))); }
|
||||
// refuel: hand the player to IAP for a verified visit; the run resumes when IAP confirms
|
||||
if (p === '/api/refuel/start' && req.method === 'POST') {
|
||||
@@ -407,3 +413,5 @@ async function memberApi(req, res, u, p, me) {
|
||||
}
|
||||
server.listen(PORT, () => console.log('Drip Runner on', PORT, '| curtain', !!CURTAIN, '| sso', sso.enabled(), '| faucet', faucetOn, faucet.dry() ? '(DRY RUN)' : '(LIVE)', '| outbound', outbound()));
|
||||
if (faucetOn) { setInterval(() => faucet.tick(notify).catch(e => console.error('faucet', e.message)), 120000); setTimeout(() => faucet.tick(notify).catch(() => {}), 8000); }
|
||||
// Game Pass: refs that could not reach InstantAdPay retry every 5 minutes (polgrant.js); carry-forward IAP still owes is collected once a day
|
||||
ledger.gp.startRetry(ledger.payQueued); setInterval(() => ledger.carrySweep().catch(e => console.error('carry', e.message)), 120000).unref();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Game Pass bridge checks (docs/GAME-PASS.md 3a), all local: a stub InstantAdPay on 127.0.0.1 answers /api/partner/polgrant
|
||||
// with scripted allowed/deferred, a 500, or nothing. The grant client (allowed / deferred / retry, fail closed, the retry
|
||||
// queue, the 48 h alert), the game's gated chapter drip (every chapter's first clear = 'progress', ref chapter:<n>), the
|
||||
// wallet-less member (negative local id -> memberId 0 + email on the wire), deferral + carry-forward, and the shield perk flag.
|
||||
// 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.DR_SSO_SECRET = 'y'.repeat(48);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dr-gp-'));
|
||||
const store = require('../lib/store'); store.init(dir);
|
||||
const ledger = require('../lib/ledger'); const gp = ledger.gp; const game = require('../lib/game'); const sso = require('../lib/sso');
|
||||
const SECRET = 'test-secret-'.padEnd(40, 'x'), GAME = 'driprunner';
|
||||
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 () => {
|
||||
const seen = []; let mode = 'ok'; const script = {};
|
||||
const stub = http.createServer((req, res) => { let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
||||
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"}'); } seen.push(Object.assign({ url: req.url }, 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: s.carried || 0, pass: !!s.pass, day: '2026-10-16' }));
|
||||
}); });
|
||||
await new Promise(r => stub.listen(0, '127.0.0.1', r)); const port = stub.address().port;
|
||||
const alerts = []; gp.use({ game: GAME, secret: SECRET, iap: 'http://127.0.0.1:' + port, store, notify: async (k, p) => alerts.push([k, p]) });
|
||||
|
||||
// ---- 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 }; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:2' }); ok('daily over the cap: dropped, the nudge names the Pass', r.allowed === 0.1 && /Get the Pass/.test(gp.note(r, 'daily', 0.3)));
|
||||
script['p:1'] = { allowed: 1, deferred: 1 }; r = await gp.grant({ memberId: 7, kind: 'progress', pol: 2, ref: 'p:1' }); ok('progress over the cap: deferred', r.allowed === 1 && r.deferred === 1 && /pays out over the next days/.test(gp.note(r, 'progress', 2)));
|
||||
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 });
|
||||
const paidQ = []; const payQ = async (item, resp) => paidQ.push([item.ref, resp.allowed]);
|
||||
mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:1', kind: 'progress', pol: 0.5 }); let rr = await gp.retry(payQ, Date.now() + gp.RETRY_MS + 1); ok('IAP down: tried and kept', rr.tried === 1 && rr.paid === 0 && gp.queued(7, '', 'q:1'));
|
||||
mode = 'ok'; rr = await gp.retry(payQ, Date.now() + 2 * gp.RETRY_MS + 2); ok('IAP back: paid and dequeued', rr.paid === 1 && paidQ[0][1] === 0.5 && !gp.queued(7, '', 'q:1'));
|
||||
mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:old', kind: 'daily', pol: 0.2, at: Date.now() - gp.GIVE_UP_MS - 1000 }); rr = await gp.retry(payQ, Date.now() + gp.RETRY_MS + 1);
|
||||
ok('48 h without an answer: stuck, the admin chat told once', rr.stuck === 1 && alerts.length === 1 && alerts[0][0] === 'gpstuck'); gp.dequeue(7, '', 'q:old'); mode = 'ok';
|
||||
|
||||
// ---- the game: a chapter's first clear pays once -> 'progress'; the only POL Drip Runner pays
|
||||
ledger.setSettings({ seedPol: 100, dailyCapPol: 5, dripPol: 0.01 });
|
||||
const me = { memberId: 7, email: 'hugh@example.com', username: 'hugh', wallet: '0x' + 'a'.repeat(40) }, today = ledger.ctDay();
|
||||
ok('classification: every chapter is progress', ledger.kindOf('chapter:1') === 'progress' && ledger.kindOf('chapter:9') === 'progress');
|
||||
seen.length = 0; let g = await ledger.chapterDripGated(me, 1, true);
|
||||
ok('chapter 1 pays what IAP allowed, asked as progress with ref chapter:1', g.reason === 'paid' && g.pol === 0.01 && seen[0].ref === 'chapter:1' && seen[0].kind === 'progress' && seen[0].memberId === 7 && seen[0].email === 'hugh@example.com', g);
|
||||
g = await ledger.chapterDripGated(me, 1, false); ok('a replay is not a reward (no IAP call)', g.reason === 'replay' && seen.length === 1);
|
||||
script['chapter:2'] = { allowed: 0, deferred: 0.01 }; g = await ledger.chapterDripGated(me, 2, true);
|
||||
ok('chapter 2 deferred: handled, owed, the player told', g.reason === 'deferred' && g.pol === 0 && ledger.account(7).gpOwed === 0.01 && /pays out over the next days/.test(g.note) && store.read('drips', []).some(d => d.chapter === 2 && d.pol === 0));
|
||||
script['carry:' + today] = { allowed: 0.01, carried: 0.01 }; ok('carry sweep collects it once a day', (await ledger.carrySweep()) === 0.01 && ledger.account(7).gpOwed === 0 && (await ledger.carrySweep()) === 0);
|
||||
mode = '500'; g = await ledger.chapterDripGated(me, 3, true); ok('IAP down: queued, nothing paid, the player told', g.reason === 'iap' && gp.queued(7, me.email, 'chapter:3') && /recorded/.test(g.note));
|
||||
const n = seen.length; g = await ledger.chapterDripGated(me, 3, true); ok('a queued chapter is not asked again', g.reason === 'iap' && seen.length === n);
|
||||
mode = 'ok'; await gp.retry(ledger.payQueued, Date.now() + gp.RETRY_MS + 1); ok('the queued chapter pays on retry', !gp.queued(7, me.email, 'chapter:3') && store.read('drips', []).some(d => d.chapter === 3 && d.pol === 0.01) && ledger.account(7).unpaid === 0.03);
|
||||
ok('the pool only counts what was paid', ledger.pool().out === 0.03);
|
||||
// a member with no wallet: negative local id (sso.emailId) -> memberId 0 + email on the wire; the pass flag keyed by email
|
||||
const nw = { memberId: sso.emailId('nowallet@example.com'), email: 'nowallet@example.com', username: 'nw', wallet: null };
|
||||
ok('the negative local id is never sent', nw.memberId < 0 && ledger.iapId(nw) === 0);
|
||||
g = await ledger.chapterDripGated(nw, 1, true); ok('a wallet-less member is gated by email', g.reason === 'paid' && seen.at(-1).memberId === 0 && seen.at(-1).email === 'nowallet@example.com');
|
||||
const guest = { memberId: -999999999999, guest: true, email: null }; seen.length = 0; g = await ledger.chapterDripGated(guest, 1, true); ok('a guest gets the plain chapterDrip (no IAP call)', seen.length === 0 && g.reason === 'paid');
|
||||
ledger.setSettings({ dailyCapPol: 0.001 }); g = await ledger.chapterDripGated(me, 4, true); ok('the local daily cap still stands in front of IAP', g.reason === 'cap'); ledger.setSettings({ dailyCapPol: 5 });
|
||||
process.env.GAMEPASS = 'off'; seen.length = 0; g = await ledger.chapterDripGated(me, 4, true); ok('GAMEPASS=off: the plain chapterDrip, no IAP call', g.reason === 'paid' && seen.length === 0); process.env.GAMEPASS = 'on';
|
||||
ok('history explains deferral and carry', ledger.balance(7).history.some(h => /paying out over the next days/.test(h.label)) && ledger.balance(7).history.some(h => /Carried-over/.test(h.label)));
|
||||
// the perk: a shield at the start of every run while the pass is active
|
||||
gp.rememberPass(7, me.email, false); let run = game.start(me, 390, 760); ok('no pass: no free shield', run.armed.shield === false && !run.armed.passShield);
|
||||
gp.rememberPass(7, me.email, { active: true, until: Date.now() + 86400000 }); run = game.start(me, 390, 760); ok('pass active: a shield at run start', run.armed.shield === true && run.armed.passShield === true && ledger.passActive(me));
|
||||
game.updPlayer(7, x => { x.items.shield = true; }); run = game.start(me, 390, 760); ok('a bought Shield Core is kept for a later run while the pass covers this one', run.armed.shield === true && game.player(7).items.shield === true);
|
||||
process.env.GAMEPASS = 'off'; run = game.start(me, 390, 760); ok('GAMEPASS=off: no perk (the bought shield is used as before)', run.armed.shield === true && !run.armed.passShield && !game.player(7).items.shield); process.env.GAMEPASS = 'on';
|
||||
|
||||
stub.close(); console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
Reference in New Issue
Block a user