Drip Runner trial: IAP hand-off, seeded runs with server replay check, self-funding POL pool (refuel ad share + hangar spends), chapter drips, threshold payouts via faucet (dry run), tester allowlist + briefing page, admin page, e2e test
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
// The faucet: pays due payouts from the dedicated hot wallet (PolHunter's sender, trimmed).
|
||||
//
|
||||
// DR_WALLET_KEY the hot wallet's private key (env only, never on disk)
|
||||
// DR_RPC comma list of RPC urls; a transient node error rotates to the next
|
||||
// DR_CHAIN_ID 137 (mainnet) or 80002 (Amoy)
|
||||
// DR_DRY_RUN anything but 'off' means no transaction is ever sent; rows stay due and the
|
||||
// tick reports what it would have paid (the trial starts here)
|
||||
//
|
||||
// One plain POL transfer per payout row, hash recorded before the wait, settled from the receipt
|
||||
// on a later tick if the wait times out or the process restarts. Never sent twice.
|
||||
'use strict';
|
||||
const { ethers } = require('ethers');
|
||||
const ledger = require('./ledger');
|
||||
const store = require('./store');
|
||||
|
||||
let provider = null, wallet = null, ticking = false, rpcs = [], rpcAt = 0;
|
||||
const dry = () => String(process.env.DR_DRY_RUN || 'on').toLowerCase() !== 'off';
|
||||
function enabled() { return !!(process.env.DR_WALLET_KEY && process.env.DR_RPC); }
|
||||
function init() { if (!enabled()) return false; rpcs = String(process.env.DR_RPC).split(',').map(s => s.trim()).filter(Boolean); rpcAt = 0; connect(); return true; }
|
||||
function connect() { provider = new ethers.JsonRpcProvider(rpcs[rpcAt % rpcs.length], Number(process.env.DR_CHAIN_ID) || undefined); wallet = new ethers.Wallet(process.env.DR_WALLET_KEY.trim(), provider); }
|
||||
const TRANSIENT = /server response 5\d\d|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|429|rate limit|missing response|could not detect network|bad response|SERVER_ERROR|NETWORK_ERROR/i;
|
||||
function rotate(reason) { if (rpcs.length > 1) { rpcAt = (rpcAt + 1) % rpcs.length; connect(); console.warn('faucet: RPC rotated after', reason.slice(0, 80)); } }
|
||||
function address() { return wallet ? wallet.address : null; }
|
||||
async function balance() { if (!provider || !wallet) return null; return Number(ethers.formatEther(await provider.getBalance(wallet.address))); }
|
||||
function state() { return Object.assign({ dryRun: dry(), address: address(), enabled: enabled() }, store.read('faucet-state', {})); }
|
||||
|
||||
async function settle(p, rc, notify) {
|
||||
const ok = rc && rc.status === 1;
|
||||
ledger.mark(p.id, { status: ok ? 'paid' : 'failed', paidAt: Date.now(), error: ok ? null : 'reverted' });
|
||||
if (notify) await notify(ok ? 'paid' : 'failed', Object.assign({}, p, ok ? {} : { error: 'reverted' }));
|
||||
return ok;
|
||||
}
|
||||
|
||||
async function tick(notify) {
|
||||
if (!wallet || ticking) return { paid: 0 };
|
||||
ticking = true; let paid = 0, would = 0;
|
||||
try {
|
||||
for (const p of store.read('payouts', []).filter(x => x.status === 'sent' && x.tx)) {
|
||||
try { const rc = await provider.getTransactionReceipt(p.tx); if (rc && (await settle(p, rc, notify))) paid++; } catch (e) {}
|
||||
}
|
||||
const due = ledger.payable();
|
||||
let bal = null; try { bal = await balance(); } catch (e) {}
|
||||
if (dry()) {
|
||||
would = due.reduce((n, p) => n + p.pol, 0);
|
||||
if (due.length) console.log('faucet DRY RUN: would pay', due.length, 'payout(s),', would, 'POL; balance', bal);
|
||||
store.update('faucet-state', {}, x => Object.assign(x, { balance: bal, checkedAt: Date.now(), lastTick: { due: due.length, would } }));
|
||||
return { paid: 0, dryRun: true, due: due.length, would, balance: bal };
|
||||
}
|
||||
for (const p of due) {
|
||||
if (bal != null && bal < p.pol + 0.005) { await lowOnce(notify, bal, p.pol); break; }
|
||||
try {
|
||||
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)) });
|
||||
ledger.mark(p.id, { status: 'sent', tx: tx.hash });
|
||||
let rc = null;
|
||||
try { rc = await tx.wait(1, 90000); } catch (e) { if (e && e.code === 'TIMEOUT') continue; throw e; }
|
||||
if (await settle(Object.assign({}, p, { tx: tx.hash }), rc, notify)) { paid++; if (bal != null) bal -= p.pol; }
|
||||
} catch (e) {
|
||||
const msg = String(e.message || e);
|
||||
if (/insufficient funds/i.test(msg)) { ledger.mark(p.id, { status: 'due', error: null }); break; }
|
||||
const cur = store.read('payouts', []).find(x => x.id === p.id);
|
||||
if (cur && cur.status === 'sent' && cur.tx) continue;
|
||||
if (TRANSIENT.test(msg)) { ledger.mark(p.id, { status: 'due', error: 'node: ' + msg.slice(0, 120) }); rotate(msg); break; }
|
||||
ledger.mark(p.id, { status: 'failed', error: msg.slice(0, 200) });
|
||||
if (notify) await notify('failed', Object.assign({}, p, { error: msg.slice(0, 200) }));
|
||||
}
|
||||
}
|
||||
const b2 = await balance();
|
||||
if (b2 != null) { if (b2 < Number(ledger.settings().lowBalancePol)) await lowOnce(notify, b2, ledger.settings().lowBalancePol); store.update('faucet-state', {}, x => Object.assign(x, { balance: b2, checkedAt: Date.now(), lastTick: { paid } })); }
|
||||
} finally { ticking = false; }
|
||||
return { paid };
|
||||
}
|
||||
async function lowOnce(notify, bal, need) {
|
||||
const day = ledger.ctDay(); const st = store.read('faucet-state', {});
|
||||
if (st.lowAlertDay === day || !notify) return;
|
||||
st.lowAlertDay = day; store.write('faucet-state', st);
|
||||
await notify('low', { balance: bal, threshold: need, address: wallet.address });
|
||||
}
|
||||
|
||||
module.exports = { enabled, init, address, balance, tick, state, dry };
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// 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,
|
||||
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; });
|
||||
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
|
||||
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
|
||||
function events(me, runId, t, list, wantGoal) {
|
||||
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 = ledger.chapterDrip(me, ch, first && !out.flagged);
|
||||
if (first && out.flagged) grant.reason = 'flagged';
|
||||
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) };
|
||||
}
|
||||
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
|
||||
function buy(me, item) {
|
||||
const s = ledger.settings(); const p = player(me.memberId) || updPlayer(me.memberId, () => {});
|
||||
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 (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.' };
|
||||
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.' };
|
||||
}
|
||||
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 };
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
// The money: the self-funding pool, drips, spends, member balances and payouts.
|
||||
//
|
||||
// Marty's rule (2026-09-30): no POL is ever given away that the game did not earn. The pool is
|
||||
// fed only by (a) the admin share of the advertiser credits a refuel visit consumed, (b) POL a
|
||||
// player spent in the hangar out of their balance, and (c) an optional seed the admin puts in on
|
||||
// purpose. A chapter drip is granted only while the pool covers it and today's cap allows it;
|
||||
// otherwise the chapter still counts as cleared and pays nothing, and the card says why.
|
||||
//
|
||||
// Stores (volume): settings, refuels[], drips[], spends[], accounts{memberId}, payouts[], pool.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const store = require('./store');
|
||||
const polusd = require('./polusd');
|
||||
|
||||
const DEFAULTS = {
|
||||
usdPerCredit: 0.01, // every IAP pack is 100 credits per dollar (catalog, 2026-09-30)
|
||||
creditsPerVisit: 3, // what a visits campaign pays per delivered visit (IAP rates.visitCostPerVisit)
|
||||
poolSharePct: 30, // the admin share of a pack purchase, the only money the pool may use
|
||||
usdPerPolFallback: 0.12,// used only when the live rate cannot be read
|
||||
dripPol: 0.01, // per first-time chapter clear
|
||||
dailyCapPol: 5, // hard ceiling on drips granted per Central day, whatever the pool holds
|
||||
thresholdPol: 0.25, // a member's unpaid balance is sent to their wallet once it reaches this
|
||||
seedPol: 0, // admin float; set on purpose, never by code
|
||||
lowBalancePol: 1,
|
||||
itemPol: { shield: 0.05, slow: 0.03 }, // hangar items paid from the POL balance (the sink)
|
||||
itemDrips: { magnet: 250, ship: 600 }, // hangar items paid in drips (never money)
|
||||
testers: [], // emails or member ids allowed through the hand-off while signups = 'testers'
|
||||
signups: 'testers' // 'testers' | 'open' | 'closed'
|
||||
};
|
||||
function settings() { return Object.assign({}, DEFAULTS, store.read('settings', {})); }
|
||||
function setSettings(patch) { return store.update('settings', {}, s => Object.assign(s, patch)); }
|
||||
const ctDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const id = () => Date.now().toString(36) + crypto.randomBytes(4).toString('hex');
|
||||
const r4 = n => Math.round(Number(n) * 10000) / 10000;
|
||||
|
||||
async function usdPerPol() { try { return await polusd.usdPerPol(); } catch (e) { return Number(settings().usdPerPolFallback) || 0.12; } }
|
||||
|
||||
// ---- pool ----------------------------------------------------------------------------------
|
||||
function pool() {
|
||||
const p = Object.assign({ in: 0, spends: 0, out: 0 }, store.read('pool', {}));
|
||||
const s = settings();
|
||||
const available = r4(Number(s.seedPol) + p.in + p.spends - p.out);
|
||||
const today = ctDay();
|
||||
const grantedToday = r4(store.read('drips', []).filter(d => d.day === today && d.status !== 'void').reduce((n, d) => n + d.pol, 0));
|
||||
return { in: r4(p.in), spends: r4(p.spends), out: r4(p.out), seed: Number(s.seedPol), available, grantedToday, dailyCapPol: Number(s.dailyCapPol), capLeft: r4(Math.max(0, Number(s.dailyCapPol) - grantedToday)) };
|
||||
}
|
||||
function poolAdd(field, pol) { store.update('pool', {}, p => { p[field] = r4((p[field] || 0) + pol); return p; }); }
|
||||
|
||||
// ---- refuels: the income --------------------------------------------------------------------
|
||||
async function refuel(me, info) {
|
||||
const s = settings();
|
||||
const credits = Math.max(0, Number(info.credits) || Number(s.creditsPerVisit) || 3);
|
||||
const usd = credits * Number(s.usdPerCredit);
|
||||
const share = usd * Number(s.poolSharePct) / 100;
|
||||
const rate = await usdPerPol();
|
||||
const pol = r4(share / rate);
|
||||
const row = { id: id(), nonce: info.nonce || null, memberId: Number(me.memberId), username: me.username || null, campaignId: info.campaignId || null, credits, usd: r4(usd), share: r4(share), usdPerPol: r4(rate), pol, via: info.via || 'callback', day: ctDay(), ts: Date.now() };
|
||||
store.update('refuels', [], all => { all.push(row); return all; });
|
||||
poolAdd('in', pol);
|
||||
return row;
|
||||
}
|
||||
function refuelsToday() { const d = ctDay(); return store.read('refuels', []).filter(r => r.day === d); }
|
||||
|
||||
// ---- accounts + drips -----------------------------------------------------------------------
|
||||
function account(memberId) { return Object.assign({ memberId: Number(memberId), unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }, store.read('accounts', {})[String(memberId)] || {}); }
|
||||
function updAccount(memberId, fn) { return store.update('accounts', {}, all => { const a = Object.assign({ memberId: Number(memberId), unpaid: 0, paidTotal: 0, spentTotal: 0, earnedTotal: 0 }, all[String(memberId)] || {}); fn(a); a.unpaid = r4(a.unpaid); all[String(memberId)] = a; return all; })[String(memberId)]; }
|
||||
|
||||
// a first-time chapter clear. eligible=false means a replay or a flagged run: cleared, unpaid.
|
||||
function chapterDrip(me, chapter, eligible) {
|
||||
const s = settings(); const pol = r4(Number(s.dripPol));
|
||||
if (!eligible) return { pol: 0, reason: 'replay' };
|
||||
const p = pool();
|
||||
if (p.capLeft < pol) return { pol: 0, reason: 'cap' };
|
||||
if (p.available < pol) return { pol: 0, reason: 'pool' };
|
||||
const row = { id: id(), memberId: Number(me.memberId), username: me.username || null, wallet: me.wallet || null, pol, chapter, day: ctDay(), ts: Date.now(), status: 'granted' };
|
||||
store.update('drips', [], all => { all.push(row); return all; });
|
||||
poolAdd('out', pol);
|
||||
updAccount(me.memberId, a => { a.unpaid += pol; a.earnedTotal = r4((a.earnedTotal || 0) + pol); a.wallet = me.wallet || a.wallet || null; a.username = me.username || a.username || null; });
|
||||
return { pol, reason: 'paid', id: row.id };
|
||||
}
|
||||
|
||||
// the sink: a hangar item paid from the member's unpaid POL balance goes back to the pool
|
||||
function spend(me, item, pol) {
|
||||
pol = r4(pol);
|
||||
const a = account(me.memberId);
|
||||
if (a.unpaid + 1e-9 < pol) return { error: 'Not enough POL in your game balance yet. Clear a chapter or two first.' };
|
||||
updAccount(me.memberId, x => { x.unpaid -= pol; x.spentTotal = r4((x.spentTotal || 0) + pol); });
|
||||
const row = { id: id(), memberId: Number(me.memberId), username: me.username || null, item, pol, day: ctDay(), ts: Date.now() };
|
||||
store.update('spends', [], all => { all.push(row); return all; });
|
||||
poolAdd('spends', pol);
|
||||
return { ok: true, pol };
|
||||
}
|
||||
|
||||
// ---- 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
|
||||
function sweep() {
|
||||
const s = settings(); const th = Number(s.thresholdPol);
|
||||
const accts = store.read('accounts', {}); const made = [];
|
||||
for (const k of Object.keys(accts)) {
|
||||
const a = accts[k];
|
||||
if (!(a.unpaid >= th) || !a.wallet || !/^0x[a-f0-9]{40}$/i.test(a.wallet)) continue;
|
||||
const pending = store.read('payouts', []).some(p => p.memberId === a.memberId && (p.status === 'due' || p.status === 'sent'));
|
||||
if (pending) continue; // one open payout per member at a time
|
||||
const pol = r4(a.unpaid);
|
||||
const row = { id: id(), memberId: a.memberId, username: a.username || null, wallet: a.wallet, pol, day: ctDay(), ts: Date.now(), status: 'due' };
|
||||
store.update('payouts', [], all => { all.push(row); return all; });
|
||||
updAccount(a.memberId, x => { x.unpaid -= pol; });
|
||||
made.push(row);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
function payable() { sweep(); return store.read('payouts', []).filter(p => p.status === 'due'); }
|
||||
function mark(pid, patch) {
|
||||
let row = null;
|
||||
store.update('payouts', [], all => { const p = all.find(x => x.id === pid); if (p) { Object.assign(p, patch); row = p; } return all; });
|
||||
if (row && patch.status === 'paid') updAccount(row.memberId, a => { a.paidTotal = r4((a.paidTotal || 0) + row.pol); });
|
||||
if (row && patch.status === 'failed') updAccount(row.memberId, a => { a.unpaid += row.pol; }); // the money is still theirs
|
||||
return row;
|
||||
}
|
||||
|
||||
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('spends', []).filter(d => d.memberId === Number(memberId)).map(d => ({ t: d.ts, kind: 'spend', label: 'Hangar · ' + d.item, 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 })))
|
||||
.sort((x, y) => y.t - x.t).slice(0, 40);
|
||||
return { unpaid: r4(a.unpaid), paidTotal: r4(a.paidTotal || 0), spentTotal: r4(a.spentTotal || 0), earnedTotal: r4(a.earnedTotal || 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 };
|
||||
@@ -0,0 +1,89 @@
|
||||
// What a dollar is worth in POL right now.
|
||||
//
|
||||
// Mission blocks are priced in dollars ($30 entry, $10 listing) because that is how Marty thinks
|
||||
// about them and how a buyer judges them. The faucet pays in POL. So something has to convert,
|
||||
// and it has to be a rate nobody can argue with.
|
||||
//
|
||||
// It is read from the InstantAdPay contract's own quote: the contract stores each package's price
|
||||
// in cents and quotes the POL to pay right now, so priceCents / quoteWei IS the rate members are
|
||||
// already paying at today. No third-party price feed, no oracle to trust, no disagreement between
|
||||
// what a mission costs here and what a package costs there.
|
||||
//
|
||||
// Cached for a few minutes and fail-soft: a purchase is refused rather than priced off a stale or
|
||||
// missing rate, because getting this wrong silently means selling delivery below cost.
|
||||
'use strict';
|
||||
const https = require('https');
|
||||
|
||||
const IAP = '0xbe1eca72aff47d13d8e907e523f55eb9e2d365e0';
|
||||
const RPCS = ['https://polygon-bor-rpc.publicnode.com', 'https://1rpc.io/matic'];
|
||||
const SEL_COUNT = '0xe0f6ef87'; // productCount()
|
||||
const SEL_PRODUCT = '0xbf712fd6'; // products(uint32) -> priceCents is word 0, active word 3
|
||||
const SEL_QUOTE = '0x7de85694'; // quoteWei(uint32)
|
||||
const TTL = 5 * 60000;
|
||||
|
||||
let cache = { usdPerPol: 0, at: 0 };
|
||||
|
||||
function rpc(method, params) {
|
||||
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
|
||||
return new Promise((resolve, reject) => {
|
||||
let i = 0;
|
||||
const attempt = () => {
|
||||
const u = new URL(RPCS[i]);
|
||||
const rq = https.request({ hostname: u.hostname, path: u.pathname, method: 'POST', timeout: 12000,
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, res => {
|
||||
let d = ''; res.on('data', c => d += c);
|
||||
res.on('end', () => {
|
||||
try { const j = JSON.parse(d); if (j.error) throw new Error(j.error.message); resolve(j.result); }
|
||||
catch (e) { if (++i < RPCS.length) attempt(); else reject(e); }
|
||||
});
|
||||
});
|
||||
rq.on('error', () => { if (++i < RPCS.length) attempt(); else reject(new Error('rpc unreachable')); });
|
||||
rq.on('timeout', () => { rq.destroy(); });
|
||||
rq.end(body);
|
||||
};
|
||||
attempt();
|
||||
});
|
||||
}
|
||||
const call = data => rpc('eth_call', [{ to: IAP, data }, 'latest']);
|
||||
const enc = n => BigInt(n).toString(16).padStart(64, '0');
|
||||
const word = (r, i) => r.slice(2 + i * 64, 2 + (i + 1) * 64);
|
||||
|
||||
// Walk the catalogue until a product quotes a non-zero POL cost, then take cents / POL from it.
|
||||
async function fetchRate() {
|
||||
const n = parseInt(word(await call(SEL_COUNT), 0), 16);
|
||||
for (let id = 1; id <= Math.min(n, 12); id++) {
|
||||
let wei = 0n, cents = 0;
|
||||
try { wei = BigInt('0x' + word(await call(SEL_QUOTE + enc(id)), 0)); } catch (e) { continue; }
|
||||
if (wei <= 0n) continue;
|
||||
try {
|
||||
const p = await call(SEL_PRODUCT + enc(id));
|
||||
cents = parseInt(word(p, 0), 16); // priceCents
|
||||
const active = parseInt(word(p, 3), 16) === 1;
|
||||
const exists = parseInt(word(p, 4), 16) === 1;
|
||||
if (!active || !exists) cents = 0;
|
||||
} catch (e) { /* fall through */ }
|
||||
if (!cents) continue;
|
||||
const pol = Number(wei / 10n ** 12n) / 1e6;
|
||||
if (pol > 0) return (cents / 100) / pol; // dollars per POL
|
||||
}
|
||||
throw new Error('no product quoted a usable price');
|
||||
}
|
||||
|
||||
// dollars per POL, e.g. 0.1019
|
||||
async function usdPerPol(force) {
|
||||
if (!force && cache.usdPerPol > 0 && Date.now() - cache.at < TTL) return cache.usdPerPol;
|
||||
const r = await fetchRate();
|
||||
if (!(r > 0) || !isFinite(r)) throw new Error('rate came back unusable');
|
||||
cache = { usdPerPol: r, at: Date.now() };
|
||||
return r;
|
||||
}
|
||||
|
||||
// POL needed for a price in cents. Throws rather than guessing: a purchase priced off a rate we
|
||||
// could not read is a purchase that might sell delivery below cost.
|
||||
async function polForCents(cents) {
|
||||
const rate = await usdPerPol();
|
||||
const pol = (Number(cents) / 100) / rate;
|
||||
return Math.round(pol * 10000) / 10000;
|
||||
}
|
||||
|
||||
module.exports = { usdPerPol, polForCents, _cache: () => cache };
|
||||
@@ -0,0 +1,43 @@
|
||||
// The deterministic spawn schedule, shared by the browser and the server (served at /spawn.js).
|
||||
//
|
||||
// A run is seeded once by the server. Every drip the courier can ever collect in that run comes
|
||||
// from this schedule, so the server knows when drip #i appeared and roughly when it could have
|
||||
// been reached, and can refuse a collection that the schedule says was impossible. Bots and
|
||||
// firewall gates come from their own streams (seed+1, seed+2): they matter to the player, not
|
||||
// to the payout, so the server never regenerates them.
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) module.exports = factory(); else root.DRSpawn = factory();
|
||||
})(typeof self !== 'undefined' ? self : this, function () {
|
||||
'use strict';
|
||||
// mulberry32: tiny, good enough, identical in every JS engine
|
||||
function rng(seed) {
|
||||
let a = (seed >>> 0) || 1;
|
||||
return function () { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
|
||||
}
|
||||
const FLOOR = 92; // px from the bottom to the rail
|
||||
const PX = 0.27; // the courier's x as a fraction of the width
|
||||
// drip groups: every call returns the next group { t, drips: [{ i, x0, y }] }
|
||||
function drips(seed, W, H) {
|
||||
const r = rng(seed); let t = 0, i = 0; const floorY = H - FLOOR;
|
||||
return function next() {
|
||||
t += 0.5 + r() * 0.3;
|
||||
const arc = r() < 0.35, n = arc ? 4 : 1, y0 = 120 + r() * (floorY - 170);
|
||||
const g = { t: Math.round(t * 1000) / 1000, drips: [] };
|
||||
for (let k = 0; k < n; k++) g.drips.push({ i: i++, x0: W + 40 + k * 34, y: y0 - (arc ? Math.sin(k / 3 * Math.PI) * 46 : 0) });
|
||||
return g;
|
||||
};
|
||||
}
|
||||
function bots(seed, chapter, H) {
|
||||
const r = rng(seed + 1); let t = 0.8; const floorY = H - FLOOR;
|
||||
return function () { t += Math.max(0.75, 1.7 - chapter * 0.08) + r() * 0.5; const y = 110 + r() * (floorY - 150); return { t, y, amp: r() < 0.5 ? 0 : 40 + r() * 50, ph: r() * 6 }; };
|
||||
}
|
||||
function gates(seed, chapter, H) {
|
||||
const r = rng(seed + 2); let t = 3; const floorY = H - FLOOR;
|
||||
return function () { t += 4 + r() * 3; const gap = 190 - Math.min(60, chapter * 6); return { t, y: 140 + r() * (floorY - 160 - gap), gap }; };
|
||||
}
|
||||
function goalFor(ch) { return 20 + (ch - 1) * 12; }
|
||||
function speedFor(ch) { return 230 + (ch - 1) * 14; }
|
||||
// when drip { x0 } spawned at time s reaches the courier's x at a constant speed
|
||||
function arrival(s, x0, W, speed) { return s + (x0 - W * PX) / speed; }
|
||||
return { rng, drips, bots, gates, goalFor, speedFor, arrival, PX, FLOOR };
|
||||
});
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// Sign-in by hand-off from InstantAdPay, the PolHunter pattern. There is no sign-up here and
|
||||
// no mailer: a member opens the game from their IAP dashboard (or the tester page sends them
|
||||
// through IAP), IAP signs a short-lived token with the shared secret, and this turns it into a
|
||||
// game session. The same signing scheme carries the refuel token to IAP and IAP's receipt back.
|
||||
//
|
||||
// Token: base64url(JSON payload) + '.' + base64url(HMAC-SHA256(secret, payload)).
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const store = require('./store');
|
||||
|
||||
const SECRET = String(process.env.DR_SSO_SECRET || '').trim();
|
||||
const SESSION_TTL = 30 * 86400000;
|
||||
const used = new Map(); // nonce -> exp (single-use guard for hand-off tokens)
|
||||
|
||||
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
const sign = payload => b64u(crypto.createHmac('sha256', SECRET).update(payload).digest());
|
||||
|
||||
function enabled() { return SECRET.length >= 32; }
|
||||
function mint(claims, ttlMs) {
|
||||
const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 5 * 60000), nonce: crypto.randomBytes(12).toString('hex') }, claims));
|
||||
return b64u(payload) + '.' + sign(payload);
|
||||
}
|
||||
// generic check: signature + expiry, no replay guard (the caller keeps its own nonce book)
|
||||
function open(token) {
|
||||
if (!enabled()) return { error: 'Sign-in from InstantAdPay is not configured on this server.' };
|
||||
const [p, sig] = String(token || '').split('.');
|
||||
if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
let payload; try { payload = unb64u(p).toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
const want = sign(payload);
|
||||
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
if (!c.exp || Date.now() > c.exp) return { error: 'That link has expired. Open Drip Runner from your InstantAdPay dashboard again.' };
|
||||
return { ok: true, claims: c };
|
||||
}
|
||||
// the hand-off: single use
|
||||
function verify(token) {
|
||||
const r = open(token); if (r.error) return r;
|
||||
const c = r.claims;
|
||||
if (!c.memberId || !c.email) return { error: 'That sign-in link is missing your account.' };
|
||||
for (const [n, exp] of used) if (exp < Date.now()) used.delete(n);
|
||||
if (used.has(c.nonce)) return { error: 'That sign-in link was already used.' };
|
||||
used.set(c.nonce, c.exp);
|
||||
return { ok: true, claims: c };
|
||||
}
|
||||
function startSession(claims) {
|
||||
const id = crypto.randomBytes(24).toString('hex');
|
||||
store.update('sessions', {}, s => {
|
||||
const now = Date.now();
|
||||
for (const k of Object.keys(s)) if ((s[k].since || 0) + SESSION_TTL < now) delete s[k];
|
||||
s[id] = { memberId: Number(claims.memberId), email: String(claims.email).toLowerCase(), wallet: claims.wallet ? String(claims.wallet).toLowerCase() : null, username: claims.username || null, since: now };
|
||||
return s;
|
||||
});
|
||||
return id;
|
||||
}
|
||||
const secure = () => process.env.NODE_ENV === 'production' ? '; Secure' : '';
|
||||
function cookie(id) { return 'dr.sid=' + id + '; Path=/; Max-Age=' + Math.floor(SESSION_TTL / 1000) + '; HttpOnly; SameSite=Lax' + secure(); }
|
||||
function clearCookie() { return 'dr.sid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); }
|
||||
function fromRequest(req) {
|
||||
const m = /(?:^|;\s*)dr\.sid=([a-f0-9]{48})/.exec(req.headers.cookie || '');
|
||||
if (!m) return null;
|
||||
const s = store.read('sessions', {})[m[1]];
|
||||
if (!s || (s.since || 0) + SESSION_TTL < Date.now()) return null;
|
||||
return Object.assign({ sid: m[1] }, s);
|
||||
}
|
||||
function endSession(sid) { store.update('sessions', {}, s => { delete s[sid]; return s; }); }
|
||||
function refresh(sid, claims) { store.update('sessions', {}, s => { if (s[sid]) { s[sid].wallet = claims.wallet ? String(claims.wallet).toLowerCase() : null; s[sid].username = claims.username || s[sid].username; } return s; }); }
|
||||
|
||||
module.exports = { enabled, mint, open, verify, startSession, cookie, clearCookie, fromRequest, endSession, refresh };
|
||||
@@ -0,0 +1,28 @@
|
||||
// Tiny JSON store on the volume. Every collection is one file; writes are atomic (tmp + rename).
|
||||
// PolHunter's data is small (missions, completions, payouts) and a member's balance never lives
|
||||
// here, so a database would be ceremony. If it ever grows, this is the one file to swap.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let DIR = null;
|
||||
function init(dir) { DIR = dir; fs.mkdirSync(DIR, { recursive: true }); }
|
||||
const file = name => path.join(DIR, name + '.json');
|
||||
|
||||
function read(name, fallback) {
|
||||
try { return JSON.parse(fs.readFileSync(file(name), 'utf8')); } catch (e) { return fallback; }
|
||||
}
|
||||
function write(name, data) {
|
||||
const f = file(name), tmp = f + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(data));
|
||||
fs.renameSync(tmp, f);
|
||||
}
|
||||
// read-modify-write in one place so callers never race themselves
|
||||
function update(name, fallback, fn) {
|
||||
const cur = read(name, fallback);
|
||||
const out = fn(cur) || cur;
|
||||
write(name, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { init, read, write, update };
|
||||
Reference in New Issue
Block a user