b70ecf6f75
InstantAdPay now pushes a member's signature-linked wallet whether or not it is activated (memberId 0 when not on chain). - POST /api/iap/wallet accepts memberId 0/missing: the wallet fills the email-keyed player (sso.emailId) and its account; a player with no account row yet gets one holding the wallet. Signature check, fill-empty-only (different wallet 409), same wallet no-op and 404 for an unknown player are unchanged; a real memberId still adopts the email history first. - /auth: a hand-off wallet fills an EMPTY account wallet so POL earned so far pays on the next sweep (never replaces one). - game.adopt carries the wallet when the target account has none. - /api/me: me.hasWallet (own wallet on file, also when it arrived by the push after the session began). - play.js: no-wallet players see "Link your wallet to receive this POL" (IAP /my#wallet, new tab) on the chapter-clear result, the lobby member line and the balance card (which also lost a line that always overwrote the waiting-POL note); players with a wallet see the same text as before. play.js?v=20261027lw. - test/run.js: memberId 0 push -> 200 changed:true -> sweep pays it; /auth memberId 0 wallet; 409; activation later. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
172 lines
12 KiB
JavaScript
172 lines
12 KiB
JavaScript
// Runs, players and the server-side replay check.
|
|
//
|
|
// The client never says "pay me". It reports what happened (drip #i collected at run time t,
|
|
// chapter goal reached) and the server checks each claim against the seeded schedule it
|
|
// handed out at run start: a drip cannot be collected before it spawned, nor far from the
|
|
// moment it would have crossed the courier, nor twice. A run with too many refused claims is
|
|
// flagged and its chapter clears pay nothing. Bots, crashes and fuel are the client's business:
|
|
// a modified client can only avoid dying, it cannot invent a drip.
|
|
'use strict';
|
|
const crypto = require('crypto');
|
|
const store = require('./store');
|
|
const spawn = require('./spawn');
|
|
const ledger = require('./ledger');
|
|
|
|
const EARLY = 1.2, LATE = 0.9; // seconds around the computed arrival (magnet pulls ~150 px early)
|
|
const KEEP_RUNS_MS = 2 * 86400000;
|
|
const sched = new Map(); // runId -> { next, groups[] } regenerated lazily after a restart
|
|
|
|
function player(memberId) { return store.read('players', {})[String(memberId)] || null; }
|
|
function updPlayer(memberId, fn) {
|
|
return store.update('players', {}, all => {
|
|
const k = String(memberId);
|
|
const p = all[k] || (all[k] = { memberId: Number(memberId), bank: 0, chapter: 1, cleared: {}, items: {}, best: 0, runs: 0, since: Date.now() });
|
|
fn(p); return all;
|
|
})[String(memberId)];
|
|
}
|
|
function view(me) {
|
|
const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
|
const s = ledger.settings();
|
|
return { bank: p.bank, chapter: p.chapter, cleared: p.cleared, items: p.items, best: p.runs ? p.best : 0, runs: p.runs, freeUpgrades: Number(p.freeUpgrades) || 0,
|
|
goal: spawn.goalFor(p.chapter), prices: { pol: s.itemPol, drips: s.itemDrips }, dripPol: Number(s.dripPol) };
|
|
}
|
|
|
|
function runs() { return store.read('runs', {}); }
|
|
function run(id) { return runs()[id] || null; }
|
|
function updRun(id, fn) { let out = null; store.update('runs', {}, all => { if (all[id]) { fn(all[id]); out = all[id]; } return all; }); return out; }
|
|
function prune() {
|
|
const cut = Date.now() - KEEP_RUNS_MS;
|
|
store.update('runs', {}, all => { for (const k of Object.keys(all)) if (all[k].status !== 'live' && all[k].startedAt < cut) { delete all[k]; sched.delete(k); } return all; });
|
|
}
|
|
|
|
function start(me, W, H) {
|
|
W = Math.max(300, Math.min(1200, Math.round(Number(W) || 390))); H = Math.max(500, Math.min(1400, Math.round(Number(H) || 760)));
|
|
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; });
|
|
// 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: [] };
|
|
store.update('runs', {}, all => { all[r.id] = r; return all; });
|
|
if (Math.random() < 0.05) prune();
|
|
return r;
|
|
}
|
|
function groupsUpTo(r, t) {
|
|
let s = sched.get(r.id);
|
|
if (!s) { s = { next: spawn.drips(r.seed, r.W, r.H), groups: [] }; sched.set(r.id, s); }
|
|
while (!s.groups.length || s.groups[s.groups.length - 1].t <= t + 5) s.groups.push(s.next());
|
|
return s.groups;
|
|
}
|
|
function dripInfo(r, i, t) {
|
|
const groups = groupsUpTo(r, t);
|
|
for (const g of groups) for (const d of g.drips) if (d.i === i) return { s: g.t, x0: d.x0 };
|
|
return null;
|
|
}
|
|
|
|
// the client's batch of claims for a live run
|
|
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 };
|
|
t = Math.max(0, Number(t) || 0);
|
|
const wall = (Date.now() - r.startedAt) / 1000 + 3; // run time cannot outrun the clock
|
|
const seen = new Set(r.collected); let ok = 0, bad = 0, badWhy = [];
|
|
for (const e of (Array.isArray(list) ? list : []).slice(0, 400)) {
|
|
if (!e || e.k !== 'd') continue;
|
|
const i = Number(e.i), et = Number(e.t);
|
|
if (!Number.isInteger(i) || i < 0 || !(et >= 0) || et > wall) { bad++; badWhy.push('shape'); continue; }
|
|
if (seen.has(i)) { bad++; badWhy.push('dup'); continue; }
|
|
const d = dripInfo(r, i, Math.max(et, t)); if (!d || d.s > et + 0.05) { bad++; badWhy.push('early'); continue; }
|
|
const arr = spawn.arrival(d.s, d.x0, r.W, r.speed);
|
|
if (et < arr - EARLY || et > arr + LATE) { bad++; badWhy.push('window'); continue; }
|
|
seen.add(i); ok++;
|
|
}
|
|
const out = updRun(runId, x => {
|
|
x.collected = [...seen]; x.drips += ok; x.chapDrips += ok; x.bad += bad; x.t = Math.max(x.t, t);
|
|
if (x.bad > 5 && x.bad > (x.drips + x.bad) * 0.1) x.flagged = true;
|
|
});
|
|
if (ok) updPlayer(me.memberId, p => { p.bank += ok; if (out.drips > p.best) p.best = out.drips; });
|
|
const res = { ok, refused: bad, drips: out.drips, chapDrips: out.chapDrips, goal: out.goal, flagged: out.flagged };
|
|
if (bad) res.why = badWhy.slice(0, 5);
|
|
if (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' } : 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, note: grant.note || null, next: ch + 1, nextGoal: spawn.goalFor(ch + 1), playTime: Math.round(out.t) }; // note = the Game Pass truth
|
|
}
|
|
return res;
|
|
}
|
|
function end(me, runId) {
|
|
const r = run(runId); if (!r || r.memberId !== Number(me.memberId)) return { error: 'Not your run.' };
|
|
updRun(runId, x => { if (x.status === 'live') x.status = 'ended'; x.endedAt = Date.now(); });
|
|
sched.delete(runId);
|
|
return { ok: true };
|
|
}
|
|
function refuelled(me, runId) { return updRun(runId, x => { x.refuels++; }); }
|
|
|
|
// hangar
|
|
// a free upgrade token (the member perk, lib/starter.js) pays for the next purchase whatever it is: no drips, no POL moved
|
|
function useFree(me, item) { updPlayer(me.memberId, x => { x.freeUpgrades = Math.max(0, (Number(x.freeUpgrades) || 0) - 1); x.items[item] = true; }); return { ok: true, free: true, paid: 'free upgrade' }; }
|
|
function buy(me, item) {
|
|
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
|
const free = Number(p.freeUpgrades) > 0;
|
|
if (s.itemDrips[item] != null) {
|
|
const cost = Number(s.itemDrips[item]);
|
|
if (item === 'ship' && p.items.ship) return { error: 'You already own the Courier Mk II.' };
|
|
if (p.items[item] && item !== 'ship') return { error: 'That one is already armed for your next run.' };
|
|
if (free) return useFree(me, item);
|
|
if (p.bank < cost) return { error: 'Not enough drips. You have ' + p.bank + ', it costs ' + cost + '.' };
|
|
updPlayer(me.memberId, x => { x.bank -= cost; x.items[item] = true; });
|
|
return { ok: true, paid: cost + ' drips' };
|
|
}
|
|
if (s.itemPol[item] != null) {
|
|
if (p.items[item]) return { error: 'That one is already armed for your next run.' };
|
|
if (free) return useFree(me, item);
|
|
const r = ledger.spend(me, item, Number(s.itemPol[item])); if (r.error) return r;
|
|
updPlayer(me.memberId, x => { x.items[item] = true; });
|
|
return { ok: true, paid: r.pol + ' POL' };
|
|
}
|
|
return { error: 'No such item.' };
|
|
}
|
|
// Move everything one id owns onto another (a guest who signs in, or a wallet-less member who links a wallet).
|
|
// Returns the chapters the old id cleared as a guest that the new id has never cleared: the caller pays those.
|
|
function adopt(fromId, toId) {
|
|
fromId = Number(fromId); toId = Number(toId); if (!fromId || fromId === toId) return { moved: false, pending: [] };
|
|
const all = store.read('players', {}); const a = all[String(fromId)]; if (!a) return { moved: false, pending: [] };
|
|
const b = all[String(toId)]; const pending = (a.pending || []).filter(ch => !(b && b.cleared && b.cleared[ch]));
|
|
store.update('players', {}, ps => {
|
|
const src = ps[String(fromId)]; const dst = ps[String(toId)];
|
|
if (!dst) { ps[String(toId)] = Object.assign({}, src, { memberId: toId, pending: [] }); }
|
|
else { dst.bank += src.bank; dst.runs += src.runs; dst.best = Math.max(dst.best, src.best); dst.chapter = Math.max(dst.chapter, src.chapter); dst.cleared = Object.assign({}, src.cleared, dst.cleared); dst.items = Object.assign({}, src.items, dst.items); }
|
|
delete ps[String(fromId)]; return ps;
|
|
});
|
|
for (const name of ['drips', 'spends', 'refuels', 'payouts']) store.update(name, [], rows => { for (const r of rows) if (r.memberId === fromId) r.memberId = toId; return rows; });
|
|
store.update('accounts', {}, acc => { const x = acc[String(fromId)]; if (x) { const y = acc[String(toId)]; if (y) { y.unpaid = Math.round((y.unpaid + x.unpaid) * 10000) / 10000; y.earnedTotal = Math.round(((y.earnedTotal || 0) + (x.earnedTotal || 0)) * 10000) / 10000; y.spentTotal = Math.round(((y.spentTotal || 0) + (x.spentTotal || 0)) * 10000) / 10000; if (!y.wallet && x.wallet) y.wallet = x.wallet; } else acc[String(toId)] = Object.assign({}, x, { memberId: toId }); delete acc[String(fromId)]; } return acc; });
|
|
store.update('runs', {}, rs => { for (const k of Object.keys(rs)) if (rs[k].memberId === fromId) rs[k].memberId = toId; return rs; });
|
|
store.update('posted', {}, ps => { if (ps[String(fromId)]) { ps[String(toId)] = Array.from(new Set([...(ps[String(toId)] || []), ...ps[String(fromId)]])); delete ps[String(fromId)]; } return ps; });
|
|
return { moved: true, pending };
|
|
}
|
|
// the players whose InstantAdPay sponsor is this member (their referrals in the game)
|
|
function referralsOf(me) {
|
|
const keys = [String(me.memberId), String(me.username || '').toLowerCase()].filter(Boolean);
|
|
return Object.values(store.read('players', {})).filter(p => p.memberId > 0 && p.sponsorRef && keys.includes(String(p.sponsorRef).toLowerCase()));
|
|
}
|
|
// the game player a sponsorRef points at (username, or on-chain member id)
|
|
function byRef(ref) {
|
|
const r = String(ref || '').trim().toLowerCase(); if (!r) return null;
|
|
return Object.values(store.read('players', {})).find(p => p.memberId > 0 && ((p.username && p.username.toLowerCase() === r) || String(p.memberId) === r)) || null;
|
|
}
|
|
function byUsername(u) { const r = String(u || '').trim().toLowerCase().replace(/^@/, ''); return r ? Object.values(store.read('players', {})).find(p => p.username && p.username.toLowerCase() === r) || null : null; }
|
|
function recent(n) { return Object.values(runs()).sort((a, b) => b.startedAt - a.startedAt).slice(0, n || 50).map(r => Object.assign({}, r, { collected: r.collected.length })); }
|
|
|
|
module.exports = { player, updPlayer, view, run, start, events, end, refuelled, buy, recent, prune, adopt, referralsOf, byRef, byUsername };
|